feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑
This commit is contained in:
1 parent
34d489a2d1
commit
ce26d6d0c4
144 files changed
+12241
-4233
No files matched your search
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取领域 Run,调用显式绑定的 Dify Workflow 并持久化订单结果。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
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 Agent, Job, ShippingOrderExtractionRun
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workflow import execute_order_extraction_workflow
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次订单抽取 Job。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
payload: 须含 job_id;业务身份只从 Job.business_ref 对应 Run 读取。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
if run is None:
|
||||
fail_job(job.id, error='order extraction run not found', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
if run.status in {'completed', 'needs_review'}:
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'run_no': run.run_no, 'status': run.status, 'idempotent_replay': True},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
if run.status == 'result_persisted':
|
||||
final_status = 'needs_review' if (run.result_json or {}).get('pending_count') else 'completed'
|
||||
transition_order_extraction_run(run, target_status=final_status)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'status': run.status}, owned_attempt=owned_attempt)
|
||||
return
|
||||
if run.status not in {'queued', 'running'}:
|
||||
fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
ctx.logger.info(
|
||||
'shipping_order_extraction_started run_no=%s job_id=%s attempt=%s phase=%s',
|
||||
run.run_no,
|
||||
job.id,
|
||||
owned_attempt,
|
||||
run.phase,
|
||||
)
|
||||
handler_started = time.perf_counter()
|
||||
try:
|
||||
provider = db.session.get(Agent, int(run.provider_agent_id))
|
||||
if provider is None or not provider.is_active:
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED',
|
||||
message='订单抽取 Provider 不存在或已停用',
|
||||
http_status=409,
|
||||
)
|
||||
if (
|
||||
provider.runtime_provider != 'dify'
|
||||
or provider.dify_app_type != 'workflow'
|
||||
or provider.exposure_mode != 'internal'
|
||||
or not str(provider.dify_app_id or '').strip()
|
||||
or not str(provider.dify_api_key or '').strip()
|
||||
or not str(provider.api_base_url or '').strip()
|
||||
):
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CHANGED',
|
||||
message='订单抽取 Provider 配置已不符合 Run 的执行约束',
|
||||
http_status=409,
|
||||
)
|
||||
provider_snapshot = run.provider_snapshot_json if isinstance(run.provider_snapshot_json, dict) else {}
|
||||
if (
|
||||
str(provider.dify_app_id or '') != str(provider_snapshot.get('dify_app_id') or '')
|
||||
or str(provider.api_base_url or '').rstrip('/') != str(provider_snapshot.get('api_base_url') or '').rstrip('/')
|
||||
):
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CHANGED',
|
||||
message='订单抽取 Provider 的 Dify 应用或地址已变化,请创建新的 Run',
|
||||
http_status=409,
|
||||
)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
run.current_job_id = job.id
|
||||
run.attempt_count = owned_attempt
|
||||
db.session.commit()
|
||||
|
||||
timeout_seconds = int((run.provider_config_json or {}).get('timeout_seconds') or 900)
|
||||
saved_provider_result = run.provider_result_json if isinstance(run.provider_result_json, dict) else {}
|
||||
saved_orders = saved_provider_result.get('orders')
|
||||
if isinstance(saved_orders, list) and all(isinstance(item, dict) for item in saved_orders):
|
||||
orders = saved_orders
|
||||
workflow_meta = saved_provider_result.get('workflow')
|
||||
workflow_meta = workflow_meta if isinstance(workflow_meta, dict) else {}
|
||||
else:
|
||||
orders, workflow_meta = execute_order_extraction_workflow(
|
||||
run=run,
|
||||
provider=provider,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
run.provider_result_json = {'orders': orders, 'workflow': workflow_meta}
|
||||
from datetime import datetime
|
||||
|
||||
run.provider_completed_at = datetime.utcnow()
|
||||
if workflow_meta.get('workflow_run_id'):
|
||||
run.dify_workflow_run_id = str(workflow_meta['workflow_run_id'])[:128]
|
||||
# [STEP 1] Provider 成功即建立独立提交边界,HXOPS 后续落库重试不得再次调用 Dify。
|
||||
db.session.commit()
|
||||
ctx.logger.info(
|
||||
'shipping_order_extraction_provider_completed run_no=%s job_id=%s attempt=%s elapsed_ms=%s',
|
||||
run.run_no,
|
||||
job.id,
|
||||
owned_attempt,
|
||||
int((time.perf_counter() - handler_started) * 1000),
|
||||
)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
|
||||
summary = {
|
||||
'run_no': run.run_no,
|
||||
'batch_no': result.get('batch_no'),
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
'opened_existing_count': int(result.get('opened_existing_count') or 0),
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
'non_shipping_count': int(result.get('non_shipping_count') or 0),
|
||||
'workflow': workflow_meta,
|
||||
}
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='result_persisted',
|
||||
phase='result_persisted',
|
||||
result=summary,
|
||||
)
|
||||
db.session.commit()
|
||||
final_status = 'needs_review' if summary['pending_count'] else 'completed'
|
||||
transition_order_extraction_run(run, target_status=final_status, result=summary)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
ctx.logger.info(
|
||||
'shipping_order_extraction_completed run_no=%s job_id=%s attempt=%s status=%s elapsed_ms=%s',
|
||||
run.run_no,
|
||||
job.id,
|
||||
owned_attempt,
|
||||
final_status,
|
||||
int((time.perf_counter() - handler_started) * 1000),
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
ctx.logger.warning(
|
||||
'shipping_order_extraction_attempt_failed run_no=%s job_id=%s attempt=%s retryable=%s error_code=%s',
|
||||
str(job.business_ref or ''),
|
||||
job.id,
|
||||
owned_attempt,
|
||||
retryable,
|
||||
str(getattr(exc, 'code', None) or 'UNCLASSIFIED'),
|
||||
)
|
||||
if run is not None and run.status in {'queued', 'running', 'failed'}:
|
||||
if retryable and owned_attempt < int(job.max_attempts or 1):
|
||||
if run.status == 'running':
|
||||
transition_order_extraction_run(run, target_status='queued', phase='retry_queued')
|
||||
elif run.status in {'queued', 'running'}:
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='failing')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'),
|
||||
error_message=str(exc),
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc),
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if retryable:
|
||||
raise
|
||||
Reference in new issue
Block a user