252 lines
9.7 KiB
Python
252 lines
9.7 KiB
Python
"""
|
|
backend/app/services/shipping_notice/intake_service.py
|
|
|
|
用途:发货通知接入记录(ShippingNoticeIntake)业务编排。
|
|
依赖:file_assets.service、intake_parse_workflow、jobs.queue、models。
|
|
逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
from datetime import datetime, timedelta
|
|
from typing import Any
|
|
|
|
from flask import current_app
|
|
|
|
from app import db
|
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
|
from app.core.response import utc_iso
|
|
from app.jobs.queue import enqueue
|
|
from app.jobs.types import JobType
|
|
from app.models import FileAsset, ShippingNoticeIntake
|
|
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
|
|
|
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
|
|
|
|
|
def _parser_version() -> str:
|
|
return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip()
|
|
|
|
|
|
def _intake_ttl_hours() -> int:
|
|
return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1)
|
|
|
|
|
|
def generate_intake_no() -> str:
|
|
"""生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。"""
|
|
return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
|
|
|
|
|
def serialize_intake(intake: ShippingNoticeIntake, *, asset: FileAsset | None = None) -> dict[str, Any]:
|
|
"""对外序列化接入记录。"""
|
|
payload: dict[str, Any] = {
|
|
'intake_no': intake.intake_no,
|
|
'asset_no': asset.asset_no if asset else None,
|
|
'conversation_id': intake.conversation_id,
|
|
'parse_status': intake.parse_status,
|
|
'parser_version': intake.parser_version,
|
|
'parse_summary': intake.structured_result_json,
|
|
'warnings': list(intake.parse_warnings_json or []),
|
|
'error_code': intake.error_code,
|
|
'error_message': intake.error_message,
|
|
'expires_at': utc_iso(intake.expires_at),
|
|
'consumed_at': utc_iso(intake.consumed_at),
|
|
'created_at': utc_iso(intake.created_at),
|
|
'updated_at': utc_iso(intake.updated_at),
|
|
}
|
|
if asset:
|
|
payload['original_filename'] = asset.original_filename
|
|
payload['file_size'] = asset.file_size
|
|
payload['content_hash'] = asset.content_hash
|
|
return payload
|
|
|
|
|
|
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
|
"""按编号查询当前用户的接入记录。"""
|
|
normalized = str(intake_no or '').strip().upper()
|
|
intake = (
|
|
db.session.query(ShippingNoticeIntake)
|
|
.filter(ShippingNoticeIntake.intake_no == normalized)
|
|
.first()
|
|
)
|
|
if not intake or int(intake.user_id) != int(user_id):
|
|
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在')
|
|
return intake
|
|
|
|
|
|
def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
|
"""查询单个接入记录详情(含资产摘要)。"""
|
|
intake = get_intake_for_user(intake_no, user_id)
|
|
asset = db.session.get(FileAsset, intake.asset_id)
|
|
if not asset:
|
|
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
|
return serialize_intake(intake, asset=asset)
|
|
|
|
|
|
def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset:
|
|
asset = db.session.get(FileAsset, intake.asset_id)
|
|
if not asset or asset.deleted_at is not None:
|
|
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
|
return asset
|
|
|
|
|
|
def create_shipping_notice_intake(
|
|
*,
|
|
user_id: int,
|
|
asset_no: str,
|
|
conversation_id: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""
|
|
基于已上传 FileAsset 创建接入记录并投递解析 Job。
|
|
核心逻辑:校验资产 ready → 复用同 parser 版本 intake → 入队 shipping_notice_parse。
|
|
"""
|
|
asset = get_asset_for_user(asset_no, user_id)
|
|
if str(asset.upload_status or '') != 'ready':
|
|
raise ValidationError(code='FILE_ASSET.INVALID_STATUS', message='文件尚未上传完成')
|
|
if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
|
|
raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
|
|
|
|
parser_version = _parser_version()
|
|
intake = (
|
|
db.session.query(ShippingNoticeIntake)
|
|
.filter(
|
|
ShippingNoticeIntake.asset_id == asset.id,
|
|
ShippingNoticeIntake.purpose == 'shipping_notice',
|
|
ShippingNoticeIntake.parser_version == parser_version,
|
|
)
|
|
.first()
|
|
)
|
|
if intake and intake.parse_status in {'parsed', 'consumed'}:
|
|
return serialize_intake(intake, asset=asset)
|
|
|
|
if not intake:
|
|
intake = ShippingNoticeIntake(
|
|
intake_no=generate_intake_no(),
|
|
asset_id=asset.id,
|
|
user_id=int(user_id),
|
|
conversation_id=str(conversation_id or '').strip() or None,
|
|
purpose='shipping_notice',
|
|
parse_status='created',
|
|
parser_version=parser_version,
|
|
expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()),
|
|
)
|
|
db.session.add(intake)
|
|
db.session.flush()
|
|
|
|
if intake.parse_status in {'queued', 'parsing'}:
|
|
return serialize_intake(intake, asset=asset)
|
|
|
|
intake.parse_status = 'queued'
|
|
intake.conversation_id = str(conversation_id or intake.conversation_id or '').strip() or None
|
|
intake.error_code = None
|
|
intake.error_message = None
|
|
intake.updated_at = datetime.utcnow()
|
|
|
|
job_id = enqueue(
|
|
JobType.SHIPPING_NOTICE_PARSE,
|
|
{'intake_no': intake.intake_no},
|
|
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
|
business_ref=intake.intake_no,
|
|
created_by_id=user_id,
|
|
message='等待预解析发货通知',
|
|
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
|
|
)
|
|
intake.parse_job_id = job_id
|
|
db.session.commit()
|
|
return serialize_intake(intake, asset=asset)
|
|
|
|
|
|
def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
|
|
"""列出会话下未消费的活跃接入记录,供页面恢复。"""
|
|
query = db.session.query(ShippingNoticeIntake, FileAsset).join(
|
|
FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
|
|
).filter(
|
|
ShippingNoticeIntake.user_id == int(user_id),
|
|
ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
|
ShippingNoticeIntake.consumed_at.is_(None),
|
|
)
|
|
conv = str(conversation_id or '').strip()
|
|
if conv:
|
|
query = query.filter(ShippingNoticeIntake.conversation_id == conv)
|
|
rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all()
|
|
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
|
|
|
|
|
def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]:
|
|
"""批量查询接入状态。"""
|
|
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
|
|
if not normalized:
|
|
return []
|
|
rows = (
|
|
db.session.query(ShippingNoticeIntake, FileAsset)
|
|
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
|
.filter(
|
|
ShippingNoticeIntake.user_id == int(user_id),
|
|
ShippingNoticeIntake.intake_no.in_(normalized),
|
|
)
|
|
.all()
|
|
)
|
|
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
|
|
|
|
|
def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
|
"""重试 parse_failed 的接入记录。"""
|
|
intake = get_intake_for_user(intake_no, user_id)
|
|
if intake.parse_status not in {'parse_failed'}:
|
|
raise ConflictError(
|
|
code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
|
|
message='当前状态不允许重试解析',
|
|
)
|
|
asset = _load_asset_for_intake(intake)
|
|
intake.parse_status = 'queued'
|
|
intake.error_code = None
|
|
intake.error_message = None
|
|
job_id = enqueue(
|
|
JobType.SHIPPING_NOTICE_PARSE,
|
|
{'intake_no': intake.intake_no},
|
|
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
|
business_ref=intake.intake_no,
|
|
created_by_id=user_id,
|
|
message='等待重试预解析发货通知',
|
|
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
|
|
dedupe_active=False,
|
|
)
|
|
intake.parse_job_id = job_id
|
|
db.session.commit()
|
|
return serialize_intake(intake, asset=asset)
|
|
|
|
|
|
def cancel_intake(*, user_id: int, intake_no: str) -> None:
|
|
"""取消未消费的接入记录。"""
|
|
intake = get_intake_for_user(intake_no, user_id)
|
|
if intake.consumed_at is not None or intake.parse_status == 'consumed':
|
|
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费')
|
|
intake.parse_status = 'cancelled'
|
|
intake.updated_at = datetime.utcnow()
|
|
db.session.commit()
|
|
|
|
|
|
def mark_intakes_consumed(
|
|
*,
|
|
intakes: list[ShippingNoticeIntake],
|
|
batch_id: int | None,
|
|
task_ids_by_intake: dict[int, int] | None = None,
|
|
) -> None:
|
|
"""
|
|
标记 intake 为 consumed 并增加资产引用计数。
|
|
|
|
核心逻辑:可在建批 commit 前预占(batch_id=None),避免 FOR UPDATE 在 create_batch_tasks 提交后释放导致并发双消费。
|
|
"""
|
|
now = datetime.utcnow()
|
|
task_map = task_ids_by_intake or {}
|
|
for intake in intakes:
|
|
intake.parse_status = 'consumed'
|
|
intake.consumed_at = now
|
|
intake.consumed_batch_id = int(batch_id) if batch_id else None
|
|
intake.consumed_task_id = task_map.get(intake.id)
|
|
intake.updated_at = now
|
|
asset = db.session.get(FileAsset, intake.asset_id)
|
|
if asset:
|
|
mark_asset_referenced(asset)
|