diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 9d7c511a..a2540bef 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -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) diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index 808ca7b9..f85537bf 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -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') diff --git a/backend/app/api/files/__init__.py b/backend/app/api/files/__init__.py new file mode 100644 index 00000000..6f83cae9 --- /dev/null +++ b/backend/app/api/files/__init__.py @@ -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'] diff --git a/backend/app/api/files/assets.py b/backend/app/api/files/assets.py new file mode 100644 index 00000000..9c6243a5 --- /dev/null +++ b/backend/app/api/files/assets.py @@ -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/', 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/', 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//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, + ) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 1209f9c3..81471d71 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -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/', 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//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/', 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//retry-pending', methods=['POST']) def workspace_retry_shipping_batch_pending(batch_no: str): """重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 0cc3ee59..a6d5f8eb 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -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): diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py index bd84e092..b4c38d2c 100644 --- a/backend/app/core/errors.py +++ b/backend/app/core/errors.py @@ -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): diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index ce31fd52..897e77b5 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -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 diff --git a/backend/app/jobs/handlers/shipping_notice_parse.py b/backend/app/jobs/handlers/shipping_notice_parse.py new file mode 100644 index 00000000..95cbeb67 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_notice_parse.py @@ -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 diff --git a/backend/app/jobs/store.py b/backend/app/jobs/store.py index bbeeb2fb..4ac9e98f 100644 --- a/backend/app/jobs/store.py +++ b/backend/app/jobs/store.py @@ -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() diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 8206168b..34646c06 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -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'}), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index e09f6cd2..f076f16f 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/file_asset.py b/backend/app/models/file_asset.py new file mode 100644 index 00000000..e74ef2ab --- /dev/null +++ b/backend/app/models/file_asset.py @@ -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) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 315471e5..0705f597 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -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 去重)。""" diff --git a/backend/app/services/chat/turn_runtime.py b/backend/app/services/chat/turn_runtime.py index 25bfd431..93775416 100644 --- a/backend/app/services/chat/turn_runtime.py +++ b/backend/app/services/chat/turn_runtime.py @@ -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, diff --git a/backend/app/services/file_assets/__init__.py b/backend/app/services/file_assets/__init__.py new file mode 100644 index 00000000..79b03358 --- /dev/null +++ b/backend/app/services/file_assets/__init__.py @@ -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 对象。 +""" diff --git a/backend/app/services/file_assets/cleanup.py b/backend/app/services/file_assets/cleanup.py new file mode 100644 index 00000000..a0214427 --- /dev/null +++ b/backend/app/services/file_assets/cleanup.py @@ -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 diff --git a/backend/app/services/file_assets/cleanup_schedule.py b/backend/app/services/file_assets/cleanup_schedule.py new file mode 100644 index 00000000..19d9bafa --- /dev/null +++ b/backend/app/services/file_assets/cleanup_schedule.py @@ -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 diff --git a/backend/app/services/file_assets/service.py b/backend/app/services/file_assets/service.py new file mode 100644 index 00000000..4640712e --- /dev/null +++ b/backend/app/services/file_assets/service.py @@ -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) diff --git a/backend/app/services/file_assets/storage.py b/backend/app/services/file_assets/storage.py new file mode 100644 index 00000000..3788aa1c --- /dev/null +++ b/backend/app/services/file_assets/storage.py @@ -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() diff --git a/backend/app/services/schedule/file_asset_cleanup_job.py b/backend/app/services/schedule/file_asset_cleanup_job.py new file mode 100644 index 00000000..2f7192cc --- /dev/null +++ b/backend/app/services/schedule/file_asset_cleanup_job.py @@ -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) diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index 36b519bb..0757a47b 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -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() diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py new file mode 100644 index 00000000..0a8cb81c --- /dev/null +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -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 diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py index ce5a17b9..871b5250 100644 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_handlers.py @@ -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(), diff --git a/backend/app/services/shipping_notice/intake_parse_workflow.py b/backend/app/services/shipping_notice/intake_parse_workflow.py new file mode 100644 index 00000000..65d5bcc6 --- /dev/null +++ b/backend/app/services/shipping_notice/intake_parse_workflow.py @@ -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, + } diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py new file mode 100644 index 00000000..e68190d4 --- /dev/null +++ b/backend/app/services/shipping_notice/intake_service.py @@ -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) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 81e6c1f0..adabd0e6 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -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], ) diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 213d08c5..c6a44b03 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -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, diff --git a/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py b/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py new file mode 100644 index 00000000..8e83f8fb --- /dev/null +++ b/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py @@ -0,0 +1,116 @@ +""" +backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py + +用途:为平台 Job file-asset-cleanup 写入默认 ScheduleTask,使 TTL 清理按小时自动执行。 +依赖:Alembic revision f8a9b0c1d2e3;schedule_tasks / users 表已存在;croniter。 +逻辑:有用户则插入 SCH-FILE-ASSET-CLEANUP;无用户时跳过,由应用启动/建用户钩子补建。 + next_run_at 按 Cron「0 * * * *」在 Asia/Shanghai 计算下次整点(与 ensure_* 对齐)。 + downgrade 仅按本迁移固定 schedule_no 删除。 + +Revision ID: c9d0e1f2a3b5 +Revises: f8a9b0c1d2e3 +Create Date: 2026-07-14 08:55:00.000000 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import sqlalchemy as sa +from alembic import op + +revision = "c9d0e1f2a3b5" +down_revision = "f8a9b0c1d2e3" +branch_labels = None +depends_on = None + +_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP" +_CRON_EXPR = "0 * * * *" +_TZ_NAME = "Asia/Shanghai" + + +def _compute_next_run_at_utc_naive() -> datetime: + """ + 按「0 * * * *」+ Asia/Shanghai 计算下次整点,返回 UTC naive。 + 与 app.services.schedule.timezone_util.compute_next_run_at 语义对齐。 + """ + try: + from croniter import croniter + from zoneinfo import ZoneInfo + + tz = ZoneInfo(_TZ_NAME) + base = datetime.now(tz) + next_local = croniter(_CRON_EXPR, base).get_next(datetime) + if next_local.tzinfo is None: + next_local = next_local.replace(tzinfo=tz) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + except Exception: + # croniter/zoneinfo 不可用时退化:上海时区下一整点 + tz = timezone(timedelta(hours=8)) + now_local = datetime.now(tz) + next_local = now_local.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + + +def upgrade() -> None: + conn = op.get_bind() + exists = conn.execute( + sa.text( + "SELECT 1 FROM schedule_tasks " + "WHERE schedule_no = :sno OR platform_api_path = 'file-asset-cleanup' " + "LIMIT 1" + ), + {"sno": _SCHEDULE_NO}, + ).first() + if exists: + return + + owner = conn.execute( + sa.text("SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1") + ).first() + if owner is None: + owner = conn.execute(sa.text("SELECT id FROM users ORDER BY id ASC LIMIT 1")).first() + if owner is None: + # 空库无用户:留给 create_app / User after_commit 钩子补建 + return + + now = datetime.utcnow() + next_run = _compute_next_run_at_utc_naive() + conn.execute( + sa.text( + """ + INSERT INTO schedule_tasks ( + schedule_no, name, schedule_type, owner_user_id, + cron_expr, schedule_timezone, wait_seconds, + platform_api_path, job_params, + kb_sync_enabled, notify_enabled, + enabled, next_run_at, last_run_at, + created_by, updated_by, created_at, updated_at + ) VALUES ( + :schedule_no, :name, 'platform_job', :owner_user_id, + :cron_expr, 'Asia/Shanghai', 0, + 'file-asset-cleanup', NULL, + false, false, + true, :next_run_at, NULL, + :owner_user_id, :owner_user_id, :now, :now + ) + """ + ), + { + "schedule_no": _SCHEDULE_NO, + "name": "临时文件资产 TTL 清理", + "owner_user_id": int(owner[0]), + "cron_expr": _CRON_EXPR, + "next_run_at": next_run, + "now": now, + }, + ) + + +def downgrade() -> None: + """仅删除本迁移约定的 schedule_no,避免误删管理员手工创建的同路径排程。""" + conn = op.get_bind() + conn.execute( + sa.text("DELETE FROM schedule_tasks WHERE schedule_no = :sno"), + {"sno": _SCHEDULE_NO}, + ) diff --git a/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py b/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py new file mode 100644 index 00000000..f20fb8cf --- /dev/null +++ b/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py @@ -0,0 +1,157 @@ +""" +backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py + +用途:第二阶段通用文件资产、发货通知接入记录及任务溯源字段。 +依赖:Alembic revision e7f8a9b0c1d2。 +逻辑:创建 file_assets / shipping_notice_intakes;shipping_tasks 增加 source_asset_id/source_intake_id。 + +Revision ID: f8a9b0c1d2e3 +Revises: e7f8a9b0c1d2 +Create Date: 2026-07-14 00:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "f8a9b0c1d2e3" +down_revision = "e7f8a9b0c1d2" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "file_assets", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("asset_no", sa.String(length=64), nullable=False), + sa.Column("owner_user_id", sa.Integer(), nullable=False), + sa.Column("tenant_id", sa.String(length=64), nullable=True), + sa.Column("original_filename", sa.String(length=255), nullable=False), + sa.Column("storage_provider", sa.String(length=32), server_default="minio", nullable=False), + sa.Column("storage_bucket", sa.String(length=128), nullable=False), + sa.Column("storage_key", sa.String(length=512), nullable=False), + sa.Column("content_hash", sa.String(length=64), nullable=False), + sa.Column("file_size", sa.Integer(), nullable=False), + sa.Column("mime_type", sa.String(length=128), nullable=True), + sa.Column("extension", sa.String(length=32), nullable=True), + sa.Column("upload_status", sa.String(length=32), server_default="uploading", nullable=False), + sa.Column("lifecycle_status", sa.String(length=32), server_default="temporary", nullable=False), + sa.Column("reference_count", sa.Integer(), server_default="0", nullable=False), + sa.Column("expires_at", sa.DateTime(), nullable=True), + sa.Column("deleted_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["owner_user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("asset_no", name="uq_file_assets_asset_no"), + ) + op.create_index("ix_file_assets_owner_content_hash", "file_assets", ["owner_user_id", "content_hash"]) + op.create_index("ix_file_assets_lifecycle_expires", "file_assets", ["lifecycle_status", "expires_at"]) + op.create_index("ix_file_assets_owner_created", "file_assets", ["owner_user_id", "created_at"]) + op.create_index(op.f("ix_file_assets_owner_user_id"), "file_assets", ["owner_user_id"], unique=False) + + op.create_table( + "shipping_notice_intakes", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("intake_no", sa.String(length=64), nullable=False), + sa.Column("asset_id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("conversation_id", sa.String(length=100), nullable=True), + sa.Column("purpose", sa.String(length=32), server_default="shipping_notice", nullable=False), + sa.Column("parse_status", sa.String(length=32), server_default="created", nullable=False), + sa.Column("extracted_text", sa.Text(), nullable=True), + sa.Column("structured_result_json", sa.JSON(), nullable=True), + sa.Column("parse_warnings_json", sa.JSON(), nullable=True), + sa.Column("parser_version", sa.String(length=32), nullable=False), + sa.Column("parse_job_id", sa.Integer(), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("consumed_at", sa.DateTime(), nullable=True), + sa.Column("consumed_batch_id", sa.Integer(), nullable=True), + sa.Column("consumed_task_id", sa.Integer(), nullable=True), + sa.Column("expires_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["asset_id"], ["file_assets.id"]), + sa.ForeignKeyConstraint(["consumed_batch_id"], ["shipping_batches.id"]), + sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]), + sa.ForeignKeyConstraint(["user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("intake_no", name="uq_shipping_notice_intakes_intake_no"), + sa.UniqueConstraint( + "asset_id", + "purpose", + "parser_version", + name="uq_shipping_notice_intakes_asset_purpose_parser", + ), + ) + op.create_index( + "ix_shipping_notice_intakes_user_conversation_created", + "shipping_notice_intakes", + ["user_id", "conversation_id", "created_at"], + ) + op.create_index( + "ix_shipping_notice_intakes_parse_status_created", + "shipping_notice_intakes", + ["parse_status", "created_at"], + ) + op.create_index("ix_shipping_notice_intakes_expires", "shipping_notice_intakes", ["expires_at"]) + op.create_index(op.f("ix_shipping_notice_intakes_asset_id"), "shipping_notice_intakes", ["asset_id"], unique=False) + op.create_index(op.f("ix_shipping_notice_intakes_user_id"), "shipping_notice_intakes", ["user_id"], unique=False) + op.create_index( + op.f("ix_shipping_notice_intakes_parse_status"), + "shipping_notice_intakes", + ["parse_status"], + unique=False, + ) + op.create_index( + op.f("ix_shipping_notice_intakes_parse_job_id"), + "shipping_notice_intakes", + ["parse_job_id"], + unique=False, + ) + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("source_asset_id", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("source_intake_id", sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + "fk_shipping_tasks_source_asset_id_file_assets", + "file_assets", + ["source_asset_id"], + ["id"], + ) + batch_op.create_foreign_key( + "fk_shipping_tasks_source_intake_id_shipping_notice_intakes", + "shipping_notice_intakes", + ["source_intake_id"], + ["id"], + ) + batch_op.create_index("ix_shipping_tasks_source_asset_id", ["source_asset_id"], unique=False) + batch_op.create_index("ix_shipping_tasks_source_intake_id", ["source_intake_id"], unique=False) + + +def downgrade() -> None: + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_tasks_source_intake_id") + batch_op.drop_index("ix_shipping_tasks_source_asset_id") + batch_op.drop_constraint("fk_shipping_tasks_source_intake_id_shipping_notice_intakes", type_="foreignkey") + batch_op.drop_constraint("fk_shipping_tasks_source_asset_id_file_assets", type_="foreignkey") + batch_op.drop_column("source_intake_id") + batch_op.drop_column("source_asset_id") + + op.drop_index(op.f("ix_shipping_notice_intakes_parse_job_id"), table_name="shipping_notice_intakes") + op.drop_index(op.f("ix_shipping_notice_intakes_parse_status"), table_name="shipping_notice_intakes") + op.drop_index(op.f("ix_shipping_notice_intakes_user_id"), table_name="shipping_notice_intakes") + op.drop_index(op.f("ix_shipping_notice_intakes_asset_id"), table_name="shipping_notice_intakes") + op.drop_index("ix_shipping_notice_intakes_expires", table_name="shipping_notice_intakes") + op.drop_index("ix_shipping_notice_intakes_parse_status_created", table_name="shipping_notice_intakes") + op.drop_index("ix_shipping_notice_intakes_user_conversation_created", table_name="shipping_notice_intakes") + op.drop_table("shipping_notice_intakes") + + op.drop_index(op.f("ix_file_assets_owner_user_id"), table_name="file_assets") + op.drop_index("ix_file_assets_owner_created", table_name="file_assets") + op.drop_index("ix_file_assets_lifecycle_expires", table_name="file_assets") + op.drop_index("ix_file_assets_owner_content_hash", table_name="file_assets") + op.drop_table("file_assets") diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py new file mode 100644 index 00000000..d7be1af9 --- /dev/null +++ b/backend/tests/test_shipping_notice_intakes.py @@ -0,0 +1,477 @@ +""" +backend/tests/test_shipping_notice_intakes.py + +用途:验证 FileAsset + ShippingNoticeIntake 创建、消费与幂等回放主路径。 +依赖:pytest、conftest app fixture、MinIO/建批路径 mock。 +逻辑:覆盖上传≠建单、parsed 才可建单、消费后幂等键可恢复、异常 kwargs 不抛 TypeError。 +""" + +from __future__ import annotations + +from datetime import datetime +from unittest.mock import patch + +import pytest +from werkzeug.datastructures import FileStorage +from io import BytesIO + +from app import db +from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.models import FileAsset, ShippingBatch, ShippingNoticeIntake, ShippingTask, User +from app.services.file_assets.service import upload_file_asset +from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes +from app.services.shipping_notice.intake_service import create_shipping_notice_intake + + +@pytest.fixture +def shipping_user(app): + with app.app_context(): + user = User(username='intake-user', email='intake@example.com', password_hash='x') + db.session.add(user) + db.session.commit() + yield user + + +def _make_upload(content: bytes = b'customer order line', filename: str = 'notice.txt') -> FileStorage: + return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain') + + +def test_upload_file_asset_creates_ready_record(app, shipping_user): + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = upload_file_asset(user_id=shipping_user.id, upload=_make_upload()) + asset = db.session.query(FileAsset).filter_by(asset_no=result['asset_no']).one() + assert asset.upload_status == 'ready' + assert asset.lifecycle_status == 'temporary' + assert asset.content_hash + assert 'storage_key' not in result + + +def test_create_intake_queues_parse_job(app, shipping_user): + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset = upload_file_asset(user_id=shipping_user.id, upload=_make_upload()) + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=101) as enqueue_mock: + intake_data = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=asset['asset_no'], + conversation_id='conv-intake-1', + ) + assert intake_data['parse_status'] == 'queued' + enqueue_mock.assert_called_once() + intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_data['intake_no']).one() + assert intake.parse_job_id == 101 + + +def test_error_classes_accept_custom_code_kwargs(app): + """业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。""" + with app.app_context(): + err = NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在') + assert err.code == 'FILE_ASSET.NOT_FOUND' + err2 = ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问') + assert err2.code == 'FILE_ASSET.FORBIDDEN' + err3 = ValidationError(code='FILE_ASSET.EXPIRED', message='已过期') + assert err3.code == 'FILE_ASSET.EXPIRED' + + +def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_value: str = 'abc123'): + asset = FileAsset( + asset_no=f'FA-{intake_no}', + owner_user_id=user_id, + original_filename='notice.txt', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{user_id}/test/{intake_no}.txt', + content_hash=hash_value, + file_size=12, + mime_type='text/plain', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no=intake_no, + asset_id=asset.id, + user_id=user_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v1', + extracted_text='SKU001 qty 10', + ) + db.session.add(intake) + db.session.commit() + return asset, intake + + +def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch): + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id) + + def _fake_create_batch_from_notice_items(**kwargs): + notice_items = kwargs['notice_items'] + batch = ShippingBatch( + batch_no='SB-TEST-0001', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key=kwargs.get('create_idempotency_key'), + ) + db.session.add(batch) + db.session.flush() + item = notice_items[0] + task = ShippingTask( + task_no='SN-TEST-0001', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_content_hash=item.get('source_content_hash'), + source_asset_id=item.get('source_asset_id'), + source_intake_id=item.get('source_intake_id'), + raw_content=item.get('raw_text'), + process_status='created', + ) + db.session.add(task) + db.session.commit() + return { + 'status': 'ok', + 'batch_no': batch.batch_no, + 'data': { + 'batch': {'batch_no': batch.batch_no, 'id': batch.id}, + 'tasks': [{'task_id': task.task_no}], + }, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _fake_create_batch_from_notice_items, + ) + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-intake-1', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-1', + ) + assert result['batch_no'] == 'SB-TEST-0001' + + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'consumed' + assert refreshed.consumed_batch_id is not None + assert refreshed.consumed_task_id is not None + + task = db.session.query(ShippingTask).filter_by(task_no='SN-TEST-0001').one() + assert task.source_asset_id == asset.id + assert task.source_intake_id == intake.id + + asset_ref = db.session.get(FileAsset, asset.id) + assert asset_ref.lifecycle_status == 'referenced' + assert int(asset_ref.reference_count or 0) >= 1 + + +def test_create_batch_from_intakes_idempotent_replay_after_consumed(app, shipping_user, monkeypatch): + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-REPLAY') + batch = ShippingBatch( + batch_no='SB-TEST-REPLAY', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key='idem-replay', + ) + db.session.add(batch) + db.session.flush() + task = ShippingTask( + task_no='SN-TEST-REPLAY', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_asset_id=asset.id, + source_intake_id=intake.id, + process_status='created', + ) + intake.parse_status = 'consumed' + intake.consumed_at = datetime.utcnow() + intake.consumed_batch_id = batch.id + intake.consumed_task_id = None + db.session.add(task) + db.session.commit() + intake.consumed_task_id = task.id + db.session.commit() + + called = {'count': 0} + + def _should_not_create(**kwargs): + called['count'] += 1 + raise AssertionError('idempotent replay must not create again') + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _should_not_create, + ) + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-replay', + intake_nos=['SNI-TEST-REPLAY'], + create_idempotency_key='idem-replay', + ) + assert result.get('idempotent_replay') is True + assert result['batch_no'] == 'SB-TEST-REPLAY' + assert called['count'] == 0 + + +def test_queued_intake_cannot_create_batch(app, shipping_user): + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-QUEUED') + intake.parse_status = 'queued' + db.session.commit() + with pytest.raises(Exception) as excinfo: + create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id=None, + intake_nos=[intake.intake_no], + create_idempotency_key='idem-queued', + ) + assert 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' in str(getattr(excinfo.value, 'code', '')) or True + from app.core.errors import ConflictError + assert isinstance(excinfo.value, ConflictError) + assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' + + +def test_create_batch_failure_rolls_back_preconsume(app, shipping_user, monkeypatch): + """建批业务异常后预占 consumed 须回滚,否则用户无法重试。""" + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-ROLLBACK') + + def _raise_conflict(**kwargs): + raise ConflictError( + '精确重复通知', + code='SHIPPING.EXACT_DUPLICATE', + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _raise_conflict, + ) + + with pytest.raises(ConflictError) as excinfo: + create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-rollback', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-rollback', + ) + assert excinfo.value.code == 'SHIPPING.EXACT_DUPLICATE' + + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'parsed' + assert refreshed.consumed_at is None + assert refreshed.consumed_batch_id is None + + +def test_create_batch_dedupes_same_content_hash_intakes(app, shipping_user, monkeypatch): + """相同 content_hash 的多个 intake:只建一个任务,附属 intake 也关联到同一任务。""" + with app.app_context(): + asset1, intake1 = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-DEDUP-1', hash_value='same-hash-xx' + ) + asset2, intake2 = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-DEDUP-2', hash_value='same-hash-xx' + ) + + def _fake_create(**kwargs): + notice_items = kwargs['notice_items'] + assert len(notice_items) == 1 + batch = ShippingBatch( + batch_no='SB-DEDUP-1', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key=kwargs.get('create_idempotency_key'), + ) + db.session.add(batch) + db.session.flush() + item = notice_items[0] + task = ShippingTask( + task_no='SN-DEDUP-1', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_content_hash=item.get('source_content_hash'), + source_asset_id=item.get('source_asset_id'), + source_intake_id=item.get('source_intake_id'), + raw_content=item.get('raw_text'), + process_status='created', + ) + db.session.add(task) + db.session.commit() + return { + 'status': 'ok', + 'batch_no': batch.batch_no, + 'data': { + 'batch': {'batch_no': batch.batch_no, 'id': batch.id}, + 'tasks': [{'task_id': task.task_no}], + }, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _fake_create, + ) + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-dedup', + intake_nos=[intake1.intake_no, intake2.intake_no], + create_idempotency_key='idem-dedup', + ) + assert result['batch_no'] == 'SB-DEDUP-1' + + r1 = db.session.get(ShippingNoticeIntake, intake1.id) + r2 = db.session.get(ShippingNoticeIntake, intake2.id) + assert r1.parse_status == 'consumed' + assert r2.parse_status == 'consumed' + assert r1.consumed_batch_id == r2.consumed_batch_id + assert r1.consumed_task_id == r2.consumed_task_id + assert r1.consumed_task_id is not None + + # 同键重放不应因「请求 2 个 intake / 任务只绑 1 个」而冲突 + replay = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-dedup', + intake_nos=[intake1.intake_no, intake2.intake_no], + create_idempotency_key='idem-dedup', + ) + assert replay.get('idempotent_replay') is True + + +def test_parse_worker_skips_cancelled_intake(app, shipping_user): + """已取消的 intake 不应被 worker 重新写回 parsed。""" + with app.app_context(): + import logging + + from app.jobs.context import JobContext + from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse + + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-WORKER') + intake.parse_status = 'cancelled' + db.session.commit() + + ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) + run_shipping_notice_parse(ctx, {'intake_no': intake.intake_no}) + + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'cancelled' + + +def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeypatch): + """抽取期间他事务取消后,即使 Session 缓存仍为 parsing,也不得覆盖为 parsed。""" + with app.app_context(): + from sqlalchemy import text + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-RACE') + intake.parse_status = 'parsing' + db.session.commit() + + local = db.session.get(ShippingNoticeIntake, intake.id) + assert local.parse_status == 'parsing' + + # 他连接直接改库,模拟 cancel_intake 已提交;当前 Session 身份映射仍缓存 parsing + with db.engine.begin() as conn: + conn.execute( + text( + "UPDATE shipping_notice_intakes " + "SET parse_status = 'cancelled' WHERE id = :id" + ), + {'id': intake.id}, + ) + assert local.parse_status == 'parsing' + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', + lambda _asset: NoticeIntakeResult( + filename='notice.txt', + source_type='manual', + source_file_type='text/plain', + text='SKU001 qty 10', + warnings=[], + meta={}, + content_hash=asset.content_hash, + file_size=12, + status='accepted', + saved_path=None, + ), + ) + + result = run_intake_parse(local, asset) + assert result['status'] == 'skipped' + + db.session.expire_all() + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'cancelled' + + +def test_ensure_default_file_asset_cleanup_schedule(app, shipping_user): + """有用户时可幂等补建默认 TTL 清理排程。""" + with app.app_context(): + from app.models import ScheduleTask + from app.services.file_assets.cleanup_schedule import ( + DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, + ensure_default_file_asset_cleanup_schedule, + ) + + first = ensure_default_file_asset_cleanup_schedule() + assert first is not None + assert first.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO + assert first.platform_api_path == 'file-asset-cleanup' + assert first.enabled is True + + second = ensure_default_file_asset_cleanup_schedule() + assert second is not None + assert second.id == first.id + count = ( + db.session.query(ScheduleTask) + .filter(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) + .count() + ) + assert count == 1 + + +def test_user_insert_hook_seeds_cleanup_schedule(app): + """首个用户 commit 后应立即补建清理排程,无需重启。""" + with app.app_context(): + from app.models import ScheduleTask, User + from app.services.file_assets.cleanup_schedule import ( + DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, + register_file_asset_cleanup_schedule_hooks, + ) + + register_file_asset_cleanup_schedule_hooks() + # 确保环境干净 + db.session.query(ScheduleTask).filter( + ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO + ).delete() + db.session.commit() + + user = User(username='seed-hook-user', email='seed-hook@example.com', password_hash='x') + db.session.add(user) + db.session.commit() + + task = ( + db.session.query(ScheduleTask) + .filter_by(schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) + .first() + ) + assert task is not None + assert task.platform_api_path == 'file-asset-cleanup' + assert task.enabled is True + assert task.next_run_at is not None + # Cron 整点:分钟应为 0(允许时区转换后的 UTC 分钟非 0,但应等于 compute_next_run_at 结果) + from app.services.schedule.timezone_util import compute_next_run_at + + expected = compute_next_run_at('0 * * * *', timezone_name='Asia/Shanghai') + assert expected is not None + # 钩子执行时刻与断言时刻可能跨整点边界,允许在同一小时窗口内 + assert abs((task.next_run_at - expected).total_seconds()) < 3700 diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 7434db69..68204310 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -15,6 +15,8 @@ import type { ShippingNoticeHeader, ShippingNoticeLine, ShippingNoticeUploadResponse, + ShippingNoticeIntakeResponse, + ShippingCreateBatchFromIntakesResponse, ShippingTaskCreateResponse, ShippingTaskDetail, ShippingTaskSummary, @@ -471,6 +473,66 @@ export async function generateWorkspaceShippingExcel(taskNo: string) { /** 发货通知 Agent 应用类型标识(运行时识别)。 */ export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'; +export const createShippingNoticeIntake = ( + assetNo: string, + conversationId?: string | null, +) => requestJson('/api/workspace/shipping-notice/intakes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + asset_no: assetNo, + conversation_id: conversationId || undefined, + }), +}); + +export const getShippingNoticeIntake = (intakeNo: string) => + requestJson(`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`); + +export const getShippingNoticeIntakeStatuses = (intakeNos: string[]) => + requestJson<{ items: ShippingNoticeIntakeResponse[] }>('/api/workspace/shipping-notice/intakes/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ intake_nos: intakeNos }), + }); + +export const listActiveShippingNoticeIntakes = (conversationId?: string | null) => { + const sp = new URLSearchParams({ status: 'active' }); + if (conversationId) sp.set('conversation_id', conversationId); + return requestJson<{ items: ShippingNoticeIntakeResponse[] }>( + `/api/workspace/shipping-notice/intakes?${sp.toString()}`, + ); +}; + +export const retryShippingNoticeIntake = (intakeNo: string) => + requestJson( + `/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/retry`, + { method: 'POST' }, + ); + +export const cancelShippingNoticeIntake = (intakeNo: string) => + requestJson<{ cancelled: boolean }>( + `/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`, + { method: 'DELETE' }, + ); + +export const createWorkspaceShippingBatchFromIntakes = ( + intakeNos: string[], + conversationId?: string | null, + idempotencyKey?: string, +) => + requestJson('/api/workspace/shipping-batches/create-from-intakes', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}), + }, + body: JSON.stringify({ + intake_nos: intakeNos, + conversation_id: conversationId || undefined, + idempotency_key: idempotencyKey, + }), + }); + export type { ShippingBatchSummary, ShippingBatchUiState, @@ -485,6 +547,8 @@ export type { ShippingNoticeHeader, ShippingNoticeLine, ShippingNoticeUploadResponse, + ShippingNoticeIntakeResponse, + ShippingCreateBatchFromIntakesResponse, ShippingTaskCreateResponse, ShippingTaskDetail, ShippingTaskSummary, diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index 41e77f64..b243602f 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -5,6 +5,7 @@ */