feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载
This commit is contained in:
1 parent
143e054d86
commit
729546a7b7
52 files changed
+3420
-34
No files matched your search
+12
-1
@@ -3,7 +3,8 @@ backend/app/__init__.py
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
|
||||
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
@@ -64,6 +65,16 @@ def create_app(config_name='default'):
|
||||
ensure_intent_routes_loaded()
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
|
||||
try:
|
||||
from app.services.file_assets.cleanup_schedule import (
|
||||
ensure_default_file_asset_cleanup_schedule,
|
||||
register_file_asset_cleanup_schedule_hooks,
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.files import files_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
@@ -60,3 +61,4 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
backend/app/api/files/__init__.py
|
||||
|
||||
用途:平台级文件资产 API 包入口。
|
||||
依赖:files.assets。
|
||||
逻辑:register_blueprints 挂载 /api/files。
|
||||
"""
|
||||
|
||||
from app.api.files.assets import files_bp
|
||||
|
||||
__all__ = ['files_bp']
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/api/files/assets.py
|
||||
|
||||
用途:通用文件资产上传、查询、删除与受控下载 API。
|
||||
依赖:file_assets.service、app.core.auth.jwt、app.core.response。
|
||||
逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.services.file_assets.service import (
|
||||
delete_temporary_asset,
|
||||
get_asset_for_user,
|
||||
read_asset_bytes,
|
||||
serialize_asset_public,
|
||||
upload_file_asset,
|
||||
)
|
||||
|
||||
files_bp = Blueprint('files', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@files_bp.route('/assets', methods=['POST'])
|
||||
def upload_asset():
|
||||
"""上传文件并创建 FileAsset。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
if not upload.filename:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
data = upload_file_asset(user_id=user.id, upload=upload)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=201)
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['GET'])
|
||||
def get_asset(asset_no: str):
|
||||
"""查询当前用户的文件资产元数据。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['DELETE'])
|
||||
def delete_asset(asset_no: str):
|
||||
"""逻辑删除未引用的临时资产。"""
|
||||
user = _require_user()
|
||||
delete_temporary_asset(asset_no=asset_no, user_id=user.id)
|
||||
return ok({'deleted': True}, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>/download', methods=['GET'])
|
||||
def download_asset(asset_no: str):
|
||||
"""鉴权后流式下载文件内容。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
data = read_asset_bytes(asset)
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=asset.mime_type or 'application/octet-stream',
|
||||
as_attachment=True,
|
||||
download_name=asset.original_filename,
|
||||
)
|
||||
@@ -589,6 +589,110 @@ def workspace_shipping_task_export(task_no: str):
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_notice_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
|
||||
|
||||
if status and status != 'active':
|
||||
return _ok({'items': []})
|
||||
items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
asset_no = str(body.get('asset_no') or '').strip()
|
||||
if not asset_no:
|
||||
raise ValidationError('asset_no is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
data = create_shipping_notice_intake(
|
||||
user_id=user.id,
|
||||
asset_no=asset_no,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_intake(intake_no: str):
|
||||
"""查询单个接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import get_intake_detail
|
||||
|
||||
return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
|
||||
def workspace_shipping_notice_intake_statuses():
|
||||
"""批量查询接入状态。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError('intake_nos is required')
|
||||
from app.services.shipping_notice.intake_service import get_intake_statuses
|
||||
|
||||
return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_notice_intake(intake_no: str):
|
||||
"""重试失败的预解析。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import retry_intake_parse
|
||||
|
||||
return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['DELETE'])
|
||||
def workspace_cancel_shipping_notice_intake(intake_no: str):
|
||||
"""取消未消费接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import cancel_intake
|
||||
|
||||
cancel_intake(user_id=user.id, intake_no=intake_no)
|
||||
return _ok({'cancelled': True})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""从已解析接入记录确认建批。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError('intake_nos is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
|
||||
@@ -367,6 +367,16 @@ class Config:
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets')
|
||||
FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30'))
|
||||
FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72'))
|
||||
FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300'))
|
||||
SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72'))
|
||||
SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3'))
|
||||
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v1')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
|
||||
@@ -22,9 +22,15 @@ class AppError(Exception):
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Invalid request parameters",
|
||||
*,
|
||||
code: str = "VALIDATION.INVALID_PARAM",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
@@ -38,13 +44,23 @@ class UnauthorizedError(AppError):
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Forbidden",
|
||||
*,
|
||||
code: str = "AUTH.FORBIDDEN",
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource not found",
|
||||
*,
|
||||
code: str = "RESOURCE.NOT_FOUND",
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
|
||||
@@ -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_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, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_notice_parse.py
|
||||
|
||||
用途:发货通知接入记录异步预解析 handler。
|
||||
依赖:jobs.context、jobs.registry、intake_parse_workflow。
|
||||
逻辑:worker 消费 shipping_notice_parse 队列任务,更新 intake 状态 parsed/parse_failed。
|
||||
领取与写回前均跳过 cancelled/expired/consumed,避免用户取消后被重新解析。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import 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, ShippingNoticeIntake
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
|
||||
# 终态:不可再领取解析;含用户取消与 TTL 过期
|
||||
_SKIP_CLAIM_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
|
||||
# 允许领取进入 parsing 的状态(含失败后重试)
|
||||
_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parsing', 'parse_failed'})
|
||||
|
||||
|
||||
def _load_asset(asset_id: int) -> FileAsset:
|
||||
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
|
||||
|
||||
|
||||
@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
|
||||
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:
|
||||
fail_job(job, error='missing intake_no')
|
||||
raise RuntimeError('missing intake_no')
|
||||
|
||||
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
if not intake:
|
||||
if job:
|
||||
fail_job(job, error=f'intake not found: {intake_no}')
|
||||
raise RuntimeError(f'intake not found: {intake_no}')
|
||||
|
||||
# [STEP 1] 领取前跳过终态(含 cancelled/expired)
|
||||
if intake.parse_status in _SKIP_CLAIM_STATUSES:
|
||||
if job:
|
||||
finish_job(job, result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True})
|
||||
return
|
||||
if intake.parse_status not in _CLAIMABLE_STATUSES:
|
||||
if job:
|
||||
finish_job(job, result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True})
|
||||
return
|
||||
|
||||
intake.parse_status = 'parsing'
|
||||
intake.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
asset = _load_asset(intake.asset_id)
|
||||
try:
|
||||
result = run_intake_parse(intake, asset)
|
||||
if job:
|
||||
refreshed = db.session.get(Job, job.id)
|
||||
if refreshed and refreshed.status == 'running':
|
||||
status = str(result.get('status') or '')
|
||||
if status in {'parsed', 'skipped'}:
|
||||
finish_job(refreshed, result=result, message='发货通知预解析完成' if status == 'parsed' else '接入已取消或过期,跳过')
|
||||
else:
|
||||
fail_job(
|
||||
refreshed,
|
||||
error=str(result.get('error_message') or intake.error_message or 'parse failed'),
|
||||
retryable=False,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
# 取消/过期后不再覆盖为 parse_failed
|
||||
if intake and intake.parse_status not in _SKIP_CLAIM_STATUSES:
|
||||
intake.parse_status = 'parse_failed'
|
||||
intake.error_code = 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
intake.error_message = str(exc)[:1000]
|
||||
db.session.commit()
|
||||
if job:
|
||||
refreshed = db.session.get(Job, job.id)
|
||||
if refreshed:
|
||||
fail_job(refreshed, error=str(exc), retryable=True)
|
||||
raise
|
||||
+32
-12
@@ -10,7 +10,21 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
|
||||
from app.models import KbJob
|
||||
from app.models import Job, KbJob
|
||||
|
||||
|
||||
def _normalize_generic_job(job: Job) -> dict[str, Any]:
|
||||
"""将通用 Job ORM 实例转为 runner/handler 使用的归一化任务 dict。"""
|
||||
job_type_value = str(job.job_type or '').strip()
|
||||
return {
|
||||
'id': job.id,
|
||||
'job_type': JobType(job_type_value),
|
||||
'raw_job_type': job_type_value,
|
||||
'payload': {
|
||||
'job_id': job.id,
|
||||
**(job.payload_json or {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||||
@@ -59,7 +73,7 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||||
|
||||
recover_stale_running_jobs()
|
||||
if 'shipping_notice_run' in allowed_types:
|
||||
if 'shipping_notice_run' in allowed_types or 'shipping_notice_parse' in allowed_types:
|
||||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||||
|
||||
recover_stale_shipping_notice_jobs()
|
||||
@@ -77,30 +91,36 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
|
||||
job = claim_next_shipping_notice_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
return _normalize_generic_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def mark_failed(job_id: int, *, message: str) -> None:
|
||||
"""
|
||||
handler 未捕获异常时,将 KbJob 标记为 failed。
|
||||
handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。
|
||||
Args:
|
||||
job_id: KbJob 主键。
|
||||
job_id: 任务主键。
|
||||
message: 失败原因(截断至 1000 字符)。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import fail_job
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job or job.status != 'running':
|
||||
job = db.session.get(Job, job_id)
|
||||
if job and job.status == 'running':
|
||||
fail_job(job, error=message[:1000], retryable=True)
|
||||
return
|
||||
|
||||
kb_job = db.session.get(KbJob, job_id)
|
||||
if not kb_job or kb_job.status != 'running':
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
job.status = 'failed'
|
||||
job.error_message = message[:1000]
|
||||
job.message = message[:500]
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
kb_job.status = 'failed'
|
||||
kb_job.error_message = message[:1000]
|
||||
kb_job.message = message[:500]
|
||||
kb_job.finished_at = now
|
||||
kb_job.progress = 100
|
||||
db.session.commit()
|
||||
@@ -15,6 +15,7 @@ class JobType(StrEnum):
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
@@ -48,7 +49,7 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run'}),
|
||||
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -16,10 +16,12 @@ from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGro
|
||||
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
|
||||
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.file_asset import FileAsset
|
||||
from app.models.shipping import (
|
||||
ShippingBatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryMapping,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
@@ -66,6 +68,8 @@ __all__ = [
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'ShippingNoticeIntake',
|
||||
'FileAsset',
|
||||
'AgentGuide',
|
||||
'AgentDirectoryMember',
|
||||
'TrainingRecord',
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""
|
||||
backend/app/models/file_asset.py
|
||||
|
||||
用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。
|
||||
依赖:models.base.Base。
|
||||
逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 等业务通过 asset_id 引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class FileAsset(Base):
|
||||
"""通用文件资产(私有对象存储 + 审计元数据)。"""
|
||||
|
||||
__tablename__ = 'file_assets'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('asset_no', name='uq_file_assets_asset_no'),
|
||||
Index('ix_file_assets_owner_content_hash', 'owner_user_id', 'content_hash'),
|
||||
Index('ix_file_assets_lifecycle_expires', 'lifecycle_status', 'expires_at'),
|
||||
Index('ix_file_assets_owner_created', 'owner_user_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
asset_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
|
||||
tenant_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
storage_provider: Mapped[str] = mapped_column(String(32), default='minio', nullable=False)
|
||||
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
mime_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
extension: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_status: Mapped[str] = mapped_column(String(32), default='uploading', nullable=False)
|
||||
lifecycle_status: Mapped[str] = mapped_column(String(32), default='temporary', nullable=False)
|
||||
reference_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
@@ -83,6 +83,12 @@ class ShippingTask(Base):
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
|
||||
source_intake_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
@@ -280,6 +286,45 @@ class ShippingTaskInventoryLink(Base):
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeIntake(Base):
|
||||
"""发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_intakes'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
|
||||
UniqueConstraint(
|
||||
'asset_id',
|
||||
'purpose',
|
||||
'parser_version',
|
||||
name='uq_shipping_notice_intakes_asset_purpose_parser',
|
||||
),
|
||||
Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_expires', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
intake_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
|
||||
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
parser_version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
parse_job_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/chat/turn_runtime.py
|
||||
|
||||
用途:平台统一 Chat Turn 执行器,编排 SSE 生命周期、session、ChatLog 与 action 路由。
|
||||
依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema。
|
||||
依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema、db。
|
||||
逻辑:api/chat/turns/stream 调用 ChatTurnRuntime.stream();业务 handler 只 yield TurnEvent。
|
||||
失败路径先 db.session.rollback(),再 touch_chat_session,避免 handler 脏写被一并提交。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +15,7 @@ from typing import Any, Iterator
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.chat.action_registry import ensure_handlers_loaded, resolve_action_handler
|
||||
from app.services.chat.action_schema import TurnEvent, TurnInput, parse_turn_refs_from_context
|
||||
@@ -183,6 +185,8 @@ class ChatTurnRuntime:
|
||||
getattr(exc, "code", None),
|
||||
exc.message,
|
||||
)
|
||||
# 业务失败后先 rollback,避免 handler 预占/脏写被 touch_chat_session 一并提交
|
||||
db.session.rollback()
|
||||
touch_chat_session(user_id, agent_id, session.session_id, status="error")
|
||||
yield emit_run_failed(
|
||||
run_id=run_id,
|
||||
@@ -193,6 +197,7 @@ class ChatTurnRuntime:
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
||||
db.session.rollback()
|
||||
touch_chat_session(user_id, agent_id, session.session_id, status="error")
|
||||
yield emit_run_failed(
|
||||
run_id=run_id,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
backend/app/services/file_assets/__init__.py
|
||||
|
||||
用途:平台级文件资产服务包入口。
|
||||
依赖:file_assets.service、file_assets.storage、file_assets.cleanup。
|
||||
逻辑:API 与 shipping intake 经 service 层读写 FileAsset 与私有 MinIO 对象。
|
||||
"""
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
backend/app/services/file_assets/cleanup.py
|
||||
|
||||
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
|
||||
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
|
||||
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
|
||||
MinIO 删除失败不伪装成功,保留记录供下次重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingNoticeIntake
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
|
||||
"""
|
||||
清理过期或已标记 expired 但尚未物理删除的临时资产。
|
||||
Returns:
|
||||
统计字典:scanned/expired/deleted/errors。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
assets = (
|
||||
db.session.query(FileAsset)
|
||||
.filter(
|
||||
FileAsset.reference_count == 0,
|
||||
FileAsset.deleted_at.is_(None),
|
||||
or_(
|
||||
(
|
||||
(FileAsset.lifecycle_status == 'temporary')
|
||||
& (FileAsset.expires_at.isnot(None))
|
||||
& (FileAsset.expires_at < now)
|
||||
),
|
||||
FileAsset.lifecycle_status == 'expired',
|
||||
),
|
||||
)
|
||||
.order_by(FileAsset.expires_at.asc().nullsfirst(), FileAsset.id.asc())
|
||||
.limit(max(int(limit or 100), 1))
|
||||
.all()
|
||||
)
|
||||
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
|
||||
for asset in assets:
|
||||
consumed = (
|
||||
db.session.query(ShippingNoticeIntake.id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.parse_status == 'consumed',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if consumed:
|
||||
continue
|
||||
stats['expired'] += 1
|
||||
asset.lifecycle_status = 'expired'
|
||||
(
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
|
||||
)
|
||||
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
try:
|
||||
file_asset_storage.delete_object(asset.storage_key)
|
||||
asset.upload_status = 'deleted'
|
||||
asset.deleted_at = now
|
||||
asset.updated_at = now
|
||||
stats['deleted'] += 1
|
||||
except Exception:
|
||||
stats['errors'] += 1
|
||||
asset.updated_at = now
|
||||
_LOGGER.exception('failed to delete minio object for asset %s', asset.asset_no)
|
||||
db.session.commit()
|
||||
return stats
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
backend/app/services/file_assets/cleanup_schedule.py
|
||||
|
||||
用途:确保 platform Job file-asset-cleanup 存在默认 ScheduleTask(迁移补种 + 启动/建用户补建)。
|
||||
依赖:models.ScheduleTask/User、schedule.timezone_util.compute_next_run_at、SQLAlchemy Session 事件。
|
||||
逻辑:create_app 启动时 ensure 一次;User after_commit 用独立 Session 即时补建(原 session 已 committed 不可再发 SQL)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP"
|
||||
DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH = "file-asset-cleanup"
|
||||
DEFAULT_FILE_ASSET_CLEANUP_CRON = "0 * * * *"
|
||||
DEFAULT_FILE_ASSET_CLEANUP_NAME = "临时文件资产 TTL 清理"
|
||||
|
||||
_HOOKS_REGISTERED = False
|
||||
_SESSION_INFO_KEY = "_seed_file_asset_cleanup"
|
||||
|
||||
|
||||
def ensure_default_file_asset_cleanup_schedule(
|
||||
*,
|
||||
commit: bool = True,
|
||||
session: Any | None = None,
|
||||
) -> ScheduleTask | None:
|
||||
"""
|
||||
幂等确保默认 TTL 清理排程存在。
|
||||
|
||||
核心逻辑:若已有同 schedule_no 或同 platform_api_path 的排程则跳过;
|
||||
否则在存在至少一个用户时创建启用态排程(next_run_at 走 Cron 语义)。
|
||||
|
||||
Args:
|
||||
commit: 是否立即提交。
|
||||
session: 可选独立 Session(User after_commit 钩子须传入,避免 committed 态 Session 发 SQL)。
|
||||
|
||||
Returns:
|
||||
新建或已存在的 ScheduleTask;尚无用户时返回 None。
|
||||
"""
|
||||
sess = session if session is not None else db.session
|
||||
existing = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed file-asset-cleanup schedule: no users yet")
|
||||
return None
|
||||
|
||||
now = datetime.utcnow()
|
||||
next_run = compute_next_run_at(
|
||||
DEFAULT_FILE_ASSET_CLEANUP_CRON,
|
||||
timezone_name="Asia/Shanghai",
|
||||
) or now
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
|
||||
name=DEFAULT_FILE_ASSET_CLEANUP_NAME,
|
||||
schedule_type="platform_job",
|
||||
owner_user_id=int(owner.id),
|
||||
cron_expr=DEFAULT_FILE_ASSET_CLEANUP_CRON,
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
wait_seconds=0,
|
||||
platform_api_path=DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH,
|
||||
job_params=None,
|
||||
kb_sync_enabled=False,
|
||||
notify_user_ids_json=[],
|
||||
notify_enabled=False,
|
||||
enabled=True,
|
||||
next_run_at=next_run,
|
||||
created_by=int(owner.id),
|
||||
updated_by=int(owner.id),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
sess.add(task)
|
||||
if commit:
|
||||
try:
|
||||
sess.commit()
|
||||
except Exception:
|
||||
sess.rollback()
|
||||
existing = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
raise
|
||||
else:
|
||||
sess.flush()
|
||||
_LOGGER.info(
|
||||
"seeded default file-asset-cleanup schedule_no=%s owner_user_id=%s",
|
||||
task.schedule_no,
|
||||
owner.id,
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
def register_file_asset_cleanup_schedule_hooks() -> None:
|
||||
"""
|
||||
注册 Session 钩子:User 插入并 commit 后立即尝试补建默认清理排程。
|
||||
|
||||
核心逻辑:after_flush 标记;after_commit 用独立 Session 调用 ensure
|
||||
(原 session 处于 committed 态不能再发 SQL)。
|
||||
"""
|
||||
global _HOOKS_REGISTERED
|
||||
if _HOOKS_REGISTERED:
|
||||
return
|
||||
|
||||
@event.listens_for(Session, "after_flush")
|
||||
def _mark_user_insert(session: Session, _context) -> None: # type: ignore[no-untyped-def]
|
||||
if any(isinstance(obj, User) for obj in session.new):
|
||||
session.info[_SESSION_INFO_KEY] = True
|
||||
|
||||
@event.listens_for(Session, "after_commit")
|
||||
def _seed_after_user_commit(session: Session) -> None:
|
||||
if not session.info.pop(_SESSION_INFO_KEY, False):
|
||||
return
|
||||
bind = session.get_bind()
|
||||
if bind is None:
|
||||
return
|
||||
try:
|
||||
with Session(bind) as seed_session:
|
||||
ensure_default_file_asset_cleanup_schedule(commit=True, session=seed_session)
|
||||
except Exception as exc: # pragma: no cover - 防御不阻断建用户
|
||||
_LOGGER.warning("ensure file-asset-cleanup after user create failed: %s", exc)
|
||||
|
||||
_HOOKS_REGISTERED = True
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
backend/app/services/file_assets/service.py
|
||||
|
||||
用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。
|
||||
依赖:file_assets.storage、models.FileAsset、Flask current_app。
|
||||
逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_ALLOWED_EXTENSIONS = {
|
||||
'pdf', 'doc', 'docx', 'txt', 'md', 'log', 'html', 'htm', 'eml',
|
||||
'csv', 'png', 'jpg', 'jpeg', 'webp',
|
||||
}
|
||||
|
||||
|
||||
def _max_file_size_bytes() -> int:
|
||||
mb = int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30)
|
||||
return max(mb, 1) * 1024 * 1024
|
||||
|
||||
|
||||
def _temp_ttl_hours() -> int:
|
||||
return max(int(current_app.config.get('FILE_ASSET_TEMP_TTL_HOURS', 72) or 72), 1)
|
||||
|
||||
|
||||
def generate_asset_no() -> str:
|
||||
"""生成 FA-YYYYMMDD-XXXXXXXX 格式资产编号。"""
|
||||
return f"FA-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _normalize_extension(filename: str) -> str:
|
||||
ext = os.path.splitext(str(filename or '').strip())[1].lower().lstrip('.')
|
||||
return ext
|
||||
|
||||
|
||||
def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str:
|
||||
now = datetime.utcnow()
|
||||
safe_name = secure_filename(filename) or 'file'
|
||||
safe_name = re.sub(r'[^\w\-.]+', '_', safe_name)[:120] or 'file'
|
||||
return f"temporary/{user_id}/{now:%Y}/{now:%m}/{asset_no}/{safe_name}"
|
||||
|
||||
|
||||
def _serialize_asset(asset: FileAsset) -> dict[str, Any]:
|
||||
return {
|
||||
'asset_no': asset.asset_no,
|
||||
'original_filename': asset.original_filename,
|
||||
'file_size': asset.file_size,
|
||||
'mime_type': asset.mime_type,
|
||||
'content_hash': asset.content_hash,
|
||||
'upload_status': asset.upload_status,
|
||||
'lifecycle_status': asset.lifecycle_status,
|
||||
'expires_at': utc_iso(asset.expires_at),
|
||||
'created_at': utc_iso(asset.created_at),
|
||||
}
|
||||
|
||||
|
||||
def get_asset_for_user(asset_no: str, user_id: int) -> FileAsset:
|
||||
"""
|
||||
按编号查询当前用户拥有的资产。
|
||||
Raises:
|
||||
NotFoundError: 不存在或已逻辑删除。
|
||||
ForbiddenError: 非所有者。
|
||||
"""
|
||||
normalized = str(asset_no or '').strip().upper()
|
||||
asset = (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.asset_no == normalized, FileAsset.deleted_at.is_(None))
|
||||
.first()
|
||||
)
|
||||
if not asset:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
|
||||
if int(asset.owner_user_id) != int(user_id):
|
||||
raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问该文件资产')
|
||||
return asset
|
||||
|
||||
|
||||
def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]:
|
||||
"""
|
||||
上传文件并创建 FileAsset 记录。
|
||||
核心逻辑:校验类型与大小 → SHA-256 → 写 MinIO → 落库 ready/temporary。
|
||||
"""
|
||||
filename = str(upload.filename or '').strip() or 'file'
|
||||
ext = _normalize_extension(filename)
|
||||
if ext not in _ALLOWED_EXTENSIONS:
|
||||
raise ValidationError(
|
||||
code='FILE_ASSET.INVALID_TYPE',
|
||||
message=f'不支持的文件类型: .{ext or "unknown"}',
|
||||
)
|
||||
|
||||
data = upload.read()
|
||||
if not data:
|
||||
raise ValidationError(code='FILE_ASSET.UPLOAD_FAILED', message='文件内容为空')
|
||||
if len(data) > _max_file_size_bytes():
|
||||
raise ValidationError(code='FILE_ASSET.SIZE_EXCEEDED', message='文件大小超过限制')
|
||||
|
||||
content_hash = hashlib.sha256(data).hexdigest()
|
||||
asset_no = generate_asset_no()
|
||||
storage_key = _build_storage_key(user_id=user_id, asset_no=asset_no, filename=filename)
|
||||
mime_type = upload.mimetype or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours())
|
||||
|
||||
asset = FileAsset(
|
||||
asset_no=asset_no,
|
||||
owner_user_id=int(user_id),
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket=file_asset_storage.bucket_name,
|
||||
storage_key=storage_key,
|
||||
content_hash=content_hash,
|
||||
file_size=len(data),
|
||||
mime_type=mime_type,
|
||||
extension=ext or None,
|
||||
upload_status='uploading',
|
||||
lifecycle_status='temporary',
|
||||
reference_count=0,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type=mime_type)
|
||||
asset.upload_status = 'ready'
|
||||
except Exception:
|
||||
asset.upload_status = 'failed'
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
db.session.commit()
|
||||
return _serialize_asset(asset)
|
||||
|
||||
|
||||
def mark_asset_referenced(asset: FileAsset) -> None:
|
||||
"""将资产标记为被业务引用。"""
|
||||
asset.lifecycle_status = 'referenced'
|
||||
asset.reference_count = int(asset.reference_count or 0) + 1
|
||||
asset.expires_at = None
|
||||
asset.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def delete_temporary_asset(*, asset_no: str, user_id: int) -> None:
|
||||
"""
|
||||
删除未引用的临时资产:先标记 expired,再删 MinIO;成功后标记 deleted。
|
||||
Raises:
|
||||
ConflictError: 已被业务引用。
|
||||
ServiceUnavailableError: MinIO 删除失败(保留 expired 供清理重试)。
|
||||
"""
|
||||
asset = get_asset_for_user(asset_no, user_id)
|
||||
if str(asset.lifecycle_status or '') == 'referenced' or int(asset.reference_count or 0) > 0:
|
||||
raise ConflictError(code='FILE_ASSET.ALREADY_REFERENCED', message='文件已被业务引用,无法删除')
|
||||
if str(asset.upload_status or '') == 'deleted' and asset.deleted_at is not None:
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
asset.lifecycle_status = 'expired'
|
||||
asset.updated_at = now
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
file_asset_storage.delete_object(asset.storage_key)
|
||||
except Exception:
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
asset.upload_status = 'deleted'
|
||||
asset.deleted_at = now
|
||||
asset.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def read_asset_bytes(asset: FileAsset) -> bytes:
|
||||
"""读取资产对象字节,校验未过期/未删除。"""
|
||||
if asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
|
||||
raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
|
||||
return file_asset_storage.get_bytes(asset.storage_key)
|
||||
|
||||
|
||||
def serialize_asset_public(asset: FileAsset) -> dict[str, Any]:
|
||||
"""对外序列化资产(不含 storage_key)。"""
|
||||
return _serialize_asset(asset)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/services/file_assets/storage.py
|
||||
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import BinaryIO
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
from app.core.config.settings import ACTIVE_ENV_NAME, config
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
class FileAssetStorage:
|
||||
"""私有业务文件 MinIO 存储客户端。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.client = Minio(
|
||||
_cfg.MINIO_ENDPOINT,
|
||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
||||
secure=_cfg.MINIO_SECURE,
|
||||
)
|
||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||
|
||||
def _ensure_bucket_exists(self) -> None:
|
||||
"""确保私有 bucket 存在,不设置 public-read policy。"""
|
||||
try:
|
||||
if not self.client.bucket_exists(self.bucket_name):
|
||||
self.client.make_bucket(self.bucket_name)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO file assets bucket unavailable')
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件存储服务暂不可用,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def upload_bytes(
|
||||
self,
|
||||
*,
|
||||
storage_key: str,
|
||||
data: bytes,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
"""
|
||||
上传字节流到私有 bucket。
|
||||
Raises:
|
||||
ServiceUnavailableError: MinIO 不可用或上传失败。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
stream: BinaryIO = io.BytesIO(data)
|
||||
try:
|
||||
self.client.put_object(
|
||||
bucket_name=self.bucket_name,
|
||||
object_name=storage_key,
|
||||
data=stream,
|
||||
length=len(data),
|
||||
content_type=content_type or 'application/octet-stream',
|
||||
)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO upload failed key=%s', storage_key)
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件上传失败,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def get_bytes(self, storage_key: str) -> bytes:
|
||||
"""
|
||||
读取对象字节内容。
|
||||
Raises:
|
||||
ServiceUnavailableError: 读取失败(含网络异常与 S3Error)。
|
||||
"""
|
||||
try:
|
||||
response = self.client.get_object(self.bucket_name, storage_key)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO read failed key=%s', storage_key)
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件存储服务暂不可用,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def delete_object(self, storage_key: str) -> None:
|
||||
"""
|
||||
删除 MinIO 对象;失败时抛出可重试 503,供清理任务重试。
|
||||
Raises:
|
||||
ServiceUnavailableError: 删除失败。
|
||||
"""
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, storage_key)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO delete failed key=%s', storage_key)
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件对象删除失败,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def object_exists(self, storage_key: str) -> bool:
|
||||
"""判断对象是否存在。"""
|
||||
try:
|
||||
self.client.stat_object(self.bucket_name, storage_key)
|
||||
return True
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
|
||||
"""生成短期受控下载 URL。"""
|
||||
self._ensure_bucket_exists()
|
||||
return self.client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
)
|
||||
|
||||
|
||||
file_asset_storage = FileAssetStorage()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
backend/app/services/schedule/file_asset_cleanup_job.py
|
||||
|
||||
用途:排程平台 Job —— 清理过期未引用的临时文件资产。
|
||||
依赖:file_assets.cleanup。
|
||||
逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.file_assets.cleanup import cleanup_expired_temporary_assets
|
||||
|
||||
|
||||
def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]:
|
||||
"""
|
||||
执行临时文件资产 TTL 清理。
|
||||
Args:
|
||||
task: ScheduleTask。
|
||||
run: ScheduleRun。
|
||||
Returns:
|
||||
清理统计。
|
||||
"""
|
||||
_ = task, run
|
||||
return cleanup_expired_temporary_assets(limit=200)
|
||||
@@ -129,6 +129,7 @@ def run_platform_job(
|
||||
def _register_builtin_platform_jobs() -> None:
|
||||
"""模块加载时注册内置平台 Job(含参数契约)。"""
|
||||
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||||
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
|
||||
@@ -191,6 +192,14 @@ def _register_builtin_platform_jobs() -> None:
|
||||
description="同步 PLM 固资快照至本地 manifest。",
|
||||
category="assets",
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="file-asset-cleanup",
|
||||
label="临时文件资产清理",
|
||||
label_key="admin.schedule.form.platformJobFileAssetCleanup",
|
||||
handler=run_file_asset_cleanup_schedule,
|
||||
description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。",
|
||||
category="files",
|
||||
))
|
||||
|
||||
|
||||
_register_builtin_platform_jobs()
|
||||
@@ -0,0 +1,261 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/batch_from_intakes.py
|
||||
|
||||
用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。
|
||||
依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency。
|
||||
逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。
|
||||
先幂等回放;按 content_hash 去重后 FOR UPDATE 预占 consumed;建批失败须 rollback 预占。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import FileAsset, ShippingNoticeIntake, ShippingTask
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
build_existing_batch_tool_response,
|
||||
find_batch_by_create_idempotency,
|
||||
normalize_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_notices import create_shipping_batch_from_notice_items
|
||||
from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item
|
||||
from app.services.shipping_notice.intake_service import mark_intakes_consumed
|
||||
|
||||
|
||||
def _batch_intake_nos(batch_id: int) -> set[str]:
|
||||
"""
|
||||
读取批次关联的全部 intake_no 集合。
|
||||
|
||||
核心逻辑:以 consumed_batch_id 为准(含 content_hash 去重后的附属 intake),
|
||||
避免仅按 task.source_intake_id 导致幂等集合校验误报冲突。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake.intake_no)
|
||||
.filter(ShippingNoticeIntake.consumed_batch_id == int(batch_id))
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]).strip().upper() for row in rows if row and row[0]}
|
||||
|
||||
|
||||
def _try_idempotent_replay(
|
||||
*,
|
||||
user_id: int,
|
||||
create_idempotency_key: str | None,
|
||||
intake_nos: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
按 user_id + create_idempotency_key 查找已有批次,并校验 intake 集合一致。
|
||||
Returns:
|
||||
幂等重放响应;无匹配批次时返回 None。
|
||||
"""
|
||||
key = normalize_create_idempotency_key(create_idempotency_key)
|
||||
if not key:
|
||||
return None
|
||||
existing = find_batch_by_create_idempotency(user_id, key)
|
||||
if existing is None:
|
||||
return None
|
||||
expected = set(intake_nos)
|
||||
actual = _batch_intake_nos(int(existing.id))
|
||||
if expected != actual:
|
||||
raise ConflictError(
|
||||
'建单幂等键对应批次的接入集合不一致',
|
||||
code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT',
|
||||
details={'batch_no': existing.batch_no, 'expected': sorted(expected), 'actual': sorted(actual)},
|
||||
)
|
||||
result = build_existing_batch_tool_response(existing, user_id=user_id)
|
||||
result['idempotent_replay'] = True
|
||||
return result
|
||||
|
||||
|
||||
def _partition_intakes_by_content_hash(
|
||||
ordered: list[tuple[ShippingNoticeIntake, FileAsset]],
|
||||
) -> tuple[list[tuple[ShippingNoticeIntake, FileAsset]], dict[str, list[ShippingNoticeIntake]]]:
|
||||
"""
|
||||
按 FileAsset.content_hash 去重,保留首次出现的 intake 用于建单。
|
||||
|
||||
Returns:
|
||||
(primary_pairs, duplicates_by_hash):duplicates 不含 primary。
|
||||
"""
|
||||
seen: set[str] = set()
|
||||
primary: list[tuple[ShippingNoticeIntake, FileAsset]] = []
|
||||
duplicates_by_hash: dict[str, list[ShippingNoticeIntake]] = {}
|
||||
for intake, asset in ordered:
|
||||
content_hash = str(asset.content_hash or '').strip()
|
||||
if not content_hash:
|
||||
primary.append((intake, asset))
|
||||
continue
|
||||
if content_hash in seen:
|
||||
duplicates_by_hash.setdefault(content_hash, []).append(intake)
|
||||
continue
|
||||
seen.add(content_hash)
|
||||
primary.append((intake, asset))
|
||||
return primary, duplicates_by_hash
|
||||
|
||||
|
||||
def create_shipping_batch_from_intakes(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None,
|
||||
intake_nos: list[str],
|
||||
create_idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
根据已解析且未消费的 intake 列表创建批次。
|
||||
|
||||
核心逻辑:
|
||||
1. 优先按建单幂等键回放(此时 intake 可能已 consumed);
|
||||
2. FOR UPDATE 锁定 intake,校验 parsed;
|
||||
3. 按 content_hash 去重后再预标记 consumed(仅 flush),再调用建批;
|
||||
4. 建批异常必须 rollback,避免 Chat Turn 后续 commit 把预占 consumed 落库;
|
||||
5. 建批成功后回填 batch/task,并把同 hash 附属 intake 一并关联到同一任务。
|
||||
"""
|
||||
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
|
||||
if not normalized:
|
||||
raise ValidationError('intake_nos is required')
|
||||
|
||||
# [STEP 1] 幂等重放优先:相同 Idempotency-Key 在 intake 已消费后仍可恢复原批次
|
||||
replay = _try_idempotent_replay(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
intake_nos=normalized,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
|
||||
# [STEP 2] 锁定并校验接入记录
|
||||
stmt = (
|
||||
select(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
.where(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.with_for_update()
|
||||
)
|
||||
rows = list(db.session.execute(stmt).all())
|
||||
row_by_no = {intake.intake_no: (intake, asset) for intake, asset in rows}
|
||||
if len(row_by_no) != len(set(normalized)):
|
||||
raise ValidationError(
|
||||
'部分接入记录不存在或无权访问',
|
||||
code='SHIPPING_NOTICE.INTAKE_NOT_FOUND',
|
||||
)
|
||||
|
||||
# 锁后再查一次幂等键,覆盖 STEP1 与锁定之间的并发窗口
|
||||
replay = _try_idempotent_replay(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
intake_nos=normalized,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
|
||||
ordered_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = []
|
||||
now = datetime.utcnow()
|
||||
for intake_no in normalized:
|
||||
intake, asset = row_by_no[intake_no]
|
||||
if intake.consumed_at is not None or intake.parse_status == 'consumed':
|
||||
raise ConflictError(
|
||||
f'接入记录 {intake.intake_no} 已被消费',
|
||||
code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED',
|
||||
)
|
||||
if intake.parse_status != 'parsed':
|
||||
raise ConflictError(
|
||||
f'接入记录 {intake.intake_no} 尚未解析完成',
|
||||
code=(
|
||||
'SHIPPING_NOTICE.INTAKE_PARSE_PENDING'
|
||||
if intake.parse_status in {'created', 'queued', 'parsing'}
|
||||
else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
),
|
||||
)
|
||||
if intake.expires_at and intake.expires_at < now:
|
||||
raise ConflictError(
|
||||
'接入记录已过期',
|
||||
code='SHIPPING_NOTICE.INTAKE_EXPIRED',
|
||||
)
|
||||
ordered_pairs.append((intake, asset))
|
||||
|
||||
# [STEP 3] content_hash 去重:只消费真正用于建单的 primary intake
|
||||
primary_pairs, duplicates_by_hash = _partition_intakes_by_content_hash(ordered_pairs)
|
||||
primary_intakes = [intake for intake, _ in primary_pairs]
|
||||
notice_items = [intake_to_notice_item(intake, asset) for intake, asset in primary_pairs]
|
||||
|
||||
# [STEP 4] 预占消费状态(flush 不 commit),与后续 create_batch_tasks 同事务提交
|
||||
mark_intakes_consumed(intakes=primary_intakes, batch_id=None)
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
result = create_shipping_batch_from_notice_items(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
notice_items=notice_items,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
)
|
||||
except Exception:
|
||||
# [P0] 建批失败时丢弃预占 consumed,避免 Chat Turn 的 touch_chat_session commit 落脏状态
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
if bool(result.get('idempotent_replay')):
|
||||
# create 路径返回重放时不会 commit;丢弃本事务内的预占 consumed,避免脏状态落库
|
||||
db.session.rollback()
|
||||
return result
|
||||
|
||||
data = result.get('data') if isinstance(result.get('data'), dict) else {}
|
||||
batch = data.get('batch') if isinstance(data.get('batch'), dict) else {}
|
||||
batch_no = str(result.get('batch_no') or batch.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
return result
|
||||
|
||||
from app.services.shipping_notice.query_service import get_batch_for_user
|
||||
|
||||
batch_obj = get_batch_for_user(batch_no, user_id)
|
||||
if not batch_obj:
|
||||
return result
|
||||
|
||||
tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter(ShippingTask.batch_id == batch_obj.id)
|
||||
.order_by(ShippingTask.batch_index.asc(), ShippingTask.id.asc())
|
||||
.all()
|
||||
)
|
||||
task_by_intake_id = {
|
||||
int(task.source_intake_id): task
|
||||
for task in tasks
|
||||
if task.source_intake_id is not None
|
||||
}
|
||||
hash_to_task_id: dict[str, int] = {}
|
||||
for intake, asset in primary_pairs:
|
||||
task = task_by_intake_id.get(int(intake.id))
|
||||
if task is None:
|
||||
continue
|
||||
intake.consumed_batch_id = int(batch_obj.id)
|
||||
intake.consumed_task_id = int(task.id)
|
||||
intake.updated_at = datetime.utcnow()
|
||||
content_hash = str(asset.content_hash or '').strip()
|
||||
if content_hash:
|
||||
hash_to_task_id[content_hash] = int(task.id)
|
||||
|
||||
# [STEP 5] 同 hash 附属 intake 显式关联到同一任务,避免残留 parsed 且保证幂等集合一致
|
||||
duplicate_intakes: list[ShippingNoticeIntake] = []
|
||||
for content_hash, dups in duplicates_by_hash.items():
|
||||
task_id = hash_to_task_id.get(content_hash)
|
||||
if task_id is None:
|
||||
continue
|
||||
for dup in dups:
|
||||
duplicate_intakes.append(dup)
|
||||
dup.consumed_batch_id = int(batch_obj.id)
|
||||
dup.consumed_task_id = int(task_id)
|
||||
if duplicate_intakes:
|
||||
mark_intakes_consumed(
|
||||
intakes=duplicate_intakes,
|
||||
batch_id=int(batch_obj.id),
|
||||
task_ids_by_intake={int(i.id): int(i.consumed_task_id) for i in duplicate_intakes if i.consumed_task_id},
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
return result
|
||||
@@ -149,6 +149,58 @@ class ShippingCreateBatchFromNoticesAction:
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"})
|
||||
|
||||
|
||||
class ShippingCreateBatchFromIntakesAction:
|
||||
"""基于已解析接入记录确认建批(第二阶段主路径)。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_intakes"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
intake_nos = payload.get("intake_nos")
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError("intake_nos is required")
|
||||
# 空白新会话 payload 常无 conversation_id;回退到 Chat Turn 刚创建的本地 session_id
|
||||
conversation_id = (
|
||||
_payload_str(payload, "conversation_id", "conversationId")
|
||||
or str(getattr(ctx, "session_id", "") or "").strip()
|
||||
or None
|
||||
)
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."})
|
||||
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.batch_from_notices import format_batch_created_assistant_message
|
||||
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(intake_nos)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
message_payload = {
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
}
|
||||
yield from _stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
|
||||
|
||||
|
||||
class ShippingSubmitDecisionAction:
|
||||
"""提交人工决策:confirm / reject / rematch / retry_rpa 等。"""
|
||||
|
||||
@@ -307,6 +359,7 @@ class ShippingMarkManualUploadedAction:
|
||||
|
||||
_HANDLERS = (
|
||||
ShippingCreateBatchFromNoticesAction(),
|
||||
ShippingCreateBatchFromIntakesAction(),
|
||||
ShippingSubmitDecisionAction(),
|
||||
ShippingGenerateExcelAction(),
|
||||
ShippingRetryUploadAction(),
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/intake_parse_workflow.py
|
||||
|
||||
用途:发货通知接入记录的文本抽取与预解析编排。
|
||||
依赖:notice_upload、file_assets.service、models.ShippingNoticeIntake。
|
||||
逻辑:由 shipping_notice_parse Job handler 调用;不写 API 路由。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from sqlalchemy import update
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingNoticeIntake
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
NoticeIntakeResult,
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
truncate_notice_text,
|
||||
)
|
||||
|
||||
|
||||
def _parser_version() -> str:
|
||||
return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip()
|
||||
|
||||
|
||||
def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult:
|
||||
"""
|
||||
从 FileAsset 下载并抽取发货通知文本。
|
||||
核心逻辑:写入临时文件后复用 extract_notice_text,避免长期落盘到 notice_uploads。
|
||||
"""
|
||||
raw = read_asset_bytes(asset)
|
||||
filename = str(asset.original_filename or 'notice')
|
||||
source_type = guess_source_type(filename)
|
||||
suffix = Path(filename).suffix or '.bin'
|
||||
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
||||
tmp.write(raw)
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
text, meta = extract_notice_text(tmp_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
return NoticeIntakeResult(
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
source_file_type=asset.mime_type,
|
||||
text='',
|
||||
warnings=[f'notice_extract_failed:{exc}'],
|
||||
meta={},
|
||||
content_hash=str(asset.content_hash or ''),
|
||||
file_size=int(asset.file_size or 0),
|
||||
status='extract_failed',
|
||||
saved_path=None,
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
if not str(text or '').strip():
|
||||
return NoticeIntakeResult(
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
source_file_type=asset.mime_type,
|
||||
text='',
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=str(asset.content_hash or ''),
|
||||
file_size=int(asset.file_size or 0),
|
||||
status='empty_text',
|
||||
saved_path=None,
|
||||
)
|
||||
|
||||
text, warnings = truncate_notice_text(text, warnings)
|
||||
return NoticeIntakeResult(
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
source_file_type=asset.mime_type,
|
||||
text=text,
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=str(asset.content_hash or ''),
|
||||
file_size=int(asset.file_size or 0),
|
||||
status='accepted',
|
||||
saved_path=None,
|
||||
)
|
||||
|
||||
|
||||
def intake_result_to_structured_summary(result: NoticeIntakeResult) -> dict[str, Any]:
|
||||
"""生成前端可展示的预解析摘要。"""
|
||||
line_count = 0
|
||||
for line in str(result.text or '').splitlines():
|
||||
if line.strip():
|
||||
line_count += 1
|
||||
return {
|
||||
'filename': result.filename,
|
||||
'source_type': result.source_type,
|
||||
'text_length': len(result.text or ''),
|
||||
'line_count': line_count,
|
||||
'warnings': list(result.warnings),
|
||||
'parser_version': _parser_version(),
|
||||
}
|
||||
|
||||
|
||||
_ABORT_WRITE_STATUSES = frozenset({'cancelled', 'expired', 'consumed'})
|
||||
|
||||
|
||||
def _db_parse_status(intake_id: int) -> str | None:
|
||||
"""
|
||||
绕过 Session 身份映射强制读库中的 parse_status。
|
||||
|
||||
核心逻辑:expire 本地缓存后 refresh,避免抽取耗时窗口内他事务 cancel 后仍读到 parsing。
|
||||
"""
|
||||
obj = db.session.get(ShippingNoticeIntake, int(intake_id))
|
||||
if obj is None:
|
||||
return None
|
||||
db.session.expire(obj)
|
||||
db.session.refresh(obj)
|
||||
return str(obj.parse_status or '')
|
||||
|
||||
|
||||
def _commit_parse_result_if_writable(
|
||||
*,
|
||||
intake_id: int,
|
||||
values: dict[str, Any],
|
||||
) -> ShippingNoticeIntake | None:
|
||||
"""
|
||||
条件更新解析结果:仅当库中状态仍非 cancelled/expired/consumed 时写回。
|
||||
|
||||
Returns:
|
||||
写成功后的 ORM 对象;被取消/过期/消费则返回 None。
|
||||
"""
|
||||
# [STEP 1] 先强制刷新;若已终态则放弃
|
||||
status = _db_parse_status(intake_id)
|
||||
if status is None or status in _ABORT_WRITE_STATUSES:
|
||||
return None
|
||||
|
||||
# [STEP 2] 原子 UPDATE,防止 refresh 与 commit 之间的竞态仍覆盖 cancelled
|
||||
stmt = (
|
||||
update(ShippingNoticeIntake)
|
||||
.where(
|
||||
ShippingNoticeIntake.id == int(intake_id),
|
||||
ShippingNoticeIntake.parse_status.notin_(tuple(_ABORT_WRITE_STATUSES)),
|
||||
)
|
||||
.values(**values)
|
||||
)
|
||||
result = db.session.execute(stmt)
|
||||
if int(result.rowcount or 0) != 1:
|
||||
db.session.rollback()
|
||||
return None
|
||||
db.session.commit()
|
||||
return db.session.get(ShippingNoticeIntake, int(intake_id))
|
||||
|
||||
|
||||
def run_intake_parse(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]:
|
||||
"""
|
||||
执行单条接入记录的预解析并更新 ORM 状态。
|
||||
|
||||
核心逻辑:抽取文本后强制刷新并条件 UPDATE;抽取期间被取消则 status=skipped,不覆盖 cancelled。
|
||||
|
||||
Returns:
|
||||
解析结果摘要字典;若期间被取消/过期则 status=skipped。
|
||||
"""
|
||||
result = extract_notice_from_asset(asset)
|
||||
intake_id = int(intake.id)
|
||||
intake_no = intake.intake_no
|
||||
parser_version = _parser_version()
|
||||
summary = intake_result_to_structured_summary(result)
|
||||
warnings = list(result.warnings)
|
||||
|
||||
if result.status == 'extract_failed':
|
||||
fresh = _commit_parse_result_if_writable(
|
||||
intake_id=intake_id,
|
||||
values={
|
||||
'parser_version': parser_version,
|
||||
'parse_status': 'parse_failed',
|
||||
'error_code': 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
|
||||
'error_message': '; '.join(warnings)[:1000] or '文本抽取失败',
|
||||
'extracted_text': None,
|
||||
'structured_result_json': summary,
|
||||
'parse_warnings_json': warnings,
|
||||
},
|
||||
)
|
||||
if fresh is None:
|
||||
return {
|
||||
'status': 'skipped',
|
||||
'intake_no': intake_no,
|
||||
'parse_status': _db_parse_status(intake_id),
|
||||
}
|
||||
return {'status': 'parse_failed', 'intake_no': intake_no, 'error_message': fresh.error_message}
|
||||
|
||||
if result.status == 'empty_text':
|
||||
fresh = _commit_parse_result_if_writable(
|
||||
intake_id=intake_id,
|
||||
values={
|
||||
'parser_version': parser_version,
|
||||
'parse_status': 'parse_failed',
|
||||
'error_code': 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
|
||||
'error_message': '未提取到有效文本',
|
||||
'extracted_text': None,
|
||||
'structured_result_json': summary,
|
||||
'parse_warnings_json': warnings,
|
||||
},
|
||||
)
|
||||
if fresh is None:
|
||||
return {
|
||||
'status': 'skipped',
|
||||
'intake_no': intake_no,
|
||||
'parse_status': _db_parse_status(intake_id),
|
||||
}
|
||||
return {'status': 'parse_failed', 'intake_no': intake_no, 'error_message': fresh.error_message}
|
||||
|
||||
fresh = _commit_parse_result_if_writable(
|
||||
intake_id=intake_id,
|
||||
values={
|
||||
'parser_version': parser_version,
|
||||
'parse_status': 'parsed',
|
||||
'error_code': None,
|
||||
'error_message': None,
|
||||
'extracted_text': result.text,
|
||||
'structured_result_json': summary,
|
||||
'parse_warnings_json': warnings,
|
||||
},
|
||||
)
|
||||
if fresh is None:
|
||||
return {
|
||||
'status': 'skipped',
|
||||
'intake_no': intake_no,
|
||||
'parse_status': _db_parse_status(intake_id),
|
||||
}
|
||||
return {'status': 'parsed', 'intake_no': intake_no}
|
||||
|
||||
|
||||
def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]:
|
||||
"""将已解析 intake 转为兼容 create_batch 的 notice_item。"""
|
||||
return {
|
||||
'source_type': guess_source_type(asset.original_filename),
|
||||
'source_file_name': asset.original_filename,
|
||||
'source_file_type': asset.mime_type,
|
||||
'source_content_hash': asset.content_hash,
|
||||
'file_size': asset.file_size,
|
||||
'raw_text': intake.extracted_text or '',
|
||||
'warnings': list(intake.parse_warnings_json or []),
|
||||
'source_asset_id': asset.id,
|
||||
'source_intake_id': intake.id,
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
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)
|
||||
@@ -134,12 +134,13 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
|
||||
|
||||
def claim_next_shipping_notice_job() -> Job | None:
|
||||
"""兼容旧调用:领取下一条发货通知通用任务。"""
|
||||
"""领取下一条发货通知通用任务(单票编排或预解析)。"""
|
||||
from app.jobs.queue import claim_next_job
|
||||
from app.jobs.types import JobType
|
||||
|
||||
return claim_next_job(
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN],
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN, JobType.SHIPPING_NOTICE_PARSE],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -360,6 +360,8 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
source_file_name=str(item.get("source_file_name") or "").strip() or None,
|
||||
source_file_type=item.get("source_file_type"),
|
||||
source_content_hash=content_hash,
|
||||
source_asset_id=item.get("source_asset_id"),
|
||||
source_intake_id=item.get("source_intake_id"),
|
||||
batch_index=idx,
|
||||
batch_total=total,
|
||||
raw_content=str(item.get("raw_text") or "").strip() or None,
|
||||
|
||||
Reference in new issue
Block a user