Files
syops/backend/app/jobs/handlers/shipping_notice_parse.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

275 lines
9.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/jobs/handlers/shipping_notice_parse.py
用途:发货通知接入记录异步预解析 handler。
依赖:jobs.context、jobs.registry、intake_parse_workflow、queue.fail/finish。
逻辑:领取时写入 parse_lease="{job_id}:{attempts}";写回/失败清理均校验 lease;
Job 收口一律 finish_job/fail_job(owned_attempt=...) 条件 UPDATE,
禁止依赖 Session 身份映射判断执行权。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import and_, or_, update
from app import db
from app.core.errors import AppError, NotFoundError
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingOrderIntake
from app.services.shipping_notice.intake_parse_workflow import (
fail_intake_with_stage2_cleanup,
run_intake_parse,
)
# 真终态:无论 Job 身份都不再领取
_TERMINAL_SKIP_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
# 正常可领取进入 parsing
_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parse_failed'})
def _load_asset(asset_id: int) -> FileAsset:
"""
加载父级 FileAsset;软删或不存在则抛 NotFoundError。
Args:
asset_id: FileAsset 主键。
Returns:
可用的 FileAsset。
Raises:
NotFoundError: 资产不存在或已软删。
"""
asset = db.session.get(FileAsset, asset_id)
if not asset or asset.deleted_at is not None:
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
return asset
def _build_parse_lease(*, job_id: int | None, owned_attempt: int | None) -> str:
"""
构造本轮解析执行代次 token。
核心逻辑:有 Job 时使用 "{job_id}:{attempts}",与 claim_next_job 递增的 attempts 对齐;
无 Job(单测直调)时使用随机 UUID。
"""
if job_id is not None and owned_attempt is not None:
return f'{int(job_id)}:{int(owned_attempt)}'
return uuid.uuid4().hex
def _claim_intake_for_parsing(
intake_no: str,
*,
job_id: int | None,
owned_attempt: int | None,
) -> tuple[ShippingOrderIntake, str] | None:
"""
原子领取 Intake 并轮转 parse_lease。
核心逻辑:仅 created/queued/parse_failed,或 parsing 且 parse_job_id 精确等于当前 Job
(回收漏同步时由新 attempts 轮转 lease,旧 lease 立即失效)。
Returns:
(Intake, lease) 或 None。
"""
now = datetime.utcnow()
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
claim_predicate = ShippingOrderIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
if job_id is not None:
claim_predicate = or_(
claim_predicate,
and_(
ShippingOrderIntake.parse_status == 'parsing',
ShippingOrderIntake.parse_job_id == int(job_id),
),
)
values: dict = {
'parse_status': 'parsing',
'parse_lease': lease,
'updated_at': now,
}
if job_id is not None:
values['parse_job_id'] = int(job_id)
stmt = (
update(ShippingOrderIntake)
.where(
ShippingOrderIntake.intake_no == intake_no,
claim_predicate,
)
.values(**values)
)
result = db.session.execute(stmt)
if int(result.rowcount or 0) != 1:
db.session.rollback()
return None
db.session.commit()
intake = (
db.session.query(ShippingOrderIntake)
.filter_by(intake_no=intake_no)
.first()
)
if intake is None:
return None
return intake, lease
def _is_retryable_exc(exc: BaseException) -> bool:
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
@register_handler(JobType.SHIPPING_NOTICE_PARSE)
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
"""
消费发货通知预解析任务。
Args:
ctx: Worker 上下文。
payload: 须含 job_id 或 intake_no。
"""
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
job_id = int(job.id) if job is not None else None
# claim_next_job 已递增 attempts;该值即本轮执行代次(收口必须带入条件 UPDATE)
owned_attempt = int(job.attempts or 0) if job is not None else None
intake_no = str(
(job.payload_json or {}).get('intake_no') if job else payload.get('intake_no') or ''
).strip().upper()
if not intake_no:
if job_id is not None:
fail_job(
job_id,
error='missing intake_no',
retryable=False,
owned_attempt=owned_attempt,
)
return
intake = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
if not intake:
if job_id is not None:
fail_job(
job_id,
error=f'intake not found: {intake_no}',
retryable=False,
owned_attempt=owned_attempt,
)
return
# [STEP 1] 真终态跳过
if intake.parse_status in _TERMINAL_SKIP_STATUSES:
if job_id is not None:
finish_job(
job_id,
result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True},
owned_attempt=owned_attempt,
)
return
# [STEP 1b] parsing 但非本 Job:另一 worker 持有 → 跳过
if (
intake.parse_status == 'parsing'
and job_id is not None
and (
intake.parse_job_id is None
or int(intake.parse_job_id) != int(job_id)
)
):
finish_job(
job_id,
result={'status': 'parsing', 'intake_no': intake_no, 'skipped': True},
owned_attempt=owned_attempt,
)
return
# [STEP 2] 原子领取并轮转 lease
claimed = _claim_intake_for_parsing(
intake_no, job_id=job_id, owned_attempt=owned_attempt
)
if claimed is None:
current = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
if job_id is not None:
finish_job(
job_id,
result={
'status': str(getattr(current, 'parse_status', None) or 'unknown'),
'intake_no': intake_no,
'skipped': True,
},
owned_attempt=owned_attempt,
)
return
intake, parse_lease = claimed
intake_id = int(intake.id)
preserved_parser = str(intake.parser_version or 'v6')
preserved_text = intake.extracted_text
preserved_structured = (
dict(intake.structured_result_json)
if isinstance(intake.structured_result_json, dict)
else {}
)
preserved_warnings = list(intake.parse_warnings_json or [])
try:
asset = _load_asset(intake.asset_id)
result = run_intake_parse(intake, asset, parse_lease=parse_lease)
if job_id is None:
return
status = str(result.get('status') or '')
if status in {'parsed', 'skipped'}:
finish_job(
job_id,
result=result,
message=(
'发货通知预解析完成'
if status == 'parsed'
else '接入已取消、过期或执行代次失效,跳过'
),
owned_attempt=owned_attempt,
)
else:
fail_job(
job_id,
error=str(result.get('error_message') or 'parse failed'),
retryable=False,
owned_attempt=owned_attempt,
)
except Exception as exc:
db.session.rollback()
error_code = getattr(exc, 'code', None) or 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
fail_result = fail_intake_with_stage2_cleanup(
intake_id=intake_id,
intake_no=intake_no,
parser_version=preserved_parser,
error_code=str(error_code),
error_message=str(exc)[:1000],
extracted_text=preserved_text,
structured_result_json=preserved_structured,
parse_warnings_json=preserved_warnings,
allowed_statuses=frozenset({'parsing', 'queued', 'created'}),
required_lease=parse_lease,
)
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
return
retryable = False
if job_id is not None:
fail_job(
job_id,
error=str(exc),
retryable=retryable,
owned_attempt=owned_attempt,
)