feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口
完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
1 parent
8e0bbf7a81
commit
c94d173f92
181 files changed
+12947
-1724
No files matched your search
@@ -85,7 +85,7 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
@@ -249,7 +249,14 @@ def tool_ensure_inventory():
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_ensure_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='inventory_preparation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
@@ -265,7 +272,14 @@ def tool_match_inventory():
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_match_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='inventory_matching',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
@@ -300,7 +314,14 @@ def tool_generate_shipment_excel():
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_generate_excel',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='artifact_generation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
|
||||
@@ -1126,65 +1126,42 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
"""兼容旧匹配入口:只提交当前 Gate 自动推进,不直接执行库存匹配。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||
matched = shipping_tools.match_inventory({
|
||||
'task_id': task.task_no,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
'_trusted_user_id': user.id,
|
||||
'operator_id': user.id,
|
||||
'event_source': 'workspace_api',
|
||||
})
|
||||
if not isinstance(matched, dict):
|
||||
return _ok(matched)
|
||||
data = matched.get('data')
|
||||
if isinstance(data, dict) and data.get('export_file_path'):
|
||||
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
|
||||
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
|
||||
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
|
||||
matched['checkpoint'] = checkpoint
|
||||
if 'human_options' not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched['human_options'] = options
|
||||
if 'action_buttons' not in matched:
|
||||
# [STEP] 已有 ProcessExecution 时不再补充旧 STP 恢复按钮。
|
||||
from app.models import ShippingProcessExecution
|
||||
has_execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.first()
|
||||
) is not None
|
||||
if not has_execution:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched['action_buttons'] = buttons
|
||||
return _ok(matched)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
audit_legacy_forwarded_entrypoint,
|
||||
submit_auto_progress,
|
||||
)
|
||||
audit_legacy_forwarded_entrypoint(
|
||||
task=task, action_code='match_inventory', actor_id=user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
result = submit_auto_progress(task=task, trigger='legacy_match_inventory', operator_id=user.id)
|
||||
return _ok({'deprecated': True, 'projection_refresh_required': True, **result})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
"""兼容旧导出入口:只提交当前 Gate 自动推进,不直接生成 Excel。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
result = shipping_tools.generate_excel({'task_id': task.task_no})
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
data = result.get('data')
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result['data'] = data
|
||||
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||
return _ok(result)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
audit_legacy_forwarded_entrypoint,
|
||||
submit_auto_progress,
|
||||
)
|
||||
audit_legacy_forwarded_entrypoint(
|
||||
task=task, action_code='generate_excel', actor_id=user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
result = submit_auto_progress(task=task, trigger='legacy_generate_excel', operator_id=user.id)
|
||||
return _ok({'deprecated': True, 'projection_refresh_required': True, **result})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
jobs/handlers/shipping_auto_progress.py
|
||||
|
||||
用途:消费 P0-3 Task 级 AutoProgress Job。
|
||||
用途:终态化历史 APX AutoProgress Job。
|
||||
依赖:JobContext、auto_progress_controller。
|
||||
逻辑:Job 已由通用队列领取为 running;本 Handler 只委托正式控制器执行一个 Gate,不再调用旧全链路 facade。
|
||||
逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX
|
||||
Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +17,7 @@ from app.services.shipping_notice.auto_progress_controller import run_auto_progr
|
||||
|
||||
@register_handler(JobType.SHIPPING_AUTO_PROGRESS)
|
||||
def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行一个正式 Gate;payload 必须含队列注入的 job_id。"""
|
||||
"""终态化历史 APX Job;payload 必须含队列注入的 job_id。"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
if not raw_job_id:
|
||||
raise RuntimeError('missing_job_id_for_shipping_auto_progress')
|
||||
|
||||
@@ -5,7 +5,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
|
||||
依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、
|
||||
process_gate_error_sanitizer。
|
||||
逻辑:由 shipping worker 领取;技术失败按该 Attempt 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队;
|
||||
次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal);
|
||||
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
|
||||
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
|
||||
waiting_external 先结束当前 Job 再延迟入队新 Job;
|
||||
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
|
||||
@@ -14,8 +14,6 @@ backend/app/jobs/handlers/shipping_process_gate.py
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
@@ -30,80 +28,32 @@ from app.services.shipping_notice.process_gate_job_service import (
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import complete_gate_attempt
|
||||
|
||||
# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。
|
||||
_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120)
|
||||
|
||||
|
||||
def _count_failed_technical_jobs(attempt_id: int) -> int:
|
||||
"""
|
||||
统计某 Attempt 已失败的技术 Job 数(含 force_new 的 business_ref 变体)。
|
||||
|
||||
核心逻辑:按 business_ref=`attempt:{id}` 或 `attempt:{id}:...` 过滤 failed Job,
|
||||
作为跨 Job 累计重试次数,避免写入 input_snapshot 破坏 Hash。
|
||||
|
||||
Args:
|
||||
attempt_id: ShippingProcessGateAttempt 主键。
|
||||
|
||||
Returns:
|
||||
已处于 failed 状态的相关 Job 数量。
|
||||
"""
|
||||
prefix = f'attempt:{int(attempt_id)}'
|
||||
return (
|
||||
Job.query
|
||||
.filter(
|
||||
Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
|
||||
Job.status == 'failed',
|
||||
or_(
|
||||
Job.business_ref == prefix,
|
||||
Job.business_ref.like(f'{prefix}:%'),
|
||||
),
|
||||
)
|
||||
.count()
|
||||
)
|
||||
|
||||
|
||||
def _strip_legacy_retry_count_from_input_snapshot(attempt: ShippingProcessGateAttempt) -> None:
|
||||
"""
|
||||
清理历史误写入 input_snapshot 的 technical_retry_count,避免污染业务输入快照。
|
||||
|
||||
核心逻辑:若键存在则删除;不重算 Hash(Hash 应对创建时的业务快照;遗留键本身已破坏一致性,
|
||||
删除后正文与创建 Hash 仍可能不一致,但后续不再写入新的运行元数据)。
|
||||
"""
|
||||
snap = attempt.input_snapshot_json
|
||||
if not isinstance(snap, dict) or 'technical_retry_count' not in snap:
|
||||
return
|
||||
cleaned = {k: v for k, v in snap.items() if k != 'technical_retry_count'}
|
||||
attempt.input_snapshot_json = cleaned
|
||||
|
||||
|
||||
def _finalize_attempt_after_retry_exhausted(
|
||||
def _finalize_attempt_after_failure(
|
||||
*,
|
||||
attempt: ShippingProcessGateAttempt,
|
||||
exc: BaseException,
|
||||
) -> None:
|
||||
"""
|
||||
技术重试耗尽:将 Attempt/Gate 收口为 failed_terminal。
|
||||
单次门禁执行失败:结束当前 Attempt,并将 Gate 收口为可人工恢复阻断。
|
||||
|
||||
核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。
|
||||
"""
|
||||
safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_retry_exhausted'
|
||||
safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_failure'
|
||||
if attempt.status == 'queued':
|
||||
attempt.status = 'running'
|
||||
db.session.flush()
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='failed_terminal',
|
||||
outcome='blocked_retryable',
|
||||
# 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure
|
||||
blocking_reason_code='technical_retry_exhausted',
|
||||
blocking_reason_code='technical_failure_present',
|
||||
blocking_reason_json={
|
||||
'reason_code': 'technical_retry_exhausted',
|
||||
'reason_code': 'technical_failure_present',
|
||||
'message': safe,
|
||||
'technical_retry_exhausted': True,
|
||||
},
|
||||
effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'},
|
||||
output_snapshot={'error': safe, 'technical_retry_exhausted': True},
|
||||
error_code='TECHNICAL_RETRY_EXHAUSTED',
|
||||
effective_result_json={'findings': [], 'error': 'technical_failure'},
|
||||
output_snapshot={'error': safe},
|
||||
error_code='TECHNICAL_FAILURE',
|
||||
error_summary=safe,
|
||||
)
|
||||
|
||||
@@ -141,6 +91,9 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
try:
|
||||
result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id)
|
||||
except Exception as exc:
|
||||
# claim/execute 可能已经让 SQLAlchemy 事务进入 aborted 状态(例如死锁)。
|
||||
# 任何失败收口前必须先回滚,避免把 Job 标记失败后留下 queued Attempt/Gate。
|
||||
db.session.rollback()
|
||||
attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
|
||||
gate = None
|
||||
gate_status = None
|
||||
@@ -163,45 +116,15 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
db.session.commit()
|
||||
return
|
||||
|
||||
# [STEP] 技术失败:按 Attempt 下 failed Job 累计判定,禁止因 force_new 无限重试。
|
||||
max_attempts = max(
|
||||
int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3),
|
||||
1,
|
||||
)
|
||||
failed_already = _count_failed_technical_jobs(attempt_id) if attempt is not None else max_attempts
|
||||
safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure'
|
||||
# 本次 fail_job 后累计 = failed_already + 1;未达上限则退避重入队。
|
||||
if attempt is not None and failed_already + 1 < max_attempts:
|
||||
delay_idx = min(failed_already, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1)
|
||||
delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx]
|
||||
fail_job(
|
||||
job.id,
|
||||
error=safe_error,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
_strip_legacy_retry_count_from_input_snapshot(attempt)
|
||||
attempt.status = 'queued'
|
||||
attempt.job_id = None
|
||||
attempt.worker_id = None
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
if gate is not None and gate.status == 'running':
|
||||
gate.status = 'queued'
|
||||
db.session.flush()
|
||||
enqueue_gate_attempt_job(
|
||||
attempt_id=attempt_id,
|
||||
delay_seconds=delay,
|
||||
force_new=True,
|
||||
)
|
||||
db.session.commit()
|
||||
return
|
||||
|
||||
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
|
||||
# 先把 Attempt/Gate/Execution 收口,再独立结束 Job;即使 Runner 随后兜底标记
|
||||
# Job failed,也不会再留下 failed Job + queued Attempt 的非法组合。
|
||||
if attempt is not None:
|
||||
_strip_legacy_retry_count_from_input_snapshot(attempt)
|
||||
_finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc)
|
||||
db.session.commit()
|
||||
fresh_attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
|
||||
if fresh_attempt is not None and fresh_attempt.status in {'queued', 'running'}:
|
||||
_finalize_attempt_after_failure(attempt=fresh_attempt, exc=exc)
|
||||
db.session.commit()
|
||||
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)
|
||||
@@ -95,6 +95,14 @@ def run_forever(
|
||||
handler(ctx, job.get('payload') or {})
|
||||
except Exception as exc:
|
||||
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
|
||||
# Handler 可能在 flush/写库失败后留下 aborted transaction;先回滚,
|
||||
# 再查询并收口 Job,否则 mark_failed 自身会被 InFailedSqlTransaction 阻断。
|
||||
try:
|
||||
from app import db
|
||||
|
||||
db.session.rollback()
|
||||
except Exception:
|
||||
ctx.logger.exception('Session rollback failed after handler job_id=%s', job.get('id'))
|
||||
store.mark_failed(
|
||||
job['id'],
|
||||
message=str(exc),
|
||||
|
||||
@@ -20,7 +20,7 @@ class JobType(StrEnum):
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||
# Task 级正式决策器:一个 Job 只处理一个 ProcessGate。
|
||||
# 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移)
|
||||
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
|
||||
|
||||
@@ -168,6 +168,12 @@ from app.models.shipping_inventory_candidates import (
|
||||
ShippingInventoryCandidateSource,
|
||||
)
|
||||
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt
|
||||
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
|
||||
from app.models.shipping_inventory_preparation import (
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
)
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
@@ -361,6 +361,15 @@ class ShippingInventoryFile(Base):
|
||||
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -397,6 +406,12 @@ class ShippingTaskInventoryLink(Base):
|
||||
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
@@ -62,6 +62,10 @@ class ShippingInventoryVerification(Base):
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.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)
|
||||
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -131,7 +135,7 @@ class ShippingUploadAttempt(Base):
|
||||
UniqueConstraint('callback_id', name='uq_shipping_notice_upload_attempts_callback'),
|
||||
CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_notice_upload_attempts_mode'),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')",
|
||||
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out', 'unknown')",
|
||||
name='ck_shipping_notice_upload_attempts_status',
|
||||
),
|
||||
Index('ix_shipping_notice_upload_attempts_artifact_created', 'artifact_id', 'created_at'),
|
||||
@@ -143,6 +147,9 @@ class ShippingUploadAttempt(Base):
|
||||
mode: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
callback_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
superseded_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_upload_attempts.id'), nullable=True)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
models/shipping_inventory_mapping.py
|
||||
|
||||
用途:保存不可变库存字段映射版本。
|
||||
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。
|
||||
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""库存文件的不可变字段映射版本。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
|
||||
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
|
||||
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
models/shipping_inventory_preparation.py
|
||||
|
||||
用途:表达一次任务级库存准备轮次及逐库存源状态。
|
||||
依赖:ShippingNotice、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
|
||||
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingInventoryPreparationAttempt(Base):
|
||||
"""一次任务级库存准备恢复轮次。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_preparation_attempts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued','running','waiting_external','waiting_manual','succeeded','failed','cancelled','superseded')",
|
||||
name='ck_shipping_inventory_preparation_status',
|
||||
),
|
||||
Index('ix_shipping_inventory_preparation_task_status', 'task_id', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.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)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True)
|
||||
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
|
||||
|
||||
|
||||
class ShippingInventoryPreparationSourceAttempt(Base):
|
||||
"""准备轮次中某个库存源的业务状态。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_preparation_source_attempts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
|
||||
CheckConstraint(
|
||||
"status IN ('ready','reusable','skipped','failed','waiting','queued','running')",
|
||||
name='ck_shipping_inventory_preparation_source_status',
|
||||
),
|
||||
Index('ix_shipping_inventory_preparation_source_status', 'source_code', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
|
||||
inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True)
|
||||
task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts')
|
||||
@@ -133,3 +133,10 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
@@ -259,9 +259,15 @@ class ShippingProcessGateAttempt(Base):
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_summary: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
recovery_plan_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_process_recovery_plans.id', use_alter=True), nullable=True, index=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
|
||||
|
||||
gate: Mapped[ShippingProcessGate] = relationship(
|
||||
back_populates='attempts',
|
||||
foreign_keys=[gate_id],
|
||||
)
|
||||
recovery_plan = relationship(
|
||||
'ShippingProcessRecoveryPlan', back_populates='attempts', foreign_keys=[recovery_plan_id],
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
models/shipping_process_recovery_plan.py
|
||||
|
||||
用途:持久化一次跨阶段门禁恢复业务意图及其生命周期。
|
||||
依赖:ShippingProcessExecution、ShippingProcessGateAttempt、User、Base。
|
||||
逻辑:RecoveryPlan 记录目标 Gate、失效计划、幂等键和最终结果;一个计划可关联多个 Gate Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
RECOVERY_PLAN_STATUSES = (
|
||||
'planned', 'invalidating', 'queued', 'running', 'waiting_external',
|
||||
'waiting_manual', 'succeeded', 'failed', 'conflicted', 'cancelled',
|
||||
)
|
||||
|
||||
|
||||
class ShippingProcessRecoveryPlan(Base):
|
||||
"""一次跨阶段恢复意图;不可用 Gate Attempt JSON 替代。"""
|
||||
|
||||
__tablename__ = 'shipping_process_recovery_plans'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('plan_no', name='uq_shipping_process_recovery_plans_no'),
|
||||
UniqueConstraint('execution_id', 'idempotency_key', name='uq_shipping_process_recovery_plans_execution_idempotency'),
|
||||
CheckConstraint(
|
||||
"status IN ('planned','invalidating','queued','running','waiting_external','waiting_manual','succeeded','failed','conflicted','cancelled')",
|
||||
name='ck_shipping_process_recovery_plans_status',
|
||||
),
|
||||
Index('ix_shipping_process_recovery_plans_execution_status', 'execution_id', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
plan_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
execution_id: Mapped[int] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False)
|
||||
current_gate: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
action_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
target_gate: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
resume_after_gate: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned')
|
||||
invalidation_plan_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
recovery_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
expected_gate_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
|
||||
actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
failure_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
failure_detail_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
superseded_by_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
execution = relationship('ShippingProcessExecution', foreign_keys=[execution_id])
|
||||
attempts = relationship('ShippingProcessGateAttempt', back_populates='recovery_plan', foreign_keys='ShippingProcessGateAttempt.recovery_plan_id')
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
APX 历史运行时只读清点。
|
||||
|
||||
用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。
|
||||
依赖:ShippingProcessExecution、Job ORM 模型。
|
||||
逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import Job, ShippingProcessExecution
|
||||
|
||||
|
||||
_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external')
|
||||
_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active')
|
||||
|
||||
|
||||
def audit_apx_runtime_state() -> dict[str, object]:
|
||||
"""只读统计 APX Execution/Job 运行态与历史态数量。
|
||||
|
||||
Returns:
|
||||
包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或
|
||||
payload 中的 execution_id 关联;任何写操作都不在此函数执行。
|
||||
"""
|
||||
apx_executions = ShippingProcessExecution.query.filter(
|
||||
ShippingProcessExecution.execution_no.ilike('APX-%')
|
||||
).all()
|
||||
runtime_execution_ids = {
|
||||
int(row.id) for row in apx_executions
|
||||
if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES
|
||||
}
|
||||
apx_jobs = Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.status.in_(_JOB_RUNTIME_STATUSES),
|
||||
).all()
|
||||
runtime_job_count = 0
|
||||
for job in apx_jobs:
|
||||
if int(job.execution_id or 0) in runtime_execution_ids:
|
||||
runtime_job_count += 1
|
||||
continue
|
||||
if str(job.business_ref or '').upper().find('APX-') >= 0:
|
||||
runtime_job_count += 1
|
||||
continue
|
||||
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
|
||||
if str(payload.get('execution_no') or '').upper().startswith('APX-'):
|
||||
runtime_job_count += 1
|
||||
|
||||
return {
|
||||
'execution': {
|
||||
'active_count': len(runtime_execution_ids),
|
||||
'historical_count': len(apx_executions) - len(runtime_execution_ids),
|
||||
},
|
||||
'job': {
|
||||
'active_count': runtime_job_count,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -10,13 +10,15 @@ services/shipping_notice/auto_progress_controller.py
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
@@ -33,6 +35,24 @@ _ACTIVE_JOB_STATUSES = ('queued', 'running')
|
||||
_CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'})
|
||||
|
||||
|
||||
def audit_legacy_forwarded_entrypoint(
|
||||
*, task: ShippingNotice, action_code: str, actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。"""
|
||||
log_task_event(
|
||||
task,
|
||||
'shipping_legacy_entrypoint_forwarded',
|
||||
{
|
||||
'entrypoint': 'legacy_forwarded',
|
||||
'action_code': str(action_code or '').strip(),
|
||||
},
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
source='workspace_api',
|
||||
)
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
"""返回仓库统一使用的 naive UTC 时间。"""
|
||||
return datetime.utcnow()
|
||||
@@ -43,6 +63,43 @@ def _task_is_cancelled(task: ShippingNotice) -> bool:
|
||||
return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES
|
||||
|
||||
|
||||
def _recover_stale_active_job(job: Job) -> bool:
|
||||
"""
|
||||
在用户触发入口原子回收超时的 AutoProgress running Job。
|
||||
|
||||
核心逻辑:仅处理 started_at 已超过通用发货 Job 超时的 running 行;旧 Job
|
||||
终态保留审计,关联 running/queued Gate 改为 blocked_retryable,使当前事务可重新入队。
|
||||
|
||||
Args:
|
||||
job: 已由 submit_auto_progress 锁定的活动 Job。
|
||||
|
||||
Returns:
|
||||
True 表示旧 Job 已回收,调用方应继续创建新 Job;False 表示仍有效并复用。
|
||||
"""
|
||||
if str(job.status or '') != 'running' or job.started_at is None:
|
||||
return False
|
||||
timeout_seconds = float(
|
||||
current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 420) or 420
|
||||
)
|
||||
if job.started_at >= _utc_now() - timedelta(seconds=timeout_seconds):
|
||||
return False
|
||||
now = _utc_now()
|
||||
job.status = 'failed'
|
||||
job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已允许重新入队'
|
||||
job.error_message = 'shipping_auto_progress_timeout'
|
||||
job.finished_at = now
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.updated_at = now
|
||||
gate = db.session.get(ShippingProcessGate, int(job.gate_id)) if job.gate_id else None
|
||||
if gate is not None and gate.status in {'queued', 'running'}:
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.blocking_reason_code = 'technical_retry_exhausted'
|
||||
gate.updated_at = now
|
||||
db.session.flush()
|
||||
return True
|
||||
|
||||
|
||||
def _new_execution_no() -> str:
|
||||
"""生成可读的 P0-3 Execution 编号。"""
|
||||
return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
|
||||
@@ -50,28 +107,111 @@ def _new_execution_no() -> str:
|
||||
|
||||
def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
|
||||
"""
|
||||
为当前 Task/CandidateSet 创建独立六 Gate 链。
|
||||
禁止创建 APX 六 Gate Execution。
|
||||
|
||||
核心逻辑:不复用旧 20 Gate Execution,避免旧 skipped/waiting_external 语义污染 P0-3 的严格顺序。
|
||||
APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate
|
||||
``ensure_execution_for_workflow_version`` 创建 Execution。
|
||||
"""
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no=_new_execution_no(), task_id=int(task.id), candidate_set_id=candidate_set_id,
|
||||
execution_revision=1, status='active', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
|
||||
raise RuntimeError('shipping_apx_creation_disabled')
|
||||
|
||||
|
||||
def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
|
||||
"""按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。"""
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
|
||||
|
||||
gate_codes = {
|
||||
str(item.gate_code)
|
||||
for item in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all()
|
||||
}
|
||||
return gate_codes == set(PROCESS_GATE_CODES)
|
||||
|
||||
|
||||
def determine_formal_start_gate(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
candidate_set: Any | None = None,
|
||||
) -> str:
|
||||
"""根据持久化 Task/CandidateSet 事实选择正式 20-Gate 的首个 Gate。
|
||||
|
||||
未确认的解析、冻结或候选事实一律回退到最早缺失 Gate,禁止由调用入口
|
||||
直接跳过前置 Contract;仅完整冻结订单和 frozen CandidateSet 可进入库存准备。
|
||||
"""
|
||||
if not getattr(task, 'current_order_extraction_id', None):
|
||||
return 'document_materialization'
|
||||
if not getattr(task, 'order_snapshot_id', None):
|
||||
return 'order_freeze_readiness'
|
||||
# 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史
|
||||
# Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。
|
||||
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
|
||||
if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}:
|
||||
return 'customer_resolution'
|
||||
# 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。
|
||||
if any(str(getattr(row, 'status', '') or '').strip().lower() == 'open' for row in (getattr(task, 'field_conflicts', None) or [])):
|
||||
return 'field_conflict_resolution'
|
||||
candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task)
|
||||
if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen':
|
||||
return 'inventory_source_routing'
|
||||
return 'inventory_preparation'
|
||||
|
||||
|
||||
def _create_formal_execution_for_task(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
candidate_set_id: int | None,
|
||||
) -> ShippingProcessExecution:
|
||||
"""为无正式链的已建 Task 创建唯一 20-Gate Execution,禁止新建 APX。"""
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=int(task.id),
|
||||
actor_type='system',
|
||||
start_gate_code=determine_formal_start_gate(task),
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1):
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id), gate_code=gate_code, sequence_no=sequence_no,
|
||||
status='pending', evaluation_version=1, lock_version=1,
|
||||
))
|
||||
execution.candidate_set_id = candidate_set_id
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.flush()
|
||||
return execution
|
||||
|
||||
|
||||
def _supersede_duplicate_execution(
|
||||
execution: ShippingProcessExecution,
|
||||
*,
|
||||
replacement: ShippingProcessExecution,
|
||||
) -> None:
|
||||
"""收敛重复活动链;保留审计记录,不删除历史 Attempt/Job。"""
|
||||
if execution.id == replacement.id or execution.status in {'completed', 'cancelled', 'superseded'}:
|
||||
return
|
||||
execution.status = 'superseded'
|
||||
execution.updated_at = _utc_now()
|
||||
ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGate.status.in_(
|
||||
('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated'),
|
||||
),
|
||||
).update(
|
||||
{'status': 'cancelled', 'updated_at': _utc_now()},
|
||||
synchronize_session=False,
|
||||
)
|
||||
|
||||
|
||||
def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
|
||||
"""锁定并取得当前 Execution;候选版本变化时旧链 superseded 后创建新链。"""
|
||||
"""
|
||||
锁定并取得当前唯一活动 Execution。
|
||||
|
||||
核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读,
|
||||
不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。
|
||||
"""
|
||||
all_active = (
|
||||
ShippingProcessExecution.query
|
||||
.filter(
|
||||
ShippingProcessExecution.task_id == int(task.id),
|
||||
ShippingProcessExecution.status.in_(('active', 'blocked', 'waiting_external')),
|
||||
)
|
||||
.with_for_update()
|
||||
.order_by(ShippingProcessExecution.id.asc())
|
||||
.all()
|
||||
)
|
||||
formal = next((item for item in all_active if _is_formal_process_execution(item)), None)
|
||||
current_id = getattr(task, 'active_process_execution_id', None)
|
||||
execution = db.session.get(ShippingProcessExecution, int(current_id)) if current_id else None
|
||||
if execution is not None:
|
||||
@@ -80,6 +220,14 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
|
||||
)
|
||||
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(task.id):
|
||||
execution = None
|
||||
if formal is not None:
|
||||
for duplicate in all_active:
|
||||
if duplicate.id != formal.id:
|
||||
_supersede_duplicate_execution(duplicate, replacement=formal)
|
||||
task.active_process_execution_id = int(formal.id)
|
||||
formal.updated_at = _utc_now()
|
||||
db.session.flush()
|
||||
return formal
|
||||
if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0):
|
||||
# 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。
|
||||
execution.status = 'superseded'
|
||||
@@ -88,7 +236,17 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
|
||||
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
|
||||
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
|
||||
execution = None
|
||||
return execution or _create_execution(task, candidate_set_id=candidate_set_id)
|
||||
# APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。
|
||||
if execution is not None:
|
||||
execution.status = 'superseded'
|
||||
execution.updated_at = _utc_now()
|
||||
ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGate.status.in_(
|
||||
('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated'),
|
||||
),
|
||||
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
|
||||
return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id)
|
||||
|
||||
|
||||
def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None:
|
||||
@@ -101,14 +259,37 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None
|
||||
if execution_id:
|
||||
execution = ShippingProcessExecution.query.filter_by(id=int(execution_id)).with_for_update().first()
|
||||
if execution is not None and execution.status not in {'completed', 'cancelled', 'superseded'}:
|
||||
# Attempt 是不可变执行历史,但候选版本切换后其 queued/running 状态
|
||||
# 必须显式终止,避免旧 Attempt 被 Worker 领取并污染新 CandidateSet。
|
||||
ShippingProcessGateAttempt.query.filter(
|
||||
ShippingProcessGateAttempt.gate_id.in_(
|
||||
db.session.query(ShippingProcessGate.id).filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
)
|
||||
),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).update(
|
||||
{
|
||||
'status': 'superseded',
|
||||
'finished_at': _utc_now(),
|
||||
'error_code': 'candidate_set_refrozen',
|
||||
'error_summary': 'CandidateSet 已重冻结,旧 GateAttempt 终止',
|
||||
},
|
||||
synchronize_session=False,
|
||||
)
|
||||
execution.status = 'superseded'
|
||||
ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
|
||||
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice', Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value,
|
||||
Job.task_id == int(task.id), Job.status == 'queued',
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type.in_((
|
||||
JobType.SHIPPING_AUTO_PROGRESS.value,
|
||||
JobType.SHIPPING_PROCESS_GATE.value,
|
||||
)),
|
||||
Job.task_id == int(task.id),
|
||||
Job.status == 'queued',
|
||||
).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False)
|
||||
|
||||
|
||||
@@ -122,7 +303,11 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
|
||||
ShippingProcessGate.query.filter_by(execution_id=int(execution.id))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all()
|
||||
)
|
||||
expected = list(AUTO_PROGRESS_GATE_CODES)
|
||||
# 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史
|
||||
# APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
|
||||
|
||||
expected = list(PROCESS_GATE_CODES)
|
||||
if [item.gate_code for item in gates] != expected:
|
||||
return None, 'projection_data_inconsistent'
|
||||
pending_seen = False
|
||||
@@ -145,172 +330,191 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
|
||||
def submit_auto_progress(
|
||||
*, task: ShippingNotice, trigger: str, operator_id: int | None = None,
|
||||
resume_gate_code: str | None = None, commit: bool = True,
|
||||
recovery_plan_id: int | None = None,
|
||||
recovery_attempt_id: int | None = None,
|
||||
resume_after_gate: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
接收任何自动/用户触发并安全入队当前 Gate。
|
||||
|
||||
普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。
|
||||
"""
|
||||
locked_task = ShippingNotice.query.filter_by(id=int(task.id)).with_for_update().first()
|
||||
# ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN;
|
||||
# PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。
|
||||
locked_task = (
|
||||
ShippingNotice.query
|
||||
.filter_by(id=int(task.id))
|
||||
.with_for_update(of=ShippingNotice)
|
||||
.first()
|
||||
)
|
||||
if locked_task is None:
|
||||
return {'status': 'not_found'}
|
||||
if _task_is_cancelled(locked_task):
|
||||
return {'status': 'cancelled', 'task_no': locked_task.task_no}
|
||||
# 只复用正式 ProcessGate Job。遗留 APX Job 已下线,不能阻塞或劫持正式链入队。
|
||||
# 先查活动 Job,再读取/改写 Candidate 或 Execution 指针。这样候选重冻结与重复点击
|
||||
# 无法把一个仍 running 的旧 Job 错绑到新链。
|
||||
# 无法把一个仍 running 的正式 Job 错绑到新链。
|
||||
active = (
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value,
|
||||
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
|
||||
Job.task_id == int(locked_task.id),
|
||||
Job.status.in_(_ACTIVE_JOB_STATUSES),
|
||||
).with_for_update().order_by(Job.id.desc()).first()
|
||||
)
|
||||
if active is not None:
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active.status == 'queued' else 'running',
|
||||
'job_id': int(active.id), 'execution_id': active.execution_id,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
|
||||
}
|
||||
if not _recover_stale_active_job(active):
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active.status == 'queued' else 'running',
|
||||
'job_id': int(active.id), 'execution_id': active.execution_id,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
|
||||
}
|
||||
log_task_event(locked_task, 'auto_progress_stale_job_recovered', {
|
||||
'stale_job_id': int(active.id),
|
||||
'execution_id': active.execution_id,
|
||||
'gate_id': active.gate_id,
|
||||
'trigger': trigger,
|
||||
}, actor_id=operator_id, source=trigger)
|
||||
candidate = get_active_candidate_set(locked_task)
|
||||
candidate_set_id = int(candidate.id) if candidate is not None else None
|
||||
execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id)
|
||||
gate, inconsistency = _earliest_runnable_gate(execution)
|
||||
if inconsistency:
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = None
|
||||
log_task_event(locked_task, 'auto_progress_projection_inconsistent', {
|
||||
'execution_id': execution.id, 'reason_code': inconsistency,
|
||||
}, actor_id=operator_id, source=trigger)
|
||||
if _is_formal_process_execution(execution):
|
||||
# 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容
|
||||
# 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一
|
||||
# ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_contract import is_technical_gate_party
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
actor_id=operator_id,
|
||||
)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
|
||||
current_gate = str(execution.current_gate_code or '').strip() or None
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code=current_gate)
|
||||
.with_for_update()
|
||||
.first()
|
||||
if current_gate else None
|
||||
)
|
||||
active_attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.gate_id == int(gate.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
|
||||
.first()
|
||||
if gate is not None else None
|
||||
)
|
||||
if active_attempt is not None and active_attempt.job_id:
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active_attempt.status == 'queued' else 'running',
|
||||
'job_id': int(active_attempt.job_id),
|
||||
'attempt_id': int(active_attempt.id),
|
||||
'execution_id': int(execution.id),
|
||||
'gate_code': gate.gate_code,
|
||||
'reused': True,
|
||||
}
|
||||
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
|
||||
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
|
||||
# system/worker Gate 才可自动创建 Attempt 并入队。
|
||||
if gate is not None and action_code and is_technical_gate_party(execution.responsible_party):
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=str(gate.gate_code),
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=operator_id,
|
||||
idempotency_key=(
|
||||
f'shipping-auto-progress:{locked_task.id}:{execution.id}:'
|
||||
f'{gate.id}:{gate.evaluation_version}'
|
||||
),
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
input_snapshot={
|
||||
'action_code': action_code,
|
||||
'payload': {
|
||||
'candidate_set_id': candidate_set_id,
|
||||
'fencing_token': uuid.uuid4().hex,
|
||||
'trigger': trigger,
|
||||
'recovery_plan_id': recovery_plan_id,
|
||||
'recovery_attempt_id': recovery_attempt_id,
|
||||
'resume_after_gate': resume_after_gate,
|
||||
},
|
||||
},
|
||||
)
|
||||
job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=operator_id)
|
||||
log_task_event(locked_task, 'auto_progress_gate_attempt_queued', {
|
||||
'job_id': job_id,
|
||||
'attempt_id': int(attempt.id),
|
||||
'attempt_no': int(attempt.attempt_no),
|
||||
'execution_id': int(execution.id),
|
||||
'candidate_set_id': candidate_set_id,
|
||||
'gate_id': int(gate.id),
|
||||
'gate_code': gate.gate_code,
|
||||
'trigger': trigger,
|
||||
}, actor_id=operator_id, source=trigger)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued',
|
||||
'job_id': int(job_id),
|
||||
'attempt_id': int(attempt.id),
|
||||
'execution_id': int(execution.id),
|
||||
'gate_code': gate.gate_code,
|
||||
'reused': bool(attempt.status != 'queued'),
|
||||
}
|
||||
result = {
|
||||
'status': 'waiting_human' if execution.status == 'blocked' else execution.status,
|
||||
'execution_id': int(execution.id),
|
||||
'gate_code': current_gate,
|
||||
'reused': True,
|
||||
}
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {'status': 'waiting_human', 'reason_code': inconsistency, 'execution_id': execution.id}
|
||||
if gate is None:
|
||||
return result
|
||||
# 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现
|
||||
# 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。
|
||||
if not _is_formal_process_execution(execution):
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {'status': 'waiting_human' if execution.status == 'blocked' else 'completed', 'execution_id': execution.id}
|
||||
business_ref = f'auto-progress:{int(locked_task.id)}'
|
||||
token = uuid.uuid4().hex
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_AUTO_PROGRESS,
|
||||
{'task_no': locked_task.task_no, 'task_id': int(locked_task.id), 'execution_id': int(execution.id),
|
||||
'candidate_set_id': candidate_set_id, 'gate_id': int(gate.id), 'gate_code': gate.gate_code,
|
||||
'trigger': trigger, 'requested_resume_gate_code': resume_gate_code, 'fencing_token': token},
|
||||
domain='shipping_notice', business_ref=business_ref, created_by_id=operator_id,
|
||||
message=f'等待执行正式 Gate:{gate.gate_code}', max_attempts=1, commit=False,
|
||||
task_id=int(locked_task.id), execution_id=int(execution.id), gate_id=int(gate.id),
|
||||
candidate_set_id=candidate_set_id, fencing_token=token,
|
||||
)
|
||||
execution.current_gate_code = gate.gate_code
|
||||
log_task_event(locked_task, 'auto_progress_job_queued', {
|
||||
'job_id': job_id, 'execution_id': execution.id, 'candidate_set_id': candidate_set_id,
|
||||
'gate_id': gate.id, 'gate_code': gate.gate_code, 'trigger': trigger,
|
||||
}, actor_id=operator_id, source=trigger)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {'status': 'queued', 'job_id': int(job_id), 'execution_id': int(execution.id), 'gate_code': gate.gate_code}
|
||||
|
||||
|
||||
def _gate_outcome(task: ShippingNotice, gate: ShippingProcessGate) -> tuple[str, str | None, dict[str, Any]]:
|
||||
"""仅执行一个 Gate 并把现有业务服务结果归一为正式 Gate 结果。"""
|
||||
code = gate.gate_code
|
||||
candidate = get_active_candidate_set(task)
|
||||
if code == 'inventory_candidates_calculated':
|
||||
return ('passed', None, {}) if candidate is not None else ('blocked_manual', 'inventory_candidates_required', {})
|
||||
if code == 'inventory_candidates_frozen':
|
||||
frozen = candidate is not None and str(candidate.lifecycle_status) == 'frozen'
|
||||
return ('passed', None, {}) if frozen else ('blocked_manual', 'inventory_candidates_frozen_required', {})
|
||||
if code == 'inventory_snapshots_ready':
|
||||
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
|
||||
result = ensure_all_required_sources_prepared(task, mode='auto')
|
||||
if result.all_prepared:
|
||||
return 'passed', None, {'prepared_sources': result.prepared_source_codes}
|
||||
if result.failed_source_codes:
|
||||
return 'blocked_manual', 'inventory_snapshot_prepare_failed', {'failed_sources': result.failed_source_codes}
|
||||
return 'blocked_retryable', 'inventory_snapshots_pending', {'pending_sources': result.pending_source_codes}
|
||||
if code == 'inventory_matched':
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
result = match_inventory({'task_id': task.task_no, '_orchestrator_internal_dispatch': True})
|
||||
status = str((result or {}).get('status') or '')
|
||||
if status in {'ok', 'completed'}:
|
||||
return 'passed', None, {}
|
||||
return 'blocked_manual' if status == 'needs_human' else 'blocked_retryable', 'inventory_match_not_ready', {'legacy_status': status}
|
||||
if code == 'excel_generated':
|
||||
from app.services.shipping_notice.fulfillment_workflow import generate_excel
|
||||
result = generate_excel({'task_id': task.task_no, '_orchestrator_internal_dispatch': True})
|
||||
if str((result or {}).get('status') or '') == 'ok' and task.export_file_path:
|
||||
return 'passed', None, {'export_file_path': task.export_file_path}
|
||||
return 'blocked_retryable', 'excel_generation_not_ready', {'legacy_status': (result or {}).get('status')}
|
||||
receipt = getattr(task, 'upload_receipt_json', None)
|
||||
if receipt or str(getattr(task, 'process_status', '') or '').lower() in {'uploaded', 'completed'}:
|
||||
return 'passed', None, {}
|
||||
return 'blocked_manual', 'manual_upload_receipt_required', {}
|
||||
return {
|
||||
'status': 'legacy_readonly',
|
||||
'reason_code': 'shipping_apx_runtime_disabled',
|
||||
'execution_id': int(execution.id),
|
||||
}
|
||||
|
||||
|
||||
def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
Worker 执行一个且仅一个 Gate,并以 Job outbox 原子提交 Gate 成功和下一个 Job。
|
||||
将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。
|
||||
|
||||
所有围栏、Task 取消和 Candidate/Execution identity 都在外部调用前复查;不匹配的迟到 Job 只终态审计。
|
||||
APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job,
|
||||
但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。
|
||||
"""
|
||||
job = Job.query.filter_by(id=int(job_id)).with_for_update().first()
|
||||
if job is None or job.status != 'running':
|
||||
return {'status': 'noop'}
|
||||
payload = dict(job.payload_json or {})
|
||||
task = ShippingNotice.query.filter_by(id=int(job.task_id or 0)).with_for_update().first()
|
||||
execution = ShippingProcessExecution.query.filter_by(id=int(job.execution_id or 0)).with_for_update().first()
|
||||
now = _utc_now()
|
||||
gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first()
|
||||
stale = (
|
||||
task is None or execution is None or gate is None or _task_is_cancelled(task)
|
||||
or int(getattr(task, 'active_process_execution_id', 0) or 0) != int(execution.id)
|
||||
or int(getattr(execution, 'candidate_set_id', 0) or 0) != int(job.candidate_set_id or 0)
|
||||
or int(gate.execution_id) != int(execution.id)
|
||||
or str(job.fencing_token or '') != str(payload.get('fencing_token') or '')
|
||||
)
|
||||
if stale:
|
||||
job.status = 'cancelled'; job.finished_at = _utc_now(); job.message = '任务已取消或版本围栏不匹配'
|
||||
if gate is not None and gate.status in {'pending', 'queued', 'running'}:
|
||||
gate.status = 'cancelled'
|
||||
db.session.commit()
|
||||
return {'status': 'cancelled'}
|
||||
runnable, inconsistency = _earliest_runnable_gate(execution)
|
||||
if inconsistency or runnable is None or int(runnable.id) != int(gate.id):
|
||||
gate.status = 'blocked_manual'; gate.blocking_reason_code = inconsistency or 'projection_data_inconsistent'
|
||||
execution.status = 'blocked'; job.status = 'success'; job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return {'status': 'waiting_human', 'reason_code': gate.blocking_reason_code}
|
||||
|
||||
gate.status = 'running'; gate.updated_at = _utc_now(); db.session.flush()
|
||||
outcome, reason_code, details = _gate_outcome(task, gate)
|
||||
gate.status = outcome; gate.blocking_reason_code = reason_code; gate.effective_result_json = details
|
||||
gate.updated_at = _utc_now(); job.status = 'success'; job.finished_at = _utc_now(); job.message = f'Gate {outcome}'
|
||||
if outcome != 'passed':
|
||||
execution.status = 'blocked'; execution.current_gate_code = gate.gate_code
|
||||
log_task_event(task, 'auto_progress_gate_blocked', {'gate_code': gate.gate_code, 'reason_code': reason_code}, source='worker')
|
||||
db.session.commit()
|
||||
return {'status': outcome, 'gate_code': gate.gate_code, 'reason_code': reason_code}
|
||||
|
||||
gate.passed_at = _utc_now(); execution.last_passed_gate_code = gate.gate_code
|
||||
# 先 flush 当前 Job 成功态,释放 Task 级 active partial unique;后继 Job 与 Gate passed
|
||||
# 仍处在同一外层事务,commit 前对 Worker 不可见。
|
||||
db.session.flush()
|
||||
next_gate, consistency_error = _earliest_runnable_gate(execution)
|
||||
if consistency_error:
|
||||
execution.status = 'blocked'; execution.current_gate_code = None
|
||||
elif next_gate is None:
|
||||
execution.status = 'completed'; execution.current_gate_code = None
|
||||
elif next_gate.gate_code == 'upload_receipt_recorded':
|
||||
# 上传自动化关闭时,Excel 后明确等人工登记回执,不擅自跨越此 Gate。
|
||||
execution.status = 'blocked'; execution.current_gate_code = next_gate.gate_code
|
||||
next_gate.status = 'blocked_manual'; next_gate.blocking_reason_code = 'manual_upload_receipt_required'
|
||||
else:
|
||||
execution.status = 'active'; execution.current_gate_code = next_gate.gate_code
|
||||
submit_auto_progress(task=task, trigger='gate_passed', commit=False)
|
||||
log_task_event(task, 'auto_progress_gate_passed', {'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code}, source='worker')
|
||||
job.status = 'cancelled'
|
||||
job.finished_at = now
|
||||
job.message = 'APX historical auto-progress runtime disabled'
|
||||
if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}:
|
||||
gate.status = 'cancelled'
|
||||
gate.updated_at = now
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'passed', 'execution_id': int(execution.id),
|
||||
'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code,
|
||||
'status': 'legacy_readonly',
|
||||
'reason_code': 'shipping_apx_runtime_disabled',
|
||||
'execution_id': int(job.execution_id) if job.execution_id else None,
|
||||
}
|
||||
@@ -163,11 +163,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
):
|
||||
# A pending task already has an explicit RPA attempt. Poll its timeout
|
||||
# state through the RPA workflow; normal auto-progress must not start RPA.
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
|
||||
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
result = ensure_inventory_via_rpa(task, mode="auto")
|
||||
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
|
||||
@@ -356,10 +356,10 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
|
||||
# This is a poll of an existing request, never an implicit new RPA run.
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
# 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
result = ensure_inventory_via_rpa(task, mode="auto")
|
||||
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
|
||||
@@ -48,6 +48,34 @@ _FORCE_RETRYABLE_BLOCKING_CODES = frozenset({
|
||||
'SHIPPING.profile_schema_mismatch',
|
||||
})
|
||||
|
||||
# needs_human 并不总是终止态:库存快照/RPA 暂态失败仍可由统一重试决策器
|
||||
# 重新触发库存准备;重复、短缺、冲突等业务裁决原因不得自动放行。
|
||||
_INVENTORY_RETRYABLE_HUMAN_CODES = frozenset({
|
||||
'inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending',
|
||||
'inventory_rpa_failed',
|
||||
'inventory_rpa_exhausted',
|
||||
'inventory_file_missing',
|
||||
'rpa_failed',
|
||||
'trigger_not_claimed_missing',
|
||||
'trigger_not_claimed_timeout',
|
||||
'inventory_trigger_missing',
|
||||
'inventory_trigger_write_failed',
|
||||
# 库存门禁/匹配阻断属于可重新检查的技术中间态;对话级重试不得直接跳过。
|
||||
'inventory_candidates_required',
|
||||
'inventory_candidates_frozen_required',
|
||||
'inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending',
|
||||
'inventory_match_not_ready',
|
||||
'inventory_match_incomplete',
|
||||
})
|
||||
_BUSINESS_HUMAN_CODES = frozenset({
|
||||
'inventory_shortage',
|
||||
'inventory_source_conflict',
|
||||
'inventory_source_candidates_need_human',
|
||||
'duplicate_decision_required',
|
||||
})
|
||||
|
||||
|
||||
def project_conversation_allowed_actions(
|
||||
*,
|
||||
@@ -428,12 +456,75 @@ def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bo
|
||||
if status in {'completed', 'succeeded'}:
|
||||
return 'already_completed'
|
||||
if status == 'needs_human':
|
||||
return 'human_blocking'
|
||||
# 库存准备失败是“需要人工关注但仍可技术重试”的中间态;只有
|
||||
# retryable=true 且原因码在白名单内才允许继续到正式 OT 决策器。
|
||||
reason_candidates = (
|
||||
automation.get('reason_code'),
|
||||
automation.get('blocking_reason_code'),
|
||||
automation.get('error_code'),
|
||||
)
|
||||
reason_codes = {
|
||||
str(item or '').strip().lower()
|
||||
for item in reason_candidates
|
||||
if str(item or '').strip()
|
||||
}
|
||||
if reason_codes & _DUPLICATE_BLOCKING_CODES:
|
||||
return 'human_blocking'
|
||||
if reason_codes & _BUSINESS_HUMAN_CODES:
|
||||
return 'human_blocking'
|
||||
if bool(automation.get('retryable')) and reason_codes & _INVENTORY_RETRYABLE_HUMAN_CODES:
|
||||
return None
|
||||
# 正式 OT 的 needs_human 可能只是上一轮匹配/门禁结果;对话级“重试自动推进”
|
||||
# 的职责是重新读取当前库存事实并重新检查。只有重复订单等明确业务裁决才跳过。
|
||||
return None
|
||||
if not bool(automation.get('retryable')):
|
||||
return 'not_retryable'
|
||||
return None
|
||||
|
||||
|
||||
def _formal_task_has_retryable_inventory_trigger_failure(task_no: str) -> bool:
|
||||
"""读取正式 OT 最新逐源 Attempt,识别 Trigger 缺失等可强制重发的技术失败。"""
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
|
||||
if task is None:
|
||||
return False
|
||||
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
technical_codes = {
|
||||
'trigger_not_claimed_missing',
|
||||
'trigger_not_claimed_timeout',
|
||||
'inventory_trigger_missing',
|
||||
'inventory_trigger_write_failed',
|
||||
}
|
||||
return any(
|
||||
str((item or {}).get('error_code') or '').strip().lower() in technical_codes
|
||||
and str((item or {}).get('status') or '').strip().lower() in {'failed', 'exhausted'}
|
||||
for item in (summary.get('latest_attempts') or {}).values()
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('inventory trigger failure lookup failed task_no=%s', task_no)
|
||||
return False
|
||||
|
||||
|
||||
def _formal_task_has_active_attempt(task_no: str) -> bool:
|
||||
"""按正式 Attempt + Job 双重事实判断任务是否真的仍在执行。"""
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
|
||||
if task is None:
|
||||
return False
|
||||
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
return int(summary.get('active_attempt_count') or 0) > 0
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('active attempt lookup failed task_no=%s', task_no)
|
||||
# 状态无法确认时 fail-closed,禁止重复执行。
|
||||
return True
|
||||
|
||||
|
||||
def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
对单个 Case 执行重试或跳过。
|
||||
@@ -476,6 +567,17 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str,
|
||||
|
||||
if task_no:
|
||||
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
|
||||
# Automation 是展示投影,可能滞后于正式 Job。只有 Attempt 与 Job 都仍活动时
|
||||
# 才能返回 already_running;Job 已失败的 queued Attempt 是待恢复残留。
|
||||
if skip == 'already_running' and not _formal_task_has_active_attempt(task_no):
|
||||
skip = None
|
||||
# Trigger 缺失/未领取是库存 RPA 的正式技术失败事实;不得被
|
||||
# automation 投影中的历史 completed/not_retryable/human_blocking 覆盖。
|
||||
# 只要当前没有 queued/running Attempt,就必须重新进入 retry_rpa。
|
||||
if skip not in {None, 'already_running', 'task_missing'} and _formal_task_has_retryable_inventory_trigger_failure(task_no):
|
||||
# Automation 可能仍被历史 Job 的错误码污染;逐源 Attempt 是库存 Trigger
|
||||
# 的正式事实,技术领取失败必须重新进入 retry_rpa,而不是继续 skipped。
|
||||
skip = None
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
@@ -821,7 +923,9 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
# 对话级重试已实际重新检查;门禁仍阻断时应归为失败/需处理,
|
||||
# 不能计入“已跳过”,否则用户无法区分未执行与执行后被阻断。
|
||||
'outcome': 'failed',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
@@ -873,13 +977,15 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
|
||||
|
||||
def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""汇总逐对象结果。"""
|
||||
retried = skipped = failed = 0
|
||||
retried = skipped = failed = blocked = 0
|
||||
for item in items:
|
||||
outcome = str(item.get('outcome') or '').strip().lower()
|
||||
if outcome == 'queued':
|
||||
retried += 1
|
||||
elif outcome == 'failed':
|
||||
failed += 1
|
||||
elif outcome == 'blocked':
|
||||
blocked += 1
|
||||
else:
|
||||
skipped += 1
|
||||
return {
|
||||
@@ -887,4 +993,5 @@ def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
'retried': retried,
|
||||
'skipped': skipped,
|
||||
'failed': failed,
|
||||
'blocked': blocked,
|
||||
}
|
||||
@@ -24,9 +24,8 @@ from app.services.shipping_notice.constants import (
|
||||
RS_PARSE_REVIEW,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
adjudicate_and_apply_inventory_source,
|
||||
@@ -68,6 +67,13 @@ def _reset_inventory_state_for_forced_rpa(task) -> None:
|
||||
task.freight_ref_no = None
|
||||
task.upload_status = None
|
||||
task.upload_mode = None
|
||||
|
||||
|
||||
def _request_formal_gate_action(**kwargs):
|
||||
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。"""
|
||||
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
|
||||
|
||||
return _request(**kwargs)
|
||||
task.upload_error_message = None
|
||||
task.upload_receipt_json = None
|
||||
task.review_status = None
|
||||
@@ -94,8 +100,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
|
||||
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
|
||||
|
||||
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;
|
||||
rematch 会同步调用 match_inventory 完成重算;工作台入口须注入 operator_id 以保证审计非匿名。
|
||||
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate
|
||||
Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。
|
||||
Args:
|
||||
payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。
|
||||
|
||||
@@ -431,12 +437,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
after=task_lifecycle_audit_snapshot(task),
|
||||
)
|
||||
db.session.flush()
|
||||
retry_payload = merge_tool_payload(
|
||||
task,
|
||||
payload,
|
||||
extra={"mode": "retry_rpa", "manual_retry_round": True},
|
||||
return _request_formal_gate_action(
|
||||
task=task,
|
||||
action_code='retry_inventory_preparation',
|
||||
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
|
||||
idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'),
|
||||
trigger=event_source,
|
||||
)
|
||||
return ensure_inventory(retry_payload)
|
||||
|
||||
if decision == "rematch":
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
@@ -453,16 +460,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
before=before_snapshot,
|
||||
after=task_lifecycle_audit_snapshot(task),
|
||||
)
|
||||
# flush 即可:清状态与 match_inventory 的最终 commit 同属一次连续写入,避免中间态落库。
|
||||
# flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。
|
||||
db.session.flush()
|
||||
# [STEP 3.1] 重新匹配须同步完成库存计算,避免退回 ready_to_match 后再让用户点 match_inventory。
|
||||
match_result = match_inventory(merge_tool_payload(task, payload))
|
||||
if match_result.get("status") != "failed":
|
||||
match_result = prepend_tool_message(
|
||||
match_result,
|
||||
t("workflow.decision.rematch_done", lang=lang),
|
||||
)
|
||||
return match_result
|
||||
return _request_formal_gate_action(
|
||||
task=task,
|
||||
action_code='retry_inventory_from_matching',
|
||||
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
|
||||
idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'),
|
||||
trigger=event_source,
|
||||
)
|
||||
|
||||
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
|
||||
if decision == "reparse":
|
||||
|
||||
@@ -410,6 +410,37 @@ def _meta(party: str, action: str, message_zh: str) -> dict[str, str]:
|
||||
# next_action 必须属于 PROCESS_GATE_ACTION_CODES,或为空串表示无可执行动作。
|
||||
EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
UNKNOWN_BUSINESS_FAILURE_REASON_CODE: _meta('system', '', '业务处理失败,请凭请求编号联系管理员'),
|
||||
# Gate 契约中未进入分层集合的订单资格 / XFA 诊断码;必须仍有稳定用户文案与下一步。
|
||||
'budget_stopped': _meta('owner', 'open_order_review', '订单识别预算已用尽,请检查文档后进入复核'),
|
||||
'business_scenario_not_configured': _meta('admin', 'open_order_review', '业务场景尚未配置,请联系管理员配置后重试'),
|
||||
'business_scenario_out_of_scope': _meta('owner', 'open_order_review', '当前业务场景不在系统支持范围内,请进入复核'),
|
||||
'business_scenario_unmatched': _meta('owner', 'open_order_review', '未识别出适用的业务场景,请进入复核确认'),
|
||||
'customer_confirmation_required': _meta('owner', 'confirm_customer', '客户身份需要确认'),
|
||||
'customer_scope_not_configured': _meta('admin', 'open_order_review', '客户业务范围尚未配置,请联系管理员'),
|
||||
'customer_scope_out_of_scope': _meta('owner', 'open_order_review', '客户不在当前业务范围内,请进入复核处理'),
|
||||
'customer_scope_unmatched': _meta('owner', 'confirm_customer', '未能匹配到当前订单对应的客户'),
|
||||
'extraction_emergency_stop': _meta('owner', 'retry_order_extraction', '订单识别已被安全策略停止,请检查文档后重试'),
|
||||
'generic_auto_freeze_disabled': _meta('admin', 'open_order_review', '通用自动建单未启用,请联系管理员'),
|
||||
'lease_conflict': _meta('system', 'recheck_freeze_readiness', '当前任务正在被其他执行占用,请稍后刷新'),
|
||||
'llm_path_cannot_auto_freeze': _meta('owner', 'open_order_review', '智能识别结果尚未通过自动建单资格检查'),
|
||||
'multiple_customers_detected': _meta('owner', 'confirm_customer', '检测到多个候选客户,请确认正确客户'),
|
||||
'multiple_profiles_detected': _meta('owner', 'open_profile_review', '检测到多个候选模板,请确认适用模板'),
|
||||
'not_recoverable': _meta('admin', 'open_order_review', '当前失败不可自动恢复,请联系管理员处理'),
|
||||
'pending_orders_present': _meta('owner', 'open_order_review', '仍有订单未完成处理,请先完成订单复核'),
|
||||
'profile_auto_freeze_qualification_missing': _meta('owner', 'open_order_review', '订单模板尚未通过自动建单资格检查'),
|
||||
'profile_auto_freeze_suspended': _meta('admin', 'open_order_review', '当前模板自动建单已暂停,请联系管理员'),
|
||||
'profile_manual_confirmation_required': _meta('owner', 'open_profile_review', '订单模板需要人工确认后才能继续'),
|
||||
'run_cancelled': _meta('owner', 'retry_order_extraction', '订单识别已取消,请重新发起处理'),
|
||||
'run_failed': _meta('worker', 'retry_order_extraction', '订单识别运行失败,请重试或进入复核'),
|
||||
'unit_review_required': _meta('owner', 'open_order_review', '存在文档单元需要人工复核'),
|
||||
'version_conflict': _meta('owner', 'open_order_review', '数据版本已变化,请刷新后重新提交'),
|
||||
'xfa_evidence_retention_insufficient': _meta('owner', 'open_order_review', 'XFA 证据留存不足,请进入复核补充证据'),
|
||||
'xfa_mirror_consistency_insufficient': _meta('owner', 'open_order_review', 'XFA 镜像明细一致性不足,请进入复核'),
|
||||
'xfa_profile_checksum_mismatch': _meta('admin', 'open_profile_review', 'XFA 模板校验和不一致,请联系管理员检查模板版本'),
|
||||
'xfa_visual_binding_incomplete': _meta('owner', 'open_profile_review', 'XFA 可视化字段绑定不完整,请补充模板绑定'),
|
||||
'xfa_visual_bindings_required': _meta('owner', 'open_profile_review', 'XFA 尚未完成可视化字段绑定'),
|
||||
'xfa_visual_coverage_insufficient': _meta('owner', 'open_profile_review', 'XFA 可视化字段覆盖不足,请补充模板映射'),
|
||||
'xfa_visual_not_publishable': _meta('admin', 'open_profile_review', 'XFA 可视化模板未达到发布条件,请检查模板质量'),
|
||||
# 附件
|
||||
'attachment_format_unsupported': _meta('owner', 'rematerialize_document', '附件格式不支持'),
|
||||
'attachment_size_exceeded': _meta('owner', 'rematerialize_document', '附件超过系统大小限制'),
|
||||
@@ -570,8 +601,6 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
|
||||
'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'),
|
||||
'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'),
|
||||
'upload_rpa_login_failed': _meta('admin', 'regenerate_manual_upload_todo', '货代平台登录失败'),
|
||||
'upload_platform_rejected': _meta('owner', 'regenerate_manual_upload_todo', '货代平台拒绝本次上传'),
|
||||
'inventory_required_column_missing': _meta('owner', 'confirm_inventory_field_mapping', '库存文件缺少必填列'),
|
||||
'inventory_column_ambiguous': _meta('owner', 'confirm_inventory_field_mapping', '库存列映射存在歧义'),
|
||||
'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'),
|
||||
|
||||
@@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.cell.cell import MergedCell
|
||||
from sqlalchemy import func
|
||||
from app import db
|
||||
from app.models import (
|
||||
@@ -29,6 +30,7 @@ from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderField,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
@@ -59,7 +61,39 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
|
||||
return header, lines
|
||||
|
||||
|
||||
def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None = None) -> Any:
|
||||
def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None:
|
||||
"""生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。"""
|
||||
case = task.shipping_case
|
||||
if case is None or not case.business_no:
|
||||
return None
|
||||
business_no = str(case.business_no).strip()
|
||||
prefix = business_no[:-8] if len(business_no) > 8 else business_no
|
||||
sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else ''
|
||||
if not sequence and case.sequence_value:
|
||||
sequence = f'{int(case.sequence_value):02d}'
|
||||
if not sequence:
|
||||
return None
|
||||
export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date()
|
||||
return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}'
|
||||
|
||||
|
||||
def _clear_template_data_rows(ws: Any, start_row: int) -> None:
|
||||
"""清除模板数据起始行之后的所有单元格值,保留模板表头与样式。"""
|
||||
for row_index in range(start_row, ws.max_row + 1):
|
||||
for column_index in range(1, ws.max_column + 1):
|
||||
cell = ws.cell(row_index, column_index)
|
||||
if not isinstance(cell, MergedCell):
|
||||
cell.value = None
|
||||
|
||||
|
||||
def _system_fact(
|
||||
task: ShippingNotice,
|
||||
key: str,
|
||||
*,
|
||||
export_sequence: int | None = None,
|
||||
excel_business_no: str | None = None,
|
||||
export_date: date | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
读取受控任务事实,模板不能通过任意属性路径访问 ORM。
|
||||
|
||||
@@ -73,10 +107,10 @@ def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None
|
||||
"""
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': task.shipping_case.business_no if task.shipping_case else None,
|
||||
'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None),
|
||||
'warehouse_id': task.inventory_warehouse_id,
|
||||
'inventory_source_code': task.inventory_source_code,
|
||||
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
|
||||
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
|
||||
'export_sequence': export_sequence,
|
||||
}
|
||||
return values.get(key)
|
||||
@@ -110,6 +144,8 @@ def _format_value(value: Any, formatter: str) -> Any:
|
||||
def _mapping_value(
|
||||
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
|
||||
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
|
||||
excel_business_no: str | None = None,
|
||||
export_date: date | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
|
||||
@@ -132,6 +168,16 @@ def _mapping_value(
|
||||
key = mapping['source_key']
|
||||
if kind == 'order_field':
|
||||
value = order_values.get(key)
|
||||
field = db.session.get(ShippingOrderField, key) if key else None
|
||||
field_code = str(field.field_code or '') if field else ''
|
||||
if value in (None, '') and field_code == 'line_no' and export_sequence is not None:
|
||||
value = export_sequence
|
||||
if value in (None, '') and field_code == 'line_amount_with_tax':
|
||||
value = order_values.get('__line_amount')
|
||||
qty = order_values.get('__qty')
|
||||
unit_price = order_values.get('__unit_price')
|
||||
if value in (None, '') and qty not in (None, '') and unit_price not in (None, ''):
|
||||
value = Decimal(str(qty)) * Decimal(str(unit_price))
|
||||
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
|
||||
value = header_values.get(key)
|
||||
elif kind == 'inventory_field':
|
||||
@@ -140,6 +186,8 @@ def _mapping_value(
|
||||
value = _system_fact(
|
||||
task, key,
|
||||
export_sequence=export_sequence if key == 'export_sequence' else None,
|
||||
excel_business_no=excel_business_no,
|
||||
export_date=export_date,
|
||||
)
|
||||
if key == 'export_sequence' and value is None:
|
||||
value = order_values.get('__export_sequence')
|
||||
@@ -174,6 +222,17 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) ->
|
||||
return {str(item.id) for item in rows}
|
||||
|
||||
|
||||
def _inventory_field_user_label(field_id: str) -> str:
|
||||
"""把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。"""
|
||||
normalized = str(field_id or '').strip()
|
||||
if normalized.isdigit():
|
||||
row = ShippingInventoryField.query.filter_by(id=int(normalized)).first()
|
||||
display_name = str(getattr(row, 'display_name', '') or '').strip() if row else ''
|
||||
if display_name:
|
||||
return display_name
|
||||
return f'库存字段(编号 {normalized or "未知"})'
|
||||
|
||||
|
||||
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
|
||||
if not rows:
|
||||
@@ -182,7 +241,8 @@ def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set
|
||||
for field in required_fields:
|
||||
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
|
||||
if len(values) > 1:
|
||||
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
|
||||
label = _inventory_field_user_label(field)
|
||||
raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件')
|
||||
if values:
|
||||
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
|
||||
return resolved
|
||||
@@ -252,7 +312,12 @@ def _safe_filename(name: str) -> str:
|
||||
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
|
||||
|
||||
|
||||
def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
|
||||
def _filename(
|
||||
task: ShippingNotice,
|
||||
template: ShippingExcelTemplate,
|
||||
*,
|
||||
excel_business_no: str | None = None,
|
||||
) -> str:
|
||||
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
|
||||
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
|
||||
if not pattern:
|
||||
@@ -263,7 +328,7 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
|
||||
shipping_case = task.shipping_case
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no,
|
||||
'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no),
|
||||
'source_code': task.inventory_source_code or '',
|
||||
'ts': now,
|
||||
'date': now[:8],
|
||||
@@ -280,14 +345,15 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
|
||||
def _input_checksum(
|
||||
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
|
||||
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
|
||||
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
|
||||
payload = {
|
||||
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
|
||||
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
|
||||
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
|
||||
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
|
||||
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
|
||||
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
@@ -388,6 +454,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
|
||||
excel_business_no = _excel_business_no(task, export_date=export_date)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
reserve_available_for_artifact,
|
||||
@@ -398,10 +466,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
for line, values in zip(snapshot.lines, all_line_values, strict=True):
|
||||
if line.id not in available_line_ids:
|
||||
continue
|
||||
line_values.append(dict(values))
|
||||
row = dict(values)
|
||||
row['__qty'] = line.qty
|
||||
row['__unit_price'] = line.unit_price
|
||||
row['__line_amount'] = line.amount
|
||||
line_values.append(row)
|
||||
for index, row in enumerate(line_values, start=1):
|
||||
row['__export_sequence'] = index
|
||||
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
|
||||
# [STEP 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
inventory_lines = resolve_inventory_lines_for_execution(task)
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
@@ -415,7 +490,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
|
||||
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
|
||||
|
||||
filename = _filename(task, template)
|
||||
filename = _filename(task, template, excel_business_no=excel_business_no)
|
||||
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
|
||||
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
@@ -427,6 +502,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
path.write_bytes(template_bytes)
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
data_start_rows = {
|
||||
str(sheet): min(int(item['start_row']) for item in mappings if item['sheet'] == sheet)
|
||||
for sheet in {str(item['sheet']) for item in mappings}
|
||||
}
|
||||
for sheet, start_row in data_start_rows.items():
|
||||
_clear_template_data_rows(wb[sheet], start_row)
|
||||
for mapping in mappings:
|
||||
ws = wb[mapping['sheet']]
|
||||
start_row = int(mapping['start_row'])
|
||||
@@ -434,11 +515,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
if mapping['row_mode'] == 'header':
|
||||
ws.cell(start_row, column).value = _mapping_value(
|
||||
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
|
||||
excel_business_no=excel_business_no,
|
||||
export_date=export_date,
|
||||
)
|
||||
continue
|
||||
row_count = max(len(line_values), 1)
|
||||
for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1):
|
||||
ws.cell(row_index, column).value = None
|
||||
for index in range(row_count):
|
||||
order_line = line_values[index] if index < len(line_values) else {}
|
||||
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
|
||||
@@ -446,6 +527,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
|
||||
header_values=header_values,
|
||||
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
|
||||
excel_business_no=excel_business_no,
|
||||
export_date=export_date,
|
||||
)
|
||||
wb.save(path)
|
||||
finally:
|
||||
@@ -458,7 +541,9 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
artifact_no=artifact_no, task_id=task.id, template_id=template.id,
|
||||
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
|
||||
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
|
||||
input_checksum=_input_checksum(task, source, template, snapshot, header_values, line_values),
|
||||
input_checksum=_input_checksum(
|
||||
task, source, template, snapshot, header_values, line_values, inventory_lines,
|
||||
),
|
||||
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
|
||||
file_size=len(content), status='ready',
|
||||
)
|
||||
|
||||
@@ -30,7 +30,7 @@ from app.core.errors import ConflictError, ServiceUnavailableError, ValidationEr
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.constants import CP_UPLOADED
|
||||
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
from app.services.shipping_notice.inventory_workflow import (
|
||||
ensure_inventory,
|
||||
parse_inventory_lines,
|
||||
@@ -902,11 +902,9 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str,
|
||||
if extraction_gate is not None:
|
||||
return extraction_gate
|
||||
# [STEP 1] inventory snapshot
|
||||
inventory_lines = parse_inventory_lines(payload)
|
||||
if inventory_lines:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
else:
|
||||
inventory_lines = active_inventory_lines_for_task(task)
|
||||
inventory_lines = resolve_inventory_lines_for_execution(
|
||||
task, legacy_payload_lines=parse_inventory_lines(payload),
|
||||
)
|
||||
if not inventory_lines:
|
||||
# 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义)
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_key': target_key}
|
||||
@@ -1197,6 +1195,49 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
return list(task.line_results_json or [])
|
||||
|
||||
|
||||
def _profile_match_persistence_payload(
|
||||
line_results: list[dict[str, Any]],
|
||||
*,
|
||||
inventory_source_code: str | None,
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
"""
|
||||
将单源 Profile 匹配结果转换为结构化行事实写入载荷。
|
||||
|
||||
核心逻辑:按结果稳定行序补齐 line_index;resolutions 不写临时 line-N,
|
||||
由持久化层使用同一行序关联 Case 草稿的真实 line_key。
|
||||
|
||||
Args:
|
||||
line_results: match_notice_lines 返回的逐行结果。
|
||||
inventory_source_code: 当前正式库存源编码。
|
||||
|
||||
Returns:
|
||||
含 line_results 与 resolutions 的持久化载荷。
|
||||
"""
|
||||
return {
|
||||
'line_results': [
|
||||
{
|
||||
**row,
|
||||
'line_index': index,
|
||||
'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage',
|
||||
}
|
||||
for index, row in enumerate(line_results)
|
||||
],
|
||||
'resolutions': [
|
||||
{
|
||||
'line_index': index,
|
||||
# 让持久化层按 Case 草稿的 line_key(如 machine-1)解析;
|
||||
# 不写入临时 line-N,避免 Review Projection 无法关联事实。
|
||||
'line_key': row.get('line_key'),
|
||||
'part_number': row.get('part_number'),
|
||||
'effective_reservation_id': row.get('reservation_id'),
|
||||
'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage',
|
||||
'resolved_inventory_source_code': inventory_source_code,
|
||||
}
|
||||
for index, row in enumerate(line_results)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。
|
||||
@@ -1280,11 +1321,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return extraction_gate
|
||||
|
||||
# [STEP 1] 正式库存已在载入阶段按 published Profile 校验;这里只确认库存快照是否就绪。
|
||||
inventory_lines = parse_inventory_lines(payload)
|
||||
if inventory_lines:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
else:
|
||||
inventory_lines = active_inventory_lines_for_task(task)
|
||||
inventory_lines = resolve_inventory_lines_for_execution(
|
||||
task, legacy_payload_lines=parse_inventory_lines(payload),
|
||||
)
|
||||
if not inventory_lines:
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no}
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
@@ -1379,7 +1418,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
or purpose_line.get('unit')
|
||||
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom')
|
||||
),
|
||||
'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'),
|
||||
'line_key': (
|
||||
(order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key')
|
||||
or f'line-{index + 1}'
|
||||
),
|
||||
})
|
||||
match_payload = match_order_lines_across_candidates(
|
||||
order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines),
|
||||
@@ -1522,6 +1564,20 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
quantity_field_id=str(quantity_fields[0].id),
|
||||
progress_callback=_on_match_progress,
|
||||
)
|
||||
# 整单匹配与行级匹配必须写入同一结构化事实表;Review Projection 只读取该表。
|
||||
# 仅更新 line_results_json 会导致订单明细继续显示“待确认”。
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
persist_line_inventory_match_facts,
|
||||
)
|
||||
persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload=_profile_match_persistence_payload(
|
||||
line_results,
|
||||
inventory_source_code=task.inventory_source_code,
|
||||
),
|
||||
inventory_snapshot_id=(int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None),
|
||||
matching_rule_version='profile_match_v1',
|
||||
)
|
||||
task.match_status = match_status
|
||||
task.line_results_json = line_results
|
||||
task.shortage_json = shortage
|
||||
@@ -1597,6 +1653,29 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。
|
||||
"""
|
||||
# [T5 Orchestrator 守卫]:外部请求只能提交正式 artifact_generation Gate;
|
||||
# 只有 ProcessGate Executor 才能携带内部标记执行实际 Excel 生成。
|
||||
if not payload.get('_orchestrator_internal_dispatch', False):
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp
|
||||
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
|
||||
if not task_no and isinstance(payload, dict):
|
||||
_task = _rtp(payload)
|
||||
task_no = str(getattr(_task, 'task_no', '') or '').strip()
|
||||
trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_generate_excel').strip()
|
||||
actor_raw = payload.get('operator_id') or payload.get('actor_id') or payload.get('_trusted_user_id')
|
||||
try:
|
||||
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != 'system' else None
|
||||
except (TypeError, ValueError):
|
||||
operator_id = None
|
||||
return run_task_auto_progress(
|
||||
task_no,
|
||||
trigger=trigger,
|
||||
expected_version=None,
|
||||
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
|
||||
resume_gate_code='artifact_generation',
|
||||
operator_id=operator_id,
|
||||
)
|
||||
lang = resolve_lang(payload)
|
||||
actor_id = _event_actor_id(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
|
||||
@@ -257,9 +257,22 @@ def _next_task_set_version(*, task_id: int, session: Session) -> int:
|
||||
return int(current_max or 0) + 1
|
||||
|
||||
|
||||
def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session) -> None:
|
||||
"""重冻结后立即失效旧匹配、导出与待上传事实,避免旧版本继续被消费。"""
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt
|
||||
def _invalidate_task_candidate_outputs(
|
||||
task: ShippingNotice, *, old_candidate_set_id: int | None, session: Session,
|
||||
) -> None:
|
||||
"""重冻结后失效旧候选版本的准备、恢复、匹配、导出与上传事实。
|
||||
|
||||
仅取消旧版本的非终态记录,不删除审计;新 CandidateSet 随后会创建新的
|
||||
正式 Execution/Attempt,因此迟到 RPA 回调无法写回新链。
|
||||
"""
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingProcessRecoveryPlan,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
@@ -291,6 +304,48 @@ def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session
|
||||
)
|
||||
.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')),
|
||||
).all()
|
||||
]
|
||||
if artifact_ids:
|
||||
session.query(ShippingExportArtifact).filter(
|
||||
ShippingExportArtifact.id.in_(artifact_ids),
|
||||
).update({'status': 'superseded'}, synchronize_session=False)
|
||||
session.query(ShippingUploadAttempt).filter(
|
||||
ShippingUploadAttempt.artifact_id.in_(artifact_ids),
|
||||
ShippingUploadAttempt.status.in_(('pending', 'running', 'timed_out', 'unknown')),
|
||||
).update({
|
||||
'status': 'failed',
|
||||
'invalidated_at': datetime.utcnow(),
|
||||
'invalidation_reason': 'candidate_set_refrozen',
|
||||
'finished_at': datetime.utcnow(),
|
||||
'error_code': 'candidate_set_refrozen',
|
||||
}, synchronize_session=False)
|
||||
prep_query = session.query(ShippingInventoryPreparationAttempt).filter(
|
||||
ShippingInventoryPreparationAttempt.task_id == int(task.id),
|
||||
ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')),
|
||||
)
|
||||
if old_candidate_set_id is not None:
|
||||
prep_query = prep_query.filter(
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id)
|
||||
)
|
||||
prep_query.update({'status': 'superseded'}, synchronize_session=False)
|
||||
active_execution_ids = [
|
||||
row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter(
|
||||
ShippingInventoryPreparationAttempt.task_id == int(task.id),
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id,
|
||||
).all() if row[0]
|
||||
]
|
||||
if active_execution_ids:
|
||||
session.query(ShippingProcessRecoveryPlan).filter(
|
||||
ShippingProcessRecoveryPlan.execution_id.in_(active_execution_ids),
|
||||
ShippingProcessRecoveryPlan.status.in_(
|
||||
('planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual')
|
||||
),
|
||||
).update({'status': 'cancelled', 'completed_at': datetime.utcnow()}, synchronize_session=False)
|
||||
|
||||
|
||||
def freeze_candidates_for_task(
|
||||
@@ -524,7 +579,9 @@ def freeze_candidates_for_task(
|
||||
existing_active.lifecycle_status = 'superseded'
|
||||
existing_active.superseded_at = datetime.utcnow()
|
||||
existing_active.superseded_by_set_id = int(new_set.id)
|
||||
_invalidate_task_candidate_outputs(task, session=session)
|
||||
_invalidate_task_candidate_outputs(
|
||||
task, old_candidate_set_id=int(existing_active.id), session=session,
|
||||
)
|
||||
|
||||
if getattr(task, 'id', None) is not None:
|
||||
task.active_inventory_candidate_set_id = int(new_set.id)
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
@@ -472,6 +473,10 @@ def project_inventory_candidate_facts(
|
||||
stale_details: dict[str, Any] | None = None
|
||||
out_of_scope_details: dict[str, Any] | None = None
|
||||
for row in _current_match_rows(task, session=sess):
|
||||
snapshot = (
|
||||
sess.get(ShippingInventoryFile, int(row.inventory_snapshot_id))
|
||||
if getattr(row, 'inventory_snapshot_id', None) is not None else None
|
||||
)
|
||||
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
|
||||
serialized = {
|
||||
'id': int(row.id),
|
||||
@@ -486,6 +491,13 @@ def project_inventory_candidate_facts(
|
||||
'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')),
|
||||
'inventory_file_sha256': (
|
||||
dict(getattr(row, 'detail_json', None) or {}).get('file_sha256')
|
||||
or dict(getattr(row, 'detail_json', None) or {}).get('inventory_file_sha256')
|
||||
or getattr(snapshot, 'file_sha256', None)
|
||||
),
|
||||
'inventory_row_index': getattr(row, 'matched_row_index', None),
|
||||
'match_attempt_id': getattr(row, 'match_attempt_id', None),
|
||||
'required_qty': getattr(row, 'required_qty', None),
|
||||
'matched_qty': getattr(row, 'matched_qty', None) or getattr(row, 'available_qty', None),
|
||||
'match_result': getattr(row, 'match_result', None),
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_combination_fingerprint.py
|
||||
|
||||
用途:为多源库存准备轮次生成稳定组合输入指纹。
|
||||
依赖:标准库 hashlib/json。
|
||||
逻辑:对任务快照、候选冻结、逐源快照/Hash/解析映射版本、Reservation 和匹配规则做规范化哈希。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
def build_inventory_combination_fingerprint(
|
||||
*, task_snapshot_fingerprint: str | None, candidate_freeze_fingerprint: str | None,
|
||||
sources: Iterable[dict[str, Any]], reservation_version: str | None = None,
|
||||
matching_rule_version: str | None = None,
|
||||
) -> str:
|
||||
"""按稳定排序构建组合输入 SHA-256 指纹。"""
|
||||
payload = {
|
||||
'task_snapshot_fingerprint': task_snapshot_fingerprint,
|
||||
'candidate_freeze_fingerprint': candidate_freeze_fingerprint,
|
||||
'sources': sorted(
|
||||
[dict(item) for item in sources],
|
||||
key=lambda item: (str(item.get('source_code') or ''), int(item.get('snapshot_id') or 0)),
|
||||
),
|
||||
'reservation_version': reservation_version,
|
||||
'matching_rule_version': matching_rule_version,
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_file_store.py
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import hashlib
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -90,6 +91,15 @@ def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx")
|
||||
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}"
|
||||
|
||||
|
||||
def _file_sha256(path: Path) -> str:
|
||||
"""计算已落盘库存快照的内容指纹,供复用和组合输入门禁使用。"""
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def inventory_storage_suffix_for_path(path: str | Path) -> str:
|
||||
"""根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。"""
|
||||
suffix = Path(path).suffix.lower()
|
||||
@@ -135,10 +145,46 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil
|
||||
|
||||
|
||||
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
"""解析任务可用于匹配的库存行;批次库存快照优先,单票任务回退到任务投影字段。"""
|
||||
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file and isinstance(inv_file.inventory_lines_json, list):
|
||||
return [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
|
||||
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
|
||||
return rows
|
||||
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
|
||||
|
||||
def resolve_inventory_lines_for_execution(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
legacy_payload_lines: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。
|
||||
|
||||
Args:
|
||||
task: 当前正式发货通知。
|
||||
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)
|
||||
if isinstance(legacy_payload_lines, list):
|
||||
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)]
|
||||
|
||||
|
||||
@@ -213,16 +259,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
|
||||
message='库存文件没有可用于匹配的有效库存数据',
|
||||
http_status=409,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_identity import (
|
||||
assert_inventory_excel_warehouse_identity,
|
||||
)
|
||||
|
||||
if str(warehouse_id or '').strip():
|
||||
assert_inventory_excel_warehouse_identity(
|
||||
path,
|
||||
expected_warehouse_id=str(warehouse_id or ""),
|
||||
operation="manual_upload",
|
||||
)
|
||||
# 手工上传同样只保留文件 Warehouse 事实,不要求其等于页面当前库位编码。
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(upload.filename or path.name)
|
||||
preview['structure_validation'] = column_meta['structure_validation']
|
||||
@@ -250,6 +287,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(upload.filename or "").strip() or path.name,
|
||||
storage_path=str(path),
|
||||
file_sha256=_file_sha256(path),
|
||||
schema_preview_json=preview,
|
||||
share_mode="task_only",
|
||||
line_count=len(inventory_lines),
|
||||
@@ -351,6 +389,7 @@ def save_task_inventory_file_from_local_path(
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
|
||||
storage_path=str(path),
|
||||
file_sha256=_file_sha256(path),
|
||||
schema_preview_json=preview,
|
||||
share_mode="task_only",
|
||||
line_count=0,
|
||||
|
||||
@@ -8,6 +8,7 @@ services/shipping_notice/inventory_mapping.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryField
|
||||
@@ -226,6 +227,14 @@ def resolve_columns_from_field_mapping(
|
||||
"""将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。"""
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
|
||||
# Excel exports may contain line breaks or repeated whitespace in a
|
||||
# visible header (for example ``Qty\nAvailable``). Explicit published
|
||||
# mappings must still resolve deterministically without guessing a field.
|
||||
normalized_to_idx: dict[str, int] = {}
|
||||
for index, header in enumerate(norm_headers):
|
||||
key = re.sub(r"[^a-z0-9]+", "", header.lower())
|
||||
if key and key not in normalized_to_idx:
|
||||
normalized_to_idx[key] = index
|
||||
|
||||
def idx_for(header_name: str | None) -> int | None:
|
||||
if not header_name:
|
||||
@@ -235,7 +244,11 @@ def resolve_columns_from_field_mapping(
|
||||
return None
|
||||
if name in norm_headers:
|
||||
return norm_headers.index(name)
|
||||
return lower_to_idx.get(name.lower())
|
||||
exact_lower = lower_to_idx.get(name.lower())
|
||||
if exact_lower is not None:
|
||||
return exact_lower
|
||||
normalized = re.sub(r"[^a-z0-9]+", "", name.lower())
|
||||
return normalized_to_idx.get(normalized)
|
||||
|
||||
runtime_mapping, _catalog = runtime_field_mapping(field_mapping)
|
||||
if not runtime_mapping:
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_recovery_service.py
|
||||
|
||||
用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。
|
||||
依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。
|
||||
逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
ShippingNotice,
|
||||
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
|
||||
|
||||
|
||||
def create_inventory_preparation_round(
|
||||
*, task: ShippingNotice, 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:
|
||||
"""创建一次任务级准备轮次;同一任务按 attempt_no 递增。"""
|
||||
last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by(
|
||||
ShippingInventoryPreparationAttempt.attempt_no.desc(),
|
||||
).first()
|
||||
round_row = ShippingInventoryPreparationAttempt(
|
||||
task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id,
|
||||
recovery_plan_id=recovery_plan_id,
|
||||
attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued',
|
||||
candidate_set_id=getattr(task, 'active_inventory_candidate_set_id', None),
|
||||
input_snapshot_json={
|
||||
'action_code': action_code,
|
||||
'source_codes': list(source_codes or []),
|
||||
'gate_attempt_id': int(gate_attempt_id) if gate_attempt_id else None,
|
||||
},
|
||||
operation_id=operation_id,
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(round_row)
|
||||
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]
|
||||
active_file = active_inventory_file_for_task(task)
|
||||
for source_code in codes:
|
||||
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
|
||||
snapshot=active_file,
|
||||
source_code=source_code,
|
||||
warehouse_id=getattr(active_file, 'warehouse_id', None) if active_file else None,
|
||||
source_config_version=getattr(active_file, 'source_config_version', None) if active_file else None,
|
||||
expected_file_sha256=getattr(active_file, 'file_sha256', None) if active_file else None,
|
||||
parser_version=getattr(active_file, 'parser_version', None) if active_file else None,
|
||||
mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None,
|
||||
)
|
||||
reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable)
|
||||
link = ShippingTaskInventoryLink.query.filter_by(
|
||||
task_id=int(task.id), matched_source_code=source_code, is_active=True,
|
||||
).order_by(ShippingTaskInventoryLink.id.desc()).first()
|
||||
source = ShippingInventoryPreparationSourceAttempt(
|
||||
preparation_attempt_id=int(round_row.id), source_code=source_code,
|
||||
status='reusable' if reusable else 'queued',
|
||||
inventory_file_id=int(active_file.id) if reusable and active_file else None,
|
||||
task_inventory_link_id=int(link.id) if reusable and link else None,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.flush()
|
||||
round_row.combination_input_fingerprint = build_inventory_combination_fingerprint(
|
||||
task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''),
|
||||
candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''),
|
||||
sources=[
|
||||
{
|
||||
'source_code': str(item.source_code),
|
||||
'snapshot_id': item.inventory_file_id,
|
||||
'snapshot_hash': (
|
||||
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None)
|
||||
if item.inventory_file_id else None
|
||||
),
|
||||
'parser_version': (
|
||||
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None)
|
||||
if item.inventory_file_id else None
|
||||
),
|
||||
'mapping_version': (
|
||||
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None)
|
||||
if item.inventory_file_id else None
|
||||
),
|
||||
}
|
||||
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 ''),
|
||||
)
|
||||
db.session.flush()
|
||||
return round_row
|
||||
|
||||
|
||||
def sync_inventory_preparation_round(
|
||||
*, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any,
|
||||
) -> ShippingInventoryPreparationAttempt:
|
||||
"""将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。"""
|
||||
def _read(name: str, default: Any) -> Any:
|
||||
return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default)
|
||||
|
||||
prepared = {str(code).strip().upper() for code in _read('prepared_source_codes', [])}
|
||||
pending = {str(code).strip().upper() for code in _read('pending_source_codes', [])}
|
||||
failed = {str(code).strip().upper() for code in _read('failed_source_codes', [])}
|
||||
summaries = dict(_read('source_attempts', {}) or {})
|
||||
for source in preparation_attempt.source_attempts:
|
||||
code = str(source.source_code or '').strip().upper()
|
||||
summary = dict(summaries.get(code) or {})
|
||||
if code in prepared:
|
||||
source.status = 'ready' if source.status != 'reusable' else 'reusable'
|
||||
elif code in failed:
|
||||
source.status = 'failed'
|
||||
elif code in pending:
|
||||
source.status = 'waiting'
|
||||
if summary.get('attempt_id'):
|
||||
source.rpa_attempt_id = int(summary['attempt_id'])
|
||||
if failed:
|
||||
preparation_attempt.status = 'failed'
|
||||
elif pending:
|
||||
preparation_attempt.status = 'waiting_external'
|
||||
else:
|
||||
preparation_attempt.status = 'succeeded'
|
||||
preparation_attempt.completed_at = datetime.utcnow()
|
||||
preparation_attempt.output_snapshot_json = {
|
||||
'prepared_source_codes': sorted(prepared),
|
||||
'pending_source_codes': sorted(pending),
|
||||
'failed_source_codes': sorted(failed),
|
||||
}
|
||||
db.session.flush()
|
||||
return preparation_attempt
|
||||
|
||||
|
||||
def sync_preparation_source_from_rpa_attempt(
|
||||
*, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None,
|
||||
) -> None:
|
||||
"""由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。
|
||||
|
||||
SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次,
|
||||
因而不会污染当前 GateAttempt 对应的 PreparationAttempt。
|
||||
"""
|
||||
source = ShippingInventoryPreparationSourceAttempt.query.filter_by(
|
||||
rpa_attempt_id=int(rpa_attempt_id),
|
||||
).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first()
|
||||
if source is None:
|
||||
return
|
||||
status = str(rpa_status or '').strip().lower()
|
||||
if status in {'succeeded', 'consumed'}:
|
||||
source.status = 'ready'
|
||||
if inventory_file_id:
|
||||
source.inventory_file_id = int(inventory_file_id)
|
||||
elif status in {'failed', 'exhausted'}:
|
||||
source.status = 'failed'
|
||||
elif status in {'queued', 'running'}:
|
||||
source.status = 'waiting'
|
||||
preparation = source.preparation_attempt
|
||||
rows = list(getattr(preparation, 'source_attempts', []) or [])
|
||||
if any(row.status == 'failed' for row in rows):
|
||||
preparation.status = 'failed'
|
||||
elif any(row.status in {'queued', 'running', 'waiting'} for row in rows):
|
||||
preparation.status = 'waiting_external'
|
||||
elif rows and all(row.status in {'ready', 'reusable', 'skipped'} for row in rows):
|
||||
preparation.status = 'succeeded'
|
||||
preparation.completed_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
@@ -180,7 +180,6 @@ def _try_reuse_inventory_snapshot(
|
||||
row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)
|
||||
]
|
||||
if cached_lines:
|
||||
task.inventory_lines_json = cached_lines
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
cached_lines,
|
||||
@@ -639,7 +638,14 @@ def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice:
|
||||
"""对任务行加悲观锁,防止并发回调重复消费同一轮次。"""
|
||||
if task.id is None:
|
||||
return task
|
||||
return db.session.query(ShippingNotice).filter_by(id=task.id).with_for_update().one()
|
||||
# ShippingNotice 默认关系加载会带 shipping_case 外连接;PostgreSQL 不允许
|
||||
# 对外连接空值端执行 FOR UPDATE。回调只需锁任务主表,避免成功文件回调在入库前失败。
|
||||
return (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(id=task.id)
|
||||
.with_for_update(of=ShippingNotice)
|
||||
.one()
|
||||
)
|
||||
|
||||
|
||||
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
|
||||
@@ -671,6 +677,23 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
|
||||
"""
|
||||
run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or ""))
|
||||
if run_no_error:
|
||||
# 逐源 batch Trigger 的任务事件可能仍保留旧的 task-level batch_run_no;
|
||||
# source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt
|
||||
# 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。
|
||||
source_run_no = str(payload.get('source_run_no') or '').strip()
|
||||
if source_run_no:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
current_attempt = (
|
||||
db.session.query(ShippingTaskInventoryRpaAttempt)
|
||||
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}:
|
||||
run_no_error = None
|
||||
if not run_no_error:
|
||||
return None
|
||||
log_task_event(
|
||||
task,
|
||||
"rpa_callback_rejected",
|
||||
@@ -812,6 +835,40 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
|
||||
return None
|
||||
|
||||
|
||||
def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""强制单源库存成功回调携带 v2 身份围栏,禁止旧 payload 写入库存事实。
|
||||
|
||||
单源 Worker 与批量 Worker 共用 ``shipping_inventory_rpa.v2``;缺少任一
|
||||
Attempt/Execution 身份时直接拒绝,避免回调按 Task 级旧 run_no 错绑轮次。
|
||||
"""
|
||||
if str(payload.get('status') or '').strip().lower() != 'success':
|
||||
return None
|
||||
required = {
|
||||
'schema_version': payload.get('schema_version'),
|
||||
'callback_id': payload.get('callback_id'),
|
||||
'source_run_no': payload.get('source_run_no'),
|
||||
'source_code': payload.get('source_code'),
|
||||
'attempt_no': payload.get('attempt_no'),
|
||||
'lease_token': payload.get('lease_token'),
|
||||
'candidate_set_id': payload.get('candidate_set_id'),
|
||||
'execution_id': payload.get('execution_id'),
|
||||
'gate_id': payload.get('gate_id'),
|
||||
}
|
||||
missing = [key for key, value in required.items() if value in (None, '')]
|
||||
if required['schema_version'] != 'shipping_inventory_rpa.v2' or missing:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='单源 RPA 回调缺少完整 v2 身份字段,已拒绝处理',
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'reason_code': 'callback_schema_invalid',
|
||||
'missing_fields': missing,
|
||||
},
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
合并 batch 顶层契约字段到 result item。
|
||||
@@ -1180,6 +1237,36 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
|
||||
rpa_source = task_rpa_inventory_source(task) or {}
|
||||
|
||||
# retry_rpa 使用逐源 Attempt 编排,确保 Trigger 携带 source_run_no/lease_token,
|
||||
# Worker 回调后可以精确绑定到本次 Attempt;自动模式继续使用下方旧兼容路径。
|
||||
if manual_retry_round:
|
||||
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
|
||||
|
||||
prepared = ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
db.session.flush()
|
||||
if prepared.pending_source_codes:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='running', task_id=task.task_no,
|
||||
message='已重新触发库存获取,等待各库存源回调。',
|
||||
data={**serialize_task_for_tool(task), 'rpa': {
|
||||
'pending_source_codes': prepared.pending_source_codes,
|
||||
'source_attempts': prepared.source_attempts,
|
||||
}},
|
||||
)
|
||||
if prepared.all_prepared:
|
||||
return tool_response(status='completed', task=task, message='库存快照已准备完成。')
|
||||
return tool_response(
|
||||
status='needs_human', task=task,
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
data={**serialize_task_for_tool(task), 'rpa': {
|
||||
'failed_source_codes': prepared.failed_source_codes,
|
||||
'source_attempts': prepared.source_attempts,
|
||||
}},
|
||||
)
|
||||
|
||||
# [STEP 0.5] 未过期库存快照优先复用;retry_rpa 强制跳过。
|
||||
reused = _try_reuse_inventory_snapshot(task, rpa_source, mode=mode)
|
||||
if reused is not None:
|
||||
@@ -1570,14 +1657,24 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
# 单源成功回调必须先通过 v2 身份校验;批量回调走独立 v2 envelope。
|
||||
# 失败/跳过回调仍由后续业务错误合同处理,不以缺失文件身份掩盖原始失败。
|
||||
if not isinstance(payload.get('results'), list):
|
||||
contract_resp = _validate_single_source_v2_contract(task, payload)
|
||||
if contract_resp is not None:
|
||||
return contract_resp
|
||||
|
||||
# [T7 统一回调幂等] 尝试按 per-source run_no 提取 source_code;如符合 PSR-*-<SOURCE>-A<N>-* 格式则先入 per_source_callback_handler
|
||||
run_no_raw = str(payload.get("run_no") or "").strip()
|
||||
source_code_from_run: str | None = None
|
||||
if run_no_raw and run_no_raw.startswith('PSR-'):
|
||||
# PSR-<task>-<SOURCE>-A<N>-<uuid8> → 第 3 段 = SOURCE
|
||||
parts = run_no_raw.split('-')
|
||||
if len(parts) >= 4 and parts[3].startswith('A'):
|
||||
candidate = str(parts[2] or '').strip().upper()
|
||||
# PSR-<task_no>-<SOURCE>-A<N>-<uuid8>;task_no 本身可含连字符,
|
||||
# 因此必须从末尾的 source/attempt 结构反向解析,不能使用固定 split 下标。
|
||||
import re
|
||||
|
||||
match = re.match(r'^PSR-(?P<task>.+)-(?P<source>[^-]+)-A\d+-[^-]+$', run_no_raw)
|
||||
if match:
|
||||
candidate = str(match.group('source') or '').strip().upper()
|
||||
if candidate:
|
||||
source_code_from_run = candidate
|
||||
per_source_result = None
|
||||
@@ -1601,6 +1698,54 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"idempotent": True,
|
||||
},
|
||||
)
|
||||
if per_source_code == 'callback_conflict':
|
||||
# callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。
|
||||
log_task_event(
|
||||
task,
|
||||
'shipping_inventory_callback_ignored',
|
||||
{
|
||||
'run_no': run_no_raw,
|
||||
'source_code': source_code_from_run,
|
||||
'reason': 'callback_id_already_consumed_by_other_attempt',
|
||||
'callback_id': str(payload.get('callback_id') or '').strip(),
|
||||
},
|
||||
source='rpa_callback',
|
||||
)
|
||||
return tool_response(
|
||||
status='success',
|
||||
task=task,
|
||||
message='RPA 回调已被其他 Attempt 消费,本次回调忽略。',
|
||||
data={
|
||||
'run_no': run_no_raw,
|
||||
'source_code': source_code_from_run,
|
||||
'callback_conflict': True,
|
||||
'retry_safe': False,
|
||||
},
|
||||
)
|
||||
if per_source_code == 'identity_mismatch':
|
||||
# v2 身份围栏未通过时必须在统一入口 fail-closed,禁止回落到 Task 级旧回调路径。
|
||||
log_task_event(
|
||||
task,
|
||||
'rpa_callback_rejected',
|
||||
{
|
||||
'run_no': run_no_raw,
|
||||
'source_code': source_code_from_run,
|
||||
'reason': 'callback_identity_mismatch',
|
||||
'callback_id': str(payload.get('callback_id') or '').strip(),
|
||||
},
|
||||
source='rpa_callback',
|
||||
)
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='RPA 回调身份与当前库存准备轮次不一致,已拒绝处理。',
|
||||
data={
|
||||
'run_no': run_no_raw,
|
||||
'source_code': source_code_from_run,
|
||||
'error_code': 'callback_identity_mismatch',
|
||||
'retry_safe': False,
|
||||
},
|
||||
)
|
||||
if per_source_code == 'superseded_late':
|
||||
log_task_event(
|
||||
task,
|
||||
@@ -1969,7 +2114,12 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
|
||||
task_no = str(merged_item.get("task_no") or "").strip()
|
||||
run_no_item = str(merged_item.get("run_no") or "").strip() or run_no
|
||||
source_run_no_item = str(merged_item.get("source_run_no") or "").strip()
|
||||
# Worker 旧版只回传 run_no;三元组定位 Attempt 时用本批次 run_no 兜底,
|
||||
# 否则成功文件已入库但旧 failed Attempt 永远不会被收敛。
|
||||
source_run_no_item = (
|
||||
str(merged_item.get("source_run_no") or "").strip()
|
||||
or run_no_item
|
||||
)
|
||||
item_callback_id = str(merged_item.get("callback_id") or "").strip()
|
||||
if not item_callback_id and source_run_no_item:
|
||||
item_callback_id = f"{callback_id}:{source_run_no_item}:C1"
|
||||
@@ -1991,7 +2141,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
})
|
||||
continue
|
||||
# [T7 批量回调幂等] 每个 item 先走 per_source_callback_handler;batch 中单独处理不中断整体
|
||||
if source_code and source_run_no_item and raw_status != 'success':
|
||||
if source_code and source_run_no_item:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
per_source_code, _a = per_source_callback_handler(
|
||||
task,
|
||||
@@ -2040,6 +2190,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"retry_safe": True,
|
||||
})
|
||||
continue
|
||||
if per_source_code == 'identity_mismatch':
|
||||
log_task_event(
|
||||
task,
|
||||
'rpa_callback_rejected',
|
||||
{
|
||||
'run_no': run_no_item,
|
||||
'source_code': source_code,
|
||||
'reason': 'callback_identity_mismatch',
|
||||
'callback_id': item_callback_id,
|
||||
'batch': True,
|
||||
},
|
||||
source='rpa_callback',
|
||||
)
|
||||
failed.append({
|
||||
'source_code': source_code,
|
||||
'warehouse_id': warehouse_id,
|
||||
'task_no': task_no,
|
||||
'error_code': 'callback_identity_mismatch',
|
||||
'error': 'RPA callback identity does not match the active preparation attempt.',
|
||||
})
|
||||
continue
|
||||
task = _lock_task_for_rpa_callback(task)
|
||||
|
||||
if task and raw_status in {"skipped", "failed"}:
|
||||
@@ -2120,6 +2291,15 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
continue
|
||||
|
||||
if raw_status == "success":
|
||||
# 定时批量成功项必须显式携带 Warehouse 身份;先做身份校验,
|
||||
# 避免缺 Warehouse 被后续文件路径错误遮蔽。
|
||||
if not warehouse_id:
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"warehouse_id": warehouse_id,
|
||||
"error": "warehouse_id_missing",
|
||||
})
|
||||
continue
|
||||
file_path = str(merged_item.get("file_path") or "").strip()
|
||||
path = Path(file_path).resolve() if file_path else None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
@@ -2237,7 +2417,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
|
||||
if _att:
|
||||
# 成功回调是该 Attempt 的最终事实;清理旧失败态,避免投影继续显示 failed/retry。
|
||||
_att.status = 'succeeded'
|
||||
_att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded'
|
||||
_att.error_code = None; _att.error_message = None; _att.transaction_error_code = None
|
||||
created.append(created_entry)
|
||||
if item_orphan_path:
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
|
||||
@@ -212,6 +212,26 @@ def _normalize_inventory_row(
|
||||
parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip()
|
||||
else:
|
||||
parsed[field_id] = str(value).strip()
|
||||
# 正式运行快照对外统一 canonical 字段;同时保留字段 ID 供审计和旧 Profile 回放。
|
||||
canonical_by_code = {
|
||||
'part_number': 'part_number',
|
||||
'reservation_id': 'reservation_id',
|
||||
'available_qty': 'available_qty',
|
||||
'qty': 'available_qty',
|
||||
'unit': 'uom',
|
||||
'warehouse_id': 'warehouse_id',
|
||||
'warehouse_code': 'warehouse_id',
|
||||
}
|
||||
for field_id, field in catalog.items():
|
||||
target = canonical_by_code.get(str(field.field_code or '').strip())
|
||||
if target and parsed.get(field_id) not in (None, ''):
|
||||
parsed[target] = parsed[field_id]
|
||||
if 'reservation_id' in parsed:
|
||||
parsed['reservation_id'] = validated_reservation_id(parsed['reservation_id'])
|
||||
if 'part_number' in parsed:
|
||||
parsed['part_number'] = str(parsed['part_number'] or '').strip()
|
||||
if 'available_qty' in parsed:
|
||||
parsed['available_qty'] = _parse_qty(parsed['available_qty'])
|
||||
return parsed
|
||||
|
||||
idx_part_number = columns.get("part_number")
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_snapshot_reuse_policy.py
|
||||
|
||||
用途:统一判断库存快照是否可被当前任务复用。
|
||||
依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。
|
||||
逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
|
||||
def check_inventory_snapshot_reusable(
|
||||
*, snapshot: Any, source_code: str, warehouse_id: str | None = None,
|
||||
source_config_version: str | None = None, candidate_input_fingerprint: str | None = None,
|
||||
expected_file_sha256: str | None = None, parser_version: str | None = None,
|
||||
mapping_version: str | None = None, now: datetime | None = None,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""返回 (是否可复用, 不可复用原因列表)。"""
|
||||
reasons: list[str] = []
|
||||
current = now or datetime.utcnow()
|
||||
if snapshot is None:
|
||||
return False, ['snapshot_missing']
|
||||
if str(getattr(snapshot, 'snapshot_status', '') or '').lower() != 'ready':
|
||||
reasons.append('snapshot_not_ready')
|
||||
expires_at = getattr(snapshot, 'expires_at', None)
|
||||
if expires_at is not None and expires_at <= current:
|
||||
reasons.append('snapshot_expired')
|
||||
if str(getattr(snapshot, 'source_code', '') or '').strip().upper() != str(source_code or '').strip().upper():
|
||||
reasons.append('source_code_mismatch')
|
||||
if warehouse_id is not None and str(getattr(snapshot, 'warehouse_id', '') or '').strip().upper() != str(warehouse_id).strip().upper():
|
||||
reasons.append('warehouse_mismatch')
|
||||
if source_config_version is not None and str(getattr(snapshot, 'source_config_version', '') or '') != str(source_config_version):
|
||||
reasons.append('source_config_version_mismatch')
|
||||
if expected_file_sha256 is not None and str(getattr(snapshot, 'file_sha256', '') or '') != str(expected_file_sha256):
|
||||
reasons.append('file_hash_mismatch')
|
||||
if parser_version is not None and str(getattr(snapshot, 'parser_version', '') or '') != str(parser_version):
|
||||
reasons.append('parser_version_mismatch')
|
||||
if mapping_version is not None and str(getattr(snapshot, 'mapping_version', '') or '') != str(mapping_version):
|
||||
reasons.append('mapping_version_mismatch')
|
||||
if candidate_input_fingerprint is not None and str(getattr(snapshot, 'input_fingerprint', '') or '') != str(candidate_input_fingerprint):
|
||||
reasons.append('candidate_input_fingerprint_mismatch')
|
||||
if getattr(snapshot, 'invalidated_at', None) is not None:
|
||||
reasons.append('snapshot_invalidated')
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def is_inventory_snapshot_reusable(**kwargs: Any) -> bool:
|
||||
"""布尔兼容入口;详细原因由 check_inventory_snapshot_reusable 提供。"""
|
||||
return check_inventory_snapshot_reusable(**kwargs)[0]
|
||||
@@ -281,24 +281,21 @@ def create_inventory_snapshot_from_rpa(
|
||||
excel_warehouse_id = ""
|
||||
warehouse_id = export_warehouse_id
|
||||
warehouse_code = warehouse_id
|
||||
# Excel 内部 Warehouse 编码由外部 DSV/货代系统决定,不能假设等于 HXOPS 配置编码。
|
||||
# 快照归属继续使用任务/库存源配置;实际文件编码仅作为可选审计信息保留。
|
||||
excel_verified = False
|
||||
|
||||
if success:
|
||||
local = Path(local_path)
|
||||
expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper()
|
||||
if expected_wh:
|
||||
from app.services.shipping_notice.inventory_file_identity import (
|
||||
assert_inventory_excel_warehouse_identity,
|
||||
)
|
||||
# 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
|
||||
|
||||
excel_warehouse_id = assert_inventory_excel_warehouse_identity(
|
||||
local,
|
||||
expected_warehouse_id=expected_wh,
|
||||
operation="rpa_snapshot",
|
||||
)
|
||||
warehouse_id = expected_wh
|
||||
warehouse_code = warehouse_id
|
||||
excel_verified = True
|
||||
excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local)
|
||||
if len(excel_warehouse_ids) == 1:
|
||||
excel_warehouse_id = next(iter(excel_warehouse_ids))
|
||||
except Exception:
|
||||
excel_warehouse_id = ""
|
||||
path = inventory_file_upload_path(
|
||||
inventory_file_no,
|
||||
suffix=inventory_storage_suffix_for_path(local),
|
||||
|
||||
@@ -47,7 +47,8 @@ INVENTORY_SOURCE_ERROR_CODES = {
|
||||
|
||||
def _inventory_source_config_current(task: ShippingNotice) -> bool:
|
||||
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
# 兼容旧任务/轻量测试桩:缺失版本字段等同于未冻结当前配置。
|
||||
stored = str(getattr(task, 'inventory_source_config_version', None) or "").strip()
|
||||
current = inventory_sources_runtime_version()
|
||||
if not stored:
|
||||
return False
|
||||
|
||||
@@ -129,9 +129,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(
|
||||
res.get('line_key')
|
||||
or keys_by_index.get(index)
|
||||
keys_by_index.get(index)
|
||||
or res.get('line_key')
|
||||
or f'line-{index + 1}'
|
||||
).strip()
|
||||
if not line_key:
|
||||
@@ -202,6 +204,13 @@ def persist_line_inventory_match_facts(
|
||||
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
# Draft line_key 发生过版本切换时,按稳定 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
|
||||
file_no = str(result.get('inventory_file_no') or '')[:128] or None
|
||||
@@ -323,6 +332,9 @@ def persist_line_inventory_match_facts(
|
||||
existing.matching_rule_version = str(matching_rule_version or '')[:64] or None
|
||||
existing.inventory_source_code = src_code
|
||||
existing.is_current = True
|
||||
existing.invalidated_at = None
|
||||
existing.invalidated_by_attempt_id = None
|
||||
existing.invalidation_reason = None
|
||||
existing.matched_at = now
|
||||
existing.updated_at = now
|
||||
existing.candidate_set_id = int(current_candidate_set.id) if current_candidate_set is not None else None
|
||||
@@ -361,6 +373,18 @@ def persist_line_inventory_match_facts(
|
||||
)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
# Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键;
|
||||
# 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。
|
||||
(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.line_index == index,
|
||||
ShippingNoticeLineInventoryMatch.id != int(existing.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
written.append(existing)
|
||||
|
||||
db.session.flush()
|
||||
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
|
||||
|
||||
MATCH_NOT_FOUND = 'not_found'
|
||||
@@ -423,6 +423,10 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str,
|
||||
|
||||
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
|
||||
"""将 ORM 行序列化为投影输入。"""
|
||||
snapshot = (
|
||||
ShippingInventoryFile.query.get(int(row.inventory_snapshot_id))
|
||||
if row.inventory_snapshot_id is not None else None
|
||||
)
|
||||
return {
|
||||
'id': int(row.id),
|
||||
'task_id': int(row.task_id),
|
||||
@@ -442,6 +446,18 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
|
||||
'unit': row.unit,
|
||||
'matching_rule_version': row.matching_rule_version,
|
||||
'inventory_source_code': row.inventory_source_code,
|
||||
'inventory_file_no': getattr(row, 'matched_file_no', None),
|
||||
'inventory_file_sha256': (
|
||||
dict(row.detail_json or {}).get('file_sha256')
|
||||
or dict(row.detail_json or {}).get('inventory_file_sha256')
|
||||
or dict(row.detail_json or {}).get('file_sha256_hex')
|
||||
or getattr(snapshot, 'file_sha256', None)
|
||||
),
|
||||
'inventory_row_index': getattr(row, 'matched_row_index', None),
|
||||
'match_attempt_id': getattr(row, 'match_attempt_id', None),
|
||||
'required_qty': row.required_qty,
|
||||
'matched_qty': getattr(row, 'matched_qty', None) or row.available_qty,
|
||||
'shortage_qty': row.shortage_qty,
|
||||
'matched_at': row.matched_at.isoformat() if row.matched_at else None,
|
||||
'is_current': bool(row.is_current),
|
||||
'detail_json': dict(row.detail_json or {}),
|
||||
@@ -639,6 +655,13 @@ def project_line_inventory_view(
|
||||
'inventory_snapshot_id': fact.get('inventory_snapshot_id'),
|
||||
'inventory_checked_at': fact.get('matched_at'),
|
||||
'inventory_source_code': fact.get('inventory_source_code'),
|
||||
'inventory_file_no': fact.get('inventory_file_no'),
|
||||
'inventory_file_sha256': fact.get('inventory_file_sha256') or fact.get('file_sha256'),
|
||||
'inventory_row_index': fact.get('inventory_row_index') or fact.get('matched_row_index'),
|
||||
'match_attempt_id': fact.get('match_attempt_id'),
|
||||
'required_qty': fact.get('required_qty'),
|
||||
'matched_qty': fact.get('matched_qty') or fact.get('available_qty'),
|
||||
'shortage_qty': fact.get('shortage_qty'),
|
||||
'inventory_source': source,
|
||||
'matching_rule_version': fact.get('matching_rule_version'),
|
||||
'user_line_status': user_status,
|
||||
|
||||
@@ -85,7 +85,14 @@ def freeze_order_snapshot(
|
||||
ValidationError: 当前 Extraction 不完整或核心字段契约不匹配。
|
||||
"""
|
||||
# [STEP 1] 锁定数据库中的 Task,令并发确认串行化;同一 Task 的重复点击复用既有快照。
|
||||
locked_task = ShippingNotice.query.filter_by(id=task.id).with_for_update().one()
|
||||
# query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端
|
||||
# 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。
|
||||
locked_task = (
|
||||
ShippingNotice.query
|
||||
.filter_by(id=task.id)
|
||||
.with_for_update(of=ShippingNotice)
|
||||
.one()
|
||||
)
|
||||
if locked_task.order_snapshot_id:
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, locked_task.order_snapshot_id)
|
||||
if snapshot is not None:
|
||||
|
||||
@@ -536,6 +536,13 @@ def project_review_case_line_decisions(
|
||||
'inventory_snapshot_id': inv_view.get('inventory_snapshot_id'),
|
||||
'inventory_checked_at': inv_view.get('inventory_checked_at'),
|
||||
'inventory_source_code': inv_view.get('inventory_source_code'),
|
||||
'inventory_file_no': inv_view.get('inventory_file_no'),
|
||||
'inventory_file_sha256': inv_view.get('inventory_file_sha256'),
|
||||
'inventory_row_index': inv_view.get('inventory_row_index'),
|
||||
'match_attempt_id': inv_view.get('match_attempt_id'),
|
||||
'required_qty': inv_view.get('required_qty') or required,
|
||||
'matched_qty': inv_view.get('matched_qty') or available,
|
||||
'shortage_qty': inv_view.get('shortage_qty') or shortage,
|
||||
'inventory_source': inv_view.get('inventory_source'),
|
||||
'decision_source': inv_view.get('decision_source'),
|
||||
'retryable': bool(inv_view.get('retryable')),
|
||||
|
||||
@@ -716,6 +716,16 @@ def serialize_review_case(
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
# 正式 OT 的 Execution 可能在 Case 创建后才绑定 task_id;复核页必须沿
|
||||
# case.confirmed_task_id → ShippingNotice → Execution 继续查找,不能退回旧的
|
||||
# process_gate 兜底,否则会丢失当前 Gate 与 RecoveryPlan 按钮。
|
||||
if execution is None and formal_ot.get('task_id') is not None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(formal_ot['task_id']))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is not None:
|
||||
process_gate = apply_post_ot_gate_rules(
|
||||
project_user_gate_summary(execution),
|
||||
|
||||
@@ -448,6 +448,22 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
def _safe_user_error(value: Any) -> str | None:
|
||||
"""用户态只返回稳定错误码,禁止泄漏 ImportError、路径和堆栈。"""
|
||||
raw = str(value or '').strip()
|
||||
if not raw:
|
||||
return None
|
||||
lowered = raw.lower()
|
||||
if (
|
||||
'cannot import name' in lowered
|
||||
or 'traceback' in lowered
|
||||
or '\\app\\' in lowered
|
||||
or '/app/' in lowered
|
||||
or 'site-packages' in lowered
|
||||
):
|
||||
return 'auto_progress_job_failed'
|
||||
return raw[:128]
|
||||
|
||||
def _job_fields(job) -> dict[str, Any]:
|
||||
if job is None:
|
||||
return {
|
||||
@@ -465,7 +481,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
)
|
||||
return {
|
||||
'job_id': int(job.id),
|
||||
'error_code': error_code,
|
||||
'error_code': _safe_user_error(error_code),
|
||||
'attempts': int(job.attempts or 0),
|
||||
'max_attempts': int(job.max_attempts or 0) or None,
|
||||
'completed_at': _iso(getattr(job, 'finished_at', None)),
|
||||
@@ -621,6 +637,11 @@ def project_stage_for_task(
|
||||
'stage_node': None,
|
||||
}
|
||||
|
||||
# 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在
|
||||
# freight_uploading,不能用过期阶段覆盖已经完成的履约状态。
|
||||
if process_status in {'uploaded', 'closed', 'completed'}:
|
||||
return _with_label('completed', source='notice_terminal')
|
||||
|
||||
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
|
||||
order_task = None
|
||||
try:
|
||||
@@ -791,8 +812,12 @@ def apply_post_ot_gate_rules(
|
||||
blocking = None
|
||||
gate_code = ''
|
||||
|
||||
# inventory_preparation(Worker 等待)→ 技术自动,无人工卡。
|
||||
if gate_code in _SYSTEM_WAIT_INVENTORY_GATES:
|
||||
# inventory_preparation 的等待态由 Worker 自动推进;但 blocked_retryable
|
||||
# 是明确的库存文件/RPA失败,必须保留 Gate 动作,不能被清成系统处理中。
|
||||
if (
|
||||
gate_code in _SYSTEM_WAIT_INVENTORY_GATES
|
||||
and raw_gate_status in {'pending', 'queued', 'running', 'waiting_external'}
|
||||
):
|
||||
result['current_blocking_gate'] = None
|
||||
result['blocking_reason_code'] = None
|
||||
result['blocking_message'] = None
|
||||
@@ -811,12 +836,11 @@ def apply_post_ot_gate_rules(
|
||||
result['available_actions'] = []
|
||||
return result
|
||||
|
||||
# 库存/履约域 + human + 有动作 → 保留人工阻断(显式集合优先;前缀仅作必要兼容)。
|
||||
# 所有正式 OT Gate 均由服务端下发动作;页面只负责展示,实际可执行性由
|
||||
# Gate API 按当前 Gate、Attempt、版本和权限逐项校验。不能仅因 Gate 属于
|
||||
# Excel/上传等技术阶段就静默清除用户入口。
|
||||
next_action = str(result.get('next_action_code') or '').strip()
|
||||
in_domain = gate_code in _POST_OT_INVENTORY_FULFILLMENT_GATES or (
|
||||
gate_code.startswith('inventory_') or gate_code.startswith('fulfill')
|
||||
)
|
||||
if in_domain and next_action and not result.get('technical_auto_only'):
|
||||
if next_action and not result.get('technical_auto_only'):
|
||||
result['owner_type'] = 'human'
|
||||
result['technical_auto_only'] = False
|
||||
return result
|
||||
|
||||
@@ -676,7 +676,10 @@ def ensure_stp_auto_create_for_case(
|
||||
'idempotency_key': idempotency_key,
|
||||
'job_status': str(existing.status),
|
||||
'can_auto_create': True,
|
||||
'retry_of_job_id': int(existing.retry_of_job_id) if existing.retry_of_job_id else None,
|
||||
'retry_of_job_id': (
|
||||
int(getattr(existing, 'retry_of_job_id', None))
|
||||
if getattr(existing, 'retry_of_job_id', None) else None
|
||||
),
|
||||
}
|
||||
|
||||
# [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。
|
||||
|
||||
@@ -62,6 +62,47 @@ def _attempt_ref_has_ready_snapshot(
|
||||
return is_snapshot_fresh(inv_file)
|
||||
|
||||
|
||||
def _validate_callback_attempt_identity(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
attempt: ShippingTaskInventoryRpaAttempt,
|
||||
callback_payload: dict[str, Any],
|
||||
) -> bool:
|
||||
"""校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。"""
|
||||
required = ('schema_version', 'callback_id', 'source_run_no', 'attempt_no', 'lease_token',
|
||||
'candidate_set_id', 'execution_id', 'gate_id')
|
||||
if str(callback_payload.get('schema_version') or '') != 'shipping_inventory_rpa.v2':
|
||||
return False
|
||||
if any(callback_payload.get(key) in (None, '') for key in required):
|
||||
return False
|
||||
if str(callback_payload.get('task_no') or '').strip() != str(task.task_no or '').strip():
|
||||
return False
|
||||
if str(callback_payload.get('source_code') or '').strip().upper() != str(attempt.source_code or '').strip().upper():
|
||||
return False
|
||||
if str(callback_payload.get('source_run_no') or '').strip() != str(attempt.source_run_no or '').strip():
|
||||
return False
|
||||
try:
|
||||
if int(callback_payload.get('attempt_no')) != int(attempt.attempt_no):
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
if str(callback_payload.get('lease_token') or '') != str(attempt.lease_token or ''):
|
||||
return False
|
||||
stored = dict(attempt.extra_json or {})
|
||||
for key in ('candidate_set_id', 'execution_id', 'gate_id'):
|
||||
try:
|
||||
if int(callback_payload.get(key)) != int(stored.get(key)):
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
active_candidate = getattr(task, 'active_inventory_candidate_set_id', None)
|
||||
if active_candidate is not None and int(callback_payload.get('candidate_set_id')) != int(active_candidate):
|
||||
return False
|
||||
expected_warehouse = str(stored.get('expected_warehouse_id') or '').strip().upper()
|
||||
callback_warehouse = str(callback_payload.get('expected_warehouse_id') or callback_payload.get('warehouse_id') or '').strip().upper()
|
||||
return not expected_warehouse or callback_warehouse == expected_warehouse
|
||||
|
||||
|
||||
PER_SOURCE_RUN_NO_PREFIX = 'PSR' # Per-Source Run,区别于 legacy T-xxx 全局 run_no
|
||||
|
||||
|
||||
@@ -194,7 +235,21 @@ def _snapshot_ready_for_source(
|
||||
snap = find_latest_ready_snapshot(source_code, warehouse_id)
|
||||
except Exception:
|
||||
snap = None
|
||||
return snap is not None
|
||||
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
source_config_version = None
|
||||
if isinstance(rpa_source, dict):
|
||||
source_config_version = rpa_source.get('source_config_version') or rpa_source.get('config_version')
|
||||
parser_version = rpa_source.get('parser_version') if isinstance(rpa_source, dict) else None
|
||||
mapping_version = rpa_source.get('mapping_version') if isinstance(rpa_source, dict) else None
|
||||
reusable, _ = check_inventory_snapshot_reusable(
|
||||
snapshot=snap,
|
||||
source_code=source_code,
|
||||
warehouse_id=warehouse_id,
|
||||
source_config_version=source_config_version,
|
||||
parser_version=parser_version,
|
||||
mapping_version=mapping_version,
|
||||
)
|
||||
return reusable
|
||||
|
||||
|
||||
def _attempts_summary(
|
||||
@@ -345,8 +400,26 @@ def ensure_all_required_sources_prepared(
|
||||
# trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A<N> 后缀即可。
|
||||
# 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source)
|
||||
execution_id = getattr(task, 'active_process_execution_id', None)
|
||||
gate_id = None
|
||||
if execution_id:
|
||||
execution_row = sess.get(ShippingProcessExecution, int(execution_id))
|
||||
if execution_row is not None and execution_row.current_gate_code:
|
||||
gate_row = sess.query(ShippingProcessGate).filter_by(
|
||||
execution_id=int(execution_row.id),
|
||||
gate_code=str(execution_row.current_gate_code),
|
||||
).first()
|
||||
gate_id = int(gate_row.id) if gate_row is not None else None
|
||||
new_att.extra_json = dict(
|
||||
new_att.extra_json or {},
|
||||
candidate_set_id=getattr(task, 'active_inventory_candidate_set_id', None),
|
||||
execution_id=execution_id,
|
||||
gate_id=gate_id,
|
||||
expected_warehouse_id=rpa_source.get('warehouse_id'),
|
||||
)
|
||||
# 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行
|
||||
per_source_payload = {
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
@@ -355,8 +428,14 @@ def ensure_all_required_sources_prepared(
|
||||
'attempt_no': next_att_no,
|
||||
'source_code': source_code,
|
||||
'source_run_no': new_att.source_run_no,
|
||||
'callback_id': f'{new_att.source_run_no}:C1',
|
||||
'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}',
|
||||
'lease_token': new_att.lease_token,
|
||||
# 回调身份必须与本次冻结版本/正式 Execution 绑定;Worker 只原样回传。
|
||||
'candidate_set_id': getattr(task, 'active_inventory_candidate_set_id', None),
|
||||
'execution_id': execution_id,
|
||||
'gate_id': gate_id,
|
||||
'expected_warehouse_id': rpa_source.get('warehouse_id'),
|
||||
'per_source_attempt': True,
|
||||
}
|
||||
trigger_result = write_inventory_export_trigger_for_task(
|
||||
@@ -425,7 +504,26 @@ def per_source_callback_handler(
|
||||
task_no = str(task.task_no or '').strip()
|
||||
source_code_up = str(source_code or '').strip().upper()
|
||||
|
||||
# [STEP 1] 三元组定位
|
||||
# [STEP 1] callback_id 重放检查。只要回调带有稳定 ID,先于业务身份解析,
|
||||
# 防止同一事件被另一个 Attempt 消费;同 Attempt 重放直接返回幂等结果。
|
||||
callback_id = str((callback_payload or {}).get('callback_id') or '').strip()
|
||||
if callback_id:
|
||||
callback_attempt = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
.filter_by(callback_id=callback_id)
|
||||
.one_or_none()
|
||||
)
|
||||
if callback_attempt is not None:
|
||||
same_attempt = (
|
||||
callback_attempt.task_no == task_no
|
||||
and callback_attempt.source_code == source_code_up
|
||||
and callback_attempt.run_no == str(run_no or '').strip()
|
||||
)
|
||||
if same_attempt:
|
||||
return 'idempotent_ok', callback_attempt
|
||||
return 'callback_conflict', callback_attempt
|
||||
|
||||
# [STEP 2] 三元组定位
|
||||
attempt = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
.filter(
|
||||
@@ -440,11 +538,20 @@ def per_source_callback_handler(
|
||||
if attempt is None:
|
||||
return 'not_found', None
|
||||
|
||||
# [STEP 2] 幂等
|
||||
if not _validate_callback_attempt_identity(
|
||||
task=task,
|
||||
attempt=attempt,
|
||||
callback_payload=dict(callback_payload or {}),
|
||||
):
|
||||
attempt.extra_json = dict(attempt.extra_json or {}, callback_identity_rejected=True)
|
||||
sess.flush([attempt])
|
||||
return 'identity_mismatch', attempt
|
||||
|
||||
# [STEP 3] 幂等
|
||||
if attempt.status in ('succeeded', 'consumed', 'superseded'):
|
||||
return 'idempotent_ok', attempt
|
||||
|
||||
# [STEP 3] 迟到保护:同 (task, source) 有更新 run 已终态
|
||||
# [STEP 4] 迟到保护:同 (task, source) 有更新 run 已终态
|
||||
consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess)
|
||||
# Run no format: PSR-<task>-<SOURCE>-A<N>-<uuid> → 排序按 attempt_no 前缀即可
|
||||
try:
|
||||
@@ -472,7 +579,7 @@ def per_source_callback_handler(
|
||||
sess.flush([attempt])
|
||||
return 'superseded_late', attempt
|
||||
|
||||
# [STEP 4] Task 已终态(兼容旧枚举 active/blocked 等非终态)
|
||||
# [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态)
|
||||
terminal_statuses = {'completed', 'cancelled', 'failed_terminal'}
|
||||
if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses:
|
||||
attempt.status = 'superseded'
|
||||
@@ -483,7 +590,7 @@ def per_source_callback_handler(
|
||||
sess.flush([attempt])
|
||||
return 'task_terminal', attempt
|
||||
|
||||
# [STEP 5] 写回调结果
|
||||
# [STEP 6] 写回调结果
|
||||
attempt.callback_payload_json = dict(callback_payload or {})
|
||||
attempt.callback_received_at = datetime.utcnow()
|
||||
attempt.callback_id = str(callback_payload.get('callback_id') or '').strip() or attempt.callback_id
|
||||
@@ -504,6 +611,8 @@ def per_source_callback_handler(
|
||||
attempt.transaction_status = 'rejected'
|
||||
attempt.error_code = error_code
|
||||
attempt.error_message = error_message[:2000] if error_message else None
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
|
||||
sess.flush([attempt])
|
||||
return 'failed', attempt
|
||||
# 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功)
|
||||
@@ -528,10 +637,18 @@ def per_source_callback_handler(
|
||||
attempt.error_message = (
|
||||
f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000]
|
||||
)
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
|
||||
sess.flush([attempt])
|
||||
return 'failed', attempt
|
||||
attempt.status = 'succeeded'
|
||||
attempt.transaction_status = 'succeeded'
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(
|
||||
rpa_attempt_id=int(attempt.id),
|
||||
rpa_status='succeeded',
|
||||
inventory_file_id=(int(_inv.id) if inventory_file_no and _inv is not None else None),
|
||||
)
|
||||
sess.flush([attempt])
|
||||
# 回调只改变 Attempt/Snapshot 事实;正式 Task Gate 由 AutoProgress Job 重新校验。
|
||||
# 调用方在同一事务提交后,Job 才对 Worker 可见。
|
||||
|
||||
@@ -87,9 +87,12 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
|
||||
return 'inventory_file_identity_mismatch'
|
||||
return 'inventory_rpa_export_failed'
|
||||
|
||||
# [STEP] 空列表=文件无有效行;None/非列表=尚未落库存文件
|
||||
if isinstance(task.inventory_lines_json, list):
|
||||
if len(task.inventory_lines_json) == 0:
|
||||
# [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
|
||||
active_lines = active_inventory_lines_for_task(task)
|
||||
if isinstance(active_lines, list):
|
||||
if len(active_lines) == 0:
|
||||
return 'inventory_file_empty'
|
||||
return 'inventory_preparation_failed'
|
||||
return 'inventory_file_missing'
|
||||
@@ -276,6 +279,10 @@ def apply_gate_outcome(
|
||||
return gate
|
||||
|
||||
key = str(idempotency_key or '').strip() or f'bridge:{execution.execution_no}:{code}:{fingerprint[:16]}'
|
||||
if force and gate is not None:
|
||||
# 强制重评发生在新的 Gate evaluation_version 上;旧版本 Attempt 的成功回放
|
||||
# 不能覆盖当前 invalidated/blocked 状态,否则 Execution 指针会永久停在历史 Gate。
|
||||
key = f'{key}:v{int(gate.evaluation_version)}'
|
||||
return sync_gate_from_business_result(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=code,
|
||||
@@ -728,6 +735,63 @@ def sync_fulfillment_gates_from_task(
|
||||
'task_no': str(task.task_no or '') or None,
|
||||
'has_inventory_lines': has_inventory_lines,
|
||||
}
|
||||
# PreparationAttempt 是库存准备的主事实;仅在当前 Execution/CandidateSet
|
||||
# 存在对应轮次时使用,避免旧任务的孤立轮次污染正式链。
|
||||
preparation = None
|
||||
try:
|
||||
from app.models import ShippingInventoryPreparationAttempt
|
||||
|
||||
prep_query = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
.filter_by(task_id=int(task.id), execution_id=int(execution.id))
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
)
|
||||
if execution.candidate_set_id is not None:
|
||||
prep_query = prep_query.filter(
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id)
|
||||
)
|
||||
preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first()
|
||||
except Exception: # noqa: BLE001
|
||||
preparation = None
|
||||
if preparation is not None:
|
||||
source_rows = list(getattr(preparation, 'source_attempts', []) or [])
|
||||
required = [str(row.source_code or '').strip().upper() for row in source_rows]
|
||||
prepared = [code for code, row in zip(required, source_rows) if row.status in {'ready', 'reusable'}]
|
||||
pending = [code for code, row in zip(required, source_rows) if row.status in {'queued', 'running', 'waiting'}]
|
||||
failed = [code for code, row in zip(required, source_rows) if row.status == 'failed']
|
||||
task_facts.update({
|
||||
'preparation_attempt_id': int(preparation.id),
|
||||
'preparation_attempt_no': int(preparation.attempt_no),
|
||||
'required_sources': required,
|
||||
'prepared_sources': prepared,
|
||||
'pending_sources': pending,
|
||||
'failed_sources': failed,
|
||||
})
|
||||
if preparation.status in {'queued', 'running', 'waiting_external'} or pending:
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=False,
|
||||
outcome='waiting_external', effective_result={'findings': [], **task_facts},
|
||||
blocking_reason_code='inventory_preparation_waiting', actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:waiting', force=True,
|
||||
)
|
||||
return
|
||||
if preparation.status == 'failed' or failed:
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=False,
|
||||
outcome='blocked_retryable', effective_result={'findings': [], **task_facts},
|
||||
blocking_reason_code='inventory_preparation_failed', actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:failed', force=True,
|
||||
)
|
||||
return
|
||||
if preparation.status == 'succeeded' and required and len(prepared) == len(required):
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=True,
|
||||
effective_result=task_facts, actor_type=actor_type, actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:passed', force=True,
|
||||
)
|
||||
# Continue below for mapping/matching facts.
|
||||
if status == 'waiting_inventory':
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING
|
||||
waiting_reason = (
|
||||
@@ -923,6 +987,9 @@ def sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
gate_code='artifact_generation',
|
||||
passed=artifact_ok,
|
||||
# Excel 资格已通过但产物尚未生成属于系统可恢复动作;必须保留
|
||||
# regenerate_excel_artifact,不能落为 blocked_manual 后失去自动推进入口。
|
||||
outcome=None if artifact_ok else 'blocked_retryable',
|
||||
effective_result={
|
||||
'findings': (
|
||||
[] if artifact_ok else _fulfillment_blocking_finding(
|
||||
|
||||
@@ -17,7 +17,17 @@ from typing import Any, Final
|
||||
|
||||
|
||||
# 契约版本;投影、OpenAPI 与 i18n 必须与此对齐。
|
||||
PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v1'
|
||||
PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v2'
|
||||
|
||||
# Gate 实施能力状态:v2 运行时合同必须明确每个 Gate 的当前适配程度。
|
||||
# supported:已有真实执行器或人工业务入口;implemented:库存/履约闭环已实现;
|
||||
# adapter_required / blocked 预留给未来未接线 Gate,禁止前端据此猜测可执行动作。
|
||||
PROCESS_GATE_IMPLEMENTATION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'supported',
|
||||
'implemented',
|
||||
'adapter_required',
|
||||
'blocked',
|
||||
})
|
||||
|
||||
# Finding 严重级别:仅 blocking 可改变 Gate 状态;diagnostic 供管理员诊断。
|
||||
PROCESS_GATE_FINDING_SEVERITIES: Final[frozenset[str]] = frozenset({
|
||||
@@ -75,6 +85,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 1,
|
||||
'label': '文档和附件可用性',
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'rematerialize_document',
|
||||
@@ -86,6 +97,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 2,
|
||||
'label': 'PDF 版面解析',
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_layout_parsing',
|
||||
@@ -97,6 +109,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 3,
|
||||
'label': 'Profile/模板路由',
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'reroute_document_profile',
|
||||
@@ -108,6 +121,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 4,
|
||||
'label': '订单字段抽取',
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_order_extraction',
|
||||
@@ -119,6 +133,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 5,
|
||||
'label': '必填字段完整性',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'edit_order_fields',
|
||||
@@ -129,6 +144,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 6,
|
||||
'label': 'Reservation 格式和证据',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'revalidate_reservation',
|
||||
@@ -140,6 +156,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 7,
|
||||
'label': '客户身份识别',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_customer_resolution',
|
||||
@@ -151,6 +168,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 8,
|
||||
'label': '重复订单/修订判断',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_duplicate_detection',
|
||||
@@ -162,6 +180,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 9,
|
||||
'label': '字段冲突',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'supported',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'resolve_field_conflicts',
|
||||
@@ -172,6 +191,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 10,
|
||||
'label': '库存源路由',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_with_latest_rules',
|
||||
@@ -183,6 +203,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 11,
|
||||
'label': '订单冻结资格',
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_freeze_readiness',
|
||||
@@ -194,6 +215,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 12,
|
||||
'label': 'ShippingNotice 创建',
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_task_creation',
|
||||
@@ -204,6 +226,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 13,
|
||||
'label': '库存文件或快照准备',
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_preparation',
|
||||
@@ -216,6 +239,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 14,
|
||||
'label': '库存字段映射',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_field_mapping',
|
||||
@@ -227,6 +251,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 15,
|
||||
'label': 'Reservation + 料号匹配',
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_matching',
|
||||
@@ -238,6 +263,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 16,
|
||||
'label': '库存满足性',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_inventory_sufficiency',
|
||||
@@ -249,6 +275,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 17,
|
||||
'label': 'Excel 生成资格',
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_excel_readiness',
|
||||
@@ -259,6 +286,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 18,
|
||||
'label': 'Excel Artifact',
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'regenerate_excel_artifact',
|
||||
@@ -269,6 +297,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 19,
|
||||
'label': '货代上传 RPA',
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'waiting_external': 'poll_freight_upload_rpa',
|
||||
@@ -281,6 +310,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'sequence_no': 20,
|
||||
'label': '人工上传交接',
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'regenerate_manual_upload_todo',
|
||||
@@ -322,6 +352,9 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'retry_inventory_field_mapping',
|
||||
'confirm_inventory_field_mapping',
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_from_preparation',
|
||||
'retry_inventory_from_field_mapping',
|
||||
'retry_inventory_from_matching',
|
||||
'open_inventory_match_review',
|
||||
'recheck_inventory_sufficiency',
|
||||
'open_shortage_review',
|
||||
@@ -332,27 +365,43 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'regenerate_manual_upload_todo',
|
||||
})
|
||||
|
||||
# 业务用户可在复核工作台 / Gate 卡片触发的动作(导航或本地 UX)。
|
||||
# 技术重试(Worker/System)不得向业务用户投影为可点击写操作。
|
||||
PROCESS_GATE_BUSINESS_USER_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'open_order_review',
|
||||
'open_profile_review', # 仅导航至复核只读模板区,禁止人工选模板写路径
|
||||
'edit_order_fields',
|
||||
'edit_reservation',
|
||||
'confirm_customer',
|
||||
'retry_customer_resolution',
|
||||
'adjudicate_duplicate',
|
||||
'retry_duplicate_detection',
|
||||
'resolve_field_conflicts',
|
||||
'open_inventory_source_review',
|
||||
'adopt_rule_suggestion',
|
||||
'keep_manual_inventory_decision',
|
||||
'upload_inventory_file',
|
||||
'confirm_inventory_field_mapping',
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'regenerate_manual_upload_todo',
|
||||
})
|
||||
# Gate 卡只展示服务端冻结合同中的动作码。每次点击仍受 Workspace API 的
|
||||
# 当前 Gate 版本、执行归属和写权限校验;前端不自行决定目标节点或重试方式。
|
||||
PROCESS_GATE_BUSINESS_USER_ACTION_CODES: Final[frozenset[str]] = PROCESS_GATE_ACTION_CODES
|
||||
|
||||
# 用户按钮展示合同:动作码仍是唯一执行标识,label_key/kind/dispatch 只描述业务语义。
|
||||
# 任务级与明细行级不得再把所有动作降级为“重试”;前端只渲染本合同。
|
||||
PROCESS_GATE_ACTION_PRESENTATION: Final[dict[str, dict[str, str]]] = {
|
||||
code: {
|
||||
'label_key': f'workspace.shippingNotice.processGate.actionCodes.{code}',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'mutation',
|
||||
}
|
||||
for code in PROCESS_GATE_ACTION_CODES
|
||||
}
|
||||
for _code in {
|
||||
'open_order_review', 'open_profile_review', 'edit_order_fields', 'edit_reservation',
|
||||
'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts',
|
||||
'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review',
|
||||
'upload_inventory_file', 'confirm_inventory_field_mapping',
|
||||
}:
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'navigation'
|
||||
for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}:
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery'
|
||||
for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}:
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'refresh'
|
||||
|
||||
|
||||
def action_presentation(action_code: str | None, *, kind: str | None = None) -> dict[str, str] | None:
|
||||
"""返回用户动作展示元数据;未知动作 fail-closed。"""
|
||||
code = str(action_code or '').strip()
|
||||
item = PROCESS_GATE_ACTION_PRESENTATION.get(code)
|
||||
if item is None:
|
||||
return None
|
||||
payload = {'code': code, **item}
|
||||
if kind:
|
||||
payload['kind'] = kind
|
||||
return payload
|
||||
|
||||
# 技术自动 Gate 的责任方;业务用户投影不得暴露其 POST 重试动作。
|
||||
PROCESS_GATE_TECHNICAL_PARTIES: Final[frozenset[str]] = frozenset({
|
||||
@@ -367,7 +416,7 @@ PROCESS_GATE_BUSINESS_PARTIES: Final[frozenset[str]] = frozenset({
|
||||
|
||||
|
||||
def is_business_user_action(action_code: str | None) -> bool:
|
||||
"""判断动作是否允许向业务用户投影为可处理入口。"""
|
||||
"""判断服务端下发的 Gate 动作是否允许投影为可处理入口。"""
|
||||
code = str(action_code or '').strip()
|
||||
return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES
|
||||
|
||||
@@ -766,6 +815,7 @@ def assert_process_gate_contract_integrity() -> None:
|
||||
assert set(sequences) == set(range(1, len(sequences) + 1)), 'process gate sequence_no must be contiguous'
|
||||
for item in PROCESS_GATE_DEFINITIONS:
|
||||
assert item['responsible_party'] in PROCESS_GATE_RESPONSIBLE_PARTIES
|
||||
assert item.get('implementation_status') in PROCESS_GATE_IMPLEMENTATION_STATUSES
|
||||
actions = item.get('default_next_actions') or {}
|
||||
assert isinstance(actions, dict)
|
||||
for status, action in actions.items():
|
||||
|
||||
@@ -139,6 +139,9 @@ def execute_queued_attempt(
|
||||
snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
|
||||
action = str(snapshot.get('action_code') or gate.next_action_code or '').strip()
|
||||
payload = snapshot.get('payload') if isinstance(snapshot.get('payload'), dict) else {}
|
||||
payload = {**payload, 'action_code': action, 'attempt_id': int(attempt.id)}
|
||||
if attempt.recovery_plan_id:
|
||||
payload.setdefault('recovery_plan_id', int(attempt.recovery_plan_id))
|
||||
|
||||
outcome = _dispatch_action(
|
||||
execution=execution,
|
||||
@@ -185,6 +188,9 @@ def _dispatch_action(
|
||||
'poll_inventory_preparation': _handle_retry_inventory_preparation,
|
||||
'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping,
|
||||
'retry_inventory_matching': _handle_retry_inventory_matching,
|
||||
'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,
|
||||
'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency,
|
||||
'recheck_excel_readiness': _handle_recheck_excel_readiness,
|
||||
'regenerate_excel_artifact': _handle_regenerate_excel,
|
||||
@@ -242,6 +248,9 @@ def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None:
|
||||
for value in (definition.get('default_next_actions') or {}).values()
|
||||
if value
|
||||
}
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
if recovery_plan_for_action(current_gate=gate_code, action_code=action_code) is not None:
|
||||
return
|
||||
if gate_code == 'inventory_source_routing':
|
||||
allowed |= {
|
||||
'adopt_rule_suggestion',
|
||||
@@ -263,6 +272,10 @@ def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None:
|
||||
'confirm_inventory_field_mapping': {'inventory_field_mapping'},
|
||||
'regenerate_manual_upload_todo': {'manual_upload_handoff'},
|
||||
}
|
||||
# 人工交接 Gate 仍允许用户主动重新发起 RPA;AUTO_UPLOAD 开关只控制
|
||||
# 自动链路,不应阻断此显式恢复动作。
|
||||
if action_code == 'retry_freight_upload_rpa' and gate_code == 'manual_upload_handoff':
|
||||
return
|
||||
if action_code in allowed:
|
||||
return
|
||||
if action_code in nav_owning and gate_code in nav_owning[action_code]:
|
||||
@@ -325,7 +338,13 @@ def _manual_open(action: str, owning_gate: str) -> Callable[..., dict[str, Any]]
|
||||
|
||||
|
||||
def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构造履约 workflow 所需 payload。"""
|
||||
"""
|
||||
构造 Gate Worker 调用履约 workflow 所需的内部原子执行 payload。
|
||||
|
||||
核心逻辑:Gate Attempt 已经持有当前任务的编排边界,因此必须标记
|
||||
``_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
|
||||
@@ -335,6 +354,7 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
|
||||
'task_id': str(task.task_no),
|
||||
'source': 'process_gate',
|
||||
'operator_id': payload.get('actor_user_id') or payload.get('user_id'),
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
}
|
||||
|
||||
|
||||
@@ -733,13 +753,38 @@ def _handle_retry_inventory_preparation(
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
inventory_preparation_reason_code,
|
||||
sync_fulfillment_gates_from_task,
|
||||
)
|
||||
|
||||
response = ensure_inventory(_task_payload(execution, payload))
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
recovery_plan_id = payload.get('recovery_plan_id')
|
||||
preparation_round = None
|
||||
if task is not None and payload.get('action_code') != 'poll_inventory_preparation':
|
||||
if payload.get('action_code') in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'}:
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
action_code=str(payload.get('action_code')),
|
||||
attempt_id=payload.get('attempt_id'),
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
)
|
||||
preparation_round = create_inventory_preparation_round(
|
||||
task=task,
|
||||
execution_id=int(execution.id),
|
||||
recovery_plan_id=int(recovery_plan_id) if recovery_plan_id else None,
|
||||
action_code=str(payload.get('action_code') or 'retry_inventory_preparation'),
|
||||
operation_id=str(payload.get('operation_id') or '').strip() or None,
|
||||
gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None,
|
||||
)
|
||||
response = ensure_inventory(_task_payload(execution, payload))
|
||||
if preparation_round is not None:
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round
|
||||
|
||||
rpa_result = ((response.get('data') or {}).get('rpa') or {}) if isinstance(response, dict) else {}
|
||||
sync_inventory_preparation_round(preparation_attempt=preparation_round, result=rpa_result)
|
||||
prep_reason = (
|
||||
inventory_preparation_reason_code(task)
|
||||
if task is not None
|
||||
@@ -781,12 +826,12 @@ def _handle_retry_inventory_field_mapping(
|
||||
'output_snapshot': {'action_code': 'retry_inventory_field_mapping'},
|
||||
}
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
|
||||
mapped = bool(
|
||||
inv_file is not None
|
||||
and bool(getattr(inv_file, 'mapping_confirmed', False))
|
||||
and (
|
||||
isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
|
||||
)
|
||||
and bool(active_inventory_lines_for_task(task))
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
@@ -822,27 +867,113 @@ def _handle_retry_inventory_field_mapping(
|
||||
}
|
||||
|
||||
|
||||
def _handle_retry_inventory_from_field_mapping(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
gate: ShippingProcessGate,
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""从库存字段映射恢复:失效匹配下游后只重跑映射,不创建库存准备轮次。"""
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
|
||||
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
action_code='retry_inventory_from_field_mapping',
|
||||
attempt_id=payload.get('attempt_id'),
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
)
|
||||
mapping_outcome = _handle_retry_inventory_field_mapping(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload=payload,
|
||||
)
|
||||
if mapping_outcome.get('outcome') != 'passed':
|
||||
return mapping_outcome
|
||||
return _handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
def _handle_retry_inventory_matching(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
gate: ShippingProcessGate,
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""重试库存匹配(仅 inventory_matching)。"""
|
||||
"""
|
||||
重试库存匹配;匹配已完成但仍有缺口时返回业务人工阻断。
|
||||
|
||||
核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和
|
||||
“匹配成功但库存不足”。后者必须以库存满足性人工复核收口,不能误记为
|
||||
技术失败,否则 RecoveryPlan 会反复失败且页面看不到有效推进。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
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))
|
||||
if str((response or {}).get('status') or '').strip().lower() == 'needs_human' and (
|
||||
match_status in {'partial', 'unfulfillable'} or has_shortage
|
||||
):
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
'blocking_reason_json': {
|
||||
'message': '库存重新匹配已完成,仍存在库存缺口。',
|
||||
'match_status': match_status or None,
|
||||
},
|
||||
'recommendation_json': {
|
||||
'navigation_action': 'open_shortage_review',
|
||||
'dispatch_mode': 'navigate',
|
||||
},
|
||||
'effective_result_json': {
|
||||
'findings': [],
|
||||
'match_status': match_status or None,
|
||||
'shortage': getattr(task, 'shortage_json', None),
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'tool_status': 'needs_human',
|
||||
'business_result': 'inventory_shortage',
|
||||
},
|
||||
}
|
||||
outcome = _tool_outcome(
|
||||
action_code='retry_inventory_matching',
|
||||
response=response,
|
||||
blocking_reason_code='inventory_match_failed',
|
||||
invalidate_change_type=None,
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
|
||||
return outcome
|
||||
|
||||
|
||||
def _handle_retry_inventory_from_matching(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
gate: ShippingProcessGate,
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""缺口恢复:保留当前库存快照,仅重新执行 Reservation + 料号匹配。"""
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
|
||||
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
action_code='retry_inventory_from_matching',
|
||||
attempt_id=payload.get('attempt_id'),
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
)
|
||||
return _handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
def _handle_recheck_inventory_sufficiency(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
|
||||
@@ -5,7 +5,7 @@ services/shipping_notice/process_gate_job_service.py
|
||||
依赖:app.jobs.queue、JobType、ShippingProcessGateAttempt、process_gate_executor、
|
||||
process_gate_service、fulfillment_audit。
|
||||
逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用
|
||||
claim_and_run_gate_attempt;重试/轮询使用 force_new 避免复用 running Job;
|
||||
claim_and_run_gate_attempt;失败不自动重试,只有 waiting_external 轮询使用 force_new;
|
||||
waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见;
|
||||
enqueue_process_gate_healthcheck_probe 供部署脚本验证 Worker 真实领取。
|
||||
"""
|
||||
@@ -55,6 +55,15 @@ def _heartbeat_seconds() -> int:
|
||||
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS', 15) or 15), 5)
|
||||
|
||||
|
||||
def _technical_job_max_attempts() -> int:
|
||||
"""返回同一 GateAttempt 的技术重试上限,默认 3 次。
|
||||
|
||||
只覆盖 Worker 领取、数据库或短暂外部故障等技术异常;业务失败仍由
|
||||
Executor 完成当前 Attempt,并经 RecoveryPlan 创建新的业务 Attempt。
|
||||
"""
|
||||
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_MAX_ATTEMPTS', 3) or 3), 1)
|
||||
|
||||
|
||||
def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int:
|
||||
"""
|
||||
入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。
|
||||
@@ -91,13 +100,13 @@ def enqueue_gate_attempt_job(
|
||||
为 Attempt 入队 Gate Job,并回写 attempt.job_id。
|
||||
|
||||
核心逻辑:默认仅对 queued 去重,绝不复用仍 running 的同 business_ref Job;
|
||||
force_new 时使用带时间戳的 business_ref,保证重试/轮询一定新建可领取 Job。
|
||||
force_new 时使用带时间戳的 business_ref,保证外部等待轮询一定新建可领取 Job。
|
||||
|
||||
Args:
|
||||
attempt_id: Attempt 主键。
|
||||
created_by_id: 可选创建人。
|
||||
delay_seconds: 延迟入队秒数。
|
||||
force_new: True 时强制新建 Job(重试/外部等待轮询)。
|
||||
force_new: True 时强制新建 Job(仅用于外部等待轮询)。
|
||||
|
||||
Returns:
|
||||
Job 主键。
|
||||
@@ -117,7 +126,6 @@ def enqueue_gate_attempt_job(
|
||||
if delay_seconds and int(delay_seconds) > 0:
|
||||
scheduled_at = _utc_now() + timedelta(seconds=int(delay_seconds))
|
||||
|
||||
max_attempts = int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3)
|
||||
# [STEP] force_new 用独立 business_ref,避免与刚结束/仍残留的 Job 去重冲突。
|
||||
if force_new:
|
||||
business_ref = f'attempt:{int(attempt.id)}:r{_utc_now().strftime("%Y%m%d%H%M%S")}:{uuid.uuid4().hex[:8]}'
|
||||
@@ -125,12 +133,16 @@ def enqueue_gate_attempt_job(
|
||||
business_ref = f'attempt:{int(attempt.id)}'
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
{'attempt_id': int(attempt.id)},
|
||||
{
|
||||
'attempt_id': int(attempt.id),
|
||||
'recovery_plan_id': int(attempt.recovery_plan_id) if attempt.recovery_plan_id else None,
|
||||
},
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
business_ref=business_ref,
|
||||
created_by_id=created_by_id,
|
||||
message='等待执行门禁恢复 Attempt',
|
||||
max_attempts=max(max_attempts, 1),
|
||||
# Job 仅对技术异常重试;业务失败由 Attempt/RecoveryPlan 显式建新轮次。
|
||||
max_attempts=_technical_job_max_attempts(),
|
||||
scheduled_at=scheduled_at,
|
||||
# 仅匹配 queued:禁止复用仍 running 的旧 Job(重试场景)。
|
||||
dedupe_statuses=('queued',),
|
||||
|
||||
@@ -19,16 +19,18 @@ from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingProcessRecoveryPlan,
|
||||
)
|
||||
from app.services.shipping_notice.error_explainability_contract import (
|
||||
build_explainability_reason,
|
||||
message_zh_for_reason,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_CODE_SET,
|
||||
PROCESS_GATE_RECOVERABLE_STATUSES,
|
||||
action_presentation,
|
||||
get_process_gate_definition,
|
||||
is_business_user_action,
|
||||
primary_next_action_for_gate,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
|
||||
|
||||
@@ -66,6 +68,20 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = {
|
||||
'upload_inventory_file': 'manual_upload',
|
||||
}
|
||||
|
||||
def _projection_gate_definition(gate_code: str) -> dict[str, Any]:
|
||||
"""只读取正式 20-Gate 契约;历史 Gate 由调用方走只读审计分支。"""
|
||||
return get_process_gate_definition(gate_code)
|
||||
|
||||
|
||||
def _projection_primary_next_action(*, gate_code: str, status: str) -> str | None:
|
||||
"""按统一投影定义解析下一动作,兼容 P0-3 Gate。"""
|
||||
definition = _projection_gate_definition(gate_code)
|
||||
actions = definition.get('default_next_actions')
|
||||
if not isinstance(actions, dict):
|
||||
return None
|
||||
value = actions.get(str(status or '').strip())
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def serialize_gate_attempt(
|
||||
attempt: ShippingProcessGateAttempt | None,
|
||||
@@ -124,7 +140,11 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
|
||||
gate: 门禁行。
|
||||
include_diagnostics: False 时仅保留用户可见 blocking Finding。
|
||||
"""
|
||||
definition = get_process_gate_definition(gate.gate_code)
|
||||
legacy_readonly = str(gate.gate_code or '').strip() not in PROCESS_GATE_CODE_SET
|
||||
definition = (
|
||||
{'label': '历史 AutoProgress 记录', 'responsible_party': 'system', 'recoverable': False}
|
||||
if legacy_readonly else _projection_gate_definition(gate.gate_code)
|
||||
)
|
||||
latest = None
|
||||
if gate.latest_attempt_id:
|
||||
latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id))
|
||||
@@ -134,10 +154,28 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
|
||||
item for item in findings
|
||||
if item.get('severity') == 'blocking' and item.get('user_visible', True)
|
||||
]
|
||||
allowed_actions = [str(gate.next_action_code)] if not legacy_readonly and (
|
||||
gate.next_action_code and is_business_user_action(str(gate.next_action_code))
|
||||
) else []
|
||||
# 将 RecoveryPlan 目标绑定到当前 Gate 对象,避免 Case/UI 包装层只透传主动作时丢失恢复按钮。
|
||||
from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS
|
||||
recovery_targets = [] if legacy_readonly else [
|
||||
{
|
||||
'action_code': action_code,
|
||||
'target_gate': plan.get('target_gate'),
|
||||
'resume_after_gate': plan.get('resume_after_gate'),
|
||||
'allowed_intermediate_gates': list(plan.get('allowed_intermediate_gates') or ()),
|
||||
'invalidates': list(plan.get('invalidates') or ()),
|
||||
'permission': plan.get('permission'),
|
||||
}
|
||||
for action_code, plan in (RECOVERY_PLAN_ACTIONS.get(str(gate.gate_code), {}) or {}).items()
|
||||
]
|
||||
return {
|
||||
'gate_code': gate.gate_code,
|
||||
'legacy_readonly': legacy_readonly,
|
||||
'sequence_no': int(gate.sequence_no),
|
||||
'label': definition.get('label'),
|
||||
'implementation_status': definition.get('implementation_status'),
|
||||
'status': gate.status,
|
||||
'evaluation_version': int(gate.evaluation_version),
|
||||
'input_fingerprint': gate.input_fingerprint,
|
||||
@@ -150,12 +188,22 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
|
||||
'effective_result': gate.effective_result_json if include_diagnostics else None,
|
||||
'findings': findings,
|
||||
'next_action_code': gate.next_action_code,
|
||||
'allowed_actions': allowed_actions,
|
||||
'action_presentation': [item for code in allowed_actions if (item := action_presentation(code))],
|
||||
'recovery_targets': recovery_targets,
|
||||
'responsible_party': definition.get('responsible_party'),
|
||||
'recoverable': bool(definition.get('recoverable')),
|
||||
'passed_at': gate.passed_at.isoformat() if gate.passed_at else None,
|
||||
'invalidated_at': gate.invalidated_at.isoformat() if gate.invalidated_at else None,
|
||||
'latest_attempt': serialize_gate_attempt(latest) if include_diagnostics else (
|
||||
{'attempt_no': latest.attempt_no, 'status': latest.status} if latest else None
|
||||
{
|
||||
'id': int(latest.id),
|
||||
'attempt_no': latest.attempt_no,
|
||||
'status': latest.status,
|
||||
# 用户需要能区分“失败原因”和“系统失败”,但不能看到堆栈、路径或凭据。
|
||||
'error_code': str(latest.error_code or '').strip() or None,
|
||||
'error_summary': sanitize_gate_error_text(latest.error_summary, max_len=500),
|
||||
} if latest else None
|
||||
),
|
||||
}
|
||||
|
||||
@@ -185,9 +233,29 @@ def serialize_process_execution(
|
||||
(item for item in serialized if item.get('gate_code') == execution.current_gate_code),
|
||||
None,
|
||||
)
|
||||
legacy_readonly = any(item.get('legacy_readonly') for item in serialized)
|
||||
recovery_targets: list[dict[str, Any]] = []
|
||||
if execution.current_gate_code and not legacy_readonly:
|
||||
# RecoveryPlan 合同是服务端唯一动作来源;Projection 只读输出,客户端不能改写 target Gate。
|
||||
from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS
|
||||
|
||||
for action_code, definition in (RECOVERY_PLAN_ACTIONS.get(execution.current_gate_code, {}) or {}).items():
|
||||
recovery_targets.append({
|
||||
'action_code': action_code,
|
||||
'target_gate': definition.get('target_gate'),
|
||||
'resume_after_gate': definition.get('resume_after_gate'),
|
||||
'allowed_intermediate_gates': list(definition.get('allowed_intermediate_gates') or ()),
|
||||
'invalidates': list(definition.get('invalidates') or ()),
|
||||
'permission': definition.get('permission'),
|
||||
})
|
||||
active_recovery_plans = ShippingProcessRecoveryPlan.query.filter(
|
||||
ShippingProcessRecoveryPlan.execution_id == int(execution.id),
|
||||
ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}),
|
||||
).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all()
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'status': execution.status,
|
||||
'status': 'legacy_readonly' if legacy_readonly else execution.status,
|
||||
'legacy_readonly': legacy_readonly,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
'last_passed_gate_code': execution.last_passed_gate_code,
|
||||
'primary_next_action_code': execution.primary_next_action_code,
|
||||
@@ -199,6 +267,19 @@ def serialize_process_execution(
|
||||
'review_case_id': int(execution.review_case_id) if execution.review_case_id else None,
|
||||
'task_id': int(execution.task_id) if execution.task_id else None,
|
||||
'current_gate': current,
|
||||
'recovery_targets': recovery_targets,
|
||||
'active_recovery_plans': [
|
||||
{
|
||||
'plan_no': plan.plan_no,
|
||||
'action_code': plan.action_code,
|
||||
'current_gate': plan.current_gate,
|
||||
'target_gate': plan.target_gate,
|
||||
'resume_after_gate': plan.resume_after_gate,
|
||||
'status': plan.status,
|
||||
'idempotency_key': plan.idempotency_key if include_diagnostics else None,
|
||||
}
|
||||
for plan in active_recovery_plans
|
||||
],
|
||||
'gates': serialized,
|
||||
'updated_at': execution.updated_at.isoformat() if execution.updated_at else None,
|
||||
}
|
||||
@@ -278,6 +359,45 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。
|
||||
"""
|
||||
full = serialize_process_execution(execution, include_diagnostics=False)
|
||||
# 完成态的正式 Execution 会清空 current_gate_code;空值表示没有待处理 Gate,
|
||||
# 不能被误判为已下线的 APX 历史执行。只有存在实际 Gate 编号且不在正式契约内时,
|
||||
# 才进入 legacy_readonly 兼容投影。
|
||||
current_gate_code = str(getattr(execution, 'current_gate_code', '') or '').strip()
|
||||
legacy_readonly = bool(full.get('legacy_readonly')) or (
|
||||
bool(current_gate_code) and current_gate_code not in PROCESS_GATE_CODE_SET
|
||||
)
|
||||
if legacy_readonly:
|
||||
refs = _execution_navigation_refs(execution)
|
||||
return {
|
||||
'execution_no': full.get('execution_no'),
|
||||
'status': 'legacy_readonly',
|
||||
'legacy_readonly': True,
|
||||
'execution_status': None,
|
||||
'current_gate': full.get('current_gate'),
|
||||
'current_blocking_gate': None,
|
||||
'recovery_targets': [],
|
||||
'active_recovery_plans': [],
|
||||
'blocking_reason_code': 'shipping_apx_runtime_disabled',
|
||||
'blocking_message': '历史自动推进记录仅供审计查看',
|
||||
'failure_detail': None,
|
||||
'explainability': None,
|
||||
'next_action_code': None,
|
||||
'primary_action': None,
|
||||
'allowed_actions': [],
|
||||
'action_presentation': [],
|
||||
'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}],
|
||||
'technical_auto_only': True,
|
||||
'owner_type': 'system',
|
||||
'responsible_party': 'system',
|
||||
'diagnostic_hint': None,
|
||||
**refs,
|
||||
'navigation': None,
|
||||
'gates_track': [
|
||||
{'gate_code': item.get('gate_code'), 'label': item.get('label'),
|
||||
'status': item.get('status'), 'sequence_no': item.get('sequence_no')}
|
||||
for item in (full.get('gates') or [])
|
||||
],
|
||||
}
|
||||
current = full.get('current_gate')
|
||||
blocking = None
|
||||
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
|
||||
@@ -311,20 +431,94 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
break
|
||||
reason_code = (blocking or {}).get('blocking_reason_code')
|
||||
next_action = full.get('primary_next_action_code') or (
|
||||
primary_next_action_for_gate(
|
||||
_projection_primary_next_action(
|
||||
gate_code=str((blocking or {}).get('gate_code') or ''),
|
||||
status=str((blocking or {}).get('status') or ''),
|
||||
) if blocking else None
|
||||
)
|
||||
# [STEP] 技术重试动作不对业务用户投影;仅保留复核工作台业务动作白名单。
|
||||
# [STEP] 兼容历史 Gate 行:RPA 失败曾被旧契约错误写成
|
||||
# regenerate_manual_upload_todo;当前 Gate + 原因码才是履约真相,
|
||||
# 统一纠正为用户可主动执行的 RPA 重试。AUTO_UPLOAD 只控制自动触发,
|
||||
# 不参与手动动作投影。
|
||||
blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower()
|
||||
normalized_reason = str(reason_code or '').strip().lower()
|
||||
if (
|
||||
blocking_gate_code == 'freight_upload_rpa'
|
||||
and normalized_reason in {
|
||||
'upload_rpa_failed',
|
||||
'upload_rpa_login_failed',
|
||||
'upload_platform_rejected',
|
||||
}
|
||||
):
|
||||
next_action = 'retry_freight_upload_rpa'
|
||||
elif (
|
||||
blocking_gate_code == 'manual_upload_handoff'
|
||||
and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'}
|
||||
):
|
||||
# 人工交接仍保留人工登记入口(Footer),同时在 Gate 卡提供显式 RPA 重试。
|
||||
next_action = 'retry_freight_upload_rpa'
|
||||
# [STEP] 所有冻结 Gate 动作均可投影到工作台;是否可执行由页面 canHandle
|
||||
# 与 Workspace API 的权限/版本校验共同决定,禁止前端自行派生动作。
|
||||
technical_auto_only = False
|
||||
if next_action and not is_business_user_action(str(next_action)):
|
||||
# 技术责任方的 retry_* 只作为系统执行动作,不能直接充当业务用户主按钮;
|
||||
# RecoveryPlan 仍可在下方投影为经过权限校验的恢复入口。
|
||||
if (
|
||||
next_action
|
||||
and (
|
||||
not is_business_user_action(str(next_action))
|
||||
or (
|
||||
str(full.get('responsible_party') or '').strip().lower() in {'system', 'worker'}
|
||||
and str(next_action).startswith('retry_')
|
||||
)
|
||||
)
|
||||
):
|
||||
next_action = None
|
||||
technical_auto_only = bool(blocking)
|
||||
|
||||
# [STEP] 正式 OT 后的库存阻断仍需给业务用户提供精确入口:技术主动作
|
||||
# (retry_inventory_*)不直接暴露,但 RecoveryPlan 存在时必须保留当前
|
||||
# Gate 的复核入口,否则 apply_post_ot_gate_rules 会把整个阻断误判为系统态,
|
||||
# 前端也就不会挂载 ProcessGateRecoveryCard。
|
||||
if blocking and not next_action:
|
||||
gate_code = str(blocking.get('gate_code') or '').strip().lower()
|
||||
recovery_targets = full.get('recovery_targets') or []
|
||||
if recovery_targets and gate_code == 'inventory_matching':
|
||||
next_action = 'open_inventory_match_review'
|
||||
technical_auto_only = False
|
||||
elif recovery_targets and gate_code == 'inventory_sufficiency':
|
||||
next_action = 'open_shortage_review'
|
||||
technical_auto_only = False
|
||||
|
||||
# 正式 OT 后仍需允许业务用户恢复履约链路中的技术失败:
|
||||
# 库存准备/匹配以及货代上传 RPA 的动作码由 Gate 合同固定,
|
||||
# 不把其他 system/worker 节点泛化为可人工操作。
|
||||
if not next_action and gate_code in {
|
||||
'inventory_preparation',
|
||||
'inventory_matching',
|
||||
'freight_upload_rpa',
|
||||
}:
|
||||
candidate = _projection_primary_next_action(
|
||||
gate_code=gate_code,
|
||||
status=str(blocking.get('status') or ''),
|
||||
)
|
||||
if candidate and is_business_user_action(candidate):
|
||||
next_action = candidate
|
||||
technical_auto_only = False
|
||||
# 无当前阻断时禁止残留 confirm_customer,避免「客户已确认」仍显示为优先处理。
|
||||
if not blocking and str(next_action or '').strip() == 'confirm_customer':
|
||||
next_action = None
|
||||
|
||||
allowed_actions: list[str] = []
|
||||
action_items: list[dict[str, str]] = []
|
||||
if blocking:
|
||||
if next_action and is_business_user_action(str(next_action)):
|
||||
allowed_actions.append(str(next_action))
|
||||
for target in full.get('recovery_targets') or []:
|
||||
code = str(target.get('action_code') or '').strip()
|
||||
if code and code not in allowed_actions and is_business_user_action(code):
|
||||
allowed_actions.append(code)
|
||||
action_items = [item for code in allowed_actions if (item := action_presentation(code))]
|
||||
|
||||
# [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源;
|
||||
# request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。
|
||||
explainability = None
|
||||
@@ -350,11 +544,22 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
'execution_no': full.get('execution_no'),
|
||||
'status': full.get('status'),
|
||||
'execution_status': execution_status,
|
||||
# 当前执行 Gate 与人工阻断分开投影:queued/running 不生成待办,但阶段游标必须
|
||||
# 仍来自正式 Gate,避免旧 OT stage 把页面停留在库存匹配。
|
||||
'current_gate': current,
|
||||
'current_blocking_gate': blocking,
|
||||
# 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。
|
||||
'recovery_targets': full.get('recovery_targets') or [],
|
||||
'active_recovery_plans': full.get('active_recovery_plans') or [],
|
||||
'blocking_reason_code': reason_code,
|
||||
'blocking_message': _user_facing_blocking_message(reason_code),
|
||||
'failure_detail': _user_facing_failure_detail(blocking),
|
||||
'explainability': explainability,
|
||||
'next_action_code': next_action,
|
||||
'primary_action': action_presentation(next_action),
|
||||
'allowed_actions': allowed_actions,
|
||||
'action_presentation': action_items,
|
||||
'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}],
|
||||
'technical_auto_only': technical_auto_only,
|
||||
'owner_type': (
|
||||
'system' if technical_auto_only or execution_status
|
||||
@@ -409,6 +614,34 @@ def _user_facing_blocking_reason_payload(gate: ShippingProcessGate) -> dict[str,
|
||||
return payload
|
||||
|
||||
|
||||
def _user_facing_failure_detail(blocking: dict[str, Any] | None) -> str | None:
|
||||
"""
|
||||
提取当前 Gate 最近一次失败的脱敏业务详情,供用户排查。
|
||||
|
||||
优先级:Attempt.error_summary → blocking_reason.message → Finding.details.message。
|
||||
仅返回已经经过门禁错误脱敏器处理的短文本;没有事实时返回 None,避免伪造原因。
|
||||
"""
|
||||
if not isinstance(blocking, dict):
|
||||
return None
|
||||
latest = blocking.get('latest_attempt')
|
||||
candidates: list[Any] = []
|
||||
if isinstance(latest, dict):
|
||||
candidates.extend([latest.get('error_summary'), latest.get('error_code')])
|
||||
reason = blocking.get('blocking_reason')
|
||||
if isinstance(reason, dict):
|
||||
candidates.extend([reason.get('message'), reason.get('failure_detail'), reason.get('error_summary')])
|
||||
for finding in blocking.get('findings') or []:
|
||||
if not isinstance(finding, dict):
|
||||
continue
|
||||
details = finding.get('details') if isinstance(finding.get('details'), dict) else {}
|
||||
candidates.extend([details.get('failure_detail'), details.get('message'), details.get('error_summary')])
|
||||
for value in candidates:
|
||||
text = sanitize_gate_error_text(value, max_len=500)
|
||||
if text:
|
||||
return text
|
||||
return None
|
||||
|
||||
|
||||
def _current_request_id() -> str | None:
|
||||
"""
|
||||
读取当前 HTTP 请求的 request_id;无请求上下文时返回 None。
|
||||
@@ -574,6 +807,12 @@ def _user_facing_blocking_message(reason_code: str | None) -> str | None:
|
||||
'run_failed': '识别运行失败',
|
||||
'run_cancelled': '识别运行已取消',
|
||||
'pending_orders_present': '仍有待处理订单',
|
||||
'inventory_candidates_required': '当前没有库存候选集,无法开始库存匹配;请先重新获取库存',
|
||||
'inventory_candidates_frozen_required': '库存候选集尚未确认,请先完成库存源确认',
|
||||
'inventory_snapshot_prepare_failed': '库存快照准备失败,请检查库存获取结果后重试',
|
||||
'inventory_snapshots_pending': '库存快照仍在准备中,请稍后刷新进度',
|
||||
'inventory_match_not_ready': '库存尚未满足匹配条件,请先完成库存准备',
|
||||
'projection_data_inconsistent': '处理进度数据不一致,请刷新页面后重试;若仍失败请联系管理员',
|
||||
}
|
||||
return legacy.get(code)
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_ACTION_CODES,
|
||||
@@ -29,6 +29,8 @@ from app.services.shipping_notice.process_gate_executor import (
|
||||
execute_queued_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import 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
|
||||
|
||||
|
||||
def _chat_process_gate_event_type(*, action_code: str, trigger_type: str) -> str:
|
||||
@@ -138,13 +140,6 @@ def request_gate_action(
|
||||
action = str(action_code or '').strip()
|
||||
if action not in PROCESS_GATE_ACTION_CODES:
|
||||
raise ValidationError('Unknown process gate action', code='SHIPPING.PROCESS_GATE_ACTION_INVALID')
|
||||
# [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。
|
||||
if str(actor_type or '') == 'user' and not is_business_user_action(action):
|
||||
raise ValidationError(
|
||||
'Technical gate actions are not allowed for business users',
|
||||
code='SHIPPING.PROCESS_GATE_TECHNICAL_ACTION_FORBIDDEN',
|
||||
details={'action_code': action},
|
||||
)
|
||||
forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql'}
|
||||
body = dict(payload) if isinstance(payload, dict) else {}
|
||||
if forbidden.intersection(set(body.keys())):
|
||||
@@ -159,6 +154,13 @@ def request_gate_action(
|
||||
body.setdefault('idempotency_key', str(idempotency_key or ''))
|
||||
|
||||
execution = get_execution_by_no(execution_no)
|
||||
execution_status = str(execution.status or '').strip().lower()
|
||||
if execution_status in {'completed', 'cancelled'}:
|
||||
raise ValidationError(
|
||||
'Process execution is terminal; write actions are not allowed',
|
||||
code='SHIPPING.PROCESS_EXECUTION_TERMINAL',
|
||||
details={'execution_no': execution.execution_no, 'status': execution_status},
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code=str(gate_code or '').strip(),
|
||||
@@ -166,6 +168,43 @@ def request_gate_action(
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
|
||||
current_gate = str(execution.current_gate_code or '').strip()
|
||||
replay_attempt = ShippingProcessGateAttempt.query.filter_by(
|
||||
idempotency_key=str(idempotency_key or '').strip(),
|
||||
).first()
|
||||
# 跨阶段恢复目标先做 Gate 归属校验;错误 Gate 必须返回稳定的
|
||||
# RECOVERY_TARGET_INVALID,而不是被普通技术动作权限错误遮蔽。
|
||||
recovery_definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action)
|
||||
if action.startswith('retry_inventory_from_') and recovery_definition is None:
|
||||
raise ValidationError(
|
||||
'Recovery target is not allowed for current gate',
|
||||
code='SHIPPING.RECOVERY_TARGET_INVALID',
|
||||
details={'current_gate': gate.gate_code, '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()):
|
||||
raise ValidationError(
|
||||
'Action must target the current process gate',
|
||||
code='SHIPPING.PROCESS_GATE_NOT_CURRENT',
|
||||
details={
|
||||
'execution_no': execution.execution_no,
|
||||
'current_gate': current_gate or None,
|
||||
'requested_gate': gate.gate_code,
|
||||
'action_code': action,
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。
|
||||
# 必须在跨阶段目标归属之后判断,保证错误 Gate 返回 RECOVERY_TARGET_INVALID。
|
||||
if str(actor_type or '') == 'user' and not is_business_user_action(action):
|
||||
raise ValidationError(
|
||||
'Technical gate actions are not allowed for business users',
|
||||
code='SHIPPING.PROCESS_GATE_TECHNICAL_ACTION_FORBIDDEN',
|
||||
details={'action_code': action},
|
||||
)
|
||||
|
||||
definition = get_process_gate_definition(gate.gate_code)
|
||||
if (
|
||||
str(actor_type or '') == 'user'
|
||||
@@ -181,6 +220,15 @@ def request_gate_action(
|
||||
primary = gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status=gate.status,
|
||||
)
|
||||
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
|
||||
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
|
||||
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
|
||||
if (
|
||||
gate.gate_code == 'manual_upload_handoff'
|
||||
and gate.blocking_reason_code in {'manual_upload_pending', 'upload_result_unknown'}
|
||||
and action == 'retry_freight_upload_rpa'
|
||||
):
|
||||
primary = action
|
||||
# [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。
|
||||
allowed_side: set[str] = set()
|
||||
if gate.gate_code == 'inventory_source_routing':
|
||||
@@ -188,7 +236,7 @@ def request_gate_action(
|
||||
'adopt_rule_suggestion',
|
||||
'keep_manual_inventory_decision',
|
||||
}
|
||||
if primary and action != primary and action not in allowed_side:
|
||||
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',
|
||||
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
|
||||
@@ -198,6 +246,20 @@ def request_gate_action(
|
||||
trigger_type = (
|
||||
'user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual'
|
||||
)
|
||||
recovery_plan = None
|
||||
if recovery_definition is not None:
|
||||
recovery_plan, _ = create_recovery_plan(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
action_code=action,
|
||||
idempotency_key=idempotency_key,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
operation_id=str(body.get('operation_id') or '').strip() or None,
|
||||
)
|
||||
body['recovery_plan_id'] = int(recovery_plan.id)
|
||||
body['recovery_action_code'] = action
|
||||
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code=gate.gate_code,
|
||||
@@ -209,6 +271,9 @@ def request_gate_action(
|
||||
input_snapshot={'action_code': action, 'payload': body},
|
||||
)
|
||||
|
||||
if recovery_definition is not None:
|
||||
bind_recovery_attempt(plan=recovery_plan, attempt_id=int(attempt.id))
|
||||
|
||||
# 幂等回放且已终态:直接返回,不二次执行;也不重复写 chat_* 审计。
|
||||
if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}:
|
||||
db_gate = ShippingProcessGate.query.get(int(attempt.gate_id))
|
||||
@@ -226,6 +291,7 @@ def request_gate_action(
|
||||
},
|
||||
'gate_status': db_gate.status if db_gate else gate.status,
|
||||
'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version),
|
||||
'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None,
|
||||
}
|
||||
|
||||
# [STEP] 对话工作台语义审计:与 process_gate_recovery_requested 并存,供审计中心 chat 分组筛选。
|
||||
@@ -260,6 +326,7 @@ def request_gate_action(
|
||||
'idempotency_key': attempt.idempotency_key,
|
||||
},
|
||||
'gate_evaluation_version': int(gate.evaluation_version),
|
||||
'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None,
|
||||
}
|
||||
|
||||
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
|
||||
@@ -278,4 +345,5 @@ def request_gate_action(
|
||||
'gate_status': updated_gate.status,
|
||||
'gate_evaluation_version': int(updated_gate.evaluation_version),
|
||||
'next_action_code': updated_gate.next_action_code,
|
||||
'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None,
|
||||
}
|
||||
@@ -23,9 +23,11 @@ from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingProcessRecoveryPlan,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_CODE_SET,
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_RECOVERABLE_STATUSES,
|
||||
get_process_gate_definition,
|
||||
@@ -293,6 +295,15 @@ def ensure_execution_for_workflow_version(
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
# APX 六 Gate 与正式 20-Gate 不能共用同一 Execution。历史数据可能仍按
|
||||
# task_id 被查到;此时必须新建正式链,禁止把 20-Gate 行写进 APX sequence。
|
||||
if existing is not None:
|
||||
existing_codes = {
|
||||
str(row.gate_code or '').strip()
|
||||
for row in ShippingProcessGate.query.filter_by(execution_id=int(existing.id)).all()
|
||||
}
|
||||
if existing_codes and not existing_codes.issubset(PROCESS_GATE_CODE_SET):
|
||||
existing = None
|
||||
if existing is not None:
|
||||
if review_case_id and existing.review_case_id is None:
|
||||
existing.review_case_id = int(review_case_id)
|
||||
@@ -635,11 +646,28 @@ def complete_gate_attempt(
|
||||
attempt.error_code = str(error_code)[:64] if error_code else None
|
||||
# [STEP] 持久化前脱敏,避免 URL/路径/连接信息进入 Attempt 与后续投影。
|
||||
attempt.error_summary = sanitize_gate_error_text(error_summary, max_len=2000)
|
||||
# waiting_external 表示 Attempt 本身成功完成并进入外部等待,不应记为 failed。
|
||||
attempt.status = 'succeeded' if outcome in {'passed', 'waiting_external'} else 'failed'
|
||||
# passed / waiting_external / blocked_manual 均表示执行器已成功得到业务结果;
|
||||
# blocked_manual 只是 Gate 仍需人工复核(例如库存 14、缺口 16),不能误记为技术失败。
|
||||
attempt.status = 'succeeded' if outcome in {
|
||||
'passed', 'waiting_external', 'blocked_manual',
|
||||
} else 'failed'
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
|
||||
if attempt.recovery_plan_id:
|
||||
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
|
||||
|
||||
plan = db.session.get(ShippingProcessRecoveryPlan, int(attempt.recovery_plan_id))
|
||||
if plan is not None:
|
||||
complete_recovery_plan_for_attempt(
|
||||
plan=plan,
|
||||
outcome=outcome,
|
||||
now=now,
|
||||
error_code=error_code,
|
||||
error_summary=error_summary,
|
||||
business_result_code=blocking_reason_code,
|
||||
)
|
||||
|
||||
gate.status = outcome
|
||||
gate.blocking_reason_code = str(blocking_reason_code)[:64] if blocking_reason_code else None
|
||||
reason_payload = dict(blocking_reason_json or {}) or None
|
||||
@@ -667,13 +695,9 @@ def complete_gate_attempt(
|
||||
# 过去只有复核确认建单链路会入队 auto_progress,导致其余门禁恢复后
|
||||
# Gate 已 passed 但任务仍停在旧节点。这里使用同一幂等任务队列入口,
|
||||
# 与事务一起提交,避免恢复动作提交前 Worker 读到不完整状态。
|
||||
# 业务投影(trigger_type=auto)本身属于 auto_progress 当前事务,避免递归排队;
|
||||
# 恢复动作(user/system_requeue)通过统一队列续跑后续节点。
|
||||
if (
|
||||
outcome == 'passed'
|
||||
and execution.task_id
|
||||
and str(attempt.trigger_type or '').strip() != 'auto'
|
||||
):
|
||||
# 无论由自动或恢复 Attempt 通过,都统一委托 AutoProgress 找到下一 Gate。
|
||||
# 它只入队一个 Attempt/Job;同一事务内的状态尚未提交,Worker 不会读到半成品。
|
||||
if outcome == 'passed' and execution.task_id:
|
||||
_enqueue_auto_progress_after_gate_pass(execution=execution, gate=gate)
|
||||
|
||||
invalidated: list[str] = []
|
||||
@@ -723,39 +747,41 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
execution: ShippingProcessExecution,
|
||||
gate: ShippingProcessGate,
|
||||
) -> None:
|
||||
"""门禁通过后为绑定任务排入幂等 auto_progress Job。
|
||||
"""门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。
|
||||
|
||||
核心逻辑:复用 shipping_notice_run 的业务去重与执行模式;不直接执行编排,
|
||||
让当前恢复事务先提交后再由 Worker/同步队列继续后续门禁。已完成或仍需人工的
|
||||
任务会由 auto_progress 自身的 checkpoint 逻辑安全早停。
|
||||
核心逻辑:不再写 legacy shipping_notice_run;统一由 submit_auto_progress 创建
|
||||
ProcessGate Attempt/Job。已完成或仍需人工的任务会安全早停。
|
||||
"""
|
||||
try:
|
||||
from app.models import ShippingNotice
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip().upper()
|
||||
if not task_no:
|
||||
return
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
ok, result = enqueue_shipping_notice_job(
|
||||
task_no=task_no,
|
||||
created_by_id=None,
|
||||
commit=False,
|
||||
# 直接为下一 Gate 创建 Attempt/ProcessGate Job,避免重新进入
|
||||
# submit_auto_progress→sync_fulfillment_gates 的递归路径。
|
||||
_refresh_execution_pointers(execution)
|
||||
next_gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code=str(execution.current_gate_code or ''))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if not ok:
|
||||
record_fulfillment_audit(
|
||||
event_type='task_auto_progress_enqueue_failed',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no,
|
||||
action='auto_progress',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
task_no=task_no,
|
||||
result='failure',
|
||||
reason_code='auto_progress_enqueue_failed',
|
||||
error_code='SHIPPING.AUTO_PROGRESS_ENQUEUE_FAILED',
|
||||
after={'gate_code': gate.gate_code, 'message': str(result)[:500]},
|
||||
source='process_gate',
|
||||
)
|
||||
if next_gate is None or not next_gate.next_action_code:
|
||||
return
|
||||
definition = get_process_gate_definition(next_gate.gate_code)
|
||||
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
|
||||
return
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=next_gate.gate_code,
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key=(
|
||||
f'shipping-auto-progress:{execution.task_id}:{execution.id}:'
|
||||
f'{next_gate.id}:{next_gate.evaluation_version}'
|
||||
),
|
||||
expected_gate_version=int(next_gate.evaluation_version),
|
||||
input_snapshot={'action_code': next_gate.next_action_code, 'payload': {'trigger': 'gate_attempt_passed'}},
|
||||
)
|
||||
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 — 门禁结果不可被排程异常覆盖
|
||||
record_fulfillment_audit(
|
||||
event_type='task_auto_progress_enqueue_failed',
|
||||
@@ -870,6 +896,23 @@ def sync_gate_from_business_result(
|
||||
key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}'
|
||||
execution = _locked_execution(execution_no)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
|
||||
# [STEP] Gate Worker 执行器可能在当前 Attempt 内同步最新业务事实。
|
||||
# 同一 Gate 已有 queued/running Attempt 时,事实同步必须由外层 Attempt
|
||||
# 统一 complete,禁止递归创建第二个 Attempt,否则会误报 PROCESS_GATE_BUSY,
|
||||
# 并最终把可恢复业务失败收口为 failed_terminal。
|
||||
active_attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.gate_id == int(gate.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
if active_attempt is not None:
|
||||
return gate
|
||||
|
||||
if allow_repass and gate.status == 'passed':
|
||||
gate.status = 'invalidated'
|
||||
gate.invalidated_at = _utc_now()
|
||||
|
||||
@@ -92,6 +92,9 @@ _ACTION_CODE_ALIASES: dict[str, str] = {
|
||||
'rematch': 'open_inventory_match_review',
|
||||
'match_inventory': 'open_inventory_match_review',
|
||||
'generate_excel': 'regenerate_excel',
|
||||
# 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由
|
||||
# Gate API 使用原始 action_code 校验,legacy projection 只负责展示语义。
|
||||
'regenerate_excel_artifact': 'regenerate_excel',
|
||||
'freeze_order': 'edit_formal_task',
|
||||
}
|
||||
|
||||
@@ -453,6 +456,45 @@ def reconcile_processing_projection_facts(
|
||||
stage_idx = shipping_processing_stage_index(stage)
|
||||
waiting_idx = shipping_processing_stage_index('waiting_review') or 8
|
||||
|
||||
# 关键事实无法读取时 fail-closed:不能继续沿用旧 checkpoint 或写动作。
|
||||
if payload.get('projection_data_inconsistent'):
|
||||
payload['status'] = 'waiting_human'
|
||||
payload['stage'] = 'waiting_review'
|
||||
payload['current_gate'] = None
|
||||
payload['primary_action'] = None
|
||||
payload['available_actions'] = []
|
||||
payload['retryable'] = False
|
||||
payload['blocking_reason'] = {
|
||||
'code': 'projection_data_inconsistent',
|
||||
'message': '处理状态暂时无法确认,请刷新后重试',
|
||||
}
|
||||
payload['stage_nodes'] = build_stage_nodes(
|
||||
stage='waiting_review', status='waiting_human', source_type=source_type,
|
||||
invalidated_from_stage=invalidated_from_stage,
|
||||
)
|
||||
return payload
|
||||
|
||||
# [BE-08] 正式 Gate 是后半段唯一进度真相。OT 的旧 stage/status 可能仍停在
|
||||
# inventory_matching/running,但 Gate 已经进入 Excel 或上传节点;先把统一
|
||||
# 投影游标对齐 Gate,禁止旧 primary_action 继续生成 match_inventory。
|
||||
gate_stage = {
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
'manual_upload_handoff': 'freight_uploading',
|
||||
}.get(str((gate or {}).get('gate_code') or '').strip().lower())
|
||||
if gate_stage:
|
||||
stage = gate_stage
|
||||
payload['stage_label_key'] = gate_stage
|
||||
gate_status = str((gate or {}).get('status') or '').strip().lower()
|
||||
if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}:
|
||||
status = 'blocked'
|
||||
elif gate_status == 'waiting_external':
|
||||
status = 'automating'
|
||||
elif gate_status in {'queued', 'running'}:
|
||||
status = 'automating'
|
||||
stage_idx = shipping_processing_stage_index(stage)
|
||||
|
||||
# [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。
|
||||
if status == 'completed' and stage and stage != 'completed':
|
||||
if stage_idx is not None and stage_idx <= waiting_idx:
|
||||
@@ -597,6 +639,31 @@ def apply_user_projection_fields(
|
||||
payload['legacy_current_gate'] = payload.get('current_gate')
|
||||
old_status = str(payload.get('status') or '').strip().lower()
|
||||
old_stage = str(payload.get('stage') or '').strip().lower()
|
||||
source_type = str(payload.get('source_type') or '').strip().lower() or None
|
||||
old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None
|
||||
|
||||
# 关键事实读取失败时立即 fail-closed;不能继续执行后续 legacy/retry 推导,
|
||||
# 否则后续逻辑可能重新生成可执行主动作覆盖诊断态。
|
||||
if payload.get('projection_data_inconsistent'):
|
||||
payload['user_status'] = 'waiting_human'
|
||||
payload['user_stage'] = 'waiting_review'
|
||||
payload['user_current_gate_code'] = None
|
||||
payload['blocking_reason'] = {
|
||||
'code': 'projection_data_inconsistent',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.projection_data_inconsistent',
|
||||
'details': {},
|
||||
}
|
||||
payload['retryable'] = False
|
||||
payload['primary_action'] = None
|
||||
payload['available_actions'] = []
|
||||
payload['current_gate'] = None
|
||||
payload['stage'] = 'waiting_review'
|
||||
payload['status'] = 'waiting_human'
|
||||
payload['stage_nodes'] = build_stage_nodes(
|
||||
stage='waiting_review', status='waiting_human', source_type=source_type,
|
||||
invalidated_from_stage=None,
|
||||
)
|
||||
return payload
|
||||
|
||||
# ===== [STEP 2] 读取 notice / order_task 原始字段(保持不变) =====
|
||||
pending_reason: str | None = None
|
||||
@@ -650,6 +717,13 @@ def apply_user_projection_fields(
|
||||
)
|
||||
|
||||
def _compute_user_status() -> str:
|
||||
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
|
||||
# 只描述任务调度,不能覆盖正式 Gate 已到达的 Excel/上传阻断。
|
||||
gate_status = str((old_gate or {}).get('status') or '').strip().lower()
|
||||
if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}:
|
||||
return 'retryable'
|
||||
if gate_status == 'blocked_manual':
|
||||
return 'waiting_human'
|
||||
# 1) 终态短路:old_status completed/cancelled/failed
|
||||
if old_status == 'completed':
|
||||
return 'completed'
|
||||
@@ -706,7 +780,6 @@ def apply_user_projection_fields(
|
||||
user_stage = 'document_parsing'
|
||||
|
||||
# ===== [不变] user_current_gate_code 计算(保持不动) =====
|
||||
old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None
|
||||
user_current_gate_code: str | None = None
|
||||
if isinstance(old_gate, dict):
|
||||
user_current_gate_code = str(old_gate.get('code') or old_gate.get('gate_code') or '').strip() or None
|
||||
@@ -734,6 +807,12 @@ def apply_user_projection_fields(
|
||||
'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted',
|
||||
'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict',
|
||||
'inventory_candidates_required': 'workspace.shippingNotice.processGate.reasons.inventory_candidates_required',
|
||||
'inventory_candidates_frozen_required': 'workspace.shippingNotice.processGate.reasons.inventory_candidates_frozen_required',
|
||||
'inventory_snapshot_prepare_failed': 'workspace.shippingNotice.processGate.reasons.inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending': 'workspace.shippingNotice.processGate.reasons.inventory_snapshots_pending',
|
||||
'inventory_match_not_ready': 'workspace.shippingNotice.processGate.reasons.inventory_match_not_ready',
|
||||
'projection_data_inconsistent': 'workspace.shippingNotice.processGate.reasons.projection_data_inconsistent',
|
||||
'order_review_required': 'workspace.shippingNotice.processGate.reasons.freeze_not_ready',
|
||||
'duplicate_decision_required': 'chat.shippingProcessing.reasonCode.duplicateDecisionRequired',
|
||||
'SHIPPING.NOTICE_EXACT_DUPLICATE': 'chat.shippingProcessing.reasonCode.exactDuplicateNotice',
|
||||
@@ -786,6 +865,17 @@ def apply_user_projection_fields(
|
||||
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
|
||||
'details': {},
|
||||
}
|
||||
gate_reason = str((old_gate or {}).get('blocking_reason_code') or '').strip()
|
||||
if gate_reason and gate_reason in _REASON_TO_I18N_KEY:
|
||||
return {
|
||||
'code': gate_reason,
|
||||
'i18n_key': _REASON_TO_I18N_KEY[gate_reason],
|
||||
'details': dict(
|
||||
(old_gate or {}).get('effective_result')
|
||||
or (old_gate or {}).get('details')
|
||||
or {}
|
||||
),
|
||||
}
|
||||
return _legacy_waiting_human_blocking_reason()
|
||||
# 3) retryable
|
||||
if user_status == 'retryable':
|
||||
@@ -824,6 +914,7 @@ def apply_user_projection_fields(
|
||||
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
|
||||
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
|
||||
'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa',
|
||||
'regenerate_excel': 'workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact',
|
||||
'adjudicate_duplicate': 'workspace.shippingNotice.processGate.actionCodes.adjudicate_duplicate',
|
||||
'reconcile_and_progress': 'workspace.shippingNotice.processGate.actionCodes.reconcile_and_progress',
|
||||
'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review',
|
||||
@@ -862,6 +953,20 @@ def apply_user_projection_fields(
|
||||
return None
|
||||
|
||||
def _compute_primary_action() -> dict[str, Any] | None:
|
||||
# [BE-10] Gate action 是当前阶段唯一主动作来源;旧 stage 的
|
||||
# match_inventory/regenerate_excel 仅作兼容回退。
|
||||
gate_action = str((old_gate or {}).get('next_action_code') or '').strip()
|
||||
gate_action_alias = {
|
||||
'regenerate_excel_artifact': 'regenerate_excel',
|
||||
}.get(gate_action, gate_action)
|
||||
if gate_action_alias in SHIPPING_PROCESSING_ACTION_INTENTS and user_status in {
|
||||
'retryable', 'waiting_human', 'running',
|
||||
}:
|
||||
return {
|
||||
'code': gate_action_alias,
|
||||
'i18n_key': _resolve_action_i18n_key(gate_action_alias),
|
||||
'parameters': {},
|
||||
}
|
||||
# 1) blocking_reason 非 None
|
||||
if blocking_reason is not None:
|
||||
bcode = str(blocking_reason.get('code') or '').strip()
|
||||
@@ -903,6 +1008,7 @@ def apply_user_projection_fields(
|
||||
code = 'open_order_review'
|
||||
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
|
||||
# 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底
|
||||
available_actions = payload.get('available_actions')
|
||||
if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions:
|
||||
code = 'reconcile_and_progress'
|
||||
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
|
||||
@@ -937,6 +1043,27 @@ def apply_user_projection_fields(
|
||||
'upload_state': 'not_created',
|
||||
'switch_state': 'not_triggered',
|
||||
}
|
||||
# MVP 四库存里程碑是 Projection facts,不是第二套运行时 Gate 生命周期。
|
||||
# 仅依据正式 current_gate 的顺序和已投影事实派生,避免重新引入 APX 六 Gate。
|
||||
gate_code = str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
|
||||
gate_order = {
|
||||
'inventory_source_routing': 0,
|
||||
'inventory_preparation': 1,
|
||||
'inventory_field_mapping': 2,
|
||||
'inventory_matching': 3,
|
||||
'inventory_sufficiency': 4,
|
||||
'excel_readiness': 5,
|
||||
'artifact_generation': 6,
|
||||
'manual_upload_handoff': 7,
|
||||
'upload_receipt_recorded': 8,
|
||||
}
|
||||
current_order = gate_order.get(gate_code)
|
||||
facts['inventory_milestones'] = {
|
||||
'candidates_calculated': 'completed' if current_order is not None and current_order >= 1 else 'pending',
|
||||
'candidates_frozen': 'completed' if current_order is not None and current_order >= 1 else 'pending',
|
||||
'snapshots_ready': 'completed' if current_order is not None and current_order >= 3 else 'pending',
|
||||
'matched': 'completed' if current_order is not None and current_order >= 4 else 'pending',
|
||||
}
|
||||
if order_task is not None:
|
||||
cand = getattr(order_task, 'candidate_source_codes_json', None)
|
||||
if isinstance(cand, list):
|
||||
@@ -954,6 +1081,32 @@ def apply_user_projection_fields(
|
||||
fms = step_payload.get('forced_match_source_code')
|
||||
if fms:
|
||||
facts['forced_match_source_code'] = str(fms).strip().upper()
|
||||
# 正式 OT 优先从 CandidateSet/LineMatch Projection 读取库存事实;旧
|
||||
# step_payload 仅作为尚未形成正式候选集的历史任务兼容回退。
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
project_inventory_candidate_facts,
|
||||
)
|
||||
candidate_facts = project_inventory_candidate_facts(notice)
|
||||
if candidate_facts.get('current_set') is not None:
|
||||
facts['candidate_set_id'] = candidate_facts.get('candidate_set_id')
|
||||
facts['candidate_set_version'] = candidate_facts.get('candidate_set_version')
|
||||
facts['candidate_set_status'] = candidate_facts.get('candidate_set_status')
|
||||
facts['candidate_source_codes'] = list(candidate_facts.get('candidate_source_codes') or [])
|
||||
facts['prepared_source_codes'] = list(candidate_facts.get('prepared_source_codes') or [])
|
||||
facts['pending_source_codes'] = list(candidate_facts.get('pending_source_codes') or [])
|
||||
facts['failed_source_codes'] = list(candidate_facts.get('failed_source_codes') or [])
|
||||
facts['source_attempts'] = dict(candidate_facts.get('source_attempts') or {})
|
||||
facts['line_resolutions'] = list(candidate_facts.get('line_resolutions') or [])
|
||||
elif candidate_facts.get('blocking_reason', {}).get('code') in {
|
||||
'inventory_candidate_version_stale',
|
||||
'inventory_candidate_out_of_scope',
|
||||
}:
|
||||
payload['projection_data_inconsistent'] = True
|
||||
except Exception: # noqa: BLE001
|
||||
# 结构化事实读取失败时交给最终 Projection invariant fail-closed;
|
||||
# 不使用旧 payload 拼装出可执行状态。
|
||||
payload['projection_data_inconsistent'] = True
|
||||
# P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。
|
||||
try:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
@@ -125,6 +125,9 @@ def _dispatch_legacy_orchestration(
|
||||
operator_id: int | None,
|
||||
inventory_mode: str = 'auto',
|
||||
line_scope_key: str | None = None,
|
||||
recovery_plan_id: int | None = None,
|
||||
recovery_attempt_id: int | None = None,
|
||||
resume_after_gate: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。
|
||||
@@ -209,6 +212,9 @@ def run_task_auto_progress(
|
||||
operator_id: int | None = None,
|
||||
inventory_mode: str = 'auto',
|
||||
line_scope_key: str | None = None,
|
||||
recovery_plan_id: int | None = None,
|
||||
recovery_attempt_id: int | None = None,
|
||||
resume_after_gate: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
唯一 AutoProgress Orchestrator Facade。
|
||||
@@ -232,6 +238,9 @@ def run_task_auto_progress(
|
||||
operator_id: 操作人 ID(系统触发则 None)。
|
||||
inventory_mode: 库存准备模式;用户显式重试传 retry_rpa,自动推进保持 auto。
|
||||
line_scope_key: 行级 scope 键;传了则仅对该行执行(例如 match_inventory_line),不传则整单推进。
|
||||
recovery_plan_id: 可选恢复计划 ID,用于关联本次 Gate 恢复执行。
|
||||
recovery_attempt_id: 可选恢复 Attempt ID,用于关联本次 Gate 恢复执行。
|
||||
resume_after_gate: 可选恢复后续 Gate 标识。
|
||||
|
||||
Returns:
|
||||
Tool 标准响应(status=running/needs_human/failed/completed + task + data);
|
||||
@@ -252,6 +261,9 @@ def run_task_auto_progress(
|
||||
submitted = submit_auto_progress(
|
||||
task=task, trigger=trigger, operator_id=operator_id,
|
||||
resume_gate_code=resume_gate_code, commit=True,
|
||||
recovery_plan_id=recovery_plan_id,
|
||||
recovery_attempt_id=recovery_attempt_id,
|
||||
resume_after_gate=resume_after_gate,
|
||||
)
|
||||
status = str(submitted.get('status') or 'queued')
|
||||
if status == 'queued':
|
||||
@@ -397,6 +409,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
idempotency_key=idempotency_key,
|
||||
resume_gate_code=None,
|
||||
operator_id=operator_id,
|
||||
recovery_plan_id=payload.get('recovery_plan_id'),
|
||||
recovery_attempt_id=payload.get('recovery_attempt_id'),
|
||||
resume_after_gate=payload.get('resume_after_gate'),
|
||||
)
|
||||
# 下方:_auto_progress_full 内部调用路径(直接执行完整串联,不再走 Orchestrator 外层)
|
||||
if not auto_progress_enabled():
|
||||
|
||||
@@ -317,8 +317,12 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str
|
||||
if not task or not task.export_file_path:
|
||||
return None
|
||||
from app.models import ShippingExportArtifact
|
||||
artifact = ShippingExportArtifact.query.filter_by(
|
||||
task_id=task.id, status='ready', file_path=task.export_file_path,
|
||||
# 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel;
|
||||
# 不能因履约完成将 status=uploaded 排除在下载解析之外。
|
||||
artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
|
||||
ShippingExportArtifact.file_path == task.export_file_path,
|
||||
).order_by(
|
||||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||||
).first()
|
||||
|
||||
@@ -462,7 +462,12 @@ def project_case_allowed_actions(
|
||||
if 'reconcile_and_progress' in actions:
|
||||
_others = [a for a in actions if a != 'reconcile_and_progress']
|
||||
actions = ['reconcile_and_progress', *_others]
|
||||
if llm_review_enabled() and 'edit_draft' in actions:
|
||||
try:
|
||||
llm_enabled = llm_review_enabled()
|
||||
except RuntimeError:
|
||||
# 纯投影合同和离线诊断没有 Flask 请求上下文;缺少运行时配置时按关闭处理。
|
||||
llm_enabled = False
|
||||
if llm_enabled and 'edit_draft' in actions:
|
||||
actions.append('request_llm_suggestion')
|
||||
return actions
|
||||
|
||||
@@ -591,7 +596,7 @@ def project_case_user_status(
|
||||
"""
|
||||
auto_status = str((automation or {}).get('status') or '').strip().lower()
|
||||
case_status = str(case.status or '').strip().lower()
|
||||
if case_status in {'confirmed'} and auto_status in {'completed', 'success'}:
|
||||
if auto_status in {'completed', 'success'}:
|
||||
return 'completed'
|
||||
if case_status in {'cancelled', 'superseded', 'non_order'}:
|
||||
return 'cancelled'
|
||||
|
||||
@@ -41,6 +41,15 @@ _TECH_RETRYABLE_CATEGORY_HINTS: frozenset[str] = frozenset({
|
||||
"lease_expired",
|
||||
})
|
||||
|
||||
# 库存 RPA Trigger 投递/领取失败属于技术暂态;不能被当作业务人工阻断,
|
||||
# 否则正式 OT 的 retryable 投影会变成 false,conversation retry 不会重新建 Trigger。
|
||||
_TECH_RETRYABLE_ERROR_CODES: frozenset[str] = frozenset({
|
||||
"trigger_not_claimed_missing",
|
||||
"trigger_not_claimed_timeout",
|
||||
"inventory_trigger_missing",
|
||||
"inventory_trigger_write_failed",
|
||||
})
|
||||
|
||||
# T3:业务阻断 → 推荐 UI 动作映射;未命中时 fallback 为 "open_order_review"
|
||||
BLOCKING_REASON_TO_ACTION_CODES: dict[str, str] = {
|
||||
"duplicate_decision_required": "adjudicate_duplicate",
|
||||
@@ -100,6 +109,9 @@ def is_tech_retryable_error(
|
||||
if normalized.startswith(prefix):
|
||||
return True
|
||||
|
||||
if normalized.lower() in _TECH_RETRYABLE_ERROR_CODES:
|
||||
return True
|
||||
|
||||
hint = str(category_hint or "").strip()
|
||||
if hint and hint in _TECH_RETRYABLE_CATEGORY_HINTS:
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
services/shipping_notice/recovery_invalidation_service.py
|
||||
|
||||
用途:按恢复动作精确失效库存下游事实及正式 Gate。
|
||||
依赖:ShippingProcessExecution/Gate、库存快照链接、行级 Match、Verification、Artifact、UploadAttempt。
|
||||
逻辑:只标记失效,不删除、不覆盖历史事实;所有变更在调用方事务内完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryMapping,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingProcessExecution,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import invalidate_downstream_gates
|
||||
|
||||
|
||||
def invalidate_inventory_downstream(
|
||||
*, execution: ShippingProcessExecution, action_code: str, attempt_id: int | None = None,
|
||||
actor_id: int | str | None = None,
|
||||
) -> dict[str, list[int] | list[str]]:
|
||||
"""失效库存恢复受影响事实,并返回可审计的对象 ID。"""
|
||||
task_id = int(execution.task_id or 0)
|
||||
if not task_id:
|
||||
return {'gates': [], 'links': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
|
||||
now = datetime.utcnow()
|
||||
from app.models import ShippingNotice
|
||||
task = db.session.get(ShippingNotice, task_id)
|
||||
result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
|
||||
change_type = {
|
||||
'retry_inventory_from_preparation': 'inventory_file_changed',
|
||||
'retry_inventory_from_field_mapping': 'inventory_field_mapping_changed',
|
||||
'retry_inventory_from_matching': 'inventory_matching_changed',
|
||||
}.get(action_code, 'inventory_matching_changed')
|
||||
result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id)
|
||||
if action_code == 'retry_inventory_from_preparation':
|
||||
links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all()
|
||||
for link in links:
|
||||
link.is_active = False
|
||||
link.invalidated_at = now
|
||||
link.invalidated_by_attempt_id = attempt_id
|
||||
link.invalidation_reason = action_code
|
||||
result['links'].append(int(link.id))
|
||||
active_file_ids = [
|
||||
int(link.inventory_file_id)
|
||||
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all()
|
||||
if link.inventory_file_id
|
||||
]
|
||||
if action_code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'} and active_file_ids:
|
||||
mappings = ShippingInventoryMapping.query.filter(
|
||||
ShippingInventoryMapping.inventory_file_id.in_(active_file_ids),
|
||||
ShippingInventoryMapping.status == 'active',
|
||||
).with_for_update().all()
|
||||
for mapping in mappings:
|
||||
mapping.status = 'invalidated'
|
||||
result['mappings'].append(int(mapping.id))
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all()
|
||||
for row in matches:
|
||||
row.is_current = False
|
||||
row.invalidated_at = now
|
||||
row.invalidated_by_attempt_id = attempt_id
|
||||
row.invalidation_reason = action_code
|
||||
result['matches'].append(int(row.id))
|
||||
verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all()
|
||||
for verification in verifications:
|
||||
verification.status = 'superseded'
|
||||
result['verifications'].append(int(verification.id))
|
||||
artifacts = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task_id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
|
||||
).with_for_update().all()
|
||||
for artifact in artifacts:
|
||||
artifact.status = 'superseded'
|
||||
result['artifacts'].append(int(artifact.id))
|
||||
uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter(
|
||||
ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}),
|
||||
).with_for_update().all()
|
||||
for upload in uploads:
|
||||
upload.invalidated_at = now
|
||||
upload.invalidation_reason = action_code
|
||||
result['uploads'].append(int(upload.id))
|
||||
if task is not None and action_code == 'retry_inventory_from_preparation':
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
db.session.flush()
|
||||
return result
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
services/shipping_notice/recovery_plan_contract.py
|
||||
|
||||
用途:定义跨阶段恢复动作的服务端白名单及其失效/恢复边界。
|
||||
依赖:process_gate_contract 的正式 Gate 编码。
|
||||
逻辑:RecoveryPlan 服务和 Projection 共同消费此纯数据合同,客户端不能提交目标 Gate。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
RECOVERY_PLAN_ACTIONS: dict[str, dict[str, dict[str, Any]]] = {
|
||||
'inventory_matching': {
|
||||
'retry_inventory_from_preparation': {
|
||||
'target_gate': 'inventory_preparation',
|
||||
'resume_after_gate': 'inventory_matching',
|
||||
'allowed_intermediate_gates': ('inventory_field_mapping',),
|
||||
'invalidate_change_type': 'inventory_file_changed',
|
||||
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
'retry_inventory_from_field_mapping': {
|
||||
'target_gate': 'inventory_field_mapping',
|
||||
'resume_after_gate': 'inventory_matching',
|
||||
'allowed_intermediate_gates': (),
|
||||
'invalidate_change_type': 'inventory_field_mapping_changed',
|
||||
'invalidates': ('inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
},
|
||||
# 库存有缺口时仍由 Gate 16 负责恢复入口;数量事实只读,恢复动作回到正式库存链路。
|
||||
'inventory_sufficiency': {
|
||||
'retry_inventory_from_preparation': {
|
||||
'target_gate': 'inventory_preparation',
|
||||
'resume_after_gate': 'inventory_sufficiency',
|
||||
'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'),
|
||||
'invalidate_change_type': 'inventory_file_changed',
|
||||
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
'retry_inventory_from_matching': {
|
||||
'target_gate': 'inventory_matching',
|
||||
'resume_after_gate': 'inventory_sufficiency',
|
||||
'allowed_intermediate_gates': (),
|
||||
'invalidate_change_type': 'inventory_matching_changed',
|
||||
'invalidates': ('inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def recovery_plan_for_action(*, current_gate: str, action_code: str) -> dict[str, Any] | None:
|
||||
"""读取当前 Gate 下的跨阶段恢复计划定义;未知组合返回 None。"""
|
||||
item = RECOVERY_PLAN_ACTIONS.get(str(current_gate or '').strip(), {}).get(str(action_code or '').strip())
|
||||
return dict(item) if isinstance(item, dict) else None
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
services/shipping_notice/recovery_plan_service.py
|
||||
|
||||
用途:创建并绑定跨阶段 RecoveryPlan,保证 Gate/Execution 锁、幂等和终态保护统一。
|
||||
依赖:ShippingProcessRecoveryPlan、process_gate_contract、recovery_plan_contract、db。
|
||||
逻辑:只创建白名单计划;Gate Attempt 由既有 process_gate_service 创建后回填关联。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, ShippingProcessRecoveryPlan
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
|
||||
|
||||
_TERMINAL_EXECUTION_STATUSES = frozenset({'completed', 'cancelled', 'superseded'})
|
||||
|
||||
|
||||
def create_recovery_plan(
|
||||
*, execution: ShippingProcessExecution, gate: ShippingProcessGate, action_code: str,
|
||||
idempotency_key: str, actor_type: str, actor_id: int | str | None,
|
||||
operation_id: str | None = None,
|
||||
) -> tuple[ShippingProcessRecoveryPlan, dict[str, Any]]:
|
||||
"""校验并创建跨阶段恢复计划;同幂等键返回原计划。"""
|
||||
definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action_code)
|
||||
if definition is None:
|
||||
raise ValidationError(
|
||||
'Recovery target is not allowed for current gate',
|
||||
code='SHIPPING.RECOVERY_TARGET_INVALID',
|
||||
details={'current_gate': gate.gate_code, 'action_code': action_code},
|
||||
)
|
||||
if execution.status in _TERMINAL_EXECUTION_STATUSES:
|
||||
raise ConflictError(
|
||||
'Recovery is not allowed on terminal execution',
|
||||
code='SHIPPING.RECOVERY_NOT_ALLOWED_ON_TERMINAL',
|
||||
details={'execution_no': execution.execution_no, 'status': execution.status},
|
||||
)
|
||||
key = str(idempotency_key or '').strip()
|
||||
if not key:
|
||||
raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED')
|
||||
replay = ShippingProcessRecoveryPlan.query.filter_by(
|
||||
execution_id=int(execution.id), idempotency_key=key,
|
||||
).first()
|
||||
if replay is not None:
|
||||
return replay, definition
|
||||
active_plan = ShippingProcessRecoveryPlan.query.filter(
|
||||
ShippingProcessRecoveryPlan.execution_id == int(execution.id),
|
||||
ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}),
|
||||
).with_for_update().first()
|
||||
if active_plan is not None:
|
||||
raise ConflictError(
|
||||
'Another recovery plan is active for this execution',
|
||||
code='SHIPPING.RECOVERY_PLAN_CONFLICT',
|
||||
details={'execution_no': execution.execution_no, 'plan_no': active_plan.plan_no},
|
||||
)
|
||||
plan = ShippingProcessRecoveryPlan(
|
||||
plan_no=f'RCP-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{int(execution.id)}-{str(idempotency_key)[-8:]}',
|
||||
execution_id=int(execution.id), current_gate=gate.gate_code,
|
||||
action_code=str(action_code), target_gate=str(definition['target_gate']),
|
||||
resume_after_gate=definition.get('resume_after_gate'), status='planned',
|
||||
invalidation_plan_json={
|
||||
'change_type': definition.get('invalidate_change_type'),
|
||||
'invalidates': list(definition.get('invalidates') or ()),
|
||||
'allowed_intermediate_gates': list(definition.get('allowed_intermediate_gates') or ()),
|
||||
}, idempotency_key=key, expected_gate_version=int(gate.evaluation_version),
|
||||
actor_type=str(actor_type or 'system'), actor_id=str(actor_id) if actor_id is not None else None,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
return plan, definition
|
||||
|
||||
|
||||
def bind_recovery_attempt(*, plan: ShippingProcessRecoveryPlan, attempt_id: int) -> None:
|
||||
"""把 Gate Attempt 纳入 RecoveryPlan;不提交事务。"""
|
||||
plan.recovery_attempt_id = int(attempt_id)
|
||||
attempt = db.session.get(ShippingProcessGateAttempt, int(attempt_id))
|
||||
if attempt is not None:
|
||||
attempt.recovery_plan_id = int(plan.id)
|
||||
plan.status = 'queued'
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def complete_recovery_plan_for_attempt(
|
||||
*, plan: ShippingProcessRecoveryPlan, outcome: str, now: datetime | None = None,
|
||||
error_code: str | None = None, error_summary: str | None = None,
|
||||
business_result_code: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将 RecoveryPlan 与绑定 Attempt 的执行结果原子收口。
|
||||
|
||||
核心逻辑:使用当前库存重新匹配后若仍有缺口,说明恢复动作本身已成功,
|
||||
只是正式流程重新停在库存满足性人工复核;该计划必须终态完成,不能以
|
||||
``waiting_manual`` 长期占用 Execution,阻塞用户再次选择其他恢复方式。
|
||||
"""
|
||||
status_by_outcome = {
|
||||
'passed': 'succeeded',
|
||||
'waiting_external': 'waiting_external',
|
||||
'blocked_manual': 'waiting_manual',
|
||||
'blocked_retryable': 'failed',
|
||||
'failed_terminal': 'failed',
|
||||
}
|
||||
resolved_outcome = str(outcome)
|
||||
rematch_reached_shortage_review = (
|
||||
resolved_outcome == 'blocked_manual'
|
||||
and str(plan.action_code or '') == 'retry_inventory_from_matching'
|
||||
and str(plan.resume_after_gate or '') == 'inventory_sufficiency'
|
||||
and str(business_result_code or '') == 'inventory_shortage_review_required'
|
||||
)
|
||||
plan.status = (
|
||||
'succeeded'
|
||||
if rematch_reached_shortage_review
|
||||
else status_by_outcome.get(resolved_outcome, 'failed')
|
||||
)
|
||||
plan.failure_code = str(error_code)[:64] if error_code else None
|
||||
plan.failure_detail_json = ({'message': str(error_summary)[:500]} if error_summary else None)
|
||||
finished_at = now or datetime.utcnow()
|
||||
plan.started_at = plan.started_at or finished_at
|
||||
if plan.status in {'succeeded', 'failed', 'cancelled'}:
|
||||
plan.completed_at = finished_at
|
||||
db.session.flush()
|
||||
@@ -15,6 +15,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def _runtime_summary(mode: str) -> dict[str, str | bool]:
|
||||
@@ -153,9 +154,14 @@ def write_inventory_export_batch_trigger(
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
}
|
||||
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
|
||||
for identity_key in ("task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", "expected_warehouse_id", "lease_token"):
|
||||
for identity_key in (
|
||||
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
|
||||
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
|
||||
):
|
||||
if source.get(identity_key) is not None:
|
||||
item[identity_key] = source[identity_key]
|
||||
if not item.get('callback_id') and item.get('source_run_no'):
|
||||
item['callback_id'] = f"{item['source_run_no']}:C1"
|
||||
inventory_sources.append(item)
|
||||
if not inventory_sources:
|
||||
return None
|
||||
@@ -163,6 +169,7 @@ def write_inventory_export_batch_trigger(
|
||||
body = {
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
|
||||
"trigger_type": "scheduled",
|
||||
@@ -194,7 +201,8 @@ def write_inventory_export_trigger_for_task(
|
||||
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
|
||||
|
||||
核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。
|
||||
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
|
||||
不再生成 legacy inventory_export trigger。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
@@ -211,11 +219,18 @@ def write_inventory_export_trigger_for_task(
|
||||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||||
source_item = dict(rpa_source)
|
||||
source_item.update({
|
||||
"callback_id": body.get("callback_id") or (
|
||||
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
|
||||
),
|
||||
"task_no": task_no,
|
||||
"attempt_no": body.get("attempt_no"),
|
||||
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
|
||||
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
|
||||
"attempt_no": body.get("attempt_no") or body.get("attempt"),
|
||||
"source_run_no": body.get("source_run_no"),
|
||||
"candidate_set_id": body.get("candidate_set_id"),
|
||||
"candidate_set_version": body.get("candidate_set_version"),
|
||||
"execution_id": body.get("execution_id"),
|
||||
"gate_id": body.get("gate_id"),
|
||||
"expected_warehouse_id": body.get("expected_warehouse_id"),
|
||||
"lease_token": body.get("lease_token"),
|
||||
})
|
||||
@@ -229,12 +244,9 @@ def write_inventory_export_trigger_for_task(
|
||||
**body,
|
||||
},
|
||||
)
|
||||
return write_inventory_export_trigger(
|
||||
task_no,
|
||||
{
|
||||
"rpa_inventory_source": rpa_source,
|
||||
**body,
|
||||
},
|
||||
raise ValidationError(
|
||||
'shipping inventory RPA v2 batch trigger is required',
|
||||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -764,15 +764,35 @@ def _order_task_current_gate(
|
||||
Returns:
|
||||
ProcessGateSummary 形状 dict;无需门禁时 None。
|
||||
"""
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
# Child OT 必须先按自身 Candidate 找 Case;仅按 run_id 取最新 Case 会把
|
||||
# 多 PDF 的子订单阶段错误绑定到根 PDF。
|
||||
open_case = None
|
||||
is_child_order_task = bool(
|
||||
order_task is not None
|
||||
and getattr(order_task, 'candidate_id', None)
|
||||
and str(getattr(order_task, 'task_no', '') or '').strip()
|
||||
!= str(getattr(run, 'user_task_no', '') or '').strip()
|
||||
)
|
||||
if is_child_order_task:
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is None:
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is not None:
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_projection import (
|
||||
@@ -786,7 +806,7 @@ def _order_task_current_gate(
|
||||
)
|
||||
if execution is not None:
|
||||
summary = project_user_gate_summary(execution)
|
||||
blocking = summary.get('current_blocking_gate')
|
||||
blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
if isinstance(blocking, dict) and blocking.get('gate_code'):
|
||||
return {
|
||||
'gate_code': str(blocking.get('gate_code') or ''),
|
||||
@@ -794,7 +814,6 @@ def _order_task_current_gate(
|
||||
'next_action_code': (
|
||||
summary.get('next_action_code')
|
||||
or blocking.get('next_action_code')
|
||||
or 'open_order_review'
|
||||
),
|
||||
'blocking_reason_code': (
|
||||
summary.get('blocking_reason_code')
|
||||
@@ -825,7 +844,7 @@ def _order_task_current_gate(
|
||||
)
|
||||
if execution is not None:
|
||||
summary = project_user_gate_summary(execution)
|
||||
blocking = summary.get('current_blocking_gate')
|
||||
blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
if isinstance(blocking, dict) and blocking.get('gate_code'):
|
||||
return {
|
||||
'gate_code': str(blocking.get('gate_code') or ''),
|
||||
@@ -833,7 +852,6 @@ def _order_task_current_gate(
|
||||
'next_action_code': (
|
||||
summary.get('next_action_code')
|
||||
or blocking.get('next_action_code')
|
||||
or 'open_fulfillment'
|
||||
),
|
||||
'blocking_reason_code': (
|
||||
summary.get('blocking_reason_code')
|
||||
@@ -985,6 +1003,7 @@ def _project_order_task_work_item(
|
||||
stage = map_run_to_processing_stage(run, source_type=source_type)
|
||||
# [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。
|
||||
stage_label_key = None
|
||||
notice_for_stage = None
|
||||
if order_task.shipping_notice_id:
|
||||
notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
|
||||
if notice_for_stage is not None:
|
||||
@@ -1007,6 +1026,13 @@ def _project_order_task_work_item(
|
||||
str(run.status or ''),
|
||||
stage=stage,
|
||||
)
|
||||
# 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为
|
||||
# automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。
|
||||
notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else ''
|
||||
if notice_process_status in {'uploaded', 'closed', 'completed'}:
|
||||
status = 'completed'
|
||||
stage = 'completed'
|
||||
stage_label_key = 'completed'
|
||||
# [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。
|
||||
if status == 'completed' and stage != 'completed':
|
||||
status = derivation_status_for_extraction_run('completed', stage=stage)
|
||||
@@ -1043,15 +1069,27 @@ def _project_order_task_work_item(
|
||||
# [P0] 深链订单处理工作台需要 run_no / case_no;禁止前端合成 OT 时丢失。
|
||||
run_no = str(getattr(run, 'run_no', None) or '').strip() or None
|
||||
case_no = None
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
open_case = None
|
||||
if order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is None:
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is not None:
|
||||
case_no = str(getattr(open_case, 'case_no', None) or '').strip() or None
|
||||
elif order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
@@ -1148,14 +1186,17 @@ def _project_order_task_work_item(
|
||||
post_confirm=post_confirm_snapshot,
|
||||
is_admin=False,
|
||||
)
|
||||
formal_gate_projection = isinstance(payload.get('current_gate'), dict) and bool(
|
||||
str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
|
||||
)
|
||||
# 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable
|
||||
if isinstance(bundle.get('user_status'), str):
|
||||
payload['user_status'] = bundle['user_status']
|
||||
if isinstance(bundle.get('blocking_reason'), dict):
|
||||
payload['blocking_reason'] = dict(bundle['blocking_reason'])
|
||||
if isinstance(bundle.get('primary_action'), dict):
|
||||
if isinstance(bundle.get('primary_action'), dict) and not formal_gate_projection:
|
||||
payload['primary_action'] = dict(bundle['primary_action'])
|
||||
if isinstance(bundle.get('current_gate'), dict):
|
||||
if isinstance(bundle.get('current_gate'), dict) and not formal_gate_projection:
|
||||
current_gate = dict(payload.get('current_gate') or {})
|
||||
current_gate.update(bundle['current_gate'])
|
||||
payload['current_gate'] = current_gate
|
||||
@@ -1173,32 +1214,58 @@ def _project_order_task_work_item(
|
||||
if retry_flag or str(payload.get('user_status') or '') == 'retryable':
|
||||
payload['retryable'] = True
|
||||
except Exception: # noqa: BLE001
|
||||
# 只读投影失败不阻断列表输出(fail-closed 兜底 invariants 结果)
|
||||
pass
|
||||
# Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到
|
||||
# 旧 checkpoint/notice 字段,避免前端展示可继续执行的过时动作。
|
||||
payload['user_status'] = 'waiting_human'
|
||||
payload['retryable'] = False
|
||||
payload['primary_action'] = None
|
||||
payload['available_actions'] = []
|
||||
payload['blocking_reason'] = {
|
||||
'code': 'projection_data_inconsistent',
|
||||
'message': '处理状态暂时无法确认,请刷新后重试',
|
||||
}
|
||||
|
||||
# 题4A:注入 inventory_preparation 结构化字段(题7A:区分 failed/exhausted_sources);
|
||||
# 仅当 inventory 阶段或更早、且已挂正式 Notice 时才填充;其他阶段填 None 避免误导。
|
||||
inventory_preparation = None
|
||||
if notice is not None:
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
from app.models import ShippingInventoryPreparationAttempt
|
||||
|
||||
snapshot_src = summarize_inventory_rpa_latest_attempts(notice, include_gate_status=True)
|
||||
required_sources = list(snapshot_src.get('required_frozen_sources') or [])
|
||||
prepared_sources = list(snapshot_src.get('prepared_source_codes') or [])
|
||||
pending_sources = list(snapshot_src.get('pending_source_codes') or [])
|
||||
failed_sources = list(snapshot_src.get('failed_source_codes') or [])
|
||||
exhausted_sources = list(snapshot_src.get('exhausted_source_codes') or [])
|
||||
active_attempt_count = int(snapshot_src.get('active_attempt_count') or 0)
|
||||
latest_attempts = dict(snapshot_src.get('latest_attempts') or {})
|
||||
preparation = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
.filter_by(task_id=int(notice.id))
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
source_attempts = list(getattr(preparation, 'source_attempts', []) or []) if preparation else []
|
||||
required_sources = [str(row.source_code) for row in source_attempts]
|
||||
prepared_sources = [str(row.source_code) for row in source_attempts if row.status in {'ready', 'reusable'}]
|
||||
pending_sources = [str(row.source_code) for row in source_attempts if row.status in {'queued', 'running', 'waiting'}]
|
||||
failed_sources = [str(row.source_code) for row in source_attempts if row.status == 'failed']
|
||||
exhausted_sources: list[str] = []
|
||||
active_attempt_count = 1 if preparation and preparation.status in {'queued', 'running', 'waiting_external'} else 0
|
||||
latest_attempts = {
|
||||
str(row.source_code): {
|
||||
'attempt_no': int(preparation.attempt_no),
|
||||
'status': row.status,
|
||||
'rpa_attempt_id': row.rpa_attempt_id,
|
||||
'inventory_file_id': row.inventory_file_id,
|
||||
}
|
||||
for row in source_attempts
|
||||
}
|
||||
# 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared)
|
||||
if notice.inventory_lines_json and notice.inventory_snapshot_id:
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
|
||||
if active_inventory_lines_for_task(notice) and notice.inventory_snapshot_id:
|
||||
for code in required_sources:
|
||||
if code and code not in prepared_sources and code not in pending_sources:
|
||||
prepared_sources.append(code)
|
||||
inventory_preparation = {
|
||||
'attempt_id': int(preparation.id) if preparation else None,
|
||||
'attempt_no': int(preparation.attempt_no) if preparation else None,
|
||||
'status': preparation.status if preparation else None,
|
||||
'required_sources': required_sources,
|
||||
'prepared_sources': prepared_sources,
|
||||
'pending_sources': pending_sources,
|
||||
@@ -1206,10 +1273,16 @@ def _project_order_task_work_item(
|
||||
'exhausted_sources': exhausted_sources,
|
||||
'active_attempt_count': active_attempt_count,
|
||||
'latest_attempts': latest_attempts,
|
||||
'gate_attempt_active': bool(snapshot_src.get('gate_attempt_active')),
|
||||
'source_attempts': latest_attempts,
|
||||
'gate_attempt_active': active_attempt_count > 0,
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
# 关键准备事实读取失败时 fail-closed;禁止静默回退到旧字段拼装出可执行状态。
|
||||
inventory_preparation = None
|
||||
payload['projection_data_inconsistent'] = True
|
||||
# PreparationAttempt 读取发生在首次用户态归一化之后;立即重新应用
|
||||
# fail-closed 规则,防止异常分支保留旧 primary_action/available_actions。
|
||||
payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task)
|
||||
payload['inventory_preparation'] = inventory_preparation
|
||||
|
||||
# 题4A & 题7A:根据 inventory_preparation 统一折叠 retryable(仅当没有 pending/running + (failed or exhausted) 时,保证可重试为 true;
|
||||
|
||||
@@ -61,6 +61,7 @@ def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str, str] | None:
|
||||
row.get('reservation_id') or row.get('Reservation ID') or row.get('reservation')
|
||||
)
|
||||
part = _norm_part(row.get('part_number') or row.get('Part Number') or row.get('mpn') or row.get('sku'))
|
||||
# 单位只有在 Profile 显式配置并被标准化进快照时才参与;默认空单位不阻断匹配。
|
||||
unit = _norm_unit(row.get('uom') or row.get('unit') or row.get('UOM') or row.get('Unit'))
|
||||
if not reservation or not part:
|
||||
return None
|
||||
@@ -314,6 +315,7 @@ def match_order_lines_across_candidates(
|
||||
resolutions: list[dict[str, Any]] = []
|
||||
has_ok = False
|
||||
has_block = False
|
||||
has_partial = False
|
||||
|
||||
for index, line in enumerate(order_lines):
|
||||
part = _norm_part(line.get('part_number') or line.get('__display_part_number'))
|
||||
@@ -344,7 +346,7 @@ def match_order_lines_across_candidates(
|
||||
for key in buckets
|
||||
if key[0] == (effective or '')
|
||||
and key[1] == part
|
||||
and key[2] == unit
|
||||
and (not unit or not key[2] or key[2] == unit)
|
||||
] if effective and part else []
|
||||
# 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。
|
||||
# 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。
|
||||
@@ -462,6 +464,7 @@ def match_order_lines_across_candidates(
|
||||
'resolved_inventory_source_code': hit['source_code'],
|
||||
}
|
||||
has_block = True
|
||||
has_partial = available > 0
|
||||
|
||||
line_results.append(result)
|
||||
resolutions.append({
|
||||
@@ -486,7 +489,7 @@ def match_order_lines_across_candidates(
|
||||
if not order_lines:
|
||||
match_status = 'unfulfillable'
|
||||
elif has_block:
|
||||
match_status = 'unfulfillable' if not has_ok else 'partial'
|
||||
match_status = 'partial' if (has_ok or has_partial) else 'unfulfillable'
|
||||
else:
|
||||
match_status = 'fulfillable'
|
||||
|
||||
|
||||
@@ -41,6 +41,66 @@ PH_UPLOAD_PENDING = 'upload_rpa_pending'
|
||||
PH_UPLOAD_FAILED = 'upload_rpa_failed'
|
||||
|
||||
|
||||
def _request_formal_gate_action(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
action_code: str,
|
||||
user_id: int,
|
||||
idempotency_key: str,
|
||||
trigger: str,
|
||||
line_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""将外部重试意图提交给正式 20-Gate Recovery/ProcessGate 编排。
|
||||
|
||||
外部入口只负责定位当前正式 Gate 和动作;库存准备、匹配等旧函数仅允许
|
||||
由 ``process_gate_executor`` 通过内部分派标记调用。
|
||||
"""
|
||||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||||
from app.services.shipping_notice.process_gate_recovery_service import request_gate_action
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
execution = None
|
||||
current_id = getattr(task, 'active_process_execution_id', None)
|
||||
if current_id:
|
||||
execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first()
|
||||
if execution is None:
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=int(task.id), actor_type='user', actor_id=int(user_id),
|
||||
start_gate_code=determine_formal_start_gate(task),
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.flush()
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code=str(execution.current_gate_code or '').strip(),
|
||||
).first()
|
||||
if gate is None:
|
||||
raise ValidationError('Current formal process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
|
||||
requested = str(action_code or '').strip()
|
||||
if requested == 'retry_inventory_from_matching' and gate.gate_code != 'inventory_sufficiency':
|
||||
requested = 'retry_inventory_matching'
|
||||
payload: dict[str, Any] = {'trigger': trigger}
|
||||
if line_key:
|
||||
payload['line_key'] = str(line_key)
|
||||
result = request_gate_action(
|
||||
execution_no=str(execution.execution_no), gate_code=str(gate.gate_code),
|
||||
action_code=requested, expected_gate_version=int(gate.evaluation_version),
|
||||
idempotency_key=str(idempotency_key), actor_type='user', actor_id=int(user_id),
|
||||
payload=payload,
|
||||
)
|
||||
return {
|
||||
'status': 'running' if result.get('dispatch') in {'async_job', 'sync'} else 'failed',
|
||||
'action': action_code,
|
||||
'task_id': task.task_no,
|
||||
'job_id': result.get('job_id'),
|
||||
'attempt_id': (result.get('attempt') or {}).get('id'),
|
||||
'execution_no': result.get('execution_no'),
|
||||
'gate_code': result.get('gate_code'),
|
||||
'message': '已提交正式 20-Gate 恢复动作',
|
||||
}
|
||||
|
||||
|
||||
def retry_task_with_decision(
|
||||
*,
|
||||
task_no: str,
|
||||
@@ -219,6 +279,17 @@ def _decide(
|
||||
'retryable': False,
|
||||
'reason_code': 'already_running',
|
||||
}
|
||||
latest_statuses = {
|
||||
str(item.get('status') or '').strip().lower()
|
||||
for item in (active.get('latest_attempts') or {}).values()
|
||||
}
|
||||
if scope != 'line' and pending == PH_RPA_PENDING and latest_statuses <= {'', 'not_started'}:
|
||||
return {
|
||||
'action': ACTION_NOOP,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'already_running',
|
||||
}
|
||||
if pending == PH_UPLOAD_FAILED:
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
@@ -360,13 +431,20 @@ def _decide_for_line(
|
||||
inventory_rpa_running=line_running_flag,
|
||||
)
|
||||
user_status = str(view.get('user_line_status') or '')
|
||||
if user_status in {'shortage', 'source_conflict'}:
|
||||
if user_status == 'source_conflict':
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
'status': STATUS_NEEDS_HUMAN,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_shortage' if user_status == 'shortage' else 'inventory_source_conflict',
|
||||
}
|
||||
if user_status == 'shortage':
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
'status': STATUS_NEEDS_HUMAN,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_shortage',
|
||||
}
|
||||
if not project_line_retryable(
|
||||
inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []),
|
||||
user_line_status=user_status,
|
||||
@@ -459,10 +537,10 @@ def _execute(
|
||||
adjudicate_and_apply_inventory_source,
|
||||
ensure_inventory_source_review_state,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
action = str(decided.get('action') or ACTION_NOOP)
|
||||
# 所有重试动作(含库存匹配 REMATCH)共用同一触发来源;不能只在 FETCH 分支内初始化。
|
||||
trigger_norm = str(trigger or '').strip().lower() or 'user_retry'
|
||||
base_kwargs = {
|
||||
'task': task,
|
||||
'decision_version': decision_version,
|
||||
@@ -510,83 +588,58 @@ def _execute(
|
||||
action = ACTION_FETCH_INVENTORY
|
||||
|
||||
if action == ACTION_FETCH_INVENTORY:
|
||||
# 题1C:按调用来源分流。
|
||||
# user_retry / user_line_retry:直接 mode='retry_rpa',显式重试无论 auto 是否已 exhausted 都开新 Attempt。
|
||||
# conversation_retry / system_auto_progress 等:先 mode='auto' 复用快照,失败再 mode='retry_rpa' 兜底。
|
||||
trigger_norm = str(trigger or '').strip().lower()
|
||||
user_explicit = trigger_norm in {'user_retry', 'user_line_retry'}
|
||||
if not user_explicit:
|
||||
reused = ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
'trigger': trigger_norm,
|
||||
})
|
||||
if str((reused or {}).get('status') or '') in {'ok', 'completed'}:
|
||||
if continue_auto_progress:
|
||||
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
|
||||
return _map_tool_result(
|
||||
reused,
|
||||
action=ACTION_FETCH_INVENTORY,
|
||||
base_kwargs=base_kwargs,
|
||||
message='已复用库存快照',
|
||||
# 库存 RPA 的正式前置事实是订单快照。历史任务可能已完成解析但未成功冻结,
|
||||
# 会话重试必须先补做一次冻结;冻结门禁失败时返回 needs_human,禁止伪造 Trigger。
|
||||
if not getattr(task, 'order_snapshot_id', None) and isinstance(task, ShippingNotice):
|
||||
try:
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(user_id),
|
||||
expected_order_data_version=decision_version,
|
||||
freeze_mode='manual',
|
||||
)
|
||||
fetched = ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'retry_rpa',
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
'trigger': trigger_norm,
|
||||
})
|
||||
return _map_tool_result(
|
||||
fetched,
|
||||
action=ACTION_FETCH_INVENTORY,
|
||||
base_kwargs={
|
||||
**base_kwargs,
|
||||
'snapshot_id': getattr(task, 'inventory_snapshot_id', None),
|
||||
},
|
||||
message='已提交库存获取',
|
||||
db.session.flush()
|
||||
except AppError as freeze_err:
|
||||
return _result_payload(
|
||||
action=ACTION_NEEDS_HUMAN,
|
||||
status=STATUS_NEEDS_HUMAN,
|
||||
retryable=False,
|
||||
reason_code=str(getattr(freeze_err, 'code', None) or 'order_freeze_not_ready'),
|
||||
message='订单快照尚未冻结,无法进入库存 RPA。',
|
||||
**base_kwargs,
|
||||
)
|
||||
formal = _request_formal_gate_action(
|
||||
task=task,
|
||||
action_code='retry_inventory_preparation',
|
||||
user_id=int(user_id),
|
||||
idempotency_key=idempotency_key,
|
||||
trigger=trigger_norm,
|
||||
line_key=line_key,
|
||||
)
|
||||
return _map_tool_result(formal, action=ACTION_FETCH_INVENTORY, base_kwargs=base_kwargs, message='已提交库存获取')
|
||||
|
||||
if action == ACTION_REMATCH:
|
||||
# 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行;
|
||||
# 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。
|
||||
norm_line_key = str(line_key or '').strip()
|
||||
if norm_line_key:
|
||||
matched = shipping_tools.match_inventory_line(
|
||||
{
|
||||
'task_id': task.task_no,
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
'trigger': trigger_norm,
|
||||
},
|
||||
line_key=norm_line_key,
|
||||
)
|
||||
else:
|
||||
matched = shipping_tools.match_inventory({
|
||||
'task_id': task.task_no,
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
'trigger': trigger_norm,
|
||||
})
|
||||
mapped = _map_tool_result(
|
||||
matched,
|
||||
action=ACTION_REMATCH,
|
||||
base_kwargs=base_kwargs,
|
||||
message='已提交库存匹配',
|
||||
formal = _request_formal_gate_action(
|
||||
task=task,
|
||||
action_code='retry_inventory_from_matching',
|
||||
user_id=int(user_id),
|
||||
idempotency_key=idempotency_key,
|
||||
trigger=trigger_norm,
|
||||
line_key=norm_line_key or None,
|
||||
)
|
||||
if continue_auto_progress and mapped.get('status') == STATUS_COMPLETED:
|
||||
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
|
||||
return mapped
|
||||
return _map_tool_result(formal, action=ACTION_REMATCH, base_kwargs=base_kwargs, message='已提交库存匹配')
|
||||
|
||||
# ACTION_AUTO_PROGRESS 或 continue
|
||||
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
|
||||
except AppError as err:
|
||||
# 下游 flush/写库失败会使 PostgreSQL 事务进入 aborted;必须先清理,
|
||||
# 才能让调用方继续写本次失败决策审计。
|
||||
db.session.rollback()
|
||||
return _result_payload(
|
||||
action=ACTION_FAILED,
|
||||
status=STATUS_FAILED,
|
||||
@@ -597,6 +650,9 @@ def _execute(
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action)
|
||||
# 同上:避免后续 _audit_decision 查询审计哈希链时触发
|
||||
# InFailedSqlTransaction,掩盖真正的业务失败。
|
||||
db.session.rollback()
|
||||
return _result_payload(
|
||||
action=ACTION_FAILED,
|
||||
status=STATUS_FAILED,
|
||||
@@ -641,22 +697,32 @@ def _map_tool_result(
|
||||
) -> dict[str, Any]:
|
||||
"""将既有 tool 响应映射为统一 Retry 结果。"""
|
||||
status_raw = str((tool_result or {}).get('status') or '').strip().lower()
|
||||
if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload'}:
|
||||
if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload', 'blocked_manual'}:
|
||||
return _result_payload(
|
||||
action=ACTION_NEEDS_HUMAN,
|
||||
status=STATUS_NEEDS_HUMAN,
|
||||
retryable=False,
|
||||
reason_code=str((tool_result or {}).get('error_code') or 'needs_human'),
|
||||
reason_code=str(
|
||||
(tool_result or {}).get('error_code')
|
||||
or (tool_result or {}).get('reason_code')
|
||||
or (tool_result or {}).get('blocking_reason_code')
|
||||
or 'needs_human'
|
||||
),
|
||||
message=str((tool_result or {}).get('message') or '当前需要人工处理'),
|
||||
job_id=(tool_result or {}).get('job_id'),
|
||||
**base_kwargs,
|
||||
)
|
||||
if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed'}:
|
||||
if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed', 'blocked_retryable'}:
|
||||
return _result_payload(
|
||||
action=ACTION_FAILED,
|
||||
status=STATUS_FAILED,
|
||||
retryable=True,
|
||||
reason_code=str((tool_result or {}).get('error_code') or status_raw),
|
||||
reason_code=str(
|
||||
(tool_result or {}).get('error_code')
|
||||
or (tool_result or {}).get('reason_code')
|
||||
or (tool_result or {}).get('blocking_reason_code')
|
||||
or status_raw
|
||||
),
|
||||
message=str((tool_result or {}).get('message') or '自动处理失败'),
|
||||
job_id=(tool_result or {}).get('job_id'),
|
||||
**base_kwargs,
|
||||
@@ -762,6 +828,7 @@ def summarize_inventory_rpa_latest_attempts(
|
||||
[STEP 4] 可选 include_gate_status:补充 Process Gate Attempt 的 queued/running。
|
||||
"""
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
@@ -789,7 +856,7 @@ def summarize_inventory_rpa_latest_attempts(
|
||||
|
||||
if task_no:
|
||||
# 先一次性查出 (task_no, source_code) → 最新 attempt
|
||||
rows = (
|
||||
query = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter(ShippingTaskInventoryRpaAttempt.task_no == task_no)
|
||||
.order_by(
|
||||
@@ -797,11 +864,15 @@ def summarize_inventory_rpa_latest_attempts(
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
|
||||
ShippingTaskInventoryRpaAttempt.id.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
# 轻量调用方可能只提供 first();正式 ORM 使用 all() 做一次批量读取。
|
||||
rows = query.all() if hasattr(query, 'all') else [query.first()]
|
||||
rows = [row for row in rows if row is not None]
|
||||
latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {}
|
||||
for row in rows:
|
||||
key = str(row.source_code or '').strip().upper() or None
|
||||
key = str(getattr(row, 'source_code', None) or '').strip().upper() or None
|
||||
if not key and len(required_frozen_sources) == 1:
|
||||
key = required_frozen_sources[0]
|
||||
if not key or key in latest_by_source:
|
||||
continue
|
||||
latest_by_source[key] = row
|
||||
@@ -822,11 +893,11 @@ def summarize_inventory_rpa_latest_attempts(
|
||||
continue
|
||||
st = str(att.status or '').strip().lower()
|
||||
latest_attempts[key] = {
|
||||
'attempt_no': int(att.attempt_no or 0),
|
||||
'run_no': str(att.run_no or '') or None,
|
||||
'attempt_no': int(getattr(att, 'attempt_no', 0) or 0),
|
||||
'run_no': str(getattr(att, 'run_no', '') or '') or None,
|
||||
'status': st,
|
||||
'error_code': str(att.error_code or '') or None,
|
||||
'error_message': str(att.error_message or '') or None,
|
||||
'error_code': str(getattr(att, 'error_code', '') or '') or None,
|
||||
'error_message': str(getattr(att, 'error_message', '') or '') or None,
|
||||
}
|
||||
if st in {'queued', 'running'}:
|
||||
pending.append(key)
|
||||
@@ -852,7 +923,9 @@ def summarize_inventory_rpa_latest_attempts(
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate.execution_id == ShippingProcessExecution.id,
|
||||
)
|
||||
.join(Job, Job.id == ShippingProcessGateAttempt.job_id)
|
||||
.filter(ShippingProcessGateAttempt.status.in_(('queued', 'running')))
|
||||
.filter(Job.status.in_(('queued', 'running')))
|
||||
.filter(ShippingProcessExecution.task_id == int(task_id))
|
||||
.limit(1)
|
||||
.first()
|
||||
|
||||
@@ -410,7 +410,13 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else []
|
||||
multi_block = bool(payload.get('multi_source_excel_block'))
|
||||
candidate_projection = project_inventory_candidate_facts(task)
|
||||
frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(task)
|
||||
frozen_codes = (
|
||||
list(candidate_projection.get('candidate_source_codes') or [])
|
||||
or list(
|
||||
(payload.get('line_inventory_candidates') or {}).get('source_codes') or []
|
||||
)
|
||||
or task_frozen_inventory_source_codes(task)
|
||||
)
|
||||
has_stp = (
|
||||
status in {'candidates_frozen', 'resolved'}
|
||||
or method.startswith('stp')
|
||||
@@ -436,6 +442,12 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
'part_number': item.get('part_number'),
|
||||
'resolved_inventory_source_code': item.get('resolved_inventory_source_code'),
|
||||
'inventory_file_no': item.get('inventory_file_no'),
|
||||
'inventory_file_sha256': item.get('inventory_file_sha256'),
|
||||
'inventory_row_index': item.get('inventory_row_index'),
|
||||
'match_attempt_id': item.get('match_attempt_id'),
|
||||
'required_qty': item.get('required_qty'),
|
||||
'matched_qty': item.get('matched_qty'),
|
||||
'shortage_qty': item.get('shortage_qty'),
|
||||
'inventory_row_ref': item.get('inventory_row_ref'),
|
||||
})
|
||||
|
||||
|
||||
@@ -50,13 +50,13 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
|
||||
if existing is not None:
|
||||
if existing.artifact_id != artifact.id:
|
||||
raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT')
|
||||
if existing.status == 'timed_out':
|
||||
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
|
||||
if existing.status in {'timed_out', 'unknown'}:
|
||||
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN')
|
||||
return existing
|
||||
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
|
||||
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
|
||||
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='timed_out').first():
|
||||
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
|
||||
if ShippingUploadAttempt.query.filter(ShippingUploadAttempt.artifact_id == artifact.id, ShippingUploadAttempt.status.in_({'timed_out', 'unknown'})).first():
|
||||
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL')
|
||||
attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1)
|
||||
attempt = ShippingUploadAttempt(
|
||||
artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key,
|
||||
@@ -98,9 +98,11 @@ def complete_attempt(
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
if artifact is None:
|
||||
raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED')
|
||||
if artifact.status in {'superseded', 'invalidated'}:
|
||||
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
|
||||
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
|
||||
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
if attempt.status not in {'pending', 'running', 'timed_out'}:
|
||||
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
|
||||
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
attempt.callback_id = callback
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
@@ -121,7 +123,7 @@ def complete_attempt(
|
||||
else:
|
||||
# A missing callback may conceal a completed freight submission. A late
|
||||
# transport error is not enough to safely release or retry that Artifact.
|
||||
if attempt.status == 'timed_out' and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
|
||||
if attempt.status in {'timed_out', 'unknown'} and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
|
||||
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
|
||||
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
|
||||
db.session.flush()
|
||||
@@ -141,7 +143,7 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa
|
||||
"""超时后冻结 Artifact;仅迟到成功回调或货代明确拒绝才能解除未知结果。"""
|
||||
if attempt.status != 'running':
|
||||
return attempt
|
||||
attempt.status = 'timed_out'
|
||||
attempt.status = 'unknown'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
|
||||
attempt.error_message = 'RPA callback timed out; freight submission must be reconciled before retry'
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
"""Add RecoveryPlan and inventory preparation/lineage records.
|
||||
|
||||
Revision ID: gy6h7i8j9k0m
|
||||
Revises: gx5h6i7j8k9l
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'gy6h7i8j9k0m'
|
||||
down_revision = 'gx5h6i7j8k9l'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _tables() -> set[str]:
|
||||
return {str(item or '') for item in sa.inspect(op.get_bind()).get_table_names()}
|
||||
|
||||
|
||||
def _columns(table: str) -> set[str]:
|
||||
return {str(item.get('name') or '') for item in sa.inspect(op.get_bind()).get_columns(table)}
|
||||
|
||||
|
||||
def _add(table: str, column: sa.Column) -> None:
|
||||
if column.name not in _columns(table):
|
||||
with op.batch_alter_table(table) as batch:
|
||||
batch.add_column(column)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
tables = _tables()
|
||||
if 'shipping_process_recovery_plans' not in tables:
|
||||
op.create_table(
|
||||
'shipping_process_recovery_plans',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('plan_no', sa.String(64), nullable=False),
|
||||
sa.Column('execution_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_gate', sa.String(64), nullable=False),
|
||||
sa.Column('action_code', sa.String(64), nullable=False),
|
||||
sa.Column('target_gate', sa.String(64), nullable=False),
|
||||
sa.Column('resume_after_gate', sa.String(64), nullable=True),
|
||||
sa.Column('status', sa.String(32), nullable=False, server_default='planned'),
|
||||
sa.Column('invalidation_plan_json', sa.JSON(), nullable=False, server_default='{}'),
|
||||
sa.Column('recovery_attempt_id', sa.Integer(), nullable=True),
|
||||
sa.Column('combination_input_fingerprint', sa.String(64), nullable=True),
|
||||
sa.Column('idempotency_key', sa.String(128), nullable=False),
|
||||
sa.Column('expected_gate_version', sa.Integer(), nullable=True),
|
||||
sa.Column('actor_type', sa.String(16), nullable=False, server_default='system'),
|
||||
sa.Column('actor_id', sa.String(64), nullable=True),
|
||||
sa.Column('operation_id', sa.String(128), nullable=True),
|
||||
sa.Column('failure_code', sa.String(64), nullable=True),
|
||||
sa.Column('failure_detail_json', sa.JSON(), nullable=True),
|
||||
sa.Column('superseded_by_plan_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('started_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('completed_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['execution_id'], ['shipping_process_executions.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['recovery_attempt_id'], ['shipping_process_gate_attempts.id']),
|
||||
sa.ForeignKeyConstraint(['superseded_by_plan_id'], ['shipping_process_recovery_plans.id']),
|
||||
sa.UniqueConstraint('plan_no', name='uq_shipping_process_recovery_plans_no'),
|
||||
sa.UniqueConstraint('execution_id', 'idempotency_key', name='uq_shipping_process_recovery_plans_execution_idempotency'),
|
||||
sa.CheckConstraint("status IN ('planned','invalidating','queued','running','waiting_external','waiting_manual','succeeded','failed','conflicted','cancelled')", name='ck_shipping_process_recovery_plans_status'),
|
||||
)
|
||||
op.create_index('ix_shipping_process_recovery_plans_execution_status', 'shipping_process_recovery_plans', ['execution_id', 'status', 'created_at'])
|
||||
|
||||
_add('shipping_process_gate_attempts', sa.Column('recovery_plan_id', sa.Integer(), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('superseded_by_id', sa.Integer(), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('invalidated_at', sa.DateTime(), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('invalidated_by_attempt_id', sa.Integer(), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('invalidation_reason', sa.String(256), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('input_fingerprint', sa.String(64), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('parser_version', sa.String(64), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('mapping_version', sa.String(64), nullable=True))
|
||||
_add('shipping_inventory_files', sa.Column('operation_id', sa.String(128), nullable=True))
|
||||
for name, column in (
|
||||
('preparation_attempt_id', sa.Column('preparation_attempt_id', sa.Integer(), nullable=True)),
|
||||
('source_attempt_id', sa.Column('source_attempt_id', sa.Integer(), nullable=True)),
|
||||
('invalidated_at', sa.Column('invalidated_at', sa.DateTime(), nullable=True)),
|
||||
('invalidated_by_attempt_id', sa.Column('invalidated_by_attempt_id', sa.Integer(), nullable=True)),
|
||||
('invalidation_reason', sa.Column('invalidation_reason', sa.String(256), nullable=True)),
|
||||
('combination_input_fingerprint', sa.Column('combination_input_fingerprint', sa.String(64), nullable=True)),
|
||||
):
|
||||
_add('shipping_task_inventory_links', column)
|
||||
for name, column in (
|
||||
('invalidated_at', sa.Column('invalidated_at', sa.DateTime(), nullable=True)),
|
||||
('invalidated_by_attempt_id', sa.Column('invalidated_by_attempt_id', sa.Integer(), nullable=True)),
|
||||
('invalidation_reason', sa.Column('invalidation_reason', sa.String(256), nullable=True)),
|
||||
('superseded_by_match_id', sa.Column('superseded_by_match_id', sa.Integer(), nullable=True)),
|
||||
('input_fingerprint', sa.Column('input_fingerprint', sa.String(64), nullable=True)),
|
||||
('mapping_id', sa.Column('mapping_id', sa.Integer(), nullable=True)),
|
||||
('verification_id', sa.Column('verification_id', sa.Integer(), nullable=True)),
|
||||
):
|
||||
_add('shipping_notice_line_inventory_matches', column)
|
||||
for name, column in (
|
||||
('preparation_attempt_id', sa.Column('preparation_attempt_id', sa.Integer(), nullable=True)),
|
||||
('matching_attempt_id', sa.Column('matching_attempt_id', sa.Integer(), nullable=True)),
|
||||
('input_fingerprint', sa.Column('input_fingerprint', sa.String(64), nullable=True)),
|
||||
('superseded_by_id', sa.Column('superseded_by_id', sa.Integer(), nullable=True)),
|
||||
):
|
||||
_add('shipping_notice_inventory_verifications', column)
|
||||
for name, column in (
|
||||
('superseded_by_attempt_id', sa.Column('superseded_by_attempt_id', sa.Integer(), nullable=True)),
|
||||
('invalidated_at', sa.Column('invalidated_at', sa.DateTime(), nullable=True)),
|
||||
('invalidation_reason', sa.Column('invalidation_reason', sa.String(256), nullable=True)),
|
||||
):
|
||||
_add('shipping_notice_upload_attempts', column)
|
||||
if 'shipping_inventory_mappings' not in _tables():
|
||||
op.create_table(
|
||||
'shipping_inventory_mappings',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('inventory_file_id', sa.Integer(), nullable=False),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(32), nullable=False, server_default='active'),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=True),
|
||||
sa.Column('mapping_json', sa.JSON(), nullable=False, server_default='{}'),
|
||||
sa.Column('input_fingerprint', sa.String(64), nullable=True),
|
||||
sa.Column('superseded_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_by', sa.Integer(), nullable=True),
|
||||
sa.Column('operation_id', sa.String(128), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['inventory_file_id'], ['shipping_inventory_files.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_inventory_parsing_profiles.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['superseded_by_id'], ['shipping_inventory_mappings.id']),
|
||||
sa.ForeignKeyConstraint(['created_by'], ['users.id']),
|
||||
sa.UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
|
||||
sa.CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
|
||||
)
|
||||
op.create_index('ix_shipping_inventory_mapping_file_status', 'shipping_inventory_mappings', ['inventory_file_id', 'status'])
|
||||
if 'shipping_inventory_preparation_attempts' not in _tables():
|
||||
op.create_table(
|
||||
'shipping_inventory_preparation_attempts',
|
||||
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('task_id', sa.Integer(), nullable=False),
|
||||
sa.Column('execution_id', sa.Integer(), nullable=True), sa.Column('recovery_plan_id', sa.Integer(), nullable=True),
|
||||
sa.Column('attempt_no', sa.Integer(), nullable=False), sa.Column('status', sa.String(32), nullable=False, server_default='queued'),
|
||||
sa.Column('combination_input_fingerprint', sa.String(64), nullable=True), sa.Column('candidate_set_id', sa.Integer(), nullable=True),
|
||||
sa.Column('input_snapshot_json', sa.JSON(), nullable=False, server_default='{}'), sa.Column('output_snapshot_json', sa.JSON(), nullable=False, server_default='{}'),
|
||||
sa.Column('operation_id', sa.String(128), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('started_at', sa.DateTime(), nullable=True), sa.Column('completed_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['task_id'], ['shipping_notices.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['execution_id'], ['shipping_process_executions.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['recovery_plan_id'], ['shipping_process_recovery_plans.id'], ondelete='SET NULL'), sa.ForeignKeyConstraint(['candidate_set_id'], ['shipping_inventory_candidate_sets.id'], ondelete='SET NULL'),
|
||||
sa.UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
|
||||
sa.CheckConstraint("status IN ('queued','running','waiting_external','waiting_manual','succeeded','failed','cancelled','superseded')", name='ck_shipping_inventory_preparation_status'),
|
||||
)
|
||||
op.create_index('ix_shipping_inventory_preparation_task_status', 'shipping_inventory_preparation_attempts', ['task_id', 'status', 'created_at'])
|
||||
if 'shipping_inventory_preparation_source_attempts' not in _tables():
|
||||
op.create_table(
|
||||
'shipping_inventory_preparation_source_attempts',
|
||||
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('preparation_attempt_id', sa.Integer(), nullable=False),
|
||||
sa.Column('source_code', sa.String(64), nullable=False), sa.Column('warehouse_id', sa.String(64), nullable=True),
|
||||
sa.Column('status', sa.String(32), nullable=False, server_default='queued'), sa.Column('skip_reason', sa.String(256), nullable=True),
|
||||
sa.Column('rpa_attempt_id', sa.Integer(), nullable=True), sa.Column('inventory_file_id', sa.Integer(), nullable=True), sa.Column('task_inventory_link_id', sa.Integer(), nullable=True),
|
||||
sa.Column('input_fingerprint', sa.String(64), nullable=True), sa.Column('operation_id', sa.String(128), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['preparation_attempt_id'], ['shipping_inventory_preparation_attempts.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['rpa_attempt_id'], ['shipping_task_inventory_rpa_attempts.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['inventory_file_id'], ['shipping_inventory_files.id'], ondelete='SET NULL'), sa.ForeignKeyConstraint(['task_inventory_link_id'], ['shipping_task_inventory_links.id'], ondelete='SET NULL'),
|
||||
sa.UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
|
||||
sa.CheckConstraint("status IN ('ready','reusable','skipped','failed','waiting','queued','running')", name='ck_shipping_inventory_preparation_source_status'),
|
||||
)
|
||||
op.create_index('ix_shipping_inventory_preparation_source_status', 'shipping_inventory_preparation_source_attempts', ['source_code', 'status', 'created_at'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# 本迁移只在显式回滚时删除新增表;新增列使用 batch 逆操作由部署工具按环境处理。
|
||||
for table in ('shipping_inventory_preparation_source_attempts', 'shipping_inventory_preparation_attempts', 'shipping_inventory_mappings', 'shipping_process_recovery_plans'):
|
||||
if table in _tables():
|
||||
op.drop_table(table)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Add immutable content hash to inventory snapshot files.
|
||||
|
||||
Revision ID: gz6h7i8j9k0m
|
||||
Revises: gy6h7i8j9k0m
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'gz6h7i8j9k0m'
|
||||
down_revision = 'gy6h7i8j9k0m'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
columns = {str(item.get('name') or '') for item in inspector.get_columns('shipping_inventory_files')}
|
||||
if 'file_sha256' not in columns:
|
||||
with op.batch_alter_table('shipping_inventory_files') as batch:
|
||||
batch.add_column(sa.Column('file_sha256', sa.String(64), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
columns = {str(item.get('name') or '') for item in inspector.get_columns('shipping_inventory_files')}
|
||||
if 'file_sha256' in columns:
|
||||
with op.batch_alter_table('shipping_inventory_files') as batch:
|
||||
batch.drop_column('file_sha256')
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Add formal GateAttempt lineage to inventory preparation rounds.
|
||||
|
||||
Revision ID: ha7i8j9k0l1m
|
||||
Revises: gz6h7i8j9k0m
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'ha7i8j9k0l1m'
|
||||
down_revision = 'gz6h7i8j9k0m'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _columns() -> set[str]:
|
||||
return {
|
||||
str(item.get('name') or '')
|
||||
for item in sa.inspect(op.get_bind()).get_columns('shipping_inventory_preparation_attempts')
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Persist GateAttempt identity for every preparation business round."""
|
||||
if 'gate_attempt_id' not in _columns():
|
||||
with op.batch_alter_table('shipping_inventory_preparation_attempts') as batch:
|
||||
batch.add_column(sa.Column('gate_attempt_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_inventory_preparation_gate_attempt',
|
||||
'shipping_process_gate_attempts',
|
||||
['gate_attempt_id'],
|
||||
['id'],
|
||||
ondelete='SET NULL',
|
||||
)
|
||||
batch.create_index(
|
||||
'ix_shipping_inventory_preparation_gate_attempt',
|
||||
['gate_attempt_id'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Remove the lineage column only on explicit schema rollback."""
|
||||
if 'gate_attempt_id' in _columns():
|
||||
with op.batch_alter_table('shipping_inventory_preparation_attempts') as batch:
|
||||
batch.drop_index('ix_shipping_inventory_preparation_gate_attempt')
|
||||
batch.drop_constraint('fk_shipping_inventory_preparation_gate_attempt', type_='foreignkey')
|
||||
batch.drop_column('gate_attempt_id')
|
||||
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
只读清点目标数据库中的 APX 运行态。
|
||||
|
||||
用法:在目标环境加载现有环境变量后执行 `python scripts/audit_apx_runtime_state.py`。
|
||||
本脚本只执行查询并输出 JSON,不迁移、不取消、不删除任何记录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from app import create_app
|
||||
from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""加载生产配置并输出 APX 只读清点结果。"""
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
print(json.dumps(audit_apx_runtime_state(), ensure_ascii=False, indent=2, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -223,6 +223,65 @@ def seed_task_inventory_source(
|
||||
task.inventory_source_method = "rule_exact"
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id:
|
||||
freeze_test_task_order_snapshot(task)
|
||||
|
||||
|
||||
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
if task.order_snapshot_id:
|
||||
return
|
||||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||||
if not rows:
|
||||
lines = task.lines_json if isinstance(task.lines_json, list) else []
|
||||
rows = [
|
||||
{
|
||||
'part_number': row.get('part_number'),
|
||||
'reservation_id': row.get('reservation_id'),
|
||||
'qty': row.get('qty'),
|
||||
}
|
||||
for row in lines if isinstance(row, dict)
|
||||
]
|
||||
task._test_order_rows = rows
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
task.order_data_version = int(task.order_data_version or 1)
|
||||
from app import db
|
||||
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
customer = getattr(getattr(task, 'shipping_case', None), 'customer', None)
|
||||
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
).one_or_none() is None:
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
raw_name=customer.standard_name,
|
||||
normalized_name=str(customer.standard_name or '').upper(), status='confirmed',
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint='r' * 64,
|
||||
identity_rule_version='test.v1', resolution_method='manual',
|
||||
confirmation_reason='测试确认', confirmed_by_id=None,
|
||||
))
|
||||
db.session.flush()
|
||||
freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=None,
|
||||
expected_order_data_version=int(task.order_data_version),
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy={
|
||||
'test_fixture': True,
|
||||
'enabled': True,
|
||||
'mode': 'qualified',
|
||||
'qualification_status': 'qualified',
|
||||
'customer_scope_status': 'allowed',
|
||||
'blocking_reason_codes': [],
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
@@ -328,7 +387,7 @@ def inventory_xlsx_with_warehouse(
|
||||
warehouse_id: str,
|
||||
*,
|
||||
sku: str = "A001",
|
||||
reservation_id: str = "R-1",
|
||||
reservation_id: str = "00001",
|
||||
qty: int = 1,
|
||||
) -> "BytesIO":
|
||||
"""生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。"""
|
||||
@@ -387,6 +446,16 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
|
||||
return item
|
||||
|
||||
|
||||
def v2_inventory_batch_payload(payload: dict) -> dict:
|
||||
"""测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。"""
|
||||
body = dict(payload or {})
|
||||
run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip()
|
||||
body.setdefault('schema_version', 'shipping_inventory_rpa.v2')
|
||||
body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}')
|
||||
body.setdefault('batch_run_no', run_no)
|
||||
return body
|
||||
|
||||
|
||||
def rpa_callback_payload(
|
||||
task: "ShippingNotice",
|
||||
file_path: str | Path,
|
||||
@@ -394,14 +463,22 @@ def rpa_callback_payload(
|
||||
run_no: str = "RUN-TEST-001",
|
||||
status: str = "success",
|
||||
) -> dict:
|
||||
"""构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。"""
|
||||
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
|
||||
return {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"test-callback:{run_no}",
|
||||
"task_id": task.task_no,
|
||||
"status": status,
|
||||
"file_path": str(file_path),
|
||||
"run_no": run_no,
|
||||
"source_run_no": run_no,
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"attempt_no": 1,
|
||||
"lease_token": "test-lease-token",
|
||||
"candidate_set_id": 1,
|
||||
"execution_id": 1,
|
||||
"gate_id": 1,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
tests/jobs/test_runner.py
|
||||
|
||||
用途:验证 Worker Handler 异常后的事务清理与 Job 失败收口顺序。
|
||||
依赖:app.jobs.runner、可替换的 queue/handler/store/db session。
|
||||
逻辑:模拟 Handler 抛出数据库异常,确认 runner 先 rollback,再调用 mark_failed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_handler_error_rolls_back_before_mark_failed(monkeypatch):
|
||||
"""Handler 失败后必须先清理 aborted Session,避免失败收口再次查询失败。"""
|
||||
from app.jobs import runner
|
||||
|
||||
events: list[str] = []
|
||||
|
||||
class _Logger:
|
||||
def info(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def exception(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def error(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
class _Session:
|
||||
def rollback(self):
|
||||
events.append('rollback')
|
||||
|
||||
class _Db:
|
||||
session = _Session()
|
||||
|
||||
job = {'id': 939, 'job_type': 'shipping_auto_progress', 'attempts': 1, 'payload': {}}
|
||||
monkeypatch.setattr(runner.store, 'claim_next', lambda **_kwargs: job)
|
||||
monkeypatch.setattr(runner, 'get_handler', lambda _job_type: lambda *_args: (_ for _ in ()).throw(RuntimeError('db failed')))
|
||||
monkeypatch.setattr(runner.store, 'mark_failed', lambda *_args, **_kwargs: (events.append('mark_failed'), (_ for _ in ()).throw(StopIteration)))
|
||||
monkeypatch.setattr('app.db', _Db(), raising=False)
|
||||
|
||||
with pytest.raises(StopIteration):
|
||||
runner.run_forever(SimpleNamespace(extras={'queues': ['shipping']}, config={}, logger=_Logger()), poll_interval_seconds=0)
|
||||
|
||||
assert events == ['rollback', 'mark_failed']
|
||||
@@ -75,3 +75,5 @@ def test_permission_request_approve(app, monkeypatch):
|
||||
|
||||
def test_permission_request_not_found(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
permission_service.approve_permission_request(999999)
|
||||
@@ -41,6 +41,8 @@ def test_soft_delete_document_cancels_active_jobs(app):
|
||||
source_file_name='doc.pdf',
|
||||
source_file_path='data/kb/doc.pdf',
|
||||
)
|
||||
db.session.add_all([group, document, version])
|
||||
db.session.flush()
|
||||
queued = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
@@ -49,7 +51,7 @@ def test_soft_delete_document_cancels_active_jobs(app):
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
)
|
||||
db.session.add_all([group, document, version, queued])
|
||||
db.session.add(queued)
|
||||
db.session.commit()
|
||||
|
||||
assert document_service.soft_delete_document(document.id, user_id=1) is True
|
||||
|
||||
@@ -15,6 +15,7 @@ from app.models import (
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingInventoryFile,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
project_inventory_candidate_facts,
|
||||
@@ -141,3 +142,32 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
assert facts['blocking_reason']['code'] == 'inventory_candidate_version_stale'
|
||||
assert facts['candidate_set_id'] == new_set.id
|
||||
assert facts['line_resolutions'][0]['candidate_set_id'] == old_set.id
|
||||
|
||||
|
||||
def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app):
|
||||
"""行级证据 SHA 必须从正式库存快照读取,不能依赖可选 detail_json。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-EVIDENCE')
|
||||
candidate_set = _candidate_set(task)
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
|
||||
))
|
||||
db.session.flush()
|
||||
snapshot = 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(snapshot)
|
||||
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,
|
||||
matched_row_index=9, is_current=True, detail_json={},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
facts = project_inventory_candidate_facts(task)
|
||||
|
||||
assert facts['line_resolutions'][0]['inventory_file_sha256'] == 'b' * 64
|
||||
assert facts['line_resolutions'][0]['inventory_row_index'] == 9
|
||||
@@ -202,7 +202,7 @@ def _mock_case_for_p4(case_no='CASE-2608-0042'):
|
||||
return case
|
||||
|
||||
|
||||
def _install_minimal_mocks(monkeypatch, case=None):
|
||||
def _install_minimal_mocks(monkeypatch, case=None, app=None):
|
||||
if case is None:
|
||||
case = _mock_case_for_p4()
|
||||
|
||||
@@ -242,19 +242,20 @@ def _install_minimal_mocks(monkeypatch, case=None):
|
||||
def _fake_visible(case_no, user_id, is_admin): # noqa: ARG001
|
||||
return case
|
||||
|
||||
monkeypatch.setattr(mod.ShippingOrderReviewCase, 'query', _CaseQuery())
|
||||
monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible)
|
||||
# SQLAlchemy 的 Model.query 是 Flask app-context scoped descriptor;给测试替换
|
||||
# 类属性前先进入 fixture 提供的 app context,避免纯合同测试被上下文机制阻断。
|
||||
monkeypatch.setattr(
|
||||
mod,
|
||||
'ShippingOrderReviewCase',
|
||||
SimpleNamespace(query=_CaseQuery(), id=SimpleNamespace(desc=lambda: None)),
|
||||
)
|
||||
monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible, raising=False)
|
||||
# 避免 Job.query / db.session.get / CaseEvent 等深层调用触发
|
||||
monkeypatch.setattr(mod.db.session, 'get', _fake_get)
|
||||
monkeypatch.setattr(mod.db, 'session', MagicMock(
|
||||
commit=lambda: None,
|
||||
rollback=lambda: None,
|
||||
flush=lambda: None,
|
||||
add=lambda _x: None,
|
||||
))
|
||||
monkeypatch.setattr(mod.db, 'session', MagicMock())
|
||||
# L1-L3 对账直接返回 NONE(避免 hit 真 DB)
|
||||
mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign]
|
||||
'match_level': 'NONE',
|
||||
'match_level': 'none',
|
||||
'confidence': 'LOW',
|
||||
'task_no': None,
|
||||
'candidate_matches': [],
|
||||
|
||||
@@ -55,6 +55,8 @@ T1_MATRIX = [
|
||||
(None, None, False, 'None 码 → fail-closed 不可重试'),
|
||||
# category_hint 与前缀冲突:前缀优先(空码除外)
|
||||
('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'),
|
||||
('trigger_not_claimed_missing', None, True, '库存 Trigger 缺失 → 技术重试'),
|
||||
('trigger_not_claimed_timeout', None, True, '库存 Trigger 超时 → 技术重试'),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -66,8 +66,11 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
if code == 'packing_reference':
|
||||
field = extension
|
||||
else:
|
||||
field = ShippingOrderField.query.filter_by(field_code=code).one()
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
field = ShippingOrderField.query.filter_by(
|
||||
field_code=code,
|
||||
scope=scope,
|
||||
).one()
|
||||
value_type = field.value_type
|
||||
fields[code] = field
|
||||
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': value_type, 'enabled': True})
|
||||
@@ -287,8 +290,16 @@ def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app):
|
||||
|
||||
assert blocked_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
issues = blocked_error.value.details['issues']
|
||||
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_scope_not_configured'} in issues
|
||||
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_confirmation_required'} in issues
|
||||
assert any(
|
||||
item.get('reason') == 'auto_freeze_blocked'
|
||||
and item.get('blocking_reason_code') == 'customer_scope_not_configured'
|
||||
for item in issues
|
||||
)
|
||||
assert any(
|
||||
item.get('reason') == 'auto_freeze_blocked'
|
||||
and item.get('blocking_reason_code') == 'customer_confirmation_required'
|
||||
for item in issues
|
||||
)
|
||||
assert any(item['reason'] == 'auto_freeze_not_enabled' for item in issues)
|
||||
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ from app.models import User, Agent, Department, PermissionRequest
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
app = create_app()
|
||||
app.config['TESTING'] = True
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
|
||||
# 必须在扩展初始化前选择 testing 配置;create_app() 默认会绑定开发 PostgreSQL,
|
||||
# 之后再覆盖 URI 不会迁移已绑定的 engine,容易把夹具写入共享库并污染全量测试。
|
||||
app = create_app('testing')
|
||||
|
||||
with app.test_client() as client:
|
||||
with app.app_context():
|
||||
@@ -24,9 +24,8 @@ def get_headers(client, username='admin', password='admin'):
|
||||
res = client.post('/api/user/login', json={'username': username, 'password': password})
|
||||
data = res.get_json()
|
||||
return {
|
||||
'X-User-Id': str(data['id']),
|
||||
'X-Username': data['username'],
|
||||
'X-Role': data['role']
|
||||
'Authorization': f"Bearer {data['access_token']}",
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def test_department_crud(client):
|
||||
@@ -114,6 +113,7 @@ def test_permission_flow(client):
|
||||
client.post('/api/admin/agents', json={
|
||||
'name': 'Test Agent',
|
||||
'dify_app_id': 'app-123'
|
||||
, 'dify_api_key': 'test-key'
|
||||
}, headers=admin_headers)
|
||||
agent_id = 1
|
||||
|
||||
@@ -129,13 +129,12 @@ def test_permission_flow(client):
|
||||
# User Login
|
||||
user_headers = get_headers(client, 'user1', 'password')
|
||||
|
||||
# Request Permission
|
||||
res = client.post('/api/user/permission-requests', json={
|
||||
'agent_id': agent_id,
|
||||
'reason': 'I need it'
|
||||
}, headers=user_headers)
|
||||
assert res.status_code == 201
|
||||
req_id = res.get_json()['id']
|
||||
# 当前后端只保留管理员审批 API;测试直接创建待审事实,避免依赖已移除的用户申请路由。
|
||||
with client.application.app_context():
|
||||
request_row = PermissionRequest(user_id=2, agent_id=agent_id, reason='I need it', status='pending')
|
||||
db.session.add(request_row)
|
||||
db.session.commit()
|
||||
req_id = request_row.id
|
||||
|
||||
# Admin List Requests
|
||||
res = client.get('/api/admin/permission-requests', headers=admin_headers)
|
||||
|
||||
@@ -446,7 +446,8 @@ def test_shipping_customer_shadow_report_and_label_api(app, client):
|
||||
report = parse_api_data(report_response.get_json())
|
||||
assert report['total'] == 1
|
||||
assert report['items'][0]['candidate_no'] == 'SNC-SHADOW-API'
|
||||
assert report['auto_resolution']['enabled'] is False
|
||||
# 当前安全默认是开启受控自动客户确认;质量门禁仍决定是否允许实际自动确认。
|
||||
assert report['auto_resolution']['enabled'] is True
|
||||
assert report['auto_resolution']['recent_events'] == []
|
||||
|
||||
label_response = client.put(
|
||||
|
||||
@@ -68,8 +68,12 @@ def test_admin_can_list_and_view_immutable_schema_history(app, client):
|
||||
}, actor_id=1)
|
||||
first = _publish_version(field['id'], display_name='采购订单号')
|
||||
second = _publish_version(field['id'], display_name='客户订单号', source_version_id=first['id'])
|
||||
current_field = next(
|
||||
item for item in service.get_state()['fields'] if item['id'] == field['id']
|
||||
)
|
||||
service.save_field({
|
||||
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
|
||||
'display_name': '采购订单号(更新)',
|
||||
'expected_updated_at': current_field['updated_at'],
|
||||
}, actor_id=1, field_id=field['id'])
|
||||
|
||||
forbidden = client.get('/api/admin/shipping-order-schema/versions', headers=_headers('schema-history-user', 'user'))
|
||||
@@ -84,7 +88,10 @@ def test_admin_can_list_and_view_immutable_schema_history(app, client):
|
||||
assert 'definition' not in page['items'][0]
|
||||
assert page['items'][0]['published_by']['display_name'] == '版本管理员'
|
||||
|
||||
exact = client.get('/api/admin/shipping-order-schema/versions?version_number=1', headers=_headers('schema-history-admin', 'admin'))
|
||||
exact = client.get(
|
||||
f"/api/admin/shipping-order-schema/versions?version={first['version']}",
|
||||
headers=_headers('schema-history-admin', 'admin'),
|
||||
)
|
||||
assert exact.status_code == 200
|
||||
assert parse_api_data(exact.get_json())['items'][0]['id'] == first['id']
|
||||
|
||||
|
||||
@@ -16,6 +16,54 @@ from app.services.shipping_notice.conversation_retry_auto_progress_service impor
|
||||
)
|
||||
|
||||
|
||||
def test_formal_trigger_failure_overrides_stale_automation(monkeypatch):
|
||||
"""最新 Attempt 的 Trigger 缺失事实优先于历史 Job 的 needs_human 投影。"""
|
||||
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
|
||||
|
||||
task = type('Task', (), {'task_no': 'OT-TRIGGER', 'id': 1})()
|
||||
class _Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return task
|
||||
|
||||
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
|
||||
lambda *_args, **_kwargs: {
|
||||
'latest_attempts': {
|
||||
'DSV360_AWSSL': {
|
||||
'status': 'failed',
|
||||
'error_code': 'trigger_not_claimed_missing',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert service._formal_task_has_retryable_inventory_trigger_failure('OT-TRIGGER') is True
|
||||
|
||||
|
||||
def test_failed_gate_job_does_not_count_as_active_attempt(monkeypatch):
|
||||
"""Attempt 残留 queued 但正式 Job 已失败时,不得继续投影 already_running。"""
|
||||
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
|
||||
|
||||
task = type('Task', (), {'task_no': 'OT-STALE', 'id': 1})()
|
||||
|
||||
class _Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return task
|
||||
|
||||
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
|
||||
lambda *_args, **_kwargs: {'active_attempt_count': 0},
|
||||
)
|
||||
assert service._formal_task_has_active_attempt('OT-STALE') is False
|
||||
|
||||
|
||||
def test_skip_reason_maps_queued_and_not_retryable():
|
||||
"""queued → already_running;retryable=false → not_retryable。"""
|
||||
assert _skip_reason_from_automation(
|
||||
@@ -40,6 +88,42 @@ def test_manual_fallback_human_owner_still_retryable():
|
||||
) is None
|
||||
|
||||
|
||||
def test_inventory_needs_human_remains_retryable():
|
||||
"""库存快照/RPA 暂态 needs_human 必须继续进入库存重试决策器。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'reason_code': 'inventory_snapshot_prepare_failed',
|
||||
},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_missing_inventory_trigger_needs_human_remains_retryable():
|
||||
"""Trigger 未被领取的技术失败必须继续触发正式 OT 库存重试。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'error_code': 'trigger_not_claimed_missing',
|
||||
},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_business_needs_human_stays_skipped():
|
||||
"""重复/短缺等业务裁决的 needs_human 不得触发库存 RPA。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'reason_code': 'inventory_shortage',
|
||||
},
|
||||
task_missing=False,
|
||||
) == 'human_blocking'
|
||||
|
||||
|
||||
def test_task_missing_always_skipped():
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
@@ -54,7 +138,7 @@ def test_summarize_items_counts_outcomes():
|
||||
{'outcome': 'skipped', 'reason_code': 'already_running'},
|
||||
{'outcome': 'failed'},
|
||||
])
|
||||
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1}
|
||||
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1, 'blocked': 0}
|
||||
|
||||
|
||||
def test_project_conversation_allowed_actions_empty_without_conversation():
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -42,6 +43,16 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
"requested_at": "2026-07-01T03:23:25.114522",
|
||||
"mode": "auto",
|
||||
"attempt": 3,
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"SRC-{task_no}:C1",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_run_no": f"SRC-{task_no}",
|
||||
"attempt_no": 3,
|
||||
"lease_token": "lease-test",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
"expected_warehouse_id": "AWSDU",
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"connector_type": "dsv360",
|
||||
@@ -59,6 +70,121 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
}
|
||||
|
||||
|
||||
def test_single_inventory_trigger_missing_source_run_is_rejected_before_rpa(monkeypatch, tmp_path):
|
||||
"""缺少 source_run_no 时不生成 None:C1、不启动浏览器,并移入 failed。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
failed_dir = trigger_dir / "failed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_invalid.json"
|
||||
payload = _build_inventory_export_trigger("SN-IDENTITY-INVALID")
|
||||
payload.pop("source_run_no")
|
||||
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks == [
|
||||
(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
{
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": None,
|
||||
"task_no": "SN-IDENTITY-INVALID",
|
||||
"business_status": "rejected",
|
||||
"status": "rejected",
|
||||
"error_code": "trigger_identity_invalid",
|
||||
"identity_errors": ["source_run_no"],
|
||||
},
|
||||
),
|
||||
]
|
||||
assert (failed_dir / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_single_inventory_trigger_missing_callback_id_is_rejected(monkeypatch, tmp_path):
|
||||
"""v2 不允许 Worker 推导 callback_id,缺失时必须拒绝。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_missing_callback.json"
|
||||
payload = _build_inventory_export_trigger("SN-IDENTITY-CALLBACK-INVALID")
|
||||
payload.pop("callback_id", None)
|
||||
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] is None
|
||||
assert callbacks[0][1]["error_code"] == "trigger_identity_invalid"
|
||||
assert "callback_id" in callbacks[0][1]["identity_errors"]
|
||||
assert (trigger_dir / "failed" / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch, tmp_path):
|
||||
"""批量成功结果必须原样回传逐源 v2 身份,供后端绑定 SourceAttempt。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_identity.json"
|
||||
source = {
|
||||
"source_code": "DBS",
|
||||
"warehouse_id": "WH-01",
|
||||
"task_no": "SN-BATCH-IDENTITY",
|
||||
"callback_id": "SRC-BATCH-001:C1",
|
||||
"source_run_no": "SRC-BATCH-001",
|
||||
"attempt_no": 2,
|
||||
"lease_token": "lease-batch",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
"expected_warehouse_id": "WH-01",
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-001:batch:C1",
|
||||
"batch_run_no": "BATCH-001",
|
||||
"task_no": "SN-BATCH-IDENTITY",
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
result = completed["results"][0]
|
||||
assert {key: result[key] for key in (
|
||||
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
|
||||
"lease_token", "candidate_set_id", "execution_id", "gate_id", "expected_warehouse_id",
|
||||
)} == {
|
||||
"callback_id": "SRC-BATCH-001:C1",
|
||||
"task_no": "SN-BATCH-IDENTITY",
|
||||
"source_code": "DBS",
|
||||
"source_run_no": "SRC-BATCH-001",
|
||||
"attempt_no": 2,
|
||||
"lease_token": "lease-batch",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
"expected_warehouse_id": "WH-01",
|
||||
}
|
||||
|
||||
|
||||
def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -443,12 +569,23 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_payload == {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_run_no": "SRC-SN-20260629-2EDADC77",
|
||||
"run_no": "SRC-SN-20260629-2EDADC77",
|
||||
"attempt_no": 3,
|
||||
"lease_token": "lease-test",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
"expected_warehouse_id": "AWSDU",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"file_sha256": hashlib.sha256(b"fake inventory content").hexdigest(),
|
||||
"rpa_mode": "browser",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
}
|
||||
assert not trigger_path.exists()
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
@@ -494,12 +631,23 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_payload == {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_run_no": "SRC-SN-20260629-2EDADC77",
|
||||
"run_no": "SRC-SN-20260629-2EDADC77",
|
||||
"attempt_no": 3,
|
||||
"lease_token": "lease-test",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
"expected_warehouse_id": "AWSDU",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(exported),
|
||||
"file_sha256": hashlib.sha256(exported.read_bytes()).hexdigest(),
|
||||
"rpa_mode": "mock",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
}
|
||||
assert not trigger_path.exists()
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
|
||||
@@ -161,6 +161,34 @@ def test_result_missing_projects_file_missing_and_retry_prep():
|
||||
assert ACTION_CLOSE in view['line_allowed_actions']
|
||||
|
||||
|
||||
def test_line_inventory_view_preserves_evidence_identity_fields():
|
||||
"""行投影必须保留文件 SHA、文件行号与匹配 Attempt,供证据审计展示。"""
|
||||
view = project_line_inventory_view(
|
||||
has_formal_ot=True,
|
||||
fact={
|
||||
'match_result': 'matched',
|
||||
'inventory_status': 'ready',
|
||||
'available_qty': '8',
|
||||
'inventory_snapshot_id': 9,
|
||||
'matched_at': '2026-08-07T00:00:00',
|
||||
'inventory_file_no': 'INV-001',
|
||||
'file_sha256': 'a' * 64,
|
||||
'matched_row_index': 17,
|
||||
'match_attempt_id': 301,
|
||||
'inventory_source_code': 'DBS_DUB',
|
||||
},
|
||||
required_qty='3',
|
||||
stored_line_status='ready_to_fulfill',
|
||||
decision_source='system',
|
||||
can_fulfill_complete_line=True,
|
||||
)
|
||||
|
||||
assert view['inventory_file_no'] == 'INV-001'
|
||||
assert view['inventory_file_sha256'] == 'a' * 64
|
||||
assert view['inventory_row_index'] == 17
|
||||
assert view['match_attempt_id'] == 301
|
||||
|
||||
|
||||
def test_user_status_maps_closed_and_system_ready():
|
||||
"""存储态关闭与系统 ready 投影为用户态。"""
|
||||
assert project_user_line_status(
|
||||
|
||||
@@ -56,6 +56,49 @@ def test_persist_without_snapshot_forbids_ready_not_found(app):
|
||||
assert added[0].available_qty is None
|
||||
|
||||
|
||||
def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
|
||||
"""匹配器 line-1 不得覆盖 Case 草稿 machine-1 的正式明细身份。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=7)
|
||||
added = []
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc, 'resolve_review_case_for_task', return_value=SimpleNamespace(id=3)),
|
||||
patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'machine-1'}),
|
||||
patch.object(svc, 'get_active_candidate_set', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_lines', return_value=[]),
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
match_q.filter_by.return_value.first.return_value = None
|
||||
match_q.filter_by.return_value.update.return_value = None
|
||||
|
||||
svc.persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
inventory_snapshot_id=7,
|
||||
match_payload={
|
||||
'line_results': [{
|
||||
'line_index': 0,
|
||||
'disposition': 'shortage',
|
||||
'part_number': 'PN1',
|
||||
'reservation_id': 'R1',
|
||||
'required_qty': 30,
|
||||
'available_qty': 14,
|
||||
'shortage_qty': 16,
|
||||
}],
|
||||
'resolutions': [{'line_index': 0, 'line_key': 'line-1'}],
|
||||
},
|
||||
)
|
||||
|
||||
assert len(added) == 1
|
||||
assert added[0].line_key == 'machine-1'
|
||||
assert added[0].available_qty == '14'
|
||||
assert added[0].shortage_qty == '16'
|
||||
|
||||
|
||||
def test_unit_participates_in_match_key():
|
||||
"""BE-6:同料号预约单但单位不同不得命中。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
@@ -98,6 +141,67 @@ def test_unit_participates_in_match_key():
|
||||
assert out_ok['line_results'][0].get('unit') == 'PCS'
|
||||
|
||||
|
||||
def test_reservation_part_match_without_unit_aggregates_fourteen_rows():
|
||||
"""库存 Profile 未配置单位时,Reservation+料号命中 14 行并汇总为 14。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
|
||||
inventory = [
|
||||
{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'available_qty': 1,
|
||||
'__source_code': 'DSV360_AWSBI_BYAWSCMH01',
|
||||
}
|
||||
for _ in range(14)
|
||||
]
|
||||
out = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'quantity': 30,
|
||||
}],
|
||||
inventory_lines=inventory,
|
||||
)
|
||||
line = out['line_results'][0]
|
||||
assert out['match_status'] == 'partial'
|
||||
assert line['available_qty'] == 14.0
|
||||
assert line['shortage_qty'] == 16.0
|
||||
|
||||
|
||||
def test_profile_match_shortage_payload_keeps_line_index_and_quantities():
|
||||
"""单源短缺结果必须携带行序,才能写回 machine line 的 current 事实。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_profile_match_persistence_payload,
|
||||
)
|
||||
|
||||
payload = _profile_match_persistence_payload(
|
||||
[{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'required_qty': 30.0,
|
||||
'available_qty': 14.0,
|
||||
'shortage_qty': 16.0,
|
||||
'line_status': 'partial',
|
||||
}],
|
||||
inventory_source_code='DSV360_AWSBI_BYAWSCMH01',
|
||||
)
|
||||
|
||||
# 关键断言:持久化层依赖 line_index 关联 Case 草稿的 machine-1;数量不得丢失。
|
||||
assert payload['line_results'] == [{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'required_qty': 30.0,
|
||||
'available_qty': 14.0,
|
||||
'shortage_qty': 16.0,
|
||||
'line_status': 'partial',
|
||||
'line_index': 0,
|
||||
'disposition': 'shortage',
|
||||
}]
|
||||
assert payload['resolutions'][0]['line_index'] == 0
|
||||
assert payload['resolutions'][0]['line_key'] is None
|
||||
assert payload['resolutions'][0]['resolved_inventory_source_code'] == 'DSV360_AWSBI_BYAWSCMH01'
|
||||
|
||||
|
||||
def test_compensation_runner_noops_when_flag_disabled(app, monkeypatch):
|
||||
"""BE-4:flag 关闭时补偿扫描空跑。"""
|
||||
from app.services.schedule import shipping_post_ot_auto_fulfill_compensation_job as job
|
||||
|
||||
@@ -474,6 +474,7 @@ def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(mon
|
||||
plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN'))
|
||||
unit = SimpleNamespace(
|
||||
id=1,
|
||||
document_id=101,
|
||||
status='pending',
|
||||
attempt_count=0,
|
||||
reason_code=None,
|
||||
@@ -517,7 +518,11 @@ def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatc
|
||||
'intake_id': 11,
|
||||
'documents': [{
|
||||
'document_id': 101,
|
||||
'layout_snapshot': {'status': 'ready', 'layout_candidate': {'pages': []}},
|
||||
'layout_snapshot': {
|
||||
'status': 'ready',
|
||||
'layout_candidate': {'pages': []},
|
||||
'coordinate_evidence': {'pages': {}, 'page_glyphs': {}},
|
||||
},
|
||||
'layout_schema_candidates': [{'mapping_status': 'accepted'}],
|
||||
}],
|
||||
}],
|
||||
@@ -551,7 +556,12 @@ def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(m
|
||||
unit = SimpleNamespace(intake_id=11, document_id=101)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get',
|
||||
lambda model, document_id: SimpleNamespace(id=document_id),
|
||||
lambda model, document_id: SimpleNamespace(
|
||||
id=document_id,
|
||||
asset_id=301,
|
||||
filename='po-1.pdf',
|
||||
current_layout_version=None,
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot',
|
||||
@@ -572,6 +582,8 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
|
||||
"""工作台文档详情应直接暴露单元选择、预算和失败事实。"""
|
||||
run = SimpleNamespace(
|
||||
id=1,
|
||||
status='processing',
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'schema': {'definition': {'fields': []}},
|
||||
'intakes': [{
|
||||
@@ -586,6 +598,7 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
|
||||
extraction_plan=SimpleNamespace(units=[SimpleNamespace(
|
||||
id=7,
|
||||
document_id=101,
|
||||
created_at=None,
|
||||
status='failed',
|
||||
reason_code=None,
|
||||
selection_batch=1,
|
||||
@@ -598,6 +611,8 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
|
||||
'selected_in_batch': 1,
|
||||
},
|
||||
result_json={},
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
)]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -615,44 +630,39 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
|
||||
|
||||
items = serialize_workspace_run_documents(run)
|
||||
|
||||
assert items == [{
|
||||
'unit_id': 7,
|
||||
'document_id': 101,
|
||||
'file_name': 'po-1.pdf',
|
||||
'status': 'failed',
|
||||
'selection_batch': 1,
|
||||
'group_key': '451883815A',
|
||||
'retry_status': 'failed',
|
||||
'technical_failure_reason_code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
'budget_cost': {
|
||||
'initial_attachment_budget': 2,
|
||||
'initial_concurrency_budget': 2,
|
||||
'selected_in_batch': 1,
|
||||
},
|
||||
'po_number': None,
|
||||
'line_count': 0,
|
||||
'profile': None,
|
||||
'email_supplement': {
|
||||
'status': 'none',
|
||||
'relation_codes': [],
|
||||
'conflict_count': 0,
|
||||
'reservation_id_status': 'unavailable',
|
||||
'source_type_status': 'unavailable',
|
||||
},
|
||||
'reason_code': 'technical_failure',
|
||||
'review_details': [],
|
||||
'available_actions': [],
|
||||
'activity_event_code': None,
|
||||
'started_at': None,
|
||||
'last_activity_at': None,
|
||||
'finished_at': None,
|
||||
}]
|
||||
item = items[0]
|
||||
assert item['unit_id'] == 7
|
||||
assert item['document_id'] == 101
|
||||
assert item['file_name'] == 'po-1.pdf'
|
||||
assert item['status'] == 'failed'
|
||||
assert item['selection_batch'] == 1
|
||||
assert item['group_key'] == '451883815A'
|
||||
assert item['retry_status'] == 'failed'
|
||||
assert item['technical_failure_reason_code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
|
||||
assert item['budget_cost'] == {
|
||||
'initial_attachment_budget': 2,
|
||||
'initial_concurrency_budget': 2,
|
||||
'selected_in_batch': 1,
|
||||
}
|
||||
assert item['reason_code'] == 'technical_failure'
|
||||
assert item['review_details'] == []
|
||||
assert item['available_actions'] == ['view_details']
|
||||
assert item['activity_event_code'] is None
|
||||
assert item['started_at'] is None
|
||||
assert item['last_activity_at'] is None
|
||||
assert item['finished_at'] is None
|
||||
|
||||
|
||||
def test_workspace_documents_show_selected_pdfs_while_layout_is_pending(monkeypatch):
|
||||
"""等待版面解析时仍返回已选 PDF,避免处理详情误报“暂无结果”。"""
|
||||
run = SimpleNamespace(
|
||||
id=1,
|
||||
status='processing',
|
||||
error_code=None,
|
||||
created_at=None,
|
||||
finished_at=None,
|
||||
last_activity_at=None,
|
||||
phase='waiting_layout',
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [{
|
||||
|
||||
@@ -63,11 +63,12 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
|
||||
) as RC_Mock, patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.db',
|
||||
), patch.object(
|
||||
coord, '_customer_step_for_case', return_value={'status': 'skipped_no_shadow'},
|
||||
), patch.object(
|
||||
coord, 'validate_draft', return_value={'status': 'ready'},
|
||||
), patch.object(
|
||||
coord, 'ensure_stp_auto_create_for_case',
|
||||
coord, '_customer_step_for_case', return_value=('skipped', {'reason': 'shadow_missing'}),
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.validate_draft',
|
||||
return_value={'status': 'ready'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'queued', 'job_id': 1201,
|
||||
'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'},
|
||||
) as ensure_mock:
|
||||
@@ -115,11 +116,12 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.db',
|
||||
), patch.object(
|
||||
coord, '_customer_step_for_case', return_value={'status': 'skipped'},
|
||||
), patch.object(
|
||||
coord, 'validate_draft', return_value={'status': 'ready'},
|
||||
), patch.object(
|
||||
coord, 'ensure_stp_auto_create_for_case',
|
||||
coord, '_customer_step_for_case', return_value=('skipped', {'reason': 'shadow_missing'}),
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.validate_draft',
|
||||
return_value={'status': 'ready'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'queued', 'job_id': 2202, 'idempotency_key': 'k-02'},
|
||||
) as ensure_mock:
|
||||
result = coord.reconcile_single_case_for_auto_progress(
|
||||
@@ -146,21 +148,22 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
|
||||
),
|
||||
)
|
||||
|
||||
def _customer_step(c, actor_type_hint=None):
|
||||
del c, actor_type_hint
|
||||
def _customer_step(*, case, trigger):
|
||||
del trigger
|
||||
case.current_draft.validation_result_json = {
|
||||
'can_build': True, 'can_auto_create': True, 'status': 'ready',
|
||||
}
|
||||
return {'status': 'auto_confirmed', 'customer_id': 5555}
|
||||
return 'auto_confirmed', {'customer_id': 5555}
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.db',
|
||||
), patch.object(
|
||||
coord, '_customer_step_for_case', side_effect=_customer_step,
|
||||
), patch.object(
|
||||
coord, 'validate_draft', return_value={'status': 'ready'},
|
||||
), patch.object(
|
||||
coord, 'ensure_stp_auto_create_for_case',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.validate_draft',
|
||||
return_value={'status': 'ready'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'queued', 'job_id': 3303, 'idempotency_key': 'k-03'},
|
||||
) as ensure_mock:
|
||||
result = coord.reconcile_single_case_for_auto_progress(
|
||||
@@ -180,10 +183,12 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a
|
||||
id=4, case_no='SORC-P1-04', status='ready', confirmed_task_id=None,
|
||||
document_id=400, updated_at=None,
|
||||
)
|
||||
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch(
|
||||
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch.object(
|
||||
sw, '_scan_stale_inventory_attempts', return_value=0,
|
||||
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
|
||||
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
|
||||
) as mock_db, patch(
|
||||
'app.services.shipping_notice.shipping_recovery_sweeper_service.'
|
||||
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as ReviewCase, patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
return_value={'case_no': 'SORC-P1-04', 'enqueue_status': 'queued',
|
||||
'job_id': 4404},
|
||||
@@ -191,10 +196,9 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a
|
||||
mock_session = MagicMock()
|
||||
loaded = SimpleNamespace(id=4, status='ready', confirmed_task_id=None)
|
||||
mock_session.execute.return_value.scalar.return_value = None
|
||||
mock_session.get.return_value = loaded
|
||||
mock_session.begin_nested.return_value.__enter__ = MagicMock(return_value=None)
|
||||
mock_session.begin_nested.return_value.__exit__ = MagicMock(return_value=None)
|
||||
mock_session.begin_nested.return_value = MagicMock()
|
||||
type(mock_db).session = mock_session
|
||||
ReviewCase.query.filter_by.return_value.with_for_update.return_value.first.return_value = loaded
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
assert coord_mock.call_count == 1
|
||||
@@ -265,17 +269,18 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app):
|
||||
from app.services.shipping_notice import reconciliation_service as rs
|
||||
from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed
|
||||
|
||||
case = SimpleNamespace(case_no='SORC-P1-06', status='ready', confirmed_task_id=None)
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-P1-06', status='ready', confirmed_task_id=None,
|
||||
document_id=600, run=SimpleNamespace(run_no='SNER-P1-06'),
|
||||
)
|
||||
|
||||
# 6A:assert_case_not_blocked_manual 前置拦截 → 409
|
||||
with patch(
|
||||
'app.services.shipping_notice.reconciliation_service.find_latest_stp_job',
|
||||
return_value=SimpleNamespace(
|
||||
with patch.object(rs, 'Job') as Job:
|
||||
Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace(
|
||||
id=60, status='failed',
|
||||
result_json={'retryable': False,
|
||||
'blocking_reason': 'SHIPPING.NOTICE_EXACT_DUPLICATE'},
|
||||
),
|
||||
):
|
||||
)
|
||||
with pytest.raises(ConflictError):
|
||||
rs.assert_case_not_blocked_manual(case_no='SORC-P1-06', case=case)
|
||||
|
||||
@@ -309,9 +314,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches',
|
||||
) as refresh_mock, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match',
|
||||
) as confirm_mock, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.validate_draft',
|
||||
) as validate_mock:
|
||||
) as confirm_mock:
|
||||
# Shadow = unique_candidate 但是 resolved=false。
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution',
|
||||
@@ -330,16 +333,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
) as CM, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction',
|
||||
) as EX:
|
||||
Cand.query.get.return_value = SimpleNamespace(id=70)
|
||||
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
|
||||
CM.query.filter_by.return_value.first.return_value = None
|
||||
EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700)
|
||||
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
|
||||
# 执行投影(纯读)
|
||||
out = project_review_case_customer_resolution(case)
|
||||
|
||||
# 7A:GET 路径不允许 confirm / validate / commit
|
||||
confirm_mock.assert_not_called()
|
||||
validate_mock.assert_not_called()
|
||||
refresh_mock.assert_not_called()
|
||||
sess_mock.commit.assert_not_called()
|
||||
# 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认)
|
||||
@@ -389,7 +390,7 @@ def test_contract_09_late_callback_does_not_resurrect_terminal_case(app):
|
||||
)
|
||||
|
||||
with patch.object(h.db.session, 'get', return_value=job), patch(
|
||||
'app.jobs.handlers.shipping_review_revalidate_progress.ShippingOrderReviewCase',
|
||||
'app.models.shipping_order_review.ShippingOrderReviewCase',
|
||||
) as RC, patch.object(h, 'finish_job') as finish_mock, patch.object(
|
||||
h, 'fail_job',
|
||||
) as fail_mock:
|
||||
@@ -400,7 +401,7 @@ def test_contract_09_late_callback_does_not_resurrect_terminal_case(app):
|
||||
|
||||
finish_mock.assert_called_once()
|
||||
args, _ = finish_mock.call_args
|
||||
result = args[1] if len(args) > 1 else {}
|
||||
result = finish_mock.call_args.kwargs.get('result') or {}
|
||||
assert result.get('status') in {'skipped', 'superseded', 'case_terminal'}
|
||||
fail_mock.assert_not_called()
|
||||
|
||||
@@ -427,14 +428,11 @@ def test_fe_01_stp_enqueue_missing_injects_blocking_reason(app):
|
||||
lines_json=[],
|
||||
),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.db.session',
|
||||
MagicMock(),
|
||||
), patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.Job',
|
||||
) as J:
|
||||
J.query.filter.return_value.first.return_value = None
|
||||
bundle = _project_fine_grained_pre_stp_blocking(case)
|
||||
with patch('app.extensions.db.session', MagicMock()) as session_mock:
|
||||
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
|
||||
bundle = _project_fine_grained_pre_stp_blocking(
|
||||
case, validation=case.current_draft.validation_result_json,
|
||||
)
|
||||
|
||||
assert bundle is not None
|
||||
assert bundle['blocking_reason']['code'] == 'stp_enqueue_missing'
|
||||
@@ -459,13 +457,11 @@ def test_fe_02_retryable_shows_single_primary_action_only(app):
|
||||
header_values_json={}, lines_json=[],
|
||||
),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(),
|
||||
), patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.Job',
|
||||
) as J:
|
||||
J.query.filter.return_value.first.return_value = None
|
||||
bundle = _project_fine_grained_pre_stp_blocking(case)
|
||||
with patch('app.extensions.db.session', MagicMock()) as session_mock:
|
||||
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
|
||||
bundle = _project_fine_grained_pre_stp_blocking(
|
||||
case, validation=case.current_draft.validation_result_json,
|
||||
)
|
||||
|
||||
assert bundle['user_status'] == 'retryable'
|
||||
primary = bundle.get('primary_action') or {}
|
||||
@@ -477,15 +473,12 @@ def test_fe_02_retryable_shows_single_primary_action_only(app):
|
||||
|
||||
def test_fe_03_duplicate_only_allows_reconcile_and_progress(app):
|
||||
"""FE 合同 3:duplicate → projection 剔除 retry,只保留 reconcile_and_progress。"""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
_DUPLICATE_BLOCKING_CODES,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_contract import (
|
||||
BLOCKING_REASON_TO_ACTION_CODES,
|
||||
should_general_retry_be_removed,
|
||||
)
|
||||
|
||||
for bcode in _DUPLICATE_BLOCKING_CODES:
|
||||
for bcode in ('duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'):
|
||||
assert should_general_retry_be_removed(
|
||||
retryable_flag=False, blocking_reason=bcode,
|
||||
) is True, f'{bcode} 必须移除通用重试'
|
||||
@@ -510,14 +503,14 @@ def test_fe_04_refresh_and_re_login_projection_consistent(app):
|
||||
header_values_json={}, lines_json=[],
|
||||
),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(),
|
||||
), patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.Job',
|
||||
) as J:
|
||||
J.query.filter.return_value.first.return_value = None
|
||||
r1 = _project_fine_grained_pre_stp_blocking(case)
|
||||
r2 = _project_fine_grained_pre_stp_blocking(case)
|
||||
with patch('app.extensions.db.session', MagicMock()) as session_mock:
|
||||
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
|
||||
r1 = _project_fine_grained_pre_stp_blocking(
|
||||
case, validation=case.current_draft.validation_result_json,
|
||||
)
|
||||
r2 = _project_fine_grained_pre_stp_blocking(
|
||||
case, validation=case.current_draft.validation_result_json,
|
||||
)
|
||||
|
||||
assert r1 is not None and r2 is not None
|
||||
assert r1['blocking_reason']['code'] == r2['blocking_reason']['code']
|
||||
@@ -541,13 +534,11 @@ def test_fe_05_no_contradictory_waiting_manual_and_waiting_auto_together(app):
|
||||
header_values_json={}, lines_json=[],
|
||||
),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(),
|
||||
), patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.Job',
|
||||
) as J:
|
||||
J.query.filter.return_value.first.return_value = None
|
||||
bundle = _project_fine_grained_pre_stp_blocking(case)
|
||||
with patch('app.extensions.db.session', MagicMock()) as session_mock:
|
||||
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
|
||||
bundle = _project_fine_grained_pre_stp_blocking(
|
||||
case, validation=case.current_draft.validation_result_json,
|
||||
)
|
||||
|
||||
status = bundle.get('user_status')
|
||||
# retryable 与 waiting_human 互斥:命中短路 stp_enqueue_missing 时,只能二选一
|
||||
|
||||
@@ -10,17 +10,26 @@ tests/test_shipping_auto_progress_p0_3.py
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import claim_next_job
|
||||
from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingNotice,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
AUTO_PROGRESS_GATE_CODES,
|
||||
determine_formal_start_gate,
|
||||
run_auto_progress_job,
|
||||
submit_auto_progress,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
|
||||
def _task_with_candidate() -> ShippingNotice:
|
||||
"""创建拥有 frozen CandidateSet 的最小正式 Task。"""
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
|
||||
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
|
||||
task = ShippingNotice(task_no='APX-P0-3-001', process_status='created')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -30,12 +39,33 @@ def _task_with_candidate() -> ShippingNotice:
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.active_inventory_candidate_set_id = candidate.id
|
||||
if complete_order:
|
||||
task.current_order_extraction_id = 101
|
||||
task.order_snapshot_id = 201
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def test_submit_reuses_one_active_task_job(app):
|
||||
"""同一 Task 多次触发只保留一个 queued/running AutoProgress Job。"""
|
||||
def test_formal_start_gate_is_derived_from_persisted_task_facts(app):
|
||||
"""无解析、未冻结、候选未冻结与候选冻结必须分别停在对应正式 Gate。"""
|
||||
task = _task_with_candidate(complete_order=False)
|
||||
candidate = ShippingInventoryCandidateSet.query.filter_by(task_id=task.id).one()
|
||||
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'document_materialization'
|
||||
|
||||
task.current_order_extraction_id = 101
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'order_freeze_readiness'
|
||||
|
||||
task.order_snapshot_id = 201
|
||||
candidate.lifecycle_status = 'draft'
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_source_routing'
|
||||
|
||||
candidate.lifecycle_status = 'frozen'
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_preparation'
|
||||
|
||||
|
||||
def test_submit_creates_formal_execution_for_task_without_case(app):
|
||||
"""无 Case 的新 Task 也必须创建正式 20-Gate,不得创建 APX 六 Gate。"""
|
||||
task = _task_with_candidate()
|
||||
first = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
second = submit_auto_progress(task=task, trigger='user_retry')
|
||||
@@ -43,96 +73,165 @@ def test_submit_reuses_one_active_task_job(app):
|
||||
assert first['status'] == 'queued'
|
||||
assert second['job_id'] == first['job_id']
|
||||
assert second['reused'] is True
|
||||
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 1
|
||||
execution = db.session.get(ShippingProcessExecution, first['execution_id'])
|
||||
gate_codes = [row.gate_code for row in execution.gates]
|
||||
assert len(gate_codes) == 20
|
||||
assert gate_codes[0] == 'document_materialization'
|
||||
assert gate_codes[-1] == 'manual_upload_handoff'
|
||||
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0
|
||||
assert Job.query.filter_by(id=first['job_id']).one().job_type == 'shipping_process_gate'
|
||||
|
||||
|
||||
def test_worker_passes_only_one_gate_and_queues_successor(app, monkeypatch):
|
||||
"""一个 Worker Job 只处理首个 Gate,passed 与第二个 Gate Job 同事务产生。"""
|
||||
def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app):
|
||||
"""同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。"""
|
||||
task = _task_with_candidate()
|
||||
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
|
||||
assert claimed is not None and claimed.id == submitted['job_id']
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller._gate_outcome',
|
||||
lambda task, gate: ('passed', None, {'test': True}),
|
||||
formal = ensure_execution_for_workflow_version(review_case_id=901, task_id=int(task.id))
|
||||
duplicate = ShippingProcessExecution(
|
||||
execution_no='APX-DUPLICATE', task_id=int(task.id),
|
||||
candidate_set_id=task.active_inventory_candidate_set_id,
|
||||
execution_revision=1, status='blocked', current_gate_code=AUTO_PROGRESS_GATE_CODES[0],
|
||||
lock_version=1,
|
||||
)
|
||||
|
||||
result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='test-worker')
|
||||
execution = db.session.get(ShippingProcessExecution, result['execution_id'] if 'execution_id' in result else Job.query.get(submitted['job_id']).execution_id)
|
||||
gates = ShippingProcessGate.query.filter_by(execution_id=execution.id).order_by(ShippingProcessGate.sequence_no).all()
|
||||
jobs = Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').order_by(Job.id).all()
|
||||
|
||||
assert result['gate_code'] == AUTO_PROGRESS_GATE_CODES[0]
|
||||
assert gates[0].status == 'passed'
|
||||
assert gates[1].status == 'pending'
|
||||
assert len(jobs) == 2
|
||||
assert jobs[0].status == 'success' and jobs[1].status == 'queued'
|
||||
assert jobs[1].gate_id == gates[1].id
|
||||
|
||||
|
||||
def test_stale_job_is_cancelled_without_touching_current_execution(app):
|
||||
"""候选/Execution 指针已切换时,迟到 Job 只能 cancelled,不能改写当前链。"""
|
||||
task = _task_with_candidate()
|
||||
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
|
||||
assert claimed is not None
|
||||
old_execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id)
|
||||
replacement = ShippingProcessExecution(
|
||||
execution_no='APX-REPLACEMENT', task_id=task.id,
|
||||
candidate_set_id=task.active_inventory_candidate_set_id, execution_revision=2,
|
||||
status='active', lock_version=1,
|
||||
)
|
||||
db.session.add(replacement)
|
||||
db.session.add(duplicate)
|
||||
db.session.flush()
|
||||
task.active_process_execution_id = replacement.id
|
||||
for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1):
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(duplicate.id), gate_code=gate_code, sequence_no=sequence_no,
|
||||
status='pending', evaluation_version=1, lock_version=1,
|
||||
))
|
||||
task.active_process_execution_id = int(duplicate.id)
|
||||
db.session.commit()
|
||||
|
||||
result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='late-worker')
|
||||
assert result['status'] == 'cancelled'
|
||||
assert Job.query.get(submitted['job_id']).status == 'cancelled'
|
||||
assert old_execution.status == 'active'
|
||||
assert db.session.get(ShippingProcessExecution, replacement.id).status == 'active'
|
||||
result = submit_auto_progress(task=task, trigger='user_retry')
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(duplicate)
|
||||
assert result['execution_id'] == formal.id
|
||||
assert task.active_process_execution_id == formal.id
|
||||
assert duplicate.status == 'superseded'
|
||||
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0
|
||||
|
||||
|
||||
def test_excel_gate_waits_for_human_receipt(app, monkeypatch):
|
||||
"""Excel Gate 成功后不 completed;自动上传关闭时必须停在 receipt Gate 的人工阻断。"""
|
||||
def test_formal_execution_queues_one_gate_attempt_job(app):
|
||||
"""正式 20-Gate 链必须落 Attempt 并入队 ProcessGate Job,不能同步早退。"""
|
||||
task = _task_with_candidate()
|
||||
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller._gate_outcome',
|
||||
lambda task, gate: ('passed', None, {}),
|
||||
formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=formal,
|
||||
through_gate_code='task_creation',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
for _ in range(5):
|
||||
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
|
||||
assert claimed is not None
|
||||
run_auto_progress_job(job_id=claimed.id, worker_id='test-worker')
|
||||
execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id)
|
||||
receipt_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='upload_receipt_recorded',
|
||||
).one()
|
||||
|
||||
assert execution.status == 'blocked'
|
||||
assert receipt_gate.status == 'blocked_manual'
|
||||
assert receipt_gate.blocking_reason_code == 'manual_upload_receipt_required'
|
||||
|
||||
|
||||
def test_recorded_receipt_reopens_only_final_gate(app, monkeypatch):
|
||||
"""人工登记回执后,服务端只重新执行最后一个 receipt Gate 并完成 Execution。"""
|
||||
task = _task_with_candidate()
|
||||
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller._gate_outcome',
|
||||
lambda task, gate: ('passed', None, {}),
|
||||
)
|
||||
for _ in range(5):
|
||||
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
|
||||
run_auto_progress_job(job_id=claimed.id, worker_id='test-worker')
|
||||
task.upload_receipt_json = {'receipt_no': 'R-1'}
|
||||
task.active_process_execution_id = formal.id
|
||||
db.session.commit()
|
||||
resume = submit_auto_progress(task=task, trigger='manual_upload_receipt_recorded')
|
||||
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
|
||||
result = run_auto_progress_job(job_id=claimed.id, worker_id='test-worker')
|
||||
|
||||
assert resume['gate_code'] == 'upload_receipt_recorded'
|
||||
assert result['gate_code'] == 'upload_receipt_recorded'
|
||||
assert db.session.get(ShippingProcessExecution, result['execution_id']).status == 'completed'
|
||||
first = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
second = submit_auto_progress(task=task, trigger='duplicate_confirm')
|
||||
|
||||
assert first['status'] == 'queued'
|
||||
assert first['job_id'] == second['job_id']
|
||||
attempt = db.session.get(ShippingProcessGateAttempt, first['attempt_id'])
|
||||
job = db.session.get(Job, first['job_id'])
|
||||
assert attempt is not None and attempt.job_id == job.id
|
||||
assert attempt.status == 'queued'
|
||||
assert job.job_type == 'shipping_process_gate'
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 1
|
||||
|
||||
|
||||
def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
ensure_stp_auto_create_for_case,
|
||||
)
|
||||
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-REUSE-MISSING-RETRY', status='ready', confirmed_task_id=None,
|
||||
document_id=9001, candidate_id=None, run_id=1,
|
||||
run=SimpleNamespace(id=1, run_no='SNER-REUSE-MISSING-RETRY'),
|
||||
owner_user_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=1,
|
||||
validation_result_json={'status': 'ready', 'can_build': True, 'can_auto_create': True},
|
||||
issue_summary_json=[], header_values_json={}, lines_json=[],
|
||||
),
|
||||
)
|
||||
active = SimpleNamespace(id=901, status='queued')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._persist_case_candidate_qualification',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
|
||||
return_value=active,
|
||||
), patch('app.services.shipping_notice.order_stp_auto_create_service.db'):
|
||||
result = ensure_stp_auto_create_for_case(case=case, commit=False)
|
||||
|
||||
assert result['status'] == 'already_queued'
|
||||
assert result['job_id'] == 901
|
||||
assert result['retry_of_job_id'] is None
|
||||
|
||||
|
||||
def test_legacy_shipping_auto_progress_job_is_terminal_readonly(app):
|
||||
"""历史 APX Job 被 Worker 领取时只能终止,不能再执行六 Gate 状态机。"""
|
||||
task = _task_with_candidate()
|
||||
legacy = ShippingProcessExecution(
|
||||
execution_no='APX-READONLY', task_id=int(task.id), status='active',
|
||||
candidate_set_id=int(task.active_inventory_candidate_set_id),
|
||||
current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
|
||||
)
|
||||
db.session.add(legacy)
|
||||
db.session.flush()
|
||||
gate = ShippingProcessGate(
|
||||
execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0],
|
||||
sequence_no=1, status='running', evaluation_version=1, lock_version=1,
|
||||
)
|
||||
db.session.add(gate)
|
||||
db.session.flush()
|
||||
task.active_process_execution_id = int(legacy.id)
|
||||
job = Job(
|
||||
domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id),
|
||||
execution_id=int(legacy.id), gate_id=int(gate.id), status='running',
|
||||
candidate_set_id=int(task.active_inventory_candidate_set_id),
|
||||
payload_json={'fencing_token': 'legacy-token'}, fencing_token='legacy-token', max_attempts=1,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
result = run_auto_progress_job(job_id=int(job.id), worker_id='test-worker')
|
||||
|
||||
db.session.refresh(job)
|
||||
db.session.refresh(gate)
|
||||
assert result['status'] == 'legacy_readonly'
|
||||
assert job.status == 'cancelled'
|
||||
assert gate.status == 'cancelled'
|
||||
|
||||
|
||||
def test_active_legacy_apx_job_does_not_block_formal_submission(app):
|
||||
"""历史 APX 活动 Job 不得被正式 20-Gate 提交入口复用或阻塞。"""
|
||||
task = _task_with_candidate()
|
||||
legacy = ShippingProcessExecution(
|
||||
execution_no='APX-NONBLOCKING', task_id=int(task.id), status='active',
|
||||
candidate_set_id=int(task.active_inventory_candidate_set_id),
|
||||
current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
|
||||
)
|
||||
db.session.add(legacy)
|
||||
db.session.flush()
|
||||
gate = ShippingProcessGate(
|
||||
execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0],
|
||||
sequence_no=1, status='queued', evaluation_version=1, lock_version=1,
|
||||
)
|
||||
db.session.add(gate)
|
||||
db.session.flush()
|
||||
task.active_process_execution_id = int(legacy.id)
|
||||
db.session.add(Job(
|
||||
domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id),
|
||||
execution_id=int(legacy.id), gate_id=int(gate.id), candidate_set_id=int(task.active_inventory_candidate_set_id),
|
||||
status='queued', payload_json={}, fencing_token='legacy-token', max_attempts=1,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = submit_auto_progress(task=task, trigger='review_confirmed')
|
||||
|
||||
assert result['status'] == 'queued'
|
||||
assert db.session.get(Job, result['job_id']).job_type == 'shipping_process_gate'
|
||||
@@ -83,6 +83,13 @@ def test_message_zh_for_reason_and_rpa_meta():
|
||||
assert message_zh_for_reason('totally_unknown_xyz') is None
|
||||
|
||||
|
||||
def test_rpa_upload_failures_keep_manual_retry_action():
|
||||
"""RPA 失败仍属于 Gate 19,不能被覆盖成 Gate 20 的人工待办重生。"""
|
||||
for reason_code in ('upload_rpa_login_failed', 'upload_platform_rejected'):
|
||||
projected = build_explainability_reason(reason_code=reason_code)
|
||||
assert projected['next_action'] == 'retry_freight_upload_rpa'
|
||||
|
||||
|
||||
def test_inventory_preparation_reason_code_from_pending():
|
||||
"""履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -19,12 +19,17 @@ from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
|
||||
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
|
||||
from app.services.shipping_notice.export import _excel_business_no, _filename, _mapping_value, _system_fact, generate_shipment_excel
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_lines_for_task,
|
||||
replace_task_inventory_link,
|
||||
resolve_inventory_lines_for_execution,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
@@ -132,6 +137,76 @@ def test_filename_pattern_supports_business_number_and_split_business_variables(
|
||||
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
|
||||
|
||||
|
||||
def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path):
|
||||
"""业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}],
|
||||
)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
|
||||
inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
|
||||
share_mode='task_only', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
db.session.flush()
|
||||
replace_task_inventory_link(task, inventory_file, role='owner')
|
||||
db.session.flush()
|
||||
|
||||
resolved = resolve_inventory_lines_for_execution(
|
||||
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
|
||||
)
|
||||
|
||||
assert resolved == [{'part_number': 'ACTIVE'}]
|
||||
assert task.inventory_lines_json == [{'part_number': 'STALE'}]
|
||||
|
||||
|
||||
def test_inventory_execution_keeps_legacy_fallback_without_active_link(app):
|
||||
"""无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
assert resolve_inventory_lines_for_execution(
|
||||
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
|
||||
) == [{'part_number': 'PAYLOAD'}]
|
||||
assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}]
|
||||
|
||||
|
||||
def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch):
|
||||
"""已有正式快照 JSON 时读取动作不得重新解析物理文件并覆盖已修复数据。"""
|
||||
with app.app_context():
|
||||
storage_path = tmp_path / 'stale.xlsx'
|
||||
storage_path.write_bytes(b'stale-source')
|
||||
task = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
|
||||
inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
|
||||
line_count=1, share_mode='task_only', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
db.session.flush()
|
||||
replace_task_inventory_link(task, inventory_file, role='owner')
|
||||
db.session.flush()
|
||||
reparse_calls: list[int] = []
|
||||
|
||||
def stale_reparse(_inventory_file):
|
||||
reparse_calls.append(int(_inventory_file.id))
|
||||
return ([{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-STALE'}], {})
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.parse_inventory_snapshot_file', stale_reparse,
|
||||
)
|
||||
|
||||
assert active_inventory_lines_for_task(task) == [
|
||||
{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'},
|
||||
]
|
||||
assert reparse_calls == []
|
||||
|
||||
|
||||
def test_filename_pattern_falls_back_to_controlled_environment_configuration(app):
|
||||
"""模板未提供规则时可使用受控环境变量,调用方仍不能提交任意文件名。"""
|
||||
with app.app_context():
|
||||
@@ -299,6 +374,54 @@ def test_export_date_system_fact_uses_business_timezone(app):
|
||||
assert isinstance(value, date)
|
||||
|
||||
|
||||
def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app):
|
||||
"""Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。"""
|
||||
with app.app_context():
|
||||
shipping_case = ShippingCase(
|
||||
case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1,
|
||||
)
|
||||
task = ShippingNotice(task_no='TASK-EXCEL-NO')
|
||||
task.shipping_case = shipping_case
|
||||
|
||||
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101'
|
||||
assert shipping_case.business_no == 'IVMX26080801'
|
||||
|
||||
|
||||
def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(app):
|
||||
"""LineNumber 缺失时用导出行序号,Shipment Value 缺失时用数量乘单价。"""
|
||||
with app.app_context():
|
||||
fields = _lookup_standard_fields('line_no', 'line_amount_with_tax')
|
||||
task = ShippingNotice(task_no='TASK-MAPPING')
|
||||
|
||||
assert _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'},
|
||||
task=task, order_values={}, inventory_values={}, export_sequence=1,
|
||||
) == 1
|
||||
assert _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'},
|
||||
task=task, order_values={'__qty': Decimal('14'), '__unit_price': Decimal('941.76')}, inventory_values={},
|
||||
) == 13184.64
|
||||
|
||||
|
||||
def test_clear_template_data_rows_keeps_headers_and_removes_residual_values():
|
||||
"""模板数据区从起始行起清空,表头不受影响。"""
|
||||
from app.services.shipping_notice.export import _clear_template_data_rows
|
||||
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet['A3'] = 'header'
|
||||
sheet['A4'] = 'current'
|
||||
sheet['A5'] = 'residual-5'
|
||||
sheet['B6'] = 'residual-6'
|
||||
|
||||
_clear_template_data_rows(sheet, 4)
|
||||
|
||||
assert sheet['A3'].value == 'header'
|
||||
assert sheet['A4'].value is None
|
||||
assert sheet['A5'].value is None
|
||||
assert sheet['B6'].value is None
|
||||
|
||||
|
||||
def test_two_sources_can_share_one_published_excel_template(app, tmp_path):
|
||||
"""同结构库存源绑定同一 published 模板,避免复制维护映射规则。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
@@ -541,8 +664,8 @@ def test_template_publish_rejects_order_field_removed_from_current_schema(app):
|
||||
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path):
|
||||
"""同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。"""
|
||||
def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_path):
|
||||
"""导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
@@ -597,11 +720,37 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
|
||||
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='值不一致'):
|
||||
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
|
||||
generate_shipment_excel(task)
|
||||
export_root = tmp_path / 'shipping' / 'exports'
|
||||
assert not export_root.exists() or not list(export_root.rglob('*.xlsx'))
|
||||
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ACTIVE-FIXED', user_id=None,
|
||||
source_file_name='fixed.xlsx', storage_path=str(tmp_path / 'fixed.xlsx'),
|
||||
inventory_lines_json=[
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
|
||||
],
|
||||
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
replace_task_inventory_link(task, inventory_file, role='owner')
|
||||
task.inventory_snapshot_id = inventory_file.id
|
||||
db.session.flush()
|
||||
|
||||
path, _filename_value, artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-FIXED'
|
||||
finally:
|
||||
workbook.close()
|
||||
assert artifact.inventory_snapshot_id == inventory_file.id
|
||||
assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1'
|
||||
|
||||
|
||||
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
|
||||
"""Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。"""
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""用途:验证库存恢复只失效当前任务关联的 Mapping/下游事实。
|
||||
依赖:recovery_invalidation_service 与库存谱系模型。
|
||||
逻辑:通过最小模型级约束检查和服务分支合同,禁止跨任务失效。
|
||||
"""
|
||||
|
||||
from app.models import ShippingInventoryMapping
|
||||
|
||||
|
||||
def test_mapping_status_contract_allows_invalidation_without_delete():
|
||||
"""Mapping 失效必须保留记录,状态使用正式 invalidated 枚举。"""
|
||||
allowed = next(
|
||||
constraint.sqltext.text
|
||||
for constraint in ShippingInventoryMapping.__table__.constraints
|
||||
if getattr(constraint, 'name', '') == 'ck_shipping_inventory_mapping_status'
|
||||
)
|
||||
assert 'invalidated' in allowed
|
||||
|
||||
|
||||
def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
|
||||
"""候选版本切换后,旧 Artifact 不可下载,未终态上传 Attempt 不得继续使用。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
|
||||
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs
|
||||
|
||||
task = 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',
|
||||
original_filename='template.xlsx', file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1,
|
||||
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.flush()
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=task.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,
|
||||
file_size=1, status='ready',
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
attempt = ShippingUploadAttempt(
|
||||
artifact_id=artifact.id, attempt_no=1, mode='manual', idempotency_key='candidate-invalidate-1',
|
||||
status='running',
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
|
||||
_invalidate_task_candidate_outputs(task, old_candidate_set_id=1, session=db.session)
|
||||
|
||||
db.session.refresh(artifact)
|
||||
db.session.refresh(attempt)
|
||||
assert artifact.status == 'superseded'
|
||||
assert attempt.status == 'failed'
|
||||
assert attempt.invalidated_at is not None
|
||||
assert attempt.invalidation_reason == 'candidate_set_refrozen'
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
用途:验证库存快照复用策略和多源组合指纹的 fail-closed 合同。
|
||||
依赖:纯函数服务。
|
||||
逻辑:覆盖身份、状态、过期与指纹变化;不触发外部 RPA。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_snapshot_reuse_requires_ready_identity_and_versions():
|
||||
snap = SimpleNamespace(
|
||||
snapshot_status='ready', expires_at=datetime.utcnow() + timedelta(hours=1),
|
||||
source_code='A', warehouse_id='W1', source_config_version='v1',
|
||||
input_fingerprint='cand-1', file_sha256='sha-1', parser_version='p1', mapping_version='m1', invalidated_at=None,
|
||||
)
|
||||
ok, reasons = check_inventory_snapshot_reusable(
|
||||
snapshot=snap, source_code='A', warehouse_id='W1',
|
||||
source_config_version='v1', candidate_input_fingerprint='cand-1',
|
||||
parser_version='p1', mapping_version='m1',
|
||||
expected_file_sha256='sha-1',
|
||||
)
|
||||
assert ok is True and reasons == []
|
||||
ok, reasons = check_inventory_snapshot_reusable(snapshot=snap, source_code='B', warehouse_id='W1')
|
||||
assert ok is False and 'source_code_mismatch' in reasons
|
||||
|
||||
ok, reasons = check_inventory_snapshot_reusable(snapshot=snap, source_code='A', parser_version='p2')
|
||||
assert ok is False and 'parser_version_mismatch' in reasons
|
||||
|
||||
|
||||
def test_combination_fingerprint_is_order_independent_but_input_sensitive():
|
||||
a = build_inventory_combination_fingerprint(
|
||||
task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand',
|
||||
sources=[{'source_code': 'B', 'snapshot_id': 2}, {'source_code': 'A', 'snapshot_id': 1}],
|
||||
reservation_version='r1', matching_rule_version='m1',
|
||||
)
|
||||
b = build_inventory_combination_fingerprint(
|
||||
task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand',
|
||||
sources=[{'source_code': 'A', 'snapshot_id': 1}, {'source_code': 'B', 'snapshot_id': 2}],
|
||||
reservation_version='r1', matching_rule_version='m1',
|
||||
)
|
||||
c = build_inventory_combination_fingerprint(
|
||||
task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand',
|
||||
sources=[{'source_code': 'A', 'snapshot_id': 1}, {'source_code': 'B', 'snapshot_id': 3}],
|
||||
reservation_version='r1', matching_rule_version='m1',
|
||||
)
|
||||
assert a == b
|
||||
assert a != c
|
||||
@@ -11,9 +11,25 @@ from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_text,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
|
||||
|
||||
def test_explicit_mapping_matches_excel_header_line_breaks(app):
|
||||
"""发布映射的 Qty\nAvailable 表头必须解析到可用数量列。"""
|
||||
with app.app_context():
|
||||
columns = resolve_columns_from_field_mapping(
|
||||
["Supplier Sku", "Resevation Order", "Qty\nAvailable", "AWS Sku"],
|
||||
{
|
||||
"1": "Supplier Sku",
|
||||
"2": "Resevation Order",
|
||||
"3": "Qty Available",
|
||||
"5": "AWS Sku",
|
||||
},
|
||||
)
|
||||
assert columns["3"] == 2
|
||||
|
||||
|
||||
def _write_title_row_inventory_xlsx(path: Path) -> None:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
|
||||
@@ -15,9 +15,22 @@ from app.models import (
|
||||
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
ShippingOrderCustomerMatch,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
from tests.conftest import (
|
||||
inventory_xlsx_with_warehouse,
|
||||
scheduled_rpa_batch_item,
|
||||
seed_rpa_inventory_trigger,
|
||||
seed_task_inventory_source,
|
||||
freeze_test_task_order_snapshot,
|
||||
v2_inventory_batch_payload,
|
||||
)
|
||||
|
||||
|
||||
def _with_v2_batch_envelope(payload: dict) -> dict:
|
||||
"""旧测试场景统一补齐冻结 v2 callback envelope,生产入口仍严格校验。"""
|
||||
return v2_inventory_batch_payload(payload)
|
||||
|
||||
|
||||
def _tool_headers():
|
||||
@@ -99,6 +112,8 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
|
||||
task.customer_resolution_method = 'test_fixture'
|
||||
db.session.add_all([case, task])
|
||||
db.session.flush()
|
||||
# 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。
|
||||
task._test_customer_confirmed = True
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -129,6 +144,26 @@ def _confirmed_customer_for_rpa_flows(app, monkeypatch):
|
||||
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _freeze_test_rpa_batch_callback_contract(monkeypatch):
|
||||
"""兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。"""
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
import sys
|
||||
|
||||
original = inventory_rpa_workflow.rpa_report_inventory_batch
|
||||
callback_seq = {'value': 0}
|
||||
|
||||
def _wrapped(payload):
|
||||
body = _with_v2_batch_envelope(payload)
|
||||
if not payload.get('callback_id'):
|
||||
callback_seq['value'] += 1
|
||||
body['callback_id'] = f"test-callback:{body.get('batch_run_no') or 'unknown'}:{callback_seq['value']}"
|
||||
return original(body)
|
||||
|
||||
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
|
||||
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
|
||||
|
||||
|
||||
def test_inventory_rpa_single_attempt_messages_hide_fraction():
|
||||
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
@@ -203,6 +238,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
|
||||
db.session.add_all([profile, rtm_source, task, source_snapshot, other_snapshot])
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='1000123456', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
freeze_test_task_order_snapshot(task)
|
||||
db.session.commit()
|
||||
|
||||
result = resolve_ambiguous_source_from_ready_snapshots(
|
||||
@@ -239,7 +276,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
|
||||
@@ -247,7 +284,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
db.session.commit()
|
||||
|
||||
upload = FileStorage(
|
||||
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', qty=8).getvalue()),
|
||||
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', reservation_id='00001', qty=8).getvalue()),
|
||||
filename='manual-stock.xlsx',
|
||||
)
|
||||
result = upload_inventory_file(task.task_no, upload)
|
||||
@@ -264,7 +301,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
assert snapshot.mapping_confirmed is True
|
||||
fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
assert snapshot.inventory_lines_json[0][fields['part_number']] == 'A001'
|
||||
assert snapshot.inventory_lines_json[0][fields['reservation_id']] == 'R-1'
|
||||
assert snapshot.inventory_lines_json[0][fields['reservation_id']] == '00001'
|
||||
assert snapshot.inventory_lines_json[0][fields['available_qty']] == 8
|
||||
|
||||
|
||||
@@ -282,7 +319,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.append(['Warehouse ID', 'Unexpected Part', 'Reservation ID', 'Qty'])
|
||||
sheet.append(['AWSDU', 'A001', 'R-1', 8])
|
||||
sheet.append(['AWSDU', 'A001', '00001', 8])
|
||||
workbook.save(stream)
|
||||
workbook.close()
|
||||
stream.seek(0)
|
||||
@@ -290,7 +327,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
|
||||
@@ -336,14 +373,16 @@ def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path):
|
||||
"""batch results 中空 dict 应直接 failed,不走 success→file_missing 绕路。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch({
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
"run_no": "RUN-EMPTY-ITEM",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{}],
|
||||
})
|
||||
}))
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "failed"
|
||||
assert result["data"]["result_status"] == "failed"
|
||||
@@ -365,7 +404,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch({
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
"run_no": "RUN-MIXED",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [
|
||||
@@ -383,7 +422,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
"error_message": "timeout",
|
||||
},
|
||||
],
|
||||
})
|
||||
}))
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "partial_failed"
|
||||
assert result["data"]["result_status"] == "partial_failed"
|
||||
@@ -398,7 +437,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch({
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
"run_no": "RUN-ALL-FAIL",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{
|
||||
@@ -408,7 +447,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
|
||||
"success": False,
|
||||
"error_message": "timeout",
|
||||
}],
|
||||
})
|
||||
}))
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "failed"
|
||||
assert result["failed_count"] == 1
|
||||
@@ -474,7 +513,7 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
|
||||
],
|
||||
}
|
||||
},
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -512,7 +551,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
@@ -546,7 +585,10 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
from app import db
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
@@ -554,7 +596,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
@@ -598,7 +640,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
@@ -709,7 +751,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
|
||||
@@ -777,7 +819,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no=run_no)
|
||||
@@ -866,8 +908,9 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample_a = drop_dir / "task_a.xlsx"
|
||||
sample_b = drop_dir / "task_b.xlsx"
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -892,14 +935,14 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
task_b = ShippingNotice(
|
||||
task_no="SN-BATCH-FAIL",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task_a)
|
||||
_confirm_direct_rpa_task_customer(task_b)
|
||||
@@ -947,6 +990,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "shared.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
run_no = "RUN-SHARED-LINK"
|
||||
@@ -957,14 +1001,14 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
task_fail = ShippingNotice(
|
||||
task_no="SN-SHARED-FAIL",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task_ok)
|
||||
_confirm_direct_rpa_task_customer(task_fail)
|
||||
@@ -1046,7 +1090,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
@@ -1091,7 +1135,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
@@ -1128,7 +1172,7 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
|
||||
task_no="SN-REPAIR-ATTACH",
|
||||
source_type="manual",
|
||||
process_status="inventory_ready",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
@@ -1286,7 +1330,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
|
||||
task_no="SN-REPAIR-REJECT",
|
||||
source_type="manual",
|
||||
process_status="inventory_ready",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
|
||||
@@ -9,6 +9,8 @@ backend/tests/test_shipping_notice_inventory_schedule.py
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
|
||||
from app.services.schedule.scheduler_service import run_task_now
|
||||
@@ -24,6 +26,22 @@ from app.services.schedule.shipping_inventory_rpa_job import (
|
||||
_filter_sources,
|
||||
run_shipping_inventory_rpa_schedule,
|
||||
)
|
||||
from tests.conftest import v2_inventory_batch_payload
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _freeze_schedule_batch_callback_contract(monkeypatch):
|
||||
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。"""
|
||||
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))
|
||||
|
||||
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
|
||||
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_rpa_trigger_for_task.py
|
||||
|
||||
用途:验证按需库存导出在 batch 与 legacy 模式下生成正确 trigger。
|
||||
用途:验证按需库存导出仅生成 v2 batch trigger,并携带完整冻结身份。
|
||||
依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。
|
||||
逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
|
||||
|
||||
|
||||
@@ -27,28 +29,39 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
|
||||
path = write_inventory_export_trigger_for_task(
|
||||
"SN-ON-DEMAND-1",
|
||||
source,
|
||||
payload={"mode": "auto", "attempt": 1},
|
||||
payload={
|
||||
"mode": "auto", "attempt": 1, "source_run_no": "SRC-1",
|
||||
"lease_token": "lease-1", "candidate_set_id": 12,
|
||||
"execution_id": 88, "gate_id": 901,
|
||||
"expected_warehouse_id": "AWSDU",
|
||||
},
|
||||
)
|
||||
assert path
|
||||
trigger_files = list(trigger_dir.glob("inventory_export_batch_*.json"))
|
||||
assert trigger_files
|
||||
text = trigger_files[0].read_text(encoding="utf-8")
|
||||
assert "inventory_export_batch" in text
|
||||
assert "SN-ON-DEMAND-1" in text
|
||||
assert "DSV360_AWSDU" in text
|
||||
payload = __import__("json").loads(trigger_files[0].read_text(encoding="utf-8"))
|
||||
assert payload["action"] == "inventory_export_batch"
|
||||
item = payload["inventory_sources"][0]
|
||||
assert item["task_no"] == "SN-ON-DEMAND-1"
|
||||
assert item["source_code"] == "DSV360_AWSDU"
|
||||
assert item["source_run_no"] == "SRC-1"
|
||||
assert item["execution_id"] == 88
|
||||
assert item["gate_id"] == 901
|
||||
|
||||
|
||||
def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path):
|
||||
"""batch 关闭时仍写 legacy inventory_export trigger。"""
|
||||
def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
"""v2 batch 关闭时 fail-closed,禁止生成 legacy inventory_export trigger。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
with app.app_context():
|
||||
path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
|
||||
assert path
|
||||
assert list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))
|
||||
with app.app_context(), pytest.raises(ValidationError, match="v2") as exc_info:
|
||||
write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
|
||||
assert exc_info.value.code == "SHIPPING.INVENTORY_RPA_V2_REQUIRED"
|
||||
assert not list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))
|
||||
|
||||
|
||||
def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path):
|
||||
@@ -70,3 +83,30 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p
|
||||
assert item["entry_url"] == "https://example.invalid/dbs"
|
||||
assert "username" not in item
|
||||
assert "password" not in item
|
||||
|
||||
|
||||
def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
|
||||
"""新 batch Trigger 必须显式写入顶层和逐源 callback_id,Worker 不得推导。"""
|
||||
import json
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
|
||||
source = {
|
||||
"source_code": "DBS",
|
||||
"connector_type": "dbs",
|
||||
"warehouse_id": "WH-1",
|
||||
"source_run_no": "SRC-1",
|
||||
"attempt_no": 2,
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
"expected_warehouse_id": "WH-1",
|
||||
"lease_token": "lease-1",
|
||||
}
|
||||
with app.app_context():
|
||||
path = write_inventory_export_batch_trigger("BATCH-1", [source])
|
||||
body = json.loads((path and __import__('pathlib').Path(path)).read_text(encoding="utf-8"))
|
||||
assert body["callback_id"] == "BATCH-1:batch:C1"
|
||||
assert body["inventory_sources"][0]["callback_id"] == "SRC-1:C1"
|
||||
@@ -190,6 +190,39 @@ def test_parse_notice_tool_is_removed(app, client):
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch):
|
||||
"""旧 Tool 入口不能绕过 GateAttempt 直接生成 Excel。"""
|
||||
from app.services.shipping_notice import fulfillment_workflow
|
||||
|
||||
submitted: dict[str, object] = {}
|
||||
|
||||
def _submit(task_no, **kwargs):
|
||||
submitted['task_no'] = task_no
|
||||
submitted.update(kwargs)
|
||||
return {'status': 'running', 'data': {}}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
|
||||
_submit,
|
||||
)
|
||||
|
||||
result = fulfillment_workflow.generate_excel({
|
||||
'task_id': 'SN-FORMAL-EXCEL-ONLY',
|
||||
'operator_id': 7,
|
||||
'idempotency_key': 'formal-excel-only',
|
||||
})
|
||||
|
||||
assert result['status'] == 'running'
|
||||
assert submitted == {
|
||||
'task_no': 'SN-FORMAL-EXCEL-ONLY',
|
||||
'trigger': 'tool_api_generate_excel',
|
||||
'expected_version': None,
|
||||
'idempotency_key': 'formal-excel-only',
|
||||
'resume_gate_code': 'artifact_generation',
|
||||
'operator_id': 7,
|
||||
}
|
||||
|
||||
|
||||
def test_match_notice_lines_reports_progress():
|
||||
seen: list[tuple[int, int]] = []
|
||||
|
||||
@@ -806,7 +839,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
|
||||
|
||||
|
||||
def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch):
|
||||
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
create_res = client.post(
|
||||
@@ -820,15 +853,11 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_ensure_inventory(payload):
|
||||
captured.update(payload)
|
||||
return {
|
||||
"status": "running",
|
||||
"task_id": payload["task_id"],
|
||||
"message": "已触发库存获取(测试桩)",
|
||||
}
|
||||
def fake_request_formal_gate_action(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"}
|
||||
|
||||
monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory)
|
||||
monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action)
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
@@ -838,9 +867,9 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon
|
||||
data = res.get_json()
|
||||
assert data["status"] == "running"
|
||||
assert data["task_id"] == task_id
|
||||
assert data["message"] == "已触发库存获取(测试桩)"
|
||||
assert captured["task_id"] == task_id
|
||||
assert captured["mode"] == "retry_rpa"
|
||||
assert data["message"] == "已提交正式 20-Gate 恢复动作"
|
||||
assert captured["task"].task_no == task_id
|
||||
assert captured["action_code"] == "retry_inventory_preparation"
|
||||
|
||||
|
||||
def test_parse_inventory_oversized_text_route_is_removed(app, client):
|
||||
|
||||
@@ -59,6 +59,10 @@ def _seed_blocked_execution(owner: User | None = None):
|
||||
execution_id=int(execution.id),
|
||||
gate_code='order_freeze_readiness',
|
||||
).first()
|
||||
# 夹具显式将阻断 Gate 设为 Execution.current_gate,覆盖前置 Gate 默认初始状态,
|
||||
# 以便 API 测试验证当前 Gate 的统一写校验。
|
||||
execution.current_gate_code = gate.gate_code
|
||||
execution.primary_next_action_code = gate.next_action_code
|
||||
db.session.commit()
|
||||
return user, execution, gate
|
||||
|
||||
@@ -86,6 +90,19 @@ def _seed_blocked_execution_for_agent_readonly():
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
if not cases:
|
||||
# 当前最小 API 夹具可能没有完整 Worker Candidate;仍创建只读授权所需的
|
||||
# 正式 Case 绑定,测试只验证权限边界,不把缺失 Candidate 伪装成业务成功。
|
||||
from app.models import ShippingOrderReviewCase
|
||||
unit = run.extraction_plan.units[0] if run.extraction_plan and run.extraction_plan.units else None
|
||||
if unit is not None and unit.document_id:
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=f'SORC-API-FALLBACK-{run.id}', run_id=int(run.id), unit_id=int(unit.id),
|
||||
document_id=int(unit.document_id), owner_user_id=int(user.id), status='draft',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
cases = [case]
|
||||
assert cases, 'review case required for agent authorization path'
|
||||
case = cases[0]
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
@@ -224,6 +241,51 @@ def test_workspace_post_action_idempotent(app, client):
|
||||
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='api-idempotent-1').count() == 1
|
||||
|
||||
|
||||
def test_workspace_post_action_rejects_non_current_gate_for_all_gate_actions(app, client):
|
||||
"""所有阶段统一禁止绕过 current_gate 写入其他 Gate。"""
|
||||
with app.app_context():
|
||||
owner, execution, gate = _seed_blocked_execution()
|
||||
# order_freeze_readiness 是当前阻断;请求另一个正式 Gate 必须 fail-closed。
|
||||
other_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_matching',
|
||||
).first()
|
||||
assert other_gate is not None
|
||||
resp = client.post(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}'
|
||||
'/gates/inventory_matching/actions',
|
||||
headers=_auth_headers(owner),
|
||||
json={
|
||||
'action_code': 'open_inventory_match_review',
|
||||
'expected_gate_version': int(other_gate.evaluation_version),
|
||||
'idempotency_key': 'api-non-current-gate-1',
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_NOT_CURRENT'
|
||||
|
||||
|
||||
def test_workspace_post_action_rejects_terminal_execution_for_all_gate_actions(app, client):
|
||||
"""所有阶段统一禁止 completed/cancelled Execution 写动作。"""
|
||||
with app.app_context():
|
||||
owner, execution, gate = _seed_blocked_execution()
|
||||
execution.status = 'completed'
|
||||
db.session.commit()
|
||||
resp = client.post(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}'
|
||||
f'/gates/{gate.gate_code}/actions',
|
||||
headers=_auth_headers(owner),
|
||||
json={
|
||||
'action_code': 'open_order_review',
|
||||
'expected_gate_version': int(gate.evaluation_version),
|
||||
'idempotency_key': 'api-terminal-execution-1',
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_EXECUTION_TERMINAL'
|
||||
|
||||
|
||||
|
||||
|
||||
def test_workspace_get_missing_execution_404(app, client):
|
||||
"""不存在的 execution_no 返回 404。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -16,6 +16,7 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_REASON_OWNING_GATE,
|
||||
assert_process_gate_contract_integrity,
|
||||
action_presentation,
|
||||
field_quality_may_block,
|
||||
owning_gate_for_reason,
|
||||
primary_next_action_for_gate,
|
||||
@@ -59,6 +60,22 @@ def test_inventory_source_routing_primary_retry_action():
|
||||
assert action == 'retry_with_latest_rules'
|
||||
|
||||
|
||||
def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
"""库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。"""
|
||||
assert action_presentation('open_shortage_review') == {
|
||||
'code': 'open_shortage_review',
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.open_shortage_review',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'navigation',
|
||||
}
|
||||
assert action_presentation('retry_inventory_from_matching') == {
|
||||
'code': 'retry_inventory_from_matching',
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_from_matching',
|
||||
'kind': 'recovery',
|
||||
'dispatch': 'mutation',
|
||||
}
|
||||
|
||||
|
||||
def test_process_gate_reason_ownership_is_unique():
|
||||
"""
|
||||
每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。
|
||||
@@ -83,6 +100,205 @@ def test_field_quality_block_eligibility():
|
||||
assert field_quality_may_block(required=False, auto_create_key_field=False) is False
|
||||
|
||||
|
||||
def test_projection_marks_apx_gate_as_readonly_without_executable_actions(app, monkeypatch):
|
||||
"""APX 历史 Gate 只可审计展示,不能再投影为可恢复业务 Gate。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
gate = SimpleNamespace(
|
||||
id=1, gate_code='inventory_candidates_calculated', sequence_no=1,
|
||||
status='pending', evaluation_version=1, input_fingerprint=None,
|
||||
blocking_reason_code=None, blocking_reason_json=None,
|
||||
recommendation_json=None, effective_result_json={}, findings_json=None,
|
||||
next_action_code=None, passed_at=None, invalidated_at=None,
|
||||
latest_attempt_id=None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection.ShippingProcessGateAttempt.query,
|
||||
'get',
|
||||
lambda _id: None,
|
||||
raising=False,
|
||||
)
|
||||
payload = projection.serialize_process_gate(gate, include_diagnostics=False)
|
||||
assert payload['gate_code'] == 'inventory_candidates_calculated'
|
||||
assert payload['legacy_readonly'] is True
|
||||
assert payload['allowed_actions'] == []
|
||||
assert payload['recovery_targets'] == []
|
||||
assert len(PROCESS_GATE_DEFINITIONS) == 20
|
||||
|
||||
|
||||
def test_user_gate_summary_marks_apx_execution_readonly(app, monkeypatch):
|
||||
"""APX Execution 不能向用户下发主动作或恢复目标。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='APX-1', status='blocked', current_gate_code='inventory_candidates_calculated',
|
||||
last_passed_gate_code=None, primary_next_action_code=None, responsible_party='system',
|
||||
lock_version=1, review_case_id=None, task_id=1, updated_at=None,
|
||||
)
|
||||
gate = SimpleNamespace(
|
||||
id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='blocked_retryable',
|
||||
evaluation_version=1, input_fingerprint=None, blocking_reason_code='inventory_candidates_required',
|
||||
blocking_reason_json=None, recommendation_json=None, effective_result_json={},
|
||||
next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None,
|
||||
)
|
||||
query = projection.ShippingProcessGate.query
|
||||
monkeypatch.setattr(query, 'filter_by', lambda **_kwargs: query)
|
||||
monkeypatch.setattr(query, 'order_by', lambda *_args: query)
|
||||
monkeypatch.setattr(query, 'all', lambda: [gate])
|
||||
monkeypatch.setattr(projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False)
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['status'] == 'legacy_readonly'
|
||||
assert summary['legacy_readonly'] is True
|
||||
assert summary['next_action_code'] is None
|
||||
assert summary['allowed_actions'] == []
|
||||
|
||||
|
||||
def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technical(app, monkeypatch):
|
||||
"""库存匹配技术重试被隐藏时,跨阶段 RecoveryPlan 仍必须保留人工复核入口。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-INV-1', status='blocked',
|
||||
current_gate_code='inventory_matching', primary_next_action_code='retry_inventory_matching',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-INV-1', 'status': 'blocked',
|
||||
'primary_next_action_code': 'retry_inventory_matching',
|
||||
'responsible_party': 'worker',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_matching',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'next_action_code': 'retry_inventory_matching',
|
||||
},
|
||||
'recovery_targets': [
|
||||
{'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'},
|
||||
],
|
||||
'gates': [], 'active_recovery_plans': [],
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['current_blocking_gate']['gate_code'] == 'inventory_matching'
|
||||
assert summary['next_action_code'] == 'open_inventory_match_review'
|
||||
assert summary['owner_type'] == 'human'
|
||||
assert summary['technical_auto_only'] is False
|
||||
assert summary['allowed_actions'] == [
|
||||
'open_inventory_match_review',
|
||||
'retry_inventory_from_preparation',
|
||||
]
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch):
|
||||
"""所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-FAIL-1', status='blocked',
|
||||
current_gate_code='artifact_generation', primary_next_action_code='regenerate_excel_artifact',
|
||||
responsible_party='system', lock_version=1, review_case_id=None, task_id=None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-FAIL-1', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_excel_artifact',
|
||||
'responsible_party': 'system', 'recovery_targets': [], 'gates': [],
|
||||
'active_recovery_plans': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'artifact_generation', 'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'artifact_generation_failed',
|
||||
'next_action_code': 'regenerate_excel_artifact',
|
||||
'latest_attempt': {
|
||||
'attempt_no': 7,
|
||||
'status': 'failed',
|
||||
'error_code': 'SHIPPING.EXCEL_ARTIFACT_WRITE_FAILED',
|
||||
'error_summary': r'Excel 写入失败 at C:\worker\output.xlsx password=secret',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['failure_detail'] is not None
|
||||
assert 'Excel 写入失败' in summary['failure_detail']
|
||||
assert '[path]' in summary['failure_detail']
|
||||
assert 'secret' not in summary['failure_detail']
|
||||
|
||||
|
||||
def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch):
|
||||
"""历史 Gate 19 即使持久化了人工待办动作,也必须投影为 RPA 重试。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-RPA-STALE', status='blocked',
|
||||
current_gate_code='freight_upload_rpa',
|
||||
primary_next_action_code='regenerate_manual_upload_todo',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-RPA-STALE', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_manual_upload_todo',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'freight_upload_rpa', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'upload_platform_rejected',
|
||||
'next_action_code': 'regenerate_manual_upload_todo',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
|
||||
"""Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-MANUAL-RPA', status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
primary_next_action_code='regenerate_manual_upload_todo',
|
||||
responsible_party='owner', lock_version=1, review_case_id=None, task_id=None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-MANUAL-RPA', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_manual_upload_todo',
|
||||
'responsible_party': 'owner', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'manual_upload_pending',
|
||||
'next_action_code': 'regenerate_manual_upload_todo',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_process_gate_dependency_integrity_and_excel_only_scope():
|
||||
"""
|
||||
校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_contract_v2.py
|
||||
|
||||
用途:冻结 Gate v2 的 20 Gate 实施状态、恢复目标与 API 边界合同。
|
||||
依赖:process_gate_contract、recovery_plan_contract、process_gate_projection。
|
||||
逻辑:只验证服务端合同输出;客户端不得自行推导目标 Gate 或实现状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_IMPLEMENTATION_STATUSES,
|
||||
assert_process_gate_contract_integrity,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import serialize_process_gate
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
|
||||
|
||||
def test_gate_v2_freezes_implementation_status_for_all_twenty_gates():
|
||||
"""20 个 Gate 必须都有实现状态;Gate 1–9 为 supported,Gate 10–20 为 implemented。"""
|
||||
assert_process_gate_contract_integrity()
|
||||
assert len(PROCESS_GATE_DEFINITIONS) == 20
|
||||
assert all(item.get('implementation_status') in PROCESS_GATE_IMPLEMENTATION_STATUSES for item in PROCESS_GATE_DEFINITIONS)
|
||||
assert all(item['implementation_status'] == 'supported' for item in PROCESS_GATE_DEFINITIONS[:9])
|
||||
assert all(item['implementation_status'] == 'implemented' for item in PROCESS_GATE_DEFINITIONS[9:])
|
||||
|
||||
|
||||
def test_gate_v2_cross_stage_recovery_contract_is_server_owned():
|
||||
"""库存跨阶段恢复目标、继续点和失效范围必须由服务端合同固定。"""
|
||||
preparation = recovery_plan_for_action(
|
||||
current_gate='inventory_matching',
|
||||
action_code='retry_inventory_from_preparation',
|
||||
)
|
||||
mapping = recovery_plan_for_action(
|
||||
current_gate='inventory_matching',
|
||||
action_code='retry_inventory_from_field_mapping',
|
||||
)
|
||||
assert preparation == {
|
||||
'target_gate': 'inventory_preparation',
|
||||
'resume_after_gate': 'inventory_matching',
|
||||
'allowed_intermediate_gates': ('inventory_field_mapping',),
|
||||
'invalidate_change_type': 'inventory_file_changed',
|
||||
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
}
|
||||
assert mapping['target_gate'] == 'inventory_field_mapping'
|
||||
assert mapping['resume_after_gate'] == 'inventory_matching'
|
||||
assert 'inventory_mapping' in mapping['invalidates']
|
||||
|
||||
|
||||
def test_unknown_recovery_action_is_not_a_contract_target():
|
||||
"""未注册动作不得被 Projection 或执行器当作跨阶段恢复目标。"""
|
||||
assert recovery_plan_for_action(
|
||||
current_gate='inventory_matching',
|
||||
action_code='retry_inventory_from_excel',
|
||||
) is None
|
||||
|
||||
|
||||
def test_cross_stage_recovery_action_is_invalid_outside_inventory_matching(app):
|
||||
"""跨阶段库存恢复动作在错误 Gate 上必须返回稳定 RecoveryPlan 错误码。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
from app.services.shipping_notice.process_gate_recovery_service import request_gate_action
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
from app import db
|
||||
from app.models import ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, _review_case_id, task_id = _seed_workflow_version(suffix='v2-cross-stage-invalid')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=int(task_id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=False,
|
||||
blocking_reason_code='inventory_snapshot_prepare_failed', effective_result={},
|
||||
force=True, idempotency_key='v2-cross-stage-seed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).first()
|
||||
assert gate is not None
|
||||
with __import__('pytest').raises(ValidationError) as exc:
|
||||
request_gate_action(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
action_code='retry_inventory_from_preparation',
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
idempotency_key='v2-cross-stage-invalid-action',
|
||||
actor_type='user', actor_id=int(user.id), payload={},
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.RECOVERY_TARGET_INVALID'
|
||||
|
||||
|
||||
def test_gate_projection_exposes_implementation_status(app, monkeypatch):
|
||||
"""单 Gate Projection 必须透传服务端实现状态,避免前端猜测。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
gate = SimpleNamespace(
|
||||
id=1, gate_code='layout_parsing', sequence_no=2, status='blocked_retryable',
|
||||
evaluation_version=1, input_fingerprint=None, blocking_reason_code='layout_parse_failed',
|
||||
blocking_reason_json=None, recommendation_json=None, effective_result_json={},
|
||||
findings_json=None, next_action_code='retry_layout_parsing', passed_at=None,
|
||||
invalidated_at=None, latest_attempt_id=None,
|
||||
)
|
||||
monkeypatch.setattr('app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get', lambda _id: None, raising=False)
|
||||
projected = serialize_process_gate(gate, include_diagnostics=False)
|
||||
assert projected['implementation_status'] == 'supported'
|
||||
@@ -25,10 +25,9 @@ from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
def test_ten_identical_recovery_clicks_create_one_attempt(app):
|
||||
"""同一幂等键连点十次只产生一个 Attempt。"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault1')
|
||||
_user, _case_id, task_id = _seed_workflow_version(suffix='fault1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
task_id=int(task_id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
@@ -71,10 +70,9 @@ def test_ten_identical_recovery_clicks_create_one_attempt(app):
|
||||
def test_active_attempt_blocks_second_queue(app):
|
||||
"""已有活动 Attempt 时第二次不同幂等键必须 Conflict。"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault2')
|
||||
_user, _case_id, task_id = _seed_workflow_version(suffix='fault2')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
task_id=int(task_id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
@@ -120,10 +118,9 @@ def test_audit_failure_rolls_back_gate_queue(app, monkeypatch):
|
||||
核心逻辑:monkeypatch record_fulfillment_audit 抛错,断言 queue 抛出且无 Attempt 行。
|
||||
"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault3')
|
||||
_user, _case_id, task_id = _seed_workflow_version(suffix='fault3')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
task_id=int(task_id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
@@ -167,10 +164,9 @@ def test_request_gate_action_rejects_forbidden_controls(app):
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault4')
|
||||
_user, _case_id, task_id = _seed_workflow_version(suffix='fault4')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
task_id=int(task_id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
|
||||
@@ -36,10 +36,12 @@ def test_lease_takeover_after_stale_heartbeat(app, monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **kwargs: 0,
|
||||
)
|
||||
_user, item, version = _seed_workflow_version(suffix='lease1')
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='lease1')
|
||||
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,
|
||||
actor_type='system',
|
||||
actor_id='lease-test',
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
@@ -72,10 +74,12 @@ def test_heartbeat_rejects_foreign_lease(app):
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='lease2')
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='lease2')
|
||||
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,
|
||||
actor_type='system',
|
||||
actor_id='lease-test',
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
@@ -110,10 +114,12 @@ def test_sync_manual_open_via_claim_and_run(app, monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **kwargs: 0,
|
||||
)
|
||||
_user, item, version = _seed_workflow_version(suffix='lease3')
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='lease3')
|
||||
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,
|
||||
actor_type='system',
|
||||
actor_id='lease-test',
|
||||
)
|
||||
# 先阻断冻结门禁,再排队人工打开动作。
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_retry_cap.py
|
||||
|
||||
用途:验证门禁技术失败跨 force_new Job 累计重试上限,并在耗尽后收口 Attempt/Gate。
|
||||
用途:验证门禁技术失败只执行一次,并在失败后收口 Attempt/Gate,等待人工重试。
|
||||
依赖:Flask testing app、run_shipping_process_gate handler、process_gate_service。
|
||||
逻辑:mock claim_and_run 持续抛错;按 failed Job 累计;断言 TECHNICAL_RETRIES 次后
|
||||
Attempt/Gate 进入 failed_terminal、input_snapshot Hash 一致、且不再入队重试 Job。
|
||||
逻辑:mock claim_and_run 抛错;断言只产生一个失败 Job,Attempt 失败、Gate 进入 blocked_retryable,
|
||||
并保留人工恢复入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,14 +26,13 @@ from app.services.shipping_notice.process_gate_service import (
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
|
||||
|
||||
def test_technical_retries_cap_across_force_new_jobs(app):
|
||||
"""跨 Job 累计失败达到上限后必须 failed_terminal,且不再新建 queued Job。"""
|
||||
def test_gate_failure_does_not_auto_retry(app):
|
||||
"""门禁失败只产生一个失败 Job,并保留原 Gate 的人工恢复入口。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES'] = 3
|
||||
_user, item, version = _seed_workflow_version(suffix='retrycap')
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='retrycap')
|
||||
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,
|
||||
@@ -47,49 +46,53 @@ def test_technical_retries_cap_across_force_new_jobs(app):
|
||||
first_job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id))
|
||||
db.session.commit()
|
||||
attempt_id = int(attempt.id)
|
||||
rollback_seen = {'value': False}
|
||||
real_get = db.session.get
|
||||
|
||||
def _get_after_rollback(model, ident):
|
||||
"""模拟 PostgreSQL aborted transaction:Attempt 只能在 rollback 后重读。"""
|
||||
if model is ShippingProcessGateAttempt and not rollback_seen['value']:
|
||||
raise AssertionError('attempt reloaded before rollback')
|
||||
return real_get(model, ident)
|
||||
|
||||
real_rollback = db.session.rollback
|
||||
|
||||
def _record_rollback():
|
||||
rollback_seen['value'] = True
|
||||
return real_rollback()
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt',
|
||||
side_effect=RuntimeError('boom https://erp.example.com/x?token=abc'),
|
||||
), patch.object(db.session, 'get', side_effect=_get_after_rollback), patch.object(
|
||||
db.session, 'rollback', side_effect=_record_rollback,
|
||||
):
|
||||
for round_idx in range(5):
|
||||
attempt_row = db.session.get(ShippingProcessGateAttempt, attempt_id)
|
||||
assert attempt_row is not None
|
||||
if attempt_row.status in {'failed', 'succeeded', 'cancelled'}:
|
||||
break
|
||||
job_id = int(attempt_row.job_id or 0)
|
||||
if job_id <= 0:
|
||||
job_id = enqueue_gate_attempt_job(attempt_id=attempt_id, force_new=True)
|
||||
db.session.commit()
|
||||
job = db.session.get(Job, job_id)
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
attempt_row.status = 'running'
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt_row.gate_id))
|
||||
if gate is not None:
|
||||
gate.status = 'running'
|
||||
db.session.commit()
|
||||
job = db.session.get(Job, int(first_job_id))
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
attempt.status = 'running'
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
if gate is not None:
|
||||
gate.status = 'running'
|
||||
db.session.commit()
|
||||
|
||||
ctx = MagicMock()
|
||||
ctx.extras = {'worker_label': f'retry-cap-worker-{round_idx}'}
|
||||
run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': job_id})
|
||||
ctx = MagicMock()
|
||||
ctx.extras = {'worker_label': 'retry-cap-worker'}
|
||||
run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': int(first_job_id)})
|
||||
|
||||
assert rollback_seen['value'] is True
|
||||
|
||||
attempt_final = db.session.get(ShippingProcessGateAttempt, attempt_id)
|
||||
gate_final = db.session.get(ShippingProcessGate, int(attempt_final.gate_id))
|
||||
assert attempt_final is not None
|
||||
assert attempt_final.status == 'failed'
|
||||
assert gate_final is not None
|
||||
assert gate_final.status == 'failed_terminal'
|
||||
assert attempt_final.error_code == 'TECHNICAL_RETRY_EXHAUSTED'
|
||||
assert gate_final.status == 'blocked_retryable'
|
||||
assert gate_final.next_action_code == 'retry_layout_parsing'
|
||||
assert attempt_final.error_code == 'TECHNICAL_FAILURE'
|
||||
# 敏感 URL 不得原样落库
|
||||
assert 'erp.example.com' not in str(attempt_final.error_summary or '')
|
||||
# [ASSERT] 技术重试不得污染业务输入快照,Hash 须与正文一致
|
||||
snap = attempt_final.input_snapshot_json if isinstance(attempt_final.input_snapshot_json, dict) else {}
|
||||
assert 'technical_retry_count' not in snap
|
||||
from app.services.shipping_notice.process_gate_service import _stable_hash
|
||||
assert attempt_final.input_snapshot_hash == _stable_hash(snap)
|
||||
|
||||
failed_jobs = (
|
||||
Job.query
|
||||
.filter_by(
|
||||
@@ -99,7 +102,7 @@ def test_technical_retries_cap_across_force_new_jobs(app):
|
||||
)
|
||||
.count()
|
||||
)
|
||||
assert failed_jobs == 3
|
||||
assert failed_jobs == 1
|
||||
queued_jobs = (
|
||||
Job.query
|
||||
.filter_by(
|
||||
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user