Merge branch 'hugo-shipping-notice' into dev
# Conflicts: # backend/app/services/shipping_notice/receipt_report_notification.py
This commit is contained in:
commit
876a7ade7d
212 files changed
+12056
-2889
No files matched your search
@@ -4,7 +4,8 @@ services/shipping_notice/attachment_selection.py
|
||||
用途:基于 Intake 快览事实生成可审计的附件选择计划。
|
||||
依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
|
||||
所有预算内附件先物化为同一 Run 的 Unit,Worker 再按并发预算执行,避免把排队误建模为扩批。
|
||||
合格业务附件全量入选批次 1(有多少单解析多少单),仅字节预算超限转 Review;
|
||||
数量类预算字段仅作快照记录,不再截断,扩批链路不再产出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -150,10 +151,11 @@ def build_attachment_selection_snapshot(
|
||||
|
||||
Args:
|
||||
intakes: 当前发送批次的 Intake;必须已经通过上传快览。
|
||||
max_initial_attachments: 兼容旧快照的首轮附件字段;新计划不以它限制 Unit 创建。
|
||||
max_initial_attachments: 历史兼容字段,仅写入快照作审计记录,不参与选择。
|
||||
max_initial_concurrency: Worker 最大并发,仅限制执行,不限制 Unit 创建。
|
||||
expansion_batch_size: 后续每轮扩展的附件上限。
|
||||
max_total_attachments: 单次邮件深度解析总附件预算上限。
|
||||
expansion_batch_size: 历史兼容字段,仅写入快照作审计记录,不参与选择。
|
||||
max_total_attachments: 历史兼容字段,仅写入快照作审计记录,不再按数量截断。
|
||||
max_total_bytes: 唯一生效的选择预算;累计超限的附件以 budget_total_bytes 转 Review。
|
||||
|
||||
Returns:
|
||||
可写入 Run 快照的脱敏计划摘要,包含每个附件的 selected / skipped 结论与原因码。
|
||||
@@ -227,19 +229,16 @@ def build_attachment_selection_snapshot(
|
||||
eligible_ordered = sorted(eligible, key=lambda item: (-int(item['score']), str(item['filename'])))
|
||||
byte_budget = max(0, int(max_total_bytes or 0))
|
||||
planned_bytes = 0
|
||||
for index, row in enumerate(eligible_ordered):
|
||||
for row in eligible_ordered:
|
||||
size = int(row.get('size') or 0)
|
||||
if byte_budget and planned_bytes + size > byte_budget:
|
||||
row['skip_reason_codes'] = ['budget_total_bytes']
|
||||
continue
|
||||
# [STEP 1] 同一发送批次内的预算内附件必须全部创建 Unit。执行并发由
|
||||
# max_initial_concurrency 在物化/Worker 层控制,不能借“首轮选择”延迟附件身份。
|
||||
if index < max_total_attachments:
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = 1
|
||||
planned_bytes += size
|
||||
continue
|
||||
row['skip_reason_codes'] = ['budget_total_limit']
|
||||
# [STEP 1] 合格业务附件全量入选,不设数量截断:有多少单解析多少单。
|
||||
# 执行节奏由 max_initial_concurrency 与 Worker 运行时预算控制,扩批链路不再产出。
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = 1
|
||||
planned_bytes += size
|
||||
|
||||
group_counts: dict[str, int] = defaultdict(int)
|
||||
for row in rows:
|
||||
|
||||
@@ -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)
|
||||
@@ -289,20 +289,22 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
published_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||||
}
|
||||
# movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。
|
||||
referenced_field_ids = {
|
||||
str(item.get('order_field_id') or '')
|
||||
for item in (profile.definition_json or {}).get('match_keys', [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||
raise ValidationError(
|
||||
'Parsing profile match keys must reference the current published order schema',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if profile.purpose != 'movement':
|
||||
published_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||||
}
|
||||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||
raise ValidationError(
|
||||
'Parsing profile match keys must reference the current published order schema',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
profile.status = 'published'
|
||||
|
||||
@@ -453,6 +453,8 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
saved = inventory_parsing_profile.save_draft({
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
# 用途随请求透传(缺省沿用既有草稿/默认 inventory):movement 草稿端点为定死领域字段。
|
||||
'purpose': data.get('purpose'),
|
||||
'file_format': analysis.file_format,
|
||||
'sample_analysis_id': analysis.id,
|
||||
'confirm_sample_replacement': bool(data.get('confirm_sample_replacement')),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -571,7 +571,7 @@ def _require_owner_agent(*, user: User, agent_id: int) -> Agent:
|
||||
|
||||
|
||||
def _selection_budget_settings() -> dict[str, int]:
|
||||
"""读取订单抽取附件预算,统一生成首轮与后续扩展批次的选择计划。"""
|
||||
"""读取订单抽取附件预算。数量类字段仅作快照记录;唯一生效的选择预算是字节上限。"""
|
||||
max_initial_attachments = max(
|
||||
int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', 2) or 2),
|
||||
1,
|
||||
@@ -1088,10 +1088,19 @@ def synchronize_order_extraction_expansion_snapshot(
|
||||
1 for row in selection.get('items') or []
|
||||
if isinstance(row, dict) and bool(row.get('selected'))
|
||||
)
|
||||
pending_batches = selection.get('pending_expansion_batches')
|
||||
if isinstance(pending_batches, dict):
|
||||
pending_batches.pop(str(normalized_batch), None)
|
||||
pending_batches.pop(normalized_batch, None)
|
||||
# [STEP] 激活批次后必须按明细重算扩批事实:pending 标量若停留在构建期数值,
|
||||
# 投影层会在 Run 非完成态下把已全部处理的 Run 误报为「预算停扩」。
|
||||
pending_expansion: dict[int, int] = {}
|
||||
for row in selection.get('items') or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
planned_batch = int(row.get('planned_selection_batch') or 0)
|
||||
if planned_batch > 1:
|
||||
pending_expansion[planned_batch] = pending_expansion.get(planned_batch, 0) + 1
|
||||
selection['pending_expansion_attachment_count'] = sum(pending_expansion.values())
|
||||
selection['pending_expansion_batches'] = {
|
||||
str(batch): count for batch, count in sorted(pending_expansion.items())
|
||||
}
|
||||
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema_version_id = int(schema.get('schema_version_id') or run.schema_version_id or 0)
|
||||
@@ -4780,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 正式链触发下游。
|
||||
@@ -4788,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)。
|
||||
@@ -4799,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,
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
"""收料报表的企微文件及汇总投递服务。"""
|
||||
"""收料报表企微通知的管理员重发通道。
|
||||
|
||||
用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送
|
||||
textcard 汇总 + 全部收料文件(scheduler_service._notify_schedule_run_wecom,
|
||||
与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的
|
||||
强制重发能力(POST /receipt-report-files/<id>/resend),不触发 RPA。
|
||||
依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。
|
||||
逻辑:deliver_receipt_file 幂等投递单文件并落 ShippingReceiptNotificationDelivery
|
||||
与 shipping 审计;force=True 供管理员补偿重发,绕过成功幂等但仍受通知开关约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,8 +16,8 @@ from datetime import datetime
|
||||
from app import db
|
||||
from app.models import ShippingReceiptNotificationDelivery, ShippingReceiptReportFile, User
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.integrations.wecom.notify import send_wecom_file_message, send_wecom_textcard_message, upload_wecom_temp_media
|
||||
|
||||
|
||||
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
|
||||
@@ -82,58 +91,3 @@ def deliver_receipt_file(file_id: int, *, force: bool = False) -> dict:
|
||||
)
|
||||
db.session.commit()
|
||||
return {'success_count': success_count, 'failed_count': failed_count}
|
||||
|
||||
|
||||
def deliver_schedule_receipt_summary(schedule_run_id: int) -> dict:
|
||||
"""所有收料单元结束后向接收人发送汇总;无数据不附空文件。"""
|
||||
from app.models import ScheduleRun, ShippingReceiptRpaUnitRun
|
||||
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
task = run.task if run else None
|
||||
if run is None or task is None or not task.notify_enabled:
|
||||
return {'success_count': 0, 'failed_count': 0}
|
||||
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
|
||||
success = sum(unit.status == 'success' for unit in units)
|
||||
empty = sum(unit.status == 'empty' for unit in units)
|
||||
failed = sum(unit.status == 'failed' for unit in units)
|
||||
results = {'success_count': 0, 'failed_count': 0}
|
||||
for user_id in sorted({int(item) for item in (task.notify_user_ids_json or []) if str(item).isdigit()}):
|
||||
key = f'receipt:summary:{run.id}:user:{user_id}'
|
||||
delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
|
||||
if delivery and delivery.status == 'success':
|
||||
results['success_count'] += 1
|
||||
continue
|
||||
if delivery is None:
|
||||
delivery = ShippingReceiptNotificationDelivery(unit_run_id=None, report_file_id=None, recipient_user_id=user_id, message_type='summary', idempotency_key=key)
|
||||
db.session.add(delivery); db.session.flush()
|
||||
user = db.session.get(User, user_id)
|
||||
if user is None or not user.wecom_userid:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'; results['failed_count'] += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_summary_notification_attempted', aggregate_type='shipping_receipt_schedule_run',
|
||||
aggregate_id=str(run.id), actor_type='system', owner_user_id=user_id, result='failure',
|
||||
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'summary'},
|
||||
)
|
||||
continue
|
||||
try:
|
||||
response = send_wecom_textcard_message(user.wecom_userid, '收料报表导出结果', f'成功文件 {success},无数据 {empty},失败 {failed}。', '')
|
||||
if int(response.get('errcode', -1)) != 0:
|
||||
raise RuntimeError(str(response.get('errmsg') or response.get('errcode')))
|
||||
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.response_summary_json = {'errcode': 0, 'success_files': success, 'empty_units': empty, 'failed_units': failed}; results['success_count'] += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_summary_notification_attempted', aggregate_type='shipping_receipt_schedule_run',
|
||||
aggregate_id=str(run.id), actor_type='system', owner_user_id=user_id, result='success',
|
||||
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'summary', 'success_files': success, 'empty_units': empty, 'failed_units': failed},
|
||||
)
|
||||
except Exception as exc:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]; results['failed_count'] += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_summary_notification_attempted', aggregate_type='shipping_receipt_schedule_run',
|
||||
aggregate_id=str(run.id), actor_type='system', owner_user_id=user_id, result='failure',
|
||||
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'summary'},
|
||||
)
|
||||
db.session.commit()
|
||||
return results
|
||||
@@ -94,7 +94,9 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty')
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
if status != 'success':
|
||||
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
|
||||
@@ -108,7 +110,9 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_receipt_callback_file(str(payload.get('file_path') or ''))
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
@@ -128,8 +132,9 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
deliver_receipt_file(record.id)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
|
||||
if unit.schedule_run_id:
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
Reference in new issue
Block a user