""" backend/app/services/shipping_notice/intake_service.py 用途:发货通知接入记录(ShippingOrderIntake)业务编排(含重复决策投影与权限)。 依赖:file_assets.service、intake_parse_workflow、order_extraction、jobs.queue、models、 duplicate_detection、attachment_integrity、document_layout 生命周期模型、 order_submission_service(阶段 1 上传 Submission / source_type)。 逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行; 创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE; 业务 purpose 创建时挂接 shipping_order_submissions 并写入 eml|direct_pdf; cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径); 状态轮询用瘦身 parse_summary。 """ from __future__ import annotations import uuid from datetime import datetime, timedelta from typing import Any from flask import current_app from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.core.response import utc_iso from app.jobs.queue import QUEUED_ONLY_STATUSES, enqueue from app.jobs.types import JobType from app.models import ( FileAsset, ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderSubmission, ShippingNotice, User, ) from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete from app.services.shipping_notice.order_submission_service import ( attach_intake_to_order_submission, ensure_order_submission_for_upload_batch, resolve_order_intake_source_type, serialize_order_submission, ) from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN ACTIVE_INTAKE_STATUSES = frozenset( { 'created', 'queued', 'parsing', 'parsed', 'parse_failed', 'consumed', 'cancelled', 'expired', } ) _DUPLICATE_RESOLUTIONS = frozenset({'open_existing', 'create_revision', 'force_create'}) ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE = 'order_document_profile_sample' def _parser_version() -> str: return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v6') or 'v6').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 _duplicate_payload_from_intake(intake: ShippingOrderIntake) -> dict[str, Any]: """ 从 intake 投影 duplicate 载荷(供轮询/卡片展示)。 核心逻辑:blocking 与 duplicate_detection 对齐——exact/same_* / possible 均须用户确认, 避免疑似重复在前端被静默放行。 """ matches = list(intake.duplicate_matches_json or []) status = str(intake.duplicate_status or 'unchecked') strength = str(intake.fingerprint_strength or 'unavailable') blocking = status in { 'exact_file', 'same_active_task', 'same_completed_task', 'possible_duplicate', 'partial_duplicate', 'same_business_content', 'possible_revision', } if strength == 'unavailable' and status == 'none': blocking = False allowed: list[str] = [] if blocking: allowed = ['open_existing', 'create_revision', 'force_create'] return { 'status': status, 'blocking': blocking, 'fingerprint_strength': strength, 'matches': matches, 'allowed_actions': allowed, } def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]: """ 构造轮询/列表用的轻量 parse_summary:去掉附件全文与大正文,仅保留摘要字段。 核心逻辑:状态接口高频轮询不得携带 MB 级 extracted_text;详情接口再返回全文。 """ if not isinstance(structured, dict): return {} out = dict(structured) email = out.get('email') if isinstance(email, dict): lean_email = { 'message_id': email.get('message_id') or '', 'subject': email.get('subject') or '', 'from': email.get('from') or '', 'to': email.get('to') or '', 'date': email.get('date') or '', 'body_text_length': int( email.get('body_text_length') if email.get('body_text_length') is not None else len(str(email.get('body_text') or '')) ), 'stored_body_text_length': int( email.get('stored_body_text_length') if email.get('stored_body_text_length') is not None else len(str(email.get('body_text') or '')) ), 'body_html_table_count': len(email.get('body_html_tables') or []), } out['email'] = lean_email attachments = out.get('attachments') if isinstance(attachments, list): lean_rows: list[dict[str, Any]] = [] for item in attachments: if not isinstance(item, dict): continue row = { 'attachment_key': item.get('attachment_key'), 'filename': item.get('filename'), 'mime_type': item.get('mime_type'), 'size': item.get('size'), 'content_hash': item.get('content_hash'), 'parse_status': item.get('parse_status'), 'text_length': item.get('text_length'), 'stored_text_length': item.get('stored_text_length'), 'warnings': list(item.get('warnings') or []), 'ready_for_extraction': bool(item.get('ready_for_extraction')), 'is_inline_resource': bool(item.get('is_inline_resource')), 'catalog_reason': item.get('catalog_reason'), } if item.get('asset_no'): row['asset_no'] = item.get('asset_no') if item.get('document_id') is not None: row['document_id'] = item.get('document_id') lean_rows.append(row) out['attachments'] = lean_rows return out def serialize_intake( intake: ShippingOrderIntake, *, asset: FileAsset | None = None, include_parse_texts: bool = False, include_candidate_details: bool = True, ) -> dict[str, Any]: """ 对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。 Args: include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口), 并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。 include_candidate_details: False 时仅返回恢复输入状态所需的 Candidate 字段, 避免活跃列表传输 evidence / field_adjudication 等重型审核数据。 """ from app.services.shipping_notice.document_candidate_persist import ( list_intake_candidates, list_intake_documents, ) structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None resolution = None if intake.duplicate_resolution: resolution = { 'action': intake.duplicate_resolution, 'reason': intake.duplicate_resolution_reason, 'resolved_by_id': intake.duplicate_resolved_by_id, 'resolved_at': utc_iso(intake.duplicate_resolved_at), 'target_task_no': intake.duplicate_target_task_no, } parse_summary = structured if include_parse_texts else _lean_parse_summary(structured) documents = list_intake_documents(int(intake.id), include_text=include_parse_texts) candidates = list_intake_candidates( int(intake.id), include_details=include_candidate_details, ) layout_summary = _serialize_intake_layout_summary(int(intake.id)) payload: dict[str, Any] = { 'intake_no': intake.intake_no, 'asset_no': asset.asset_no if asset else None, 'conversation_id': intake.conversation_id, 'upload_batch_id': intake.upload_batch_id, 'source_type': intake.source_type, 'submission_no': None, 'parse_status': intake.parse_status, 'parser_version': intake.parser_version, 'order_extraction_status': intake.order_extraction_status, 'order_extraction_error_code': intake.order_extraction_error_code, 'order_extraction_error_message': intake.order_extraction_error_message, 'parse_summary': parse_summary, 'business_summary': business_summary, 'business_fingerprint': intake.business_fingerprint, 'fingerprint_strength': intake.fingerprint_strength, 'fingerprint_version': intake.fingerprint_version, 'duplicate': _duplicate_payload_from_intake(intake), 'duplicate_resolution': resolution, 'documents': documents, 'candidates': candidates, 'document_count': len(documents), 'candidate_count': len(candidates), 'layout_status': layout_summary['status'], 'layout_summary': layout_summary, '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 intake.order_submission_id: submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id)) if submission is not None: payload['submission_no'] = submission.submission_no payload['order_submission'] = serialize_order_submission(submission) if asset: payload['original_filename'] = asset.original_filename payload['file_size'] = asset.file_size payload['content_hash'] = asset.content_hash return payload def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]: """ 汇总 Intake 下已调度的文档版面任务,供聊天页判断订单识别是否可启动。 Args: intake_id: ShippingOrderIntake 主键;只统计其派生 Document 的布局版本。 Returns: 脱敏状态与数量。processing 表示仍有 queued/running;completed 表示所有任务已终结; not_required 表示没有独立布局任务,不阻断文本或 Dify 兜底。 """ rows = ( db.session.query(ShippingDocumentLayoutVersion.status) .join( ShippingOrderDocument, ShippingOrderDocument.id == ShippingDocumentLayoutVersion.document_id, ) .filter(ShippingOrderDocument.intake_id == int(intake_id)) .all() ) counts = { 'queued': 0, 'running': 0, 'ready': 0, 'needs_review': 0, 'failed': 0, 'unsupported': 0, } for (raw_status,) in rows: status = str(raw_status or '') if status in counts: counts[status] += 1 total = sum(counts.values()) if counts['queued'] or counts['running']: status = 'processing' elif total: status = 'completed' else: status = 'not_required' return {'status': status, 'total': total, **counts} def get_intake_for_user(intake_no: str, user_id: int) -> ShippingOrderIntake: """按编号查询当前用户的接入记录。""" normalized = str(intake_no or '').strip().upper() intake = ( db.session.query(ShippingOrderIntake) .filter(ShippingOrderIntake.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, include_parse_texts=True) def _load_asset_for_intake(intake: ShippingOrderIntake) -> 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 _lock_intake_for_asset_purpose_parser( *, asset_id: int, purpose: str, parser_version: str, ) -> ShippingOrderIntake | None: """ FOR UPDATE 锁定同一资产目的+解析器版本下的 Intake(创建/重投入口串行化)。 Returns: 锁定的 Intake;不存在则 None。 """ return ( db.session.query(ShippingOrderIntake) .filter( ShippingOrderIntake.asset_id == int(asset_id), ShippingOrderIntake.purpose == purpose, ShippingOrderIntake.parser_version == parser_version, ) .execution_options(populate_existing=True) .with_for_update() .first() ) def _link_intake_to_upload_submission( *, intake: ShippingOrderIntake, asset: FileAsset, user_id: int, upload_batch_id: str, conversation_id: str | None, ) -> None: """ 将业务 Intake 幂等挂接到同一 upload_batch 的 ShippingOrderSubmission。 核心逻辑:补齐 source_type;仅当尚未挂接时创建/复用 Submission 并写审计; 已挂接则只在 source_type 缺失时回填。Submission 创建失败 fail-closed(抛 ConflictError)。 模板样本 purpose 不调用本函数。 Args: intake: 当前 Intake。 asset: 根 FileAsset(用于推断扩展名)。 user_id: 上传用户。 upload_batch_id: 文件选择批次。 conversation_id: 可选会话。 """ source_type = intake.source_type or resolve_order_intake_source_type( extension=getattr(asset, 'extension', None), filename=getattr(asset, 'original_filename', None), ) if intake.source_type is None and source_type is not None: intake.source_type = source_type if intake.order_submission_id is not None: return submission = ensure_order_submission_for_upload_batch( user_id=user_id, upload_batch_id=upload_batch_id, conversation_id=conversation_id or intake.conversation_id, actor_id=user_id, ) attach_intake_to_order_submission( submission=submission, intake=intake, source_type=source_type, actor_id=user_id, ) def create_shipping_notice_intake( *, user_id: int, asset_no: str, conversation_id: str | None = None, upload_batch_id: str | None = None, ) -> dict[str, Any]: """ 基于已上传 FileAsset 创建接入记录并投递解析 Job。 核心逻辑: 1. 校验资产 ready; 2. FOR UPDATE 查同 (asset, purpose, parser_version);无则 SAVEPOINT 插入, IntegrityError 后回落再锁已有行(并发首次创建幂等); 3. parsed/consumed/queued/parsing 直接返回;cancelled/expired(含过期时间到期)冲突拒绝; 4. 仅 created/parse_failed 持锁重投:enqueue(commit=False) 并绑定 parse_job_id。 """ return _create_intake_for_asset( user_id=user_id, asset_no=asset_no, purpose='shipping_notice', conversation_id=conversation_id, upload_batch_id=upload_batch_id, ) def create_order_document_profile_sample_intake(*, user_id: int, asset_no: str) -> dict[str, Any]: """ 为订单文档模板页创建隔离的 PDF/EML 样本解析 Intake。 AI/调用方触发时机:仅管理员在模板页上传用于配置/复核的文件后调用。该 Intake 不绑定会话,后续预解析只生成 Document 和布局候选,禁止进入候选、建单或 Dify 链路。 """ return _create_intake_for_asset( user_id=user_id, asset_no=asset_no, purpose=ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE, conversation_id=None, upload_batch_id=None, ) def _create_intake_for_asset( *, user_id: int, asset_no: str, purpose: str, conversation_id: str | None, upload_batch_id: str | None, ) -> dict[str, Any]: """按受控 purpose 创建幂等 Intake;模板样本与业务发货通知共享基础设施但隔离用途。""" 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() conv = str(conversation_id or '').strip() or None provided_batch_id = str(upload_batch_id or '').strip() # Workspace API 强制提供批次;服务层保留内部调用的隔离默认值。 batch_id = provided_batch_id or str(uuid.uuid4()) if purpose == ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE: extension = str(asset.extension or '').strip().lower() if extension not in {'pdf', 'eml'}: raise ValidationError( code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID', message='Only PDF and EML files can be order profile samples', ) # [STEP 1] 持锁定位或创建 Intake intake = _lock_intake_for_asset_purpose_parser( asset_id=int(asset.id), purpose=purpose, parser_version=parser_version, ) if intake is None: source_type = resolve_order_intake_source_type( extension=getattr(asset, 'extension', None), filename=getattr(asset, 'original_filename', None), ) candidate = ShippingOrderIntake( intake_no=generate_intake_no(), asset_id=int(asset.id), user_id=int(user_id), conversation_id=conv, upload_batch_id=batch_id or str(uuid.uuid4()), purpose=purpose, source_type=source_type, parse_status='created', parser_version=parser_version, expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()), ) try: with db.session.begin_nested(): db.session.add(candidate) db.session.flush() intake = candidate except IntegrityError: # 并发他事务已插入:回落锁定已有行并幂等继续 intake = _lock_intake_for_asset_purpose_parser( asset_id=int(asset.id), purpose=purpose, parser_version=parser_version, ) if intake is None: raise if purpose == 'shipping_notice' and provided_batch_id and intake.upload_batch_id != batch_id: db.session.rollback() raise ConflictError( code='SHIPPING_NOTICE.UPLOAD_BATCH_MISMATCH', message='Uploaded asset already belongs to another input batch', ) # [STEP 1.5] 业务 Intake 挂接上传 Submission,并固化 eml|direct_pdf 来源。 if purpose == 'shipping_notice': _link_intake_to_upload_submission( intake=intake, asset=asset, user_id=int(user_id), upload_batch_id=str(intake.upload_batch_id), conversation_id=conv, ) # [STEP 2] 终态 / 已在飞 / 禁止复活 status_now = str(intake.parse_status or '') if status_now in {'parsed', 'consumed', 'queued', 'parsing'}: db.session.commit() return serialize_intake(intake, asset=asset) if status_now == 'cancelled': db.session.rollback() raise ConflictError( code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='接入已取消,无法再次创建', ) now = datetime.utcnow() if status_now == 'expired' or ( intake.expires_at is not None and intake.expires_at < now ): if status_now != 'expired': intake.parse_status = 'expired' intake.updated_at = now db.session.commit() else: db.session.rollback() raise ConflictError( code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入已过期,请重新上传文件', ) if status_now not in {'created', 'parse_failed'}: db.session.rollback() raise ConflictError( code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='当前接入状态不允许再次创建', ) # [STEP 3] 持锁重投解析(仅 created / parse_failed) intake.parse_status = 'queued' intake.conversation_id = conv or intake.conversation_id intake.error_code = None intake.error_message = None intake.parse_lease = None intake.updated_at = now # 与 retry 一致:仅复用 queued,不复用残留 running,避免挂到僵尸 Job 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=('等待解析订单模板样本' if purpose == ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE else '等待预解析发货通知'), max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3), dedupe_active=True, dedupe_statuses=QUEUED_ONLY_STATUSES, commit=False, ) 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]]: """列出会话下未消费的活跃接入记录,供页面恢复。""" conv = str(conversation_id or '').strip() query = db.session.query(ShippingOrderIntake, FileAsset).join( FileAsset, FileAsset.id == ShippingOrderIntake.asset_id ).filter( ShippingOrderIntake.user_id == int(user_id), ShippingOrderIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})), ShippingOrderIntake.consumed_at.is_(None), ) if conv: query = query.filter(ShippingOrderIntake.conversation_id == conv) rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all() return [ serialize_intake( intake, asset=asset, include_candidate_details=False, ) 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(ShippingOrderIntake, FileAsset) .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id) .filter( ShippingOrderIntake.user_id == int(user_id), ShippingOrderIntake.intake_no.in_(normalized), ) .all() ) return [ serialize_intake( intake, asset=asset, include_candidate_details=False, ) for intake, asset in rows ] def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: """ 重试解析:parse_failed,或顶层已 parsed 但附件不完整(含文本预算耗尽)。 核心逻辑:FOR UPDATE 持锁复检;仅复用真正 queued 的 Job(不复用 running); enqueue(commit=False) 与 queued/parse_job_id 同一事务提交,避免半提交窗口。 """ from app.jobs.queue import QUEUED_ONLY_STATUSES normalized = str(intake_no or '').strip().upper() intake = ( db.session.query(ShippingOrderIntake) .filter( ShippingOrderIntake.intake_no == normalized, ShippingOrderIntake.user_id == int(user_id), ) .execution_options(populate_existing=True) .with_for_update() .first() ) if intake is None: raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在') if intake.consumed_at is not None or intake.parse_status == 'consumed': raise ConflictError( code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费', ) if intake.parse_status == 'cancelled': raise ConflictError( code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='接入已取消,无法重试解析', ) structured = ( intake.structured_result_json if isinstance(intake.structured_result_json, dict) else None ) allow_retry = intake.parse_status == 'parse_failed' or ( intake.parse_status == 'parsed' and is_attachment_parse_incomplete(structured) ) if not allow_retry: 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 intake.parse_lease = 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), dedupe_active=True, dedupe_statuses=QUEUED_ONLY_STATUSES, commit=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: """ 取消未消费的接入记录。 核心逻辑:FOR UPDATE 锁定后幂等取消;删除阶段二 Document/Candidate、释放派生引用, 并清理 structured_result 中的阶段二投影字段,避免并发双释放与摘要自相矛盾。 """ from app.services.shipping_notice.document_candidate_persist import ( clear_intake_stage2_structured_projection, release_unconsumed_intake_stage2, ) normalized = str(intake_no or '').strip().upper() intake = ( db.session.query(ShippingOrderIntake) .filter( ShippingOrderIntake.intake_no == normalized, ShippingOrderIntake.user_id == int(user_id), ) .execution_options(populate_existing=True) .with_for_update() .first() ) if intake is None: raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在') if intake.consumed_at is not None or intake.parse_status == 'consumed': raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费') if intake.parse_status == 'cancelled': # 已取消:幂等返回,禁止再次释放引用 return release_unconsumed_intake_stage2(intake=intake) clear_intake_stage2_structured_projection(intake) intake.parse_status = 'cancelled' intake.parse_lease = None intake.updated_at = datetime.utcnow() db.session.commit() def can_force_create_shipping_duplicate(user: User | None) -> bool: """判断用户是否可强制新建重复发货通知。""" if user is None: return False return bool(user.has_feature_permission('shipping_notice_force_create')) def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[str, Any]: """ 重新执行重复检测并写回。 核心逻辑:FOR UPDATE 锁定 Intake 后确认仍为 parsed 且未消费; 与 cancel 同序持锁再改 Candidate,避免并发删除导致 StaleDataError/死锁。 """ from app.services.shipping_notice.duplicate_detection import ( classify_task_lifecycle, refresh_candidates_and_aggregate_intake, ) from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary normalized = str(intake_no or '').strip().upper() intake = ( db.session.query(ShippingOrderIntake) .filter( ShippingOrderIntake.intake_no == normalized, ShippingOrderIntake.user_id == int(user_id), ) .execution_options(populate_existing=True) .with_for_update() .first() ) if intake is None: raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在') # 持锁后复检,避免与 cancel/consume 竞态 if intake.consumed_at is not None or intake.parse_status == 'consumed': raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费') if intake.parse_status == 'cancelled': raise ConflictError(code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='接入已取消,无法刷新重复检测') if intake.parse_status != 'parsed': raise ConflictError(code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='仅已解析接入可刷新重复检测') asset = _load_asset_for_intake(intake) structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None if not business_summary: # 旧 Intake 没有冻结 Schema 时不重新猜测表头;正式订单结果只由 Run 锁定版本产生。 business_summary = parse_intake_business_summary( extracted_text=str(intake.extracted_text or ''), source_type='manual', schema_definition={'fields': []}, ) structured = {**structured, 'business_summary': business_summary} intake.structured_result_json = structured refresh_candidates_and_aggregate_intake(intake=intake, parent_asset=asset) db.session.commit() return serialize_intake(intake, asset=asset) def resolve_intake_duplicate( *, user_id: int, intake_no: str, action: str, target_task_no: str | None = None, reason: str | None = None, actor: User | None = None, ) -> dict[str, Any]: """ 保存重复决策(建单前)。 核心逻辑:刷新检测 → 校验动作/目标任务/权限与原因 → 写入 duplicate_resolution*。 """ action_norm = str(action or '').strip().lower() if action_norm not in _DUPLICATE_RESOLUTIONS: raise ValidationError(code='VALIDATION.INVALID_PARAM', message='无效的重复处理动作') # [STEP 1] 先刷新检测,避免基于陈旧结果决策 refreshed = refresh_intake_duplicate_detection(user_id=user_id, intake_no=intake_no) intake = get_intake_for_user(intake_no, user_id) dup = refreshed.get('duplicate') if isinstance(refreshed.get('duplicate'), dict) else {} matches = list(dup.get('matches') or []) if not matches and action_norm != 'force_create': # 无命中时不允许 open/revision;允许清除决策视同 none —— 此处直接返回 intake.duplicate_resolution = None intake.duplicate_target_task_no = None intake.duplicate_resolution_reason = None db.session.commit() asset = _load_asset_for_intake(intake) return serialize_intake(intake, asset=asset) target_no = str(target_task_no or '').strip().upper() if not target_no and matches: target_no = str(matches[0].get('task_no') or '').strip().upper() if action_norm in {'open_existing', 'create_revision', 'force_create'} and matches: if not target_no or not any(str(m.get('task_no') or '').upper() == target_no for m in matches): raise NotFoundError( code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在或不在命中列表中', ) target_task = None if target_no: target_task = ( db.session.query(ShippingNotice) .filter(ShippingNotice.task_no == target_no, ShippingNotice.user_id == int(user_id)) .first() ) if not target_task: raise NotFoundError( code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在', ) # 目标状态相对检测结果漂移 match_row = next((m for m in matches if str(m.get('task_no') or '').upper() == target_no), None) if match_row and ( str(match_row.get('lifecycle') or '').strip().lower() != str(classify_task_lifecycle(target_task) or '').strip().lower() ): raise ConflictError( code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED', message='目标任务状态已变化,请重新确认', ) if action_norm == 'force_create': user = actor or db.session.get(User, int(user_id)) if not can_force_create_shipping_duplicate(user): raise ForbiddenError( code='SHIPPING_NOTICE.DUPLICATE_OVERRIDE_FORBIDDEN', message='无权强制新建重复发货通知', ) if not str(reason or '').strip(): raise ValidationError( code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED', message='强制新建必须填写原因', ) if action_norm == 'create_revision' and target_task is not None: # 修订永远允许对 irreversible;open 也允许 pass if action_norm == 'open_existing' and target_task is None: raise NotFoundError( code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='打开已有任务需要有效目标', ) intake.duplicate_resolution = action_norm intake.duplicate_target_task_no = target_no or None intake.duplicate_resolution_reason = str(reason or '').strip() or None intake.duplicate_resolved_by_id = int(user_id) intake.duplicate_resolved_at = datetime.utcnow() intake.updated_at = datetime.utcnow() db.session.commit() asset = _load_asset_for_intake(intake) return serialize_intake(intake, asset=asset) def mark_intakes_consumed( *, intakes: list[ShippingOrderIntake], batch_id: int | None, task_ids_by_intake: dict[int, int] | None = None, ) -> None: """ 标记 intake 为 consumed 并增加资产引用计数。 核心逻辑:可在建单 commit 前预占(batch_id 已废弃,仅保留参数兼容); 以 consumed_task_id / consumed_at 标记消费,避免 FOR UPDATE 释放后并发双消费。 """ del batch_id # co8 起 shipping_batches / consumed_batch_id 已删除 now = datetime.utcnow() task_map = task_ids_by_intake or {} for intake in intakes: intake.parse_status = 'consumed' intake.consumed_at = now 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)