fix(shipping-notice): 修复抽取续抽与 STP 入队并发死锁并幂等草稿校验
- 抽取 Job 续抽交接时 defer_stp_enqueue,STP 入队推迟到 run 收口统一触发,消除与续抽 Job 互抢行锁的死锁(2026-09-22 生产事故) - 草稿显式 validate 在内容未变时幂等短路:不递增版本、不写事件、不重复触发下游,防连点「保存并校验」产生版本/Job 风暴(事故根因) - STP 自动建单入队前 supersede 同文档过期排队 Job,防止旧版本 Job 抢跑 - 抽取 Job 异常收口识别 PostgreSQL 瞬时锁冲突(40P01/55P03)标记可重试,不再终态失败要求人工重新识别 - 订单凭据加密抽离为 app/core/credential_crypto 通用模块,shipping_notice 委托调用并保留原错误码 - 同步复核视图与测试:新增草稿校验幂等契约测试,更新 STP 入队与 Worker 重试用例
This commit is contained in:
1 parent
13c33d063c
commit
5df204fdea
12 files changed
+865
-87
No files matched your search
@@ -0,0 +1,64 @@
|
||||
"""app/core/credential_crypto.py
|
||||
|
||||
用途:通用 Fernet 凭据加解密(主密钥只来自 Flask config 的环境注入键,绝不落库明文)。
|
||||
依赖:cryptography.fernet、Flask current_app、app.core.errors。
|
||||
逻辑:调用方通过 CredentialCryptoErrorCodes 提供各自的业务错误码;主密钥缺失/无效时
|
||||
fail-closed 拒绝加密,避免产生不可恢复密文。shipping_notice(RPA Profile)与
|
||||
integration_connector(凭据引用)共用本模块,仅密钥键名与错误码不同。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CredentialCryptoErrorCodes:
|
||||
"""加解密失败的错误码集合(按调用方业务域自定义)。"""
|
||||
|
||||
key_missing: str
|
||||
key_invalid: str
|
||||
secret_empty: str
|
||||
secret_missing: str
|
||||
secret_invalid: str
|
||||
|
||||
|
||||
def _fernet(key_config_name: str, codes: CredentialCryptoErrorCodes) -> Fernet:
|
||||
"""从 Flask config 读取主密钥并构造加密器;缺失/无效即 fail-closed。"""
|
||||
key = str(current_app.config.get(key_config_name) or '').strip()
|
||||
if not key:
|
||||
raise ServiceUnavailableError(
|
||||
f'{key_config_name} is not configured',
|
||||
code=codes.key_missing,
|
||||
)
|
||||
try:
|
||||
return Fernet(key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
f'{key_config_name} is invalid',
|
||||
code=codes.key_invalid,
|
||||
) from exc
|
||||
|
||||
|
||||
def encrypt_secret(value: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
|
||||
"""加密单个凭据字段以便持久化;调用方不得记录明文。"""
|
||||
plaintext = str(value or '')
|
||||
if not plaintext:
|
||||
raise ValidationError('credential must not be empty', code=codes.secret_empty)
|
||||
return _fernet(key_config_name, codes).encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_secret(ciphertext: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
|
||||
"""在受控运行时解密密文;仅供当次调用内存使用,禁止落日志/响应。"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('credential ciphertext is missing', code=codes.secret_missing)
|
||||
try:
|
||||
return _fernet(key_config_name, codes).decrypt(value.encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeDecodeError) as exc:
|
||||
raise ValidationError('credential ciphertext is invalid', code=codes.secret_invalid) from exc
|
||||
@@ -724,6 +724,18 @@ def _handoff_continue_order_extraction(
|
||||
return True
|
||||
|
||||
|
||||
def _is_transient_lock_error(exc: BaseException) -> bool:
|
||||
"""
|
||||
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
||||
|
||||
【AI 触发时机】:订单抽取 Job 异常收口时决定是否标记可重试。此类错误重试即可恢复,
|
||||
按终态失败收口会触发 run failed 并要求人工重新识别(2026-09-22 生产事故两次)。
|
||||
SQLAlchemy 将 DBAPI 错误包装为 exc.orig;非 DBAPI 异常(无 pgcode)一律返回 False。
|
||||
"""
|
||||
orig = getattr(exc, 'orig', None)
|
||||
return getattr(orig, 'pgcode', None) in {'40P01', '55P03'}
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
@@ -917,15 +929,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
wave_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
|
||||
try:
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
)
|
||||
except Exception:
|
||||
from flask import current_app
|
||||
current_app.logger.exception(
|
||||
'retry unit progress failed run=%s unit=%s', run.run_no, unit.id,
|
||||
)
|
||||
# [交接不变量] defer_stp_enqueue:开工快照仍有待排版附件(本 Job 必交接)时
|
||||
# 推迟 STP 入队到 run 收口,确保 STP 只由最后一个抽取 Job 提交;否则本 Job
|
||||
# 提交的 STP Job 会与续抽 Job 并发执行,双方以相反顺序抢 run/intake 行锁
|
||||
# 形成结构性死锁(2026-09-22 SNER-20260922-6466EB53 生产事故)。
|
||||
# 推送失败必须冒泡(与下方新单元推送同一规则):此处是这些 Unit 候选与
|
||||
# 复核 Case 的唯一物化触发点,吞掉等于静默丢单。
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
defer_stp_enqueue=bool(pending_layout_ids),
|
||||
)
|
||||
continue
|
||||
if unit.status == 'review_required':
|
||||
continue
|
||||
@@ -1195,9 +1208,11 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
# [交接不变量] 同 replay 路径:本 Job 仍会交接时推迟 STP 入队到 run 收口。
|
||||
try:
|
||||
unit_persist = progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=merged_unit_orders,
|
||||
defer_stp_enqueue=bool(pending_layout_ids),
|
||||
)
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
@@ -1417,6 +1432,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
# [STEP] 瞬时锁错(PostgreSQL 死锁 40P01 / 锁超时 55P03)不收口 run/unit 失败:
|
||||
# 失败标记会写 run=failed,重试 Job 将被"run status is not executable"门弹掉。
|
||||
# 直接可重试入队,由队列在 attempts 耗尽前自动重排;冲突窗口为秒级,重试即过
|
||||
# (2026-09-22 SNER-20260922-6466EB53 / 879785D1 生产事故)。attempts 耗尽后
|
||||
# 走下方常规失败收口,fail-closed 语义不变。
|
||||
if _is_transient_lock_error(exc):
|
||||
fail_job(job.id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
return
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = False
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
|
||||
@@ -1,44 +1,26 @@
|
||||
"""
|
||||
services/shipping_notice/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据。
|
||||
依赖:Flask current_app、cryptography.fernet;调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用 decrypt_credential。
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
|
||||
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
# 本域历史错误码原样保留,调用方(管理服务/测试)不受重构影响。
|
||||
_RPA_CODES = CredentialCryptoErrorCodes(
|
||||
key_missing='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
|
||||
key_invalid='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
|
||||
secret_empty='SHIPPING.RPA_CREDENTIAL_EMPTY',
|
||||
secret_missing='SHIPPING.RPA_CREDENTIAL_MISSING',
|
||||
secret_invalid='SHIPPING.RPA_CREDENTIAL_INVALID',
|
||||
)
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
"""
|
||||
构造当前环境的凭据加密器。
|
||||
|
||||
核心逻辑:主密钥只从运行环境读取,缺失或格式无效时拒绝继续,避免写入无法恢复的密文。
|
||||
|
||||
Returns:
|
||||
Fernet: 可执行对称加密的实例。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
"""
|
||||
key = str(current_app.config.get('FREIGHT_RPA_CREDENTIAL_KEY') or '').strip()
|
||||
if not key:
|
||||
raise ServiceUnavailableError(
|
||||
'FREIGHT_RPA_CREDENTIAL_KEY is not configured',
|
||||
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
|
||||
)
|
||||
try:
|
||||
return Fernet(key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'FREIGHT_RPA_CREDENTIAL_KEY is invalid',
|
||||
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
|
||||
) from exc
|
||||
_KEY_CONFIG_NAME = 'FREIGHT_RPA_CREDENTIAL_KEY'
|
||||
|
||||
|
||||
def encrypt_credential(value: str) -> str:
|
||||
@@ -52,12 +34,10 @@ def encrypt_credential(value: str) -> str:
|
||||
str: 可安全保存到数据库的 Fernet 密文。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
ValidationError: 传入空凭据。
|
||||
"""
|
||||
plaintext = str(value or '')
|
||||
if not plaintext:
|
||||
raise ValidationError('RPA credential must not be empty', code='SHIPPING.RPA_CREDENTIAL_EMPTY')
|
||||
return _fernet().encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
return encrypt_secret(value, key_config_name=_KEY_CONFIG_NAME, codes=_RPA_CODES)
|
||||
|
||||
|
||||
def decrypt_credential(ciphertext: str) -> str:
|
||||
@@ -71,12 +51,7 @@ def decrypt_credential(ciphertext: str) -> str:
|
||||
str: 仅供 RPA 执行内存使用的明文。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
ValidationError: 密文为空、已损坏或使用了错误主密钥。
|
||||
"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('RPA credential ciphertext is missing', code='SHIPPING.RPA_CREDENTIAL_MISSING')
|
||||
try:
|
||||
return _fernet().decrypt(value.encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeDecodeError) as exc:
|
||||
raise ValidationError('RPA credential ciphertext is invalid', code='SHIPPING.RPA_CREDENTIAL_INVALID') from exc
|
||||
return decrypt_secret(ciphertext, key_config_name=_KEY_CONFIG_NAME, codes=_RPA_CODES)
|
||||
@@ -1275,6 +1275,7 @@ def submit_order_extraction_unit_result(
|
||||
run: Any,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
defer_stp_enqueue: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 完成后立即落 Candidate 并按 STP 门禁建 Task,不等待同 Run 其它 Unit。
|
||||
@@ -1283,10 +1284,16 @@ def submit_order_extraction_unit_result(
|
||||
可安全复用已消费 Intake;复用 persist_order_extraction_result;
|
||||
通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。
|
||||
|
||||
[交接不变量] defer_stp_enqueue=True(Worker 开工快照仍有待排版附件、本 Job 必交接)时跳过
|
||||
本 Unit 的 STP 入队——Candidate/Review Case 仍即时物化,STP 统一由最后一个抽取 Job 的
|
||||
run 收口(submit_order_extraction_run_result)入队。否则本 Job 提交的 STP Job 会与续抽 Job
|
||||
并发执行,双方以相反顺序抢 run/intake 行锁形成结构性死锁(2026-09-22 生产事故)。
|
||||
|
||||
Args:
|
||||
run: 所属 ShippingOrderProcessingRun。
|
||||
unit: 已进入 candidate_ready 的 ShippingOrderProcessingUnit。
|
||||
orders: 该 Unit 合并邮件补充后的订单数组。
|
||||
defer_stp_enqueue: True 时跳过 STP 入队(由 run 收口统一触发)。
|
||||
|
||||
Returns:
|
||||
与 submit_order_extraction_run_result 同形的业务摘要(作用域为本 Unit)。
|
||||
@@ -1434,9 +1441,12 @@ def submit_order_extraction_unit_result(
|
||||
result['unit_id'] = int(unit.id)
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
ensure_review_case_for_unit(run=run, unit=unit)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
# [交接不变量] defer_stp_enqueue=True 时跳过本 Unit 的 STP 入队,统一由 run 收口触发
|
||||
# (submit_order_extraction_run_result);否则 STP Job 会与本 Job 的续抽后继并发死锁。
|
||||
if not defer_stp_enqueue:
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
|
||||
result['stp_auto_create'] = maybe_stp_auto_create_for_run(run=run)
|
||||
result['stp_auto_create'] = maybe_stp_auto_create_for_run(run=run)
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
|
||||
@@ -4789,6 +4789,7 @@ def progress_ready_extraction_unit(
|
||||
run: ShippingOrderProcessingRun,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
defer_stp_enqueue: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 Review Case/STP 正式链触发下游。
|
||||
@@ -4797,10 +4798,14 @@ def progress_ready_extraction_unit(
|
||||
由 submit 内的 Review Case/STP 正式链异步协调,禁止此处再以已删除的 batch_no 或
|
||||
结果数组推断并直接调用旧 auto_progress,避免重复推进。
|
||||
|
||||
[交接不变量] defer_stp_enqueue=True(Worker 开工快照仍有待排版附件、本 Job 必交接)时
|
||||
推迟 STP 入队到 run 收口,防止 STP Job 与续抽 Job 并发死锁;Candidate/Review Case 仍即时物化。
|
||||
|
||||
Args:
|
||||
run: 所属抽取 Run。
|
||||
unit: 已 candidate_ready 的 Unit。
|
||||
orders: 该 Unit 订单数组。
|
||||
defer_stp_enqueue: True 时跳过本 Unit 的 STP 入队(由 run 收口统一触发)。
|
||||
|
||||
Returns:
|
||||
Unit 级落库摘要(含 created / pending_orders)。
|
||||
@@ -4808,7 +4813,9 @@ def progress_ready_extraction_unit(
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_unit_result
|
||||
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders)
|
||||
result = submit_order_extraction_unit_result(
|
||||
run=run, unit=unit, orders=orders, defer_stp_enqueue=defer_stp_enqueue,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@ services/shipping_notice/order_review_draft_service.py
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本与 WorkflowItem 可写状态,
|
||||
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
|
||||
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
|
||||
STP 等待入队/排队/执行期间拒绝草稿内容写入(显式 validate 仍放行供自动协调器);
|
||||
STP 等待入队/排队/执行期间拒绝草稿内容写入;显式 validate 放行供自动协调器,
|
||||
但自动化持有且内容未变时幂等短路(不递增版本、不写事件、不重复触发下游),
|
||||
防止连点“保存并校验”产生版本/Job 风暴(2026-09-22 生产死锁事故的根因);
|
||||
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
|
||||
行级必填 reservation_id 空值时先回退表头(与建单资格 / Schema Runtime 一致),再报缺失;
|
||||
确认建单摘要同样回填行级 reservation_id,供物化 FieldValue / 冻结门禁消费;
|
||||
@@ -335,6 +337,48 @@ def _stp_automation_holds_draft(case: ShippingOrderReviewCase) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _draft_content_checksum(draft: ShippingOrderReviewDraft) -> str:
|
||||
"""
|
||||
计算草稿内容(表头 + 明细 JSON)的稳定摘要,用于识别“内容未变的重复校验”。
|
||||
|
||||
与 validation_checksum 的区别:后者含 validated_at / draft_version,每次校验必变;
|
||||
本摘要只看内容本身,内容不变则摘要不变。
|
||||
|
||||
Returns:
|
||||
32 位十六进制摘要。
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
payload = {
|
||||
'header_values_json': draft.header_values_json or {},
|
||||
'lines_json': draft.lines_json or [],
|
||||
}
|
||||
return hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, ensure_ascii=False, default=str).encode('utf-8'),
|
||||
).hexdigest()[:32]
|
||||
|
||||
|
||||
def _draft_content_unchanged(case: ShippingOrderReviewCase) -> bool:
|
||||
"""
|
||||
判断草稿内容相对最近一次校验是否未变化。
|
||||
|
||||
核心逻辑:对比 validation_result_json.content_checksum 与当前内容摘要;
|
||||
旧草稿(升级前校验)没有该字段时返回 False,保持原行为不短路。
|
||||
|
||||
Returns:
|
||||
True 表示内容未变(可安全幂等短路)。
|
||||
"""
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
return False
|
||||
validation = draft.validation_result_json if isinstance(draft.validation_result_json, dict) else {}
|
||||
stored = str(validation.get('content_checksum') or '').strip()
|
||||
if not stored:
|
||||
return False
|
||||
return stored == _draft_content_checksum(draft)
|
||||
|
||||
|
||||
def _expected_version(value: Any) -> int:
|
||||
"""写入接口必须明确带版本号,避免缺省值退化为最后写入者获胜。"""
|
||||
if isinstance(value, bool):
|
||||
@@ -824,6 +868,8 @@ def _record_change(
|
||||
).hexdigest()[:32]
|
||||
# 兼容旧前端:validation_version 回落为 draft_version,权威身份以 checksum 为准。
|
||||
result['validation_version'] = int(draft.draft_version)
|
||||
# 内容摘要(不含版本/时间):validate_draft 幂等短路的比对依据。
|
||||
result['content_checksum'] = _draft_content_checksum(draft)
|
||||
draft.validation_result_json = result
|
||||
draft.issue_summary_json = list(result.get('issues') or [])
|
||||
case.status = 'ready' if validate and result.get('status') == 'ready' else 'draft'
|
||||
@@ -1084,10 +1130,18 @@ def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -
|
||||
[P1-6 说明] 显式校验按钮走同步 resume(路由层调用 validate_draft 后通常紧接着
|
||||
resume_after_review_change(trigger='draft_validated')),因此本条路径不额外 enqueue
|
||||
异步 Revalidate Job;字段编辑/增删行走异步 Job 触发,两条路径互不冲突且互为补充。
|
||||
|
||||
[幂等短路] STP 自动建单持有草稿(等待入队/排队/执行)且内容相对最近一次校验
|
||||
未变化时,重复显式校验直接返回当前态:不递增 draft_version、不写 draft_validated
|
||||
事件、不重跑下游协调。否则每次点击都会产出新版本并入队新 STP Job,同文档多 Job
|
||||
并发会在建单 advisory 锁上死锁(2026-09-22 生产事故)。内容变化(含人工改脏)或
|
||||
自动化未持锁(如失败超时后重试)时行为不变。
|
||||
"""
|
||||
action = 'draft_validated'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
if _stp_automation_holds_draft(case) and _draft_content_unchanged(case):
|
||||
return serialize_review_case(case)
|
||||
return _record_change(case, actor_id=user_id, event_type=action, operation={}, validate=True)
|
||||
|
||||
|
||||
|
||||
@@ -333,6 +333,69 @@ def find_latest_stp_job(*, business_ref: str) -> Job | None:
|
||||
)
|
||||
|
||||
|
||||
def _supersede_stale_queued_stp_jobs(
|
||||
*,
|
||||
run_no: str,
|
||||
document_id: int,
|
||||
current_draft_version: int,
|
||||
) -> int:
|
||||
"""
|
||||
入队即作废同文档低版本仍 queued 的 STP Job(执行期“新版替代”检查的入队侧前置)。
|
||||
|
||||
【AI 触发时机】:为最新草稿版本入队/复用 STP 自动建单 Job 前(ensure_stp_auto_create_for_case),
|
||||
必须先调用以清理旧版本 queued Job。
|
||||
|
||||
核心逻辑:只取消 queued;running Job 的替代由 execute_stp_auto_create_job 执行期检查收口。
|
||||
同文档两个 STP Job 并发执行会在 acquire_notice_create_locks 的用户级 advisory 锁上
|
||||
与行锁交叉形成死锁(2026-09-22 生产事故 job 4654),此函数消除该并发窗口。
|
||||
|
||||
Args:
|
||||
run_no: 抽取 Run 编号。
|
||||
document_id: 文档 ID。
|
||||
current_draft_version: 即将入队/复用的草稿版本。
|
||||
|
||||
Returns:
|
||||
作废的 Job 数量。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
prefix = f'stp-auto:{str(run_no)}:doc-{int(document_id)}:v'
|
||||
stale_rows = (
|
||||
Job.query
|
||||
.filter(
|
||||
Job.domain == SHIPPING_STP_JOB_DOMAIN,
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.business_ref.like(prefix + '%'),
|
||||
Job.status == 'queued',
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
superseded_count = 0
|
||||
for stale in stale_rows:
|
||||
version_part = str(stale.business_ref or '').rsplit(':v', 1)[-1]
|
||||
try:
|
||||
stale_version = int(version_part)
|
||||
except ValueError:
|
||||
continue
|
||||
if stale_version >= current_draft_version:
|
||||
continue
|
||||
stale.status = 'success'
|
||||
stale.message = 'STP 自动建单 Job 已被新版草稿替代(入队时作废)'
|
||||
stale.finished_at = datetime.utcnow()
|
||||
stale.result_json = {
|
||||
'status': 'superseded',
|
||||
'superseded': True,
|
||||
'superseded_at_enqueue': True,
|
||||
'superseded_by_draft_version': int(current_draft_version),
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
}
|
||||
superseded_count += 1
|
||||
if superseded_count:
|
||||
db.session.flush()
|
||||
return superseded_count
|
||||
|
||||
|
||||
def ensure_stp_auto_create_for_case(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
@@ -345,7 +408,8 @@ def ensure_stp_auto_create_for_case(
|
||||
资格达标时确保写入 STP 幂等记录与 queued Job(幂等复用)。
|
||||
|
||||
核心逻辑:已 confirmed/有 Task 跳过;可选刷新 validation;XFA 硬门禁与
|
||||
人工改脏阻断;合格则 enqueue(shipping_stp_auto_create),business_ref=幂等键。
|
||||
人工改脏阻断;入队前先作废同文档旧版本 queued Job(消除并发死锁窗口);
|
||||
合格则 enqueue(shipping_stp_auto_create),business_ref=幂等键。
|
||||
若历史 Job 为 failed/dead,可新建重试 Job 并写入 retry_of_job_id(保留旧审计)。
|
||||
|
||||
Args:
|
||||
@@ -460,6 +524,12 @@ def ensure_stp_auto_create_for_case(
|
||||
document_id=int(case.document_id),
|
||||
draft_version=draft_version,
|
||||
)
|
||||
# [STEP] 入队侧先作废同文档旧版本 queued Job,消除同文档 STP Job 并发死锁窗口。
|
||||
_supersede_stale_queued_stp_jobs(
|
||||
run_no=str(resolved_run.run_no),
|
||||
document_id=int(case.document_id),
|
||||
current_draft_version=draft_version,
|
||||
)
|
||||
existing = find_active_stp_job(business_ref=idempotency_key)
|
||||
if existing is not None and str(existing.status or '') in {'queued', 'running'}:
|
||||
db.session.flush()
|
||||
@@ -512,7 +582,10 @@ def ensure_stp_auto_create_for_case(
|
||||
business_ref=idempotency_key,
|
||||
created_by_id=owner_id,
|
||||
message='等待 STP 自动建单' if retry_of_job_id is None else '重试 STP 自动建单',
|
||||
max_attempts=1,
|
||||
# [PARAM_TUNING] 1→3:死锁(40P01)等瞬时基础设施失败由 Handler 归类 retryable
|
||||
# 后可在 attempts 耗尽前自动重排(2026-09-22 生产事故 max_attempts=1 一次判死)。
|
||||
# 业务阻断走 retryable=False,不受影响,仍收口为“等待用户选择下一步动作”。
|
||||
max_attempts=3,
|
||||
dedupe_statuses=('queued', 'running'),
|
||||
dedupe_active=True,
|
||||
commit=False,
|
||||
|
||||
@@ -231,7 +231,14 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
|
||||
progress_calls: list[dict] = []
|
||||
|
||||
def _record_progress(**kwargs):
|
||||
progress_calls.append(kwargs)
|
||||
events.append('progressed')
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _record_progress)
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
|
||||
@@ -249,6 +256,8 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
|
||||
|
||||
assert 'processed' in events
|
||||
assert 'progressed' in events
|
||||
# [交接不变量] 开工快照有 pending 版面(必交接):推送照发,但 STP 入队必须推迟。
|
||||
assert progress_calls and progress_calls[0]['defer_stp_enqueue'] is True
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert run.phase == 'waiting_layout'
|
||||
@@ -474,7 +483,14 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
|
||||
progress_calls_layout_continue: list[dict] = []
|
||||
|
||||
def _record_progress_layout_continue(**kwargs):
|
||||
progress_calls_layout_continue.append(kwargs)
|
||||
events.append('progressed')
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _record_progress_layout_continue)
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
|
||||
@@ -500,6 +516,8 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
|
||||
|
||||
assert 'processed' in events
|
||||
assert 'progressed' in events
|
||||
# [交接不变量] 开工快照含 pending 版面(后续 layout 已 mock 就绪、仍走交接):STP 入队推迟。
|
||||
assert progress_calls_layout_continue[0]['defer_stp_enqueue'] is True
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert enqueue_calls == [{
|
||||
@@ -1147,3 +1165,288 @@ def test_pending_snapshot_batches_ignore_already_activated_units():
|
||||
|
||||
assert _pending_snapshot_batches(run, plan) == [3]
|
||||
assert [unit.selection_batch for unit in _units_for_batch(plan, selection_batch=1)] == [1]
|
||||
|
||||
|
||||
def test_worker_replay_pushes_without_defer_when_all_layouts_ready(monkeypatch):
|
||||
"""全量版面就绪(必为最后一个抽取 Job):重放推送 defer_stp_enqueue=False,STP 正常入队。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
progress_calls: list[dict] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=61, user_id=9, run_no='SNER-WORKER-FINAL', status='processing', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': [], 'schema': {}},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=61, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
replay_unit = SimpleNamespace(
|
||||
id=61, document_id=201, intake_id=1, status='candidate_ready',
|
||||
result_json={'orders': [{'po_number': 'PO-REPLAY', '_hxops_intake_id': 1}]},
|
||||
position=1, cancellation_requested_at=None,
|
||||
)
|
||||
process_unit = SimpleNamespace(
|
||||
id=62, document_id=202, intake_id=1, status='review_required', result_json=None,
|
||||
position=2, cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=61, unit_count=2, units=[replay_unit, process_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else replay_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [replay_unit, process_unit]),
|
||||
),
|
||||
join=lambda *_a, **_k: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
handler, '_units_for_batch',
|
||||
lambda _plan, *, selection_batch: [replay_unit, process_unit],
|
||||
)
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {'budget_limited_attachment_count': 0})
|
||||
monkeypatch.setattr(handler, '_wave_orders_for_expansion', lambda _run, *, orders: orders)
|
||||
monkeypatch.setattr(handler, '_expansion_trigger_reason_codes', lambda **_kwargs: [])
|
||||
fail_calls: dict = {}
|
||||
|
||||
def _record_progress(**kwargs):
|
||||
progress_calls.append(kwargs)
|
||||
events.append('progressed')
|
||||
return {'created_count': 1, 'pending_count': 0}
|
||||
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _record_progress)
|
||||
monkeypatch.setattr(
|
||||
handler, 'submit_order_extraction_run_result',
|
||||
lambda **_kwargs: events.append('terminalized') or {},
|
||||
)
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_a, **kwargs: finished.update(kwargs) or True)
|
||||
monkeypatch.setattr(
|
||||
handler, 'fail_job',
|
||||
lambda job_id, *, error, retryable, owned_attempt: fail_calls.update(
|
||||
{'job_id': job_id, 'error': error, 'retryable': retryable},
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 61})
|
||||
|
||||
# 断言:收口 Job(无 pending 版面)的重放推送不推迟,STP 由本 Job 正常入队;
|
||||
# review_required 单元本就不推送。
|
||||
assert len(progress_calls) == 1
|
||||
assert progress_calls[0]['defer_stp_enqueue'] is False
|
||||
assert progress_calls[0]['unit'].id == replay_unit.id
|
||||
assert 'terminalized' in events
|
||||
|
||||
|
||||
def test_worker_replay_push_failure_fails_job_non_retryable(monkeypatch):
|
||||
"""重放推送失败必须冒泡收口(禁止吞错静默丢单);非瞬时错误终态失败。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
run = SimpleNamespace(
|
||||
id=62, user_id=9, run_no='SNER-WORKER-PROP', status='processing', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=62, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
replay_unit = SimpleNamespace(
|
||||
id=62, document_id=202, intake_id=1, status='candidate_ready',
|
||||
result_json={'orders': [{'po_number': 'PO-PROP', '_hxops_intake_id': 1}]},
|
||||
position=1, cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=62, unit_count=1, units=[replay_unit])
|
||||
fail_calls: dict = {}
|
||||
transitions: list = []
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else replay_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [replay_unit]),
|
||||
),
|
||||
join=lambda *_a, **_k: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: (
|
||||
transitions.append(kwargs.get('target_status', '')),
|
||||
setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [replay_unit])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
|
||||
|
||||
def _raise_progress(**_kwargs):
|
||||
raise RuntimeError('replay push exploded')
|
||||
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _raise_progress)
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'fail_job',
|
||||
lambda job_id, *, error, retryable, owned_attempt: fail_calls.update(
|
||||
{'job_id': job_id, 'error': error, 'retryable': retryable},
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 62})
|
||||
|
||||
# 断言:推送异常冒泡到失败收口,非瞬时错误终态失败(retryable=False)。
|
||||
assert fail_calls['retryable'] is False
|
||||
assert 'replay push exploded' in fail_calls['error']
|
||||
assert 'failed' in transitions
|
||||
|
||||
|
||||
def test_worker_transient_lock_error_requeues_without_failing_run(monkeypatch):
|
||||
"""死锁 40P01 / 锁超时 55P03 为瞬时错误:retryable 重排,且不得把 run 收口为 failed。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
class _FakeDBAPIError(Exception):
|
||||
pass
|
||||
|
||||
for pgcode in ('40P01', '55P03'):
|
||||
events: list = []
|
||||
run = SimpleNamespace(
|
||||
id=63, user_id=9, run_no='SNER-WORKER-TX', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=63, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
fail_calls: dict = {}
|
||||
exc = _FakeDBAPIError('deadlock detected by postgres')
|
||||
exc.orig = SimpleNamespace(pgcode=pgcode)
|
||||
|
||||
def _raise_freeze(_run, _exc=exc):
|
||||
raise _exc
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', _raise_freeze)
|
||||
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'fail_job',
|
||||
lambda job_id, *, error, retryable, owned_attempt: fail_calls.update(
|
||||
{'job_id': job_id, 'error': error, 'retryable': retryable},
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: events.append(f"transition:{kwargs.get('target_status')}"),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('progress'))
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 63})
|
||||
|
||||
# 断言:瞬时锁错可重试;run/unit 不做失败收口(重试 Job 才不会被状态门弹掉)。
|
||||
assert fail_calls['retryable'] is True, f'pgcode={pgcode}'
|
||||
assert 'deadlock detected' in fail_calls['error']
|
||||
assert events == [], f'pgcode={pgcode} 不应收口 run: {events}'
|
||||
|
||||
|
||||
def test_sync_extraction_run_failure_sync_ignores_requeued_job():
|
||||
"""requeue(status=queued)不触发 run 失败收口;只有终态 failed 才同步。"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
sync_order_extraction_run_after_job_failure,
|
||||
)
|
||||
|
||||
requeued = SimpleNamespace(
|
||||
job_type='shipping_order_extraction', status='queued', business_ref='SNER-RQ',
|
||||
)
|
||||
# 断言:requeue 的 Job 直接跳过(不查询、不触碰 Run),自动重试不会被状态门弹掉。
|
||||
assert sync_order_extraction_run_after_job_failure(requeued) is None
|
||||
|
||||
|
||||
def test_progress_ready_extraction_unit_threads_defer_flag(monkeypatch):
|
||||
"""推送入口必须把 defer_stp_enqueue 原样传递给 unit 级 submit。"""
|
||||
from app.services.shipping_notice import order_extraction_run_service as svc
|
||||
|
||||
captured: dict = {}
|
||||
monkeypatch.setattr(svc, 'mark_order_extraction_persistence_started', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction.submit_order_extraction_unit_result',
|
||||
lambda **kwargs: captured.update(kwargs) or {'created_count': 0},
|
||||
)
|
||||
|
||||
run = SimpleNamespace(id=1)
|
||||
unit = SimpleNamespace(id=2)
|
||||
svc.progress_ready_extraction_unit(run=run, unit=unit, orders=[], defer_stp_enqueue=True)
|
||||
assert captured['defer_stp_enqueue'] is True
|
||||
|
||||
svc.progress_ready_extraction_unit(run=run, unit=unit, orders=[])
|
||||
assert captured['defer_stp_enqueue'] is False
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
tests/test_shipping_review_draft_validate_idempotency.py
|
||||
|
||||
用途:锁定显式校验(draft_validated)在 STP 自动建单持有草稿时的幂等短路契约。
|
||||
依赖:pytest、order_review_draft_service、unittest.mock。
|
||||
逻辑:不依赖 DB;内容未变且自动化持锁时不得递增版本/写事件(不触发 _record_change),
|
||||
内容变化或自动化未持锁时保持原行为;另覆盖内容摘要的稳定性与旧草稿兼容。
|
||||
背景:2026-09-22 生产事故——用户 11 秒连点 8 次“保存并校验”,每次递增 draft_version
|
||||
并入队新 STP Job,同文档多 Job 并发在建单 advisory 锁上死锁且 max_attempts=1 不重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
def test_validate_draft_short_circuits_when_automation_holds_and_content_unchanged(monkeypatch):
|
||||
"""自动化持锁 + 内容未变:重复校验必须幂等短路,不得递增版本或写事件。"""
|
||||
from app.services.shipping_notice import order_review_draft_service as svc
|
||||
|
||||
case = object()
|
||||
monkeypatch.setattr(svc, '_locked_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_assert_version', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_stp_automation_holds_draft', lambda c: True)
|
||||
monkeypatch.setattr(svc, '_draft_content_unchanged', lambda c: True)
|
||||
monkeypatch.setattr(svc, 'serialize_review_case', lambda c: {'serialized': True})
|
||||
|
||||
def _unexpected_record_change(*args, **kwargs):
|
||||
raise AssertionError('_record_change 必须被短路跳过')
|
||||
|
||||
monkeypatch.setattr(svc, '_record_change', _unexpected_record_change)
|
||||
|
||||
result = svc.validate_draft(user_id=1, case_no='SORC-IDEM-1', expected_draft_version=5)
|
||||
assert result == {'serialized': True}
|
||||
|
||||
|
||||
def test_validate_draft_runs_validation_when_content_changed(monkeypatch):
|
||||
"""内容变化(含人工改脏):不允许短路,必须走真实校验路径。"""
|
||||
from app.services.shipping_notice import order_review_draft_service as svc
|
||||
|
||||
case = object()
|
||||
monkeypatch.setattr(svc, '_locked_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_assert_version', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_stp_automation_holds_draft', lambda c: True)
|
||||
monkeypatch.setattr(svc, '_draft_content_unchanged', lambda c: False)
|
||||
monkeypatch.setattr(svc, 'serialize_review_case', lambda c: {'serialized': True})
|
||||
recorded: dict = {}
|
||||
monkeypatch.setattr(
|
||||
svc, '_record_change',
|
||||
lambda *args, **kwargs: recorded.update(kwargs) or {'recorded': True},
|
||||
)
|
||||
|
||||
result = svc.validate_draft(user_id=1, case_no='SORC-IDEM-2', expected_draft_version=6)
|
||||
assert result == {'recorded': True}
|
||||
assert recorded['event_type'] == 'draft_validated'
|
||||
assert recorded['validate'] is True
|
||||
|
||||
|
||||
def test_validate_draft_runs_validation_when_automation_not_holding(monkeypatch):
|
||||
"""自动化未持锁(如失败超 120s 逃生门后):保持原行为,允许重新校验触发重试。"""
|
||||
from app.services.shipping_notice import order_review_draft_service as svc
|
||||
|
||||
case = object()
|
||||
monkeypatch.setattr(svc, '_locked_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_assert_version', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_stp_automation_holds_draft', lambda c: False)
|
||||
monkeypatch.setattr(svc, '_draft_content_unchanged', lambda c: True)
|
||||
monkeypatch.setattr(svc, 'serialize_review_case', lambda c: {'serialized': True})
|
||||
monkeypatch.setattr(svc, '_record_change', lambda *args, **kwargs: {'recorded': True})
|
||||
|
||||
result = svc.validate_draft(user_id=1, case_no='SORC-IDEM-3', expected_draft_version=7)
|
||||
assert result == {'recorded': True}
|
||||
|
||||
|
||||
def test_draft_content_checksum_is_stable_and_content_sensitive():
|
||||
"""内容摘要:相同内容稳定一致,任一字段变化即不同;与版本/时间无关。"""
|
||||
from app.services.shipping_notice import order_review_draft_service as svc
|
||||
|
||||
draft_a = SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[{'line': 1}])
|
||||
draft_a_same = SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[{'line': 1}])
|
||||
draft_changed = SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[{'line': 2}])
|
||||
draft_none = SimpleNamespace(header_values_json=None, lines_json=None)
|
||||
|
||||
assert svc._draft_content_checksum(draft_a) == svc._draft_content_checksum(draft_a_same)
|
||||
assert svc._draft_content_checksum(draft_a) != svc._draft_content_checksum(draft_changed)
|
||||
# None 视为空内容,不抛异常
|
||||
assert svc._draft_content_checksum(draft_none)
|
||||
|
||||
|
||||
def test_draft_content_unchanged_false_for_legacy_draft_without_checksum():
|
||||
"""旧草稿(升级前校验)没有 content_checksum:不短路,保持原行为。"""
|
||||
from app.services.shipping_notice import order_review_draft_service as svc
|
||||
|
||||
legacy_case = SimpleNamespace(current_draft=SimpleNamespace(
|
||||
header_values_json={'po': 'P1'},
|
||||
lines_json=[],
|
||||
validation_result_json={'can_build': True, 'status': 'ready'},
|
||||
))
|
||||
assert svc._draft_content_unchanged(legacy_case) is False
|
||||
|
||||
unchanged_case = SimpleNamespace(current_draft=SimpleNamespace(
|
||||
header_values_json={'po': 'P1'},
|
||||
lines_json=[],
|
||||
validation_result_json={'content_checksum': svc._draft_content_checksum(
|
||||
SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[]),
|
||||
)},
|
||||
))
|
||||
assert svc._draft_content_unchanged(unchanged_case) is True
|
||||
|
||||
changed_case = SimpleNamespace(current_draft=SimpleNamespace(
|
||||
header_values_json={'po': 'P2'},
|
||||
lines_json=[],
|
||||
validation_result_json=unchanged_case.current_draft.validation_result_json,
|
||||
))
|
||||
assert svc._draft_content_unchanged(changed_case) is False
|
||||
@@ -324,3 +324,101 @@ def test_stp_handler_flattens_business_error_details(app):
|
||||
persisted = fail_mock.call_args.kwargs['result']['blocking_reason_details']
|
||||
assert persisted['fields'] == ['unexpected_field']
|
||||
assert persisted['schema_version_id'] == 31
|
||||
|
||||
|
||||
def test_ensure_stp_supersedes_stale_queued_jobs_and_enqueues_with_retries(app):
|
||||
"""入队前必须作废同文档旧版本 queued Job;max_attempts>1 允许瞬时失败自动重试。
|
||||
|
||||
背景(2026-09-22 生产事故):同文档 v8/v9 两个 STP Job 并发执行在建单 advisory 锁上
|
||||
死锁,且 max_attempts=1 一次判死、无补偿,case 永久停在 ready。
|
||||
"""
|
||||
from app.services.shipping_notice import order_stp_auto_create_service as svc
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=31,
|
||||
case_no='SORC-STP-31',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=10,
|
||||
candidate_id=None,
|
||||
disposition=None,
|
||||
run_id=1,
|
||||
run=SimpleNamespace(run_no='SNER-TEST-31', id=1),
|
||||
owner_user_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=9,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
|
||||
issue_summary_json=[],
|
||||
),
|
||||
)
|
||||
captured: dict = {}
|
||||
superseded_kwargs: dict = {}
|
||||
|
||||
def _enqueue(*args, **kwargs):
|
||||
captured['max_attempts'] = kwargs.get('max_attempts')
|
||||
captured['business_ref'] = kwargs.get('business_ref')
|
||||
return 901
|
||||
|
||||
def _supersede(**kwargs):
|
||||
superseded_kwargs.update(kwargs)
|
||||
return 1
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_draft_has_manual_edits', return_value=False
|
||||
), patch.object(svc, '_supersede_stale_queued_stp_jobs', side_effect=_supersede), patch.object(
|
||||
svc, 'find_active_stp_job', return_value=None
|
||||
), patch.object(svc, 'find_latest_stp_job', return_value=None), patch.object(
|
||||
svc, 'enqueue', side_effect=_enqueue
|
||||
), patch.object(svc, 'record_fulfillment_audit'), patch.object(svc, 'db'):
|
||||
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False)
|
||||
|
||||
# 断言:入队前先作废旧版本 queued Job,且按当前草稿版本调用
|
||||
assert superseded_kwargs == {
|
||||
'run_no': 'SNER-TEST-31',
|
||||
'document_id': 10,
|
||||
'current_draft_version': 9,
|
||||
}
|
||||
# 断言:瞬时失败可重试(死锁类不再一次判死)
|
||||
assert captured['max_attempts'] == 3
|
||||
assert captured['business_ref'] == 'stp-auto:SNER-TEST-31:doc-10:v9'
|
||||
assert result['status'] == 'queued'
|
||||
|
||||
|
||||
def test_supersede_stale_queued_stp_jobs_only_touches_lower_version_queued(app):
|
||||
"""只作废同 run+doc 低版本 queued Job;running 留给执行期检查,跨 run 不动。"""
|
||||
from app import db
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice import order_stp_auto_create_service as svc
|
||||
|
||||
def _mk(ref: str, status: str) -> Job:
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type='shipping_stp_auto_create',
|
||||
status=status,
|
||||
business_ref=ref,
|
||||
)
|
||||
db.session.add(job)
|
||||
return job
|
||||
|
||||
queued_v1 = _mk('stp-auto:SNER-T:doc-9:v1', 'queued')
|
||||
running_v2 = _mk('stp-auto:SNER-T:doc-9:v2', 'running')
|
||||
success_v3 = _mk('stp-auto:SNER-T:doc-9:v3', 'success')
|
||||
queued_v8 = _mk('stp-auto:SNER-T:doc-9:v8', 'queued')
|
||||
other_run_v1 = _mk('stp-auto:SNER-OTHER:doc-9:v1', 'queued')
|
||||
db.session.commit()
|
||||
|
||||
count = svc._supersede_stale_queued_stp_jobs(
|
||||
run_no='SNER-T', document_id=9, current_draft_version=9,
|
||||
)
|
||||
|
||||
# 断言:恰好作废同 run 的 v1/v8 两条 queued;其余状态与跨 run Job 不受影响
|
||||
assert count == 2
|
||||
superseded_v1 = db.session.get(Job, queued_v1.id)
|
||||
assert superseded_v1.status == 'success'
|
||||
assert '已被新版草稿替代' in str(superseded_v1.message or '')
|
||||
assert superseded_v1.result_json.get('superseded_at_enqueue') is True
|
||||
assert superseded_v1.result_json.get('superseded_by_draft_version') == 9
|
||||
assert db.session.get(Job, running_v2.id).status == 'running'
|
||||
assert db.session.get(Job, success_v3.id).status == 'success'
|
||||
assert db.session.get(Job, queued_v8.id).status == 'success'
|
||||
assert db.session.get(Job, other_run_v1.id).status == 'queued'
|
||||
@@ -653,6 +653,22 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
moreActions: '更多操作',
|
||||
inventorySource: '库存源',
|
||||
},
|
||||
lineActions: {
|
||||
closeLine: '结案(不再发货)',
|
||||
closeLineConfirm: '确认结案',
|
||||
editLine: '编辑',
|
||||
more: '更多操作',
|
||||
},
|
||||
inlineEdit: {
|
||||
save: '保存',
|
||||
cancel: '取消',
|
||||
busy: '系统处理中,请稍后再修改',
|
||||
},
|
||||
releaseBar: {
|
||||
label: '放行补录',
|
||||
missingPrefix: '缺 ',
|
||||
missingSuffix: ' 项放行信息',
|
||||
},
|
||||
workflowProgress: {
|
||||
automatingFooterHint: '系统自动推进中',
|
||||
},
|
||||
@@ -682,6 +698,9 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
downloadInventory: '下载库存文件',
|
||||
retryInventory: '重新获取库存',
|
||||
releaseShortage: '库存缺口放行',
|
||||
releaseShortageHint: '放行后本次发货按缺口处理。',
|
||||
releaseReasonPlaceholder: '可填写放行原因(选填)',
|
||||
releaseConfirm: '确认放行',
|
||||
shortage: '库存不足',
|
||||
pending: '库存匹配或通知文件尚未生成。',
|
||||
},
|
||||
@@ -733,6 +752,9 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
processGate: {
|
||||
inventoryActions: {
|
||||
retryInventoryPreparation: '重新获取库存(RPA)',
|
||||
retryInventoryMatching: '重新匹配库存',
|
||||
downloadInventoryFile: '下载库存文件',
|
||||
releaseInventoryShortage: '库存缺口放行',
|
||||
},
|
||||
actionCodes: {
|
||||
confirm_customer: '确认客户',
|
||||
@@ -792,6 +814,27 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开通知准备行的更多操作菜单(⋯)。
|
||||
* 核心逻辑:展示态行级动作(重试/放行/下载)已收纳进该菜单,入口按钮在表格行内。
|
||||
*/
|
||||
async function openLineOverflowMenu(wrapper: { get: (selector: string) => { trigger: (event: string) => Promise<void> } }, lineId: number | string) {
|
||||
await wrapper.get(`[data-testid="review-fulfillment-line-more-${lineId}"]`).trigger('click');
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
/**
|
||||
* 断言行级菜单项已渲染并触发点击。
|
||||
* 核心逻辑:菜单经 Teleport 渲染到 body,必须走 document.body 查询而不是 wrapper.find;
|
||||
* 点击后 flushPromises 等待菜单收起与异步动作(下载/门禁提交)落位。
|
||||
*/
|
||||
async function clickLineMenuItem(lineId: number | string, action: string) {
|
||||
const item = document.body.querySelector(`[data-testid="review-fulfillment-line-action-${action}-${lineId}"]`) as HTMLButtonElement | null;
|
||||
expect(item, `行级菜单项 ${action}-${lineId} 应已渲染`).toBeTruthy();
|
||||
item!.click();
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
|
||||
function resetActiveCaseFixture() {
|
||||
activeCase.value = createActiveCaseFixture();
|
||||
@@ -2677,16 +2720,17 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(workspace.text()).toContain('PN-FROZEN');
|
||||
expect(workspace.text()).toContain('DBS');
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-download-1001"]').attributes('title'))
|
||||
.toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-1001"]').attributes('title'))
|
||||
.toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-matching-1001"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-release-1001"]').exists()).toBe(true);
|
||||
// 展示态行级动作收纳进更多菜单(⋯):逐项断言授权动作入口存在,不再有常显按钮。
|
||||
await openLineOverflowMenu(wrapper, 1001);
|
||||
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-download_inventory_file-1001"]')).toBeTruthy();
|
||||
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_inventory_preparation-1001"]')).toBeTruthy();
|
||||
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_inventory_matching-1001"]')).toBeTruthy();
|
||||
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-release_inventory_shortage-1001"]')).toBeTruthy();
|
||||
expect(workspace.text()).toContain('库存不足');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-download-1001"]').trigger('click');
|
||||
await clickLineMenuItem(1001, 'download_inventory_file');
|
||||
expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-1001"]').trigger('click');
|
||||
await openLineOverflowMenu(wrapper, 1001);
|
||||
await clickLineMenuItem(1001, 'retry_inventory_preparation');
|
||||
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
expect.objectContaining({
|
||||
@@ -2696,7 +2740,8 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
);
|
||||
// Gate 恢复受理后立即启动五阶段轮询,不依赖浏览器手动刷新。
|
||||
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(1);
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-1001"]').trigger('click');
|
||||
await openLineOverflowMenu(wrapper, 1001);
|
||||
await clickLineMenuItem(1001, 'release_inventory_shortage');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001');
|
||||
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
|
||||
@@ -2763,11 +2808,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-1001"]').trigger('click');
|
||||
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
|
||||
await dialog.find('textarea').setValue('客户确认分批发货');
|
||||
await dialog.find('input').setValue('A-01');
|
||||
await dialog.get('button.bg-amber-600').trigger('click');
|
||||
// 缺字段短缺行:放行入口在更多菜单,必填补录在行内补录条完成(原因不再强制)。
|
||||
await openLineOverflowMenu(wrapper, 1001);
|
||||
await clickLineMenuItem(1001, 'release_inventory_shortage');
|
||||
await wrapper.get('[data-testid="review-fulfillment-release-input-1001-102"]').setValue('A-01');
|
||||
await wrapper.get('[data-testid="review-fulfillment-release-confirm-1001"]').trigger('click');
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
|
||||
@@ -2823,11 +2868,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-1002"]').trigger('click');
|
||||
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
|
||||
await dialog.find('textarea').setValue('客户确认单行放行');
|
||||
await dialog.find('input').setValue('A-01');
|
||||
await dialog.get('button.bg-amber-600').trigger('click');
|
||||
await openLineOverflowMenu(wrapper, 1002);
|
||||
await clickLineMenuItem(1002, 'release_inventory_shortage');
|
||||
await wrapper.get('[data-testid="review-fulfillment-release-input-1002-102"]').setValue('A-01');
|
||||
await wrapper.get('[data-testid="review-fulfillment-release-confirm-1002"]').trigger('click');
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
|
||||
@@ -2899,11 +2943,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
});
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-1003"]').trigger('click');
|
||||
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
|
||||
await dialog.find('textarea').setValue('客户确认分批发货');
|
||||
await dialog.find('input').setValue('A-01');
|
||||
await dialog.get('button.bg-amber-600').trigger('click');
|
||||
await openLineOverflowMenu(wrapper, 1003);
|
||||
await clickLineMenuItem(1003, 'release_inventory_shortage');
|
||||
await wrapper.get('[data-testid="review-fulfillment-release-input-1003-102"]').setValue('A-01');
|
||||
await wrapper.get('[data-testid="review-fulfillment-release-confirm-1003"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].trigger('click');
|
||||
resolvePostReleaseTask?.(taskDetail());
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
@@ -449,7 +449,18 @@ const isLifecycleFreightUpload = computed(() => lifecycleActiveStageCode.value =
|
||||
const isLifecycleUploadComplete = computed(() => lifecycleActiveStageCode.value === 'upload_complete');
|
||||
/** 正式任务已通知完成时,即使用户回看前置阶段也只能查看,不能再修改已产出通知。 */
|
||||
const isCompletedFormalTask = computed(() => lifecycleCurrentStageCode.value === 'upload_complete');
|
||||
const isReviewContentReadOnly = computed(() => isReadOnly.value || isCompletedFormalTask.value);
|
||||
/**
|
||||
* STP 自动建单进行中(等待入队/排队/执行):与 isProcessingAutomating 的 STP 分支同源。
|
||||
* 期间表单只读——后端 `_locked_case` 同步拒绝内容写入(REVIEW_DRAFT_LOCKED_BY_AUTOMATION),
|
||||
* 前端不再展示可编辑假象,避免用户误以为修改已生效。
|
||||
*/
|
||||
const isStpAutoCreateInProgress = computed(() => {
|
||||
const stpStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
|
||||
return !hasFormalOt.value && ['waiting_to_start', 'queued', 'running'].includes(stpStatus);
|
||||
});
|
||||
const isReviewContentReadOnly = computed(() => (
|
||||
isReadOnly.value || isCompletedFormalTask.value || isStpAutoCreateInProgress.value
|
||||
));
|
||||
|
||||
/** 二期编辑窗(D10):读正式任务 ui_state.edit_window;前端 fail-closed,锁定字段禁用/提示。 */
|
||||
const formalEditWindow = computed(() => formalTaskDetail.value?.ui_state?.edit_window ?? null);
|
||||
@@ -5319,7 +5330,7 @@ watch(
|
||||
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
|
||||
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
|
||||
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
|
||||
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
|
||||
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
@@ -6143,6 +6154,8 @@ watch(
|
||||
@adjudicate="({ suggestion, body }) => decideSuggestion(suggestion.suggestion_no, body)"
|
||||
/>
|
||||
|
||||
<!-- 底栏只读不含 STP 运行锁(isStpAutoCreateInProgress):运行态已由 automating 单独承载
|
||||
(隐藏全部写按钮并显示运行提示);叠加会让 footer 整体隐藏,运行提示永远不可见。 -->
|
||||
<ReviewWorkbenchFooter
|
||||
v-if="showOrderReviewEditor || isLifecycleIntakeParse"
|
||||
:available-actions="availableActions"
|
||||
@@ -6152,7 +6165,7 @@ watch(
|
||||
:show-stp-retry="showObjectRetryOnFooter"
|
||||
:auto-gate-hint="t(autoGateHintKey)"
|
||||
:saving="saving"
|
||||
:is-read-only="isReviewContentReadOnly"
|
||||
:is-read-only="isReadOnly || isCompletedFormalTask"
|
||||
:has-draft="Boolean(displayCase?.draft) || isLifecycleIntakeParse"
|
||||
:unsaved-count="unsavedEditCount"
|
||||
:flow-presentation="flowPresentation"
|
||||
|
||||
Reference in new issue
Block a user