本次提交完整实现货代发货通知的自动化批量处理能力: 1. 新增发货单票后台任务类型与专用worker队列,实现任务持久化调度 2. 实现发货批次后台编排器,支持上传后自动逐票推进解析、匹配、导出全流程 3. 新增单票重试、批次待处理重试的API与前端操作界面 4. 补充全量多语言翻译,新增重试、任务列表、状态展示相关文案 5. 优化上传交互逻辑,改为后台自动处理任务,无需手动触发解析指令 6. 修复文件检核工具无数据预检逻辑,避免创建空检核批次 7. 调整发货工作流细节,优化Excel生成幂等性与任务状态同步 8. 更新环境配置与API文档,修正货代工具接口地址端口
174 lines
6.0 KiB
Python
174 lines
6.0 KiB
Python
"""
|
||
services/shipping_notice/queue_service.py
|
||
|
||
用途:货代发货后台任务最小队列实现(基于 KbJob 持久化表)。
|
||
依赖:models.KbJob、jobs.types、shipping_notice.batch_orchestrator。
|
||
逻辑:Web 侧负责 enqueue;worker 侧通过 claim/process 消费单票任务,避免使用进程内 threading。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime, timedelta
|
||
from typing import Any
|
||
import logging
|
||
|
||
from flask import current_app
|
||
from sqlalchemy.exc import OperationalError
|
||
|
||
from app import db
|
||
from app.jobs.types import JobType
|
||
from app.models import KbJob
|
||
|
||
logger = logging.getLogger('shipping-worker')
|
||
|
||
|
||
def shipping_task_execution_mode() -> str:
|
||
return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower()
|
||
|
||
|
||
def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = None, batch_no: str | None = None) -> tuple[bool, str]:
|
||
"""持久化一条单票发货后台任务;sync 模式下直接执行。"""
|
||
normalized_task_no = str(task_no or '').strip().upper()
|
||
if not normalized_task_no:
|
||
return False, 'task_no is required'
|
||
|
||
existing = (
|
||
db.session.query(KbJob)
|
||
.filter(
|
||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||
KbJob.status.in_(('queued', 'running')),
|
||
)
|
||
.all()
|
||
)
|
||
for job in existing:
|
||
payload = job.payload_json or {}
|
||
if str(payload.get('task_no') or '').strip().upper() == normalized_task_no:
|
||
return True, 'already_queued'
|
||
|
||
job = KbJob(
|
||
job_type=JobType.SHIPPING_NOTICE_RUN.value,
|
||
status='queued',
|
||
progress=0,
|
||
message='等待后台处理发货任务',
|
||
payload_json={
|
||
'task_no': normalized_task_no,
|
||
'batch_no': str(batch_no or '').strip().upper() or None,
|
||
},
|
||
created_by_id=created_by_id,
|
||
)
|
||
db.session.add(job)
|
||
db.session.commit()
|
||
|
||
if shipping_task_execution_mode() == 'sync':
|
||
ok, result = run_shipping_notice_job({'job_id': job.id})
|
||
return ok, result
|
||
if shipping_task_execution_mode() in ('worker', 'rq'):
|
||
return True, 'queued_for_worker'
|
||
return True, 'queued_manual'
|
||
|
||
|
||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||
"""回收长时间 running 的发货后台任务,避免 worker 被卡死任务阻塞。"""
|
||
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
|
||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
|
||
stale_jobs = (
|
||
db.session.query(KbJob)
|
||
.filter(
|
||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||
KbJob.status == 'running',
|
||
KbJob.started_at.isnot(None),
|
||
KbJob.started_at < cutoff,
|
||
)
|
||
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
|
||
.all()
|
||
)
|
||
if not stale_jobs:
|
||
return 0, 'no_stale_jobs'
|
||
|
||
now = datetime.utcnow()
|
||
message = f'发货任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
|
||
for job in stale_jobs:
|
||
job.status = 'failed'
|
||
job.error_message = message
|
||
job.message = message
|
||
job.finished_at = now
|
||
job.progress = 100
|
||
db.session.commit()
|
||
logger.warning('recovered %s stale shipping_notice job(s)', len(stale_jobs))
|
||
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
|
||
|
||
|
||
def claim_next_shipping_notice_job() -> KbJob | None:
|
||
"""原子领取下一条 queued 的发货后台任务。"""
|
||
now = datetime.utcnow()
|
||
try:
|
||
job = (
|
||
db.session.query(KbJob)
|
||
.filter(
|
||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||
KbJob.status == 'queued',
|
||
)
|
||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||
.with_for_update(skip_locked=True)
|
||
.first()
|
||
)
|
||
except OperationalError:
|
||
db.session.rollback()
|
||
logger.exception('failed to claim next shipping notice job')
|
||
return None
|
||
|
||
if not job:
|
||
db.session.rollback()
|
||
return None
|
||
|
||
job.status = 'running'
|
||
job.started_at = job.started_at or now
|
||
job.progress = max(int(job.progress or 0), 1)
|
||
job.message = 'worker 已领取发货任务'
|
||
db.session.commit()
|
||
return job
|
||
|
||
|
||
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
|
||
"""执行单票发货任务;既可被 worker 调用,也可被 sync enqueue 直调。"""
|
||
from app.services.shipping_notice.batch_orchestrator import _run_single_task
|
||
|
||
job_id = payload.get('job_id')
|
||
job = db.session.get(KbJob, int(job_id)) if job_id else None
|
||
if job is None:
|
||
task_no = str(payload.get('task_no') or '').strip().upper()
|
||
else:
|
||
task_no = str((job.payload_json or {}).get('task_no') or '').strip().upper()
|
||
|
||
if not task_no:
|
||
return False, 'missing_task_no'
|
||
|
||
result = _run_single_task(task_no)
|
||
status = str(result.get('status') or '').strip().lower()
|
||
success = status in {'ok', 'running', 'needs_human', 'skipped'}
|
||
|
||
if job is not None:
|
||
job.progress = 100
|
||
job.finished_at = datetime.utcnow()
|
||
job.result_json = dict(result)
|
||
job.message = str(result.get('message') or '')[:500] or '发货任务处理完成'
|
||
if success:
|
||
job.status = 'success'
|
||
job.error_message = None
|
||
else:
|
||
job.status = 'failed'
|
||
job.error_message = str(result.get('message') or 'shipping notice job failed')[:1000]
|
||
db.session.commit()
|
||
|
||
if logger:
|
||
logger.info('shipping_notice job task_no=%s status=%s', task_no, status or 'unknown')
|
||
return success, status or 'done'
|
||
|
||
|
||
def process_next_shipping_notice_job() -> tuple[bool, str]:
|
||
"""worker 消费发货后台队列的单步入口。"""
|
||
recover_stale_shipping_notice_jobs()
|
||
job = claim_next_shipping_notice_job()
|
||
if not job:
|
||
return False, 'no_job'
|
||
return run_shipping_notice_job({'job_id': job.id})
|