From ceb49461e85fbe1f06427fc38e404d4b67546840 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 14 Jul 2026 21:12:36 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=8F=91=E8=B4=A7=E9=80=9A=E7=9F=A5=E9=87=8D=E5=A4=8D=E6=A3=80?= =?UTF-8?q?=E6=B5=8B=E4=B8=8E=E5=A4=84=E7=90=86=E6=8E=A5=E5=8F=A3=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=87=8D=E5=A4=8D=E5=86=B3=E7=AD=96=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E4=B8=8E=E9=87=8D=E6=96=B0=E6=89=A7=E8=A1=8C=E6=A3=80?= =?UTF-8?q?=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/workspace/shipping_notice.py | 37 + backend/app/core/config/settings.py | 17 +- .../jobs/handlers/shipping_notice_parse.py | 280 +- backend/app/jobs/queue.py | 830 +++- backend/app/jobs/runner.py | 14 +- backend/app/jobs/store.py | 18 +- backend/app/models/__init__.py | 4 + backend/app/models/file_asset.py | 25 +- backend/app/models/job.py | 21 +- backend/app/models/shipping.py | 184 +- backend/app/models/user.py | 2 + backend/app/services/file_assets/service.py | 445 ++- .../shipping_notice/attachment_integrity.py | 82 + .../batch_create_idempotency.py | 5 + .../shipping_notice/batch_from_intakes.py | 551 ++- .../shipping_notice/batch_from_notices.py | 9 +- .../shipping_notice/business_fingerprint.py | 173 + .../shipping_notice/chat_action_handlers.py | 25 + .../shipping_notice/decision_workflow.py | 3 +- .../document_candidate_persist.py | 645 +++ .../shipping_notice/duplicate_detection.py | 609 +++ .../app/services/shipping_notice/eml_parse.py | 1195 ++++++ .../shipping_notice/intake_business_parser.py | 76 + .../shipping_notice/intake_parse_workflow.py | 783 +++- .../shipping_notice/intake_service.py | 524 ++- .../shipping_notice/inventory_rpa_workflow.py | 5 +- .../shipping_notice/inventory_source_gate.py | 30 +- .../services/shipping_notice/notice_upload.py | 55 +- .../services/shipping_notice/parse_summary.py | 1 + .../services/shipping_notice/query_service.py | 43 +- .../services/shipping_notice/queue_service.py | 42 +- .../services/shipping_notice/task_workflow.py | 127 +- .../app/services/shipping_notice/ui_state.py | 91 +- .../config/shipping_inventory_sources.yaml | 1 + ...ipping_business_dedup_and_task_versions.py | 136 + .../a6b7c8d9e0f1_add_intake_parse_lease.py | 34 + .../b7c8d9e0f1a2_jobs_parse_active_unique.py | 145 + ...ntake_idempotency_and_supersedes_unique.py | 51 + ...repair_intake_parse_job_id_after_dedupe.py | 76 + ...c8_shipping_notice_documents_candidates.py | 238 ++ ...8d9_stage2_idempotency_and_candidate_fk.py | 225 ++ ...7c8d9e0_file_asset_partial_unique_alive.py | 181 + backend/tests/test_shipping_notice_batches.py | 37 + .../test_shipping_notice_business_dedup.py | 750 ++++ backend/tests/test_shipping_notice_extract.py | 1102 +++++- backend/tests/test_shipping_notice_intakes.py | 3454 ++++++++++++++++- ...t_shipping_notice_inventory_source_gate.py | 141 +- .../shipping-notice/inventory_source_plan.md | 9 +- docs/features/shipping-notice/technical.md | 141 +- docs/funclist.md | 6 +- .../src/features/chat/api/shipping.api.ts | 25 + .../features/chat/components/ChatInputBar.vue | 116 +- .../chat/components/ChatViewContent.vue | 1 + .../chat/components/ChatViewOverlays.vue | 10 + .../ShippingBatchWorkspaceDrawer.vue | 55 +- .../ShippingNoticeDuplicateDialog.vue | 201 + .../features/chat/composables/useChatPage.ts | 7 + .../chat/composables/useChatShipping.ts | 74 + .../shippingNoticeAttachmentIntegrity.spec.ts | 56 + .../shippingNoticeAttachmentIntegrity.ts | 54 + .../shipping/useChatShippingSendHandler.ts | 7 + .../chat/shipping/useShippingNoticeIntakes.ts | 122 +- .../features/chat/types/shipping.api.types.ts | 53 + .../src/features/chat/types/shipping.types.ts | 71 + frontend/src/locales/en/chat.json | 38 +- frontend/src/locales/en/errors.json | 12 +- frontend/src/locales/th/chat.json | 38 +- frontend/src/locales/th/errors.json | 12 +- frontend/src/locales/zh-CN/chat.json | 38 +- frontend/src/locales/zh-CN/errors.json | 12 +- frontend/src/locales/zh-TW/chat.json | 38 +- frontend/src/locales/zh-TW/errors.json | 12 +- 72 files changed, 14270 insertions(+), 460 deletions(-) create mode 100644 backend/app/services/shipping_notice/attachment_integrity.py create mode 100644 backend/app/services/shipping_notice/business_fingerprint.py create mode 100644 backend/app/services/shipping_notice/document_candidate_persist.py create mode 100644 backend/app/services/shipping_notice/duplicate_detection.py create mode 100644 backend/app/services/shipping_notice/eml_parse.py create mode 100644 backend/app/services/shipping_notice/intake_business_parser.py create mode 100644 backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py create mode 100644 backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py create mode 100644 backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py create mode 100644 backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py create mode 100644 backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py create mode 100644 backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py create mode 100644 backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py create mode 100644 backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py create mode 100644 backend/tests/test_shipping_notice_business_dedup.py create mode 100644 frontend/src/features/chat/components/ShippingNoticeDuplicateDialog.vue create mode 100644 frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts create mode 100644 frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.ts diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 81471d71..500de75c 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -664,6 +664,43 @@ def workspace_cancel_shipping_notice_intake(intake_no: str): return _ok({'cancelled': True}) +@workspace_shipping_notice_bp.route( + '/shipping-notice/intakes//duplicate-resolution', + methods=['POST'], +) +def workspace_resolve_shipping_notice_duplicate(intake_no: str): + """保存发货通知重复检测决策。""" + user = _require_user() + body = request.get_json(silent=True) or {} + action = str(body.get('action') or '').strip() + target_task_no = str(body.get('target_task_no') or '').strip() or None + reason = str(body.get('reason') or '').strip() or None + from app.services.shipping_notice.intake_service import resolve_intake_duplicate + + return _ok( + resolve_intake_duplicate( + user_id=user.id, + intake_no=intake_no, + action=action, + target_task_no=target_task_no, + reason=reason, + actor=user, + ) + ) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/intakes//duplicate-refresh', + methods=['POST'], +) +def workspace_refresh_shipping_notice_duplicate(intake_no: str): + """重新执行重复检测。""" + user = _require_user() + from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection + + return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no)) + + @workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST']) def workspace_create_shipping_batch_from_intakes(): """从已解析接入记录确认建批。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index a6d5f8eb..49a4cabb 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -376,7 +376,22 @@ class Config: 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') + SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6') + # EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本) + # parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析 + # parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文 + SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20')) + SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int( + os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024)) + ) + SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES = int( + os.getenv('SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES', str(50 * 1024 * 1024)) + ) + SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH = int(os.getenv('SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH', '3')) + # EML 全部附件 extracted_text 写入 structured_result_json 的合计字符上限 + SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int( + os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000)) + ) class DevelopmentConfig(Config): diff --git a/backend/app/jobs/handlers/shipping_notice_parse.py b/backend/app/jobs/handlers/shipping_notice_parse.py index 95cbeb67..5993b517 100644 --- a/backend/app/jobs/handlers/shipping_notice_parse.py +++ b/backend/app/jobs/handlers/shipping_notice_parse.py @@ -2,101 +2,275 @@ 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,避免用户取消后被重新解析。 +依赖:jobs.context、jobs.registry、intake_parse_workflow、queue.fail/finish。 +逻辑:领取时写入 parse_lease="{job_id}:{attempts}";写回/失败清理均校验 lease; + Job 收口一律 finish_job/fail_job(owned_attempt=...) 条件 UPDATE, + 禁止依赖 Session 身份映射判断执行权。 """ from __future__ import annotations +import uuid from datetime import datetime +from sqlalchemy import and_, or_, update + from app import db -from app.core.errors import NotFoundError +from app.core.errors import AppError, 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 +from app.services.shipping_notice.intake_parse_workflow import ( + fail_intake_with_stage2_cleanup, + run_intake_parse, +) -# 终态:不可再领取解析;含用户取消与 TTL 过期 -_SKIP_CLAIM_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'}) -# 允许领取进入 parsing 的状态(含失败后重试) -_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parsing', 'parse_failed'}) +# 真终态:无论 Job 身份都不再领取 +_TERMINAL_SKIP_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'}) +# 正常可领取进入 parsing +_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parse_failed'}) def _load_asset(asset_id: int) -> FileAsset: + """ + 加载父级 FileAsset;软删或不存在则抛 NotFoundError。 + + Args: + asset_id: FileAsset 主键。 + + Returns: + 可用的 FileAsset。 + + Raises: + NotFoundError: 资产不存在或已软删。 + """ 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 +def _build_parse_lease(*, job_id: int | None, owned_attempt: int | None) -> str: + """ + 构造本轮解析执行代次 token。 + + 核心逻辑:有 Job 时使用 "{job_id}:{attempts}",与 claim_next_job 递增的 attempts 对齐; + 无 Job(单测直调)时使用随机 UUID。 + """ + if job_id is not None and owned_attempt is not None: + return f'{int(job_id)}:{int(owned_attempt)}' + return uuid.uuid4().hex + + +def _claim_intake_for_parsing( + intake_no: str, + *, + job_id: int | None, + owned_attempt: int | None, +) -> tuple[ShippingNoticeIntake, str] | None: + """ + 原子领取 Intake 并轮转 parse_lease。 + + 核心逻辑:仅 created/queued/parse_failed,或 parsing 且 parse_job_id 精确等于当前 Job + (回收漏同步时由新 attempts 轮转 lease,旧 lease 立即失效)。 + + Returns: + (Intake, lease) 或 None。 + """ + now = datetime.utcnow() + lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt) + claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES)) + if job_id is not None: + claim_predicate = or_( + claim_predicate, + and_( + ShippingNoticeIntake.parse_status == 'parsing', + ShippingNoticeIntake.parse_job_id == int(job_id), + ), + ) + values: dict = { + 'parse_status': 'parsing', + 'parse_lease': lease, + 'updated_at': now, + } + if job_id is not None: + values['parse_job_id'] = int(job_id) + stmt = ( + update(ShippingNoticeIntake) + .where( + ShippingNoticeIntake.intake_no == intake_no, + claim_predicate, + ) + .values(**values) + ) + result = db.session.execute(stmt) + if int(result.rowcount or 0) != 1: + db.session.rollback() + return None + db.session.commit() + intake = ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no=intake_no) + .first() + ) + if intake is None: + return None + return intake, lease + + +def _is_retryable_exc(exc: BaseException) -> bool: + """业务 NotFound / AppError.retryable=False 视为不可再排队。""" + if isinstance(exc, NotFoundError): + return False + if isinstance(exc, AppError): + return bool(getattr(exc, 'retryable', False)) + return True + + @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 + job_id = int(job.id) if job is not None else None + # claim_next_job 已递增 attempts;该值即本轮执行代次(收口必须带入条件 UPDATE) + owned_attempt = int(job.attempts or 0) if job is not None 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') + if job_id is not None: + fail_job( + job_id, + error='missing intake_no', + retryable=False, + owned_attempt=owned_attempt, + ) + return 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}) + if job_id is not None: + fail_job( + job_id, + error=f'intake not found: {intake_no}', + retryable=False, + owned_attempt=owned_attempt, + ) return - intake.parse_status = 'parsing' - intake.updated_at = datetime.utcnow() - db.session.commit() + # [STEP 1] 真终态跳过 + if intake.parse_status in _TERMINAL_SKIP_STATUSES: + if job_id is not None: + finish_job( + job_id, + result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True}, + owned_attempt=owned_attempt, + ) + return + + # [STEP 1b] parsing 但非本 Job:另一 worker 持有 → 跳过 + if ( + intake.parse_status == 'parsing' + and job_id is not None + and ( + intake.parse_job_id is None + or int(intake.parse_job_id) != int(job_id) + ) + ): + finish_job( + job_id, + result={'status': 'parsing', 'intake_no': intake_no, 'skipped': True}, + owned_attempt=owned_attempt, + ) + return + + # [STEP 2] 原子领取并轮转 lease + claimed = _claim_intake_for_parsing( + intake_no, job_id=job_id, owned_attempt=owned_attempt + ) + if claimed is None: + current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first() + if job_id is not None: + finish_job( + job_id, + result={ + 'status': str(getattr(current, 'parse_status', None) or 'unknown'), + 'intake_no': intake_no, + 'skipped': True, + }, + owned_attempt=owned_attempt, + ) + return + + intake, parse_lease = claimed + intake_id = int(intake.id) + preserved_parser = str(intake.parser_version or 'v6') + preserved_text = intake.extracted_text + preserved_structured = ( + dict(intake.structured_result_json) + if isinstance(intake.structured_result_json, dict) + else {} + ) + preserved_warnings = list(intake.parse_warnings_json or []) - 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, - ) + asset = _load_asset(intake.asset_id) + result = run_intake_parse(intake, asset, parse_lease=parse_lease) + if job_id is None: + return + status = str(result.get('status') or '') + if status in {'parsed', 'skipped'}: + finish_job( + job_id, + result=result, + message=( + '发货通知预解析完成' + if status == 'parsed' + else '接入已取消、过期或执行代次失效,跳过' + ), + owned_attempt=owned_attempt, + ) + else: + fail_job( + job_id, + error=str(result.get('error_message') or 'parse failed'), + retryable=False, + owned_attempt=owned_attempt, + ) 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 + error_code = getattr(exc, 'code', None) or 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' + fail_result = fail_intake_with_stage2_cleanup( + intake_id=intake_id, + intake_no=intake_no, + parser_version=preserved_parser, + error_code=str(error_code), + error_message=str(exc)[:1000], + extracted_text=preserved_text, + structured_result_json=preserved_structured, + parse_warnings_json=preserved_warnings, + allowed_statuses=frozenset({'parsing', 'queued', 'created'}), + required_lease=parse_lease, + ) + # 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回) + if str(fail_result.get('reason') or '') == 'stale_parse_lease': + return + retryable = _is_retryable_exc(exc) + if job_id is not None: + fail_job( + job_id, + error=str(exc), + retryable=retryable, + owned_attempt=owned_attempt, + ) + if retryable: + raise diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py index e14b7e1a..3db86f52 100644 --- a/backend/app/jobs/queue.py +++ b/backend/app/jobs/queue.py @@ -2,17 +2,25 @@ backend/app/jobs/queue.py 用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。 -依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。 -逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。 +依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层; + shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。 +逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环; + recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE; + enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job; + running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled; + 替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。 """ from __future__ import annotations import socket from datetime import datetime, timedelta +from collections.abc import Callable, Sequence from typing import Any from flask import current_app -from sqlalchemy.exc import OperationalError +from sqlalchemy import update +from sqlalchemy.exc import IntegrityError, OperationalError +from sqlalchemy.orm import Session from app import db from app.core.errors import ValidationError @@ -20,7 +28,43 @@ from app.jobs.types import JobType from app.models import Job ACTIVE_STATUSES = ("queued", "running") +QUEUED_ONLY_STATUSES = ("queued",) TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled") +# 与 models.Job.uq_jobs_shipping_parse_queued_ref 对齐 +_PARSE_QUEUED_UNIQUE_TYPE = JobType.SHIPPING_NOTICE_PARSE.value + + +def _orm_session() -> Session: + """ + 取得底层 Session。 + + scoped_session 代理不转发 in_transaction/get_transaction,须解包后使用。 + """ + return db.session() + + +def _ensure_outer_dbapi_transaction(session: Session) -> None: + """ + 确保 begin_nested() 不会成为数据库最外层事务。 + + 核心逻辑:SQLite 在尚未 BEGIN 时执行 SAVEPOINT,随后 RELEASE 等价于 COMMIT, + 会破坏 commit=False / 外层 rollback。先 materialize 连接事务;SQLite 必要时 + 显式 DBAPI BEGIN(已在事务中则忽略)。 + """ + if not session.in_transaction(): + session.begin() + bind = session.connection() + if str(bind.dialect.name or "") != "sqlite": + return + dbapi_conn = bind.connection.dbapi_connection + in_txn = getattr(dbapi_conn, "in_transaction", None) + if callable(in_txn) and in_txn(): + return + try: + dbapi_conn.execute("BEGIN") + except Exception: + # 已在事务中:sqlite 会报错,可安全忽略 + pass def _normalize_job_type(job_type: JobType | str) -> str: @@ -28,6 +72,242 @@ def _normalize_job_type(job_type: JobType | str) -> str: return str(getattr(job_type, "value", job_type) or "").strip() +def _subject_to_parse_queued_unique(job_type: str | None) -> bool: + """是否受 shipping_notice_parse queued 部分唯一索引约束。""" + return str(job_type or "").strip() == _PARSE_QUEUED_UNIQUE_TYPE + + +def _lock_other_active_parse_job( + *, + domain: str, + job_type: str, + business_ref: str | None, + exclude_id: int, +) -> Job | None: + """ + FOR UPDATE 锁定同业务锚点下优先级最高的 queued/running 预解析 Job。 + + 核心逻辑:queued 受部分唯一索引保护且天然可安全替代,因此必须优先于 + running;仅无 queued 时才按最小 id 选择 running,并交由 + `_is_safe_supersede_target` 校验精确 Intake lease。持锁期间 Worker 的 + claim(SKIP LOCKED)会跳过最终候选。 + + Args: + domain / job_type / business_ref: 与待降级 Job 相同的锚点。 + exclude_id: 排除自身主键。 + + Returns: + 锁定的最高优先级同伴;没有则 None。 + """ + ref = str(business_ref or "").strip() or None + if not ref: + return None + return ( + db.session.query(Job) + .filter( + Job.domain == str(domain), + Job.job_type == str(job_type), + Job.business_ref == ref, + Job.status.in_(("queued", "running")), + Job.id != int(exclude_id), + ) + .order_by((Job.status == "queued").desc(), Job.id.asc()) + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + + +def _parse_lease_for_job(job: Job) -> str: + """构造 `{job_id}:{attempts}` 执行代次 lease。""" + return f"{int(job.id)}:{int(job.attempts or 0)}" + + +def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool: + """ + 判定锁定的同伴是否可安全取代旧 running Job。 + + 核心逻辑: + - queued:可 supersede(旧取消,Intake 回到排队挂 keep); + - running:仅当 Intake 已明确持有该 Job 的精确 parse_job_id + parse_lease + (Worker 已真正 claim Intake)。否则可能 Worker 已按旧 id 决定 skip+finish, + 若此时伪造 lease 会导致 Intake 永久 parsing。 + + Returns: + True 表示可取消旧 Job 并重指;False 表示应让旧 Job 正常 requeue。 + """ + db.session.refresh(sibling) + status = str(sibling.status or "") + if status == "queued": + return True + if status != "running": + return False + + from app.models import ShippingNoticeIntake + + intake_no = str( + (cancelled_job.payload_json or {}).get("intake_no") + or cancelled_job.business_ref + or sibling.business_ref + or "" + ).strip().upper() + if not intake_no: + return False + locked = ( + db.session.query(ShippingNoticeIntake) + .filter(ShippingNoticeIntake.intake_no == intake_no) + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + if locked is None: + return False + expected_lease = _parse_lease_for_job(sibling) + return ( + str(locked.parse_status or "") == "parsing" + and locked.parse_job_id is not None + and int(locked.parse_job_id) == int(sibling.id) + and str(locked.parse_lease or "") == expected_lease + ) + + +def _resolve_safe_supersede_sibling( + *, + domain: str, + job_type: str, + business_ref: str | None, + exclude_id: int, + cancelled_job: Job, +) -> Job | None: + """ + 锁定同伴并过滤为可安全 supersede 的目标;不安全则视为无替代者。 + """ + sibling = _lock_other_active_parse_job( + domain=domain, + job_type=job_type, + business_ref=business_ref, + exclude_id=exclude_id, + ) + if sibling is None: + return None + if not _is_safe_supersede_target(sibling, cancelled_job=cancelled_job): + return None + return sibling + + +def _retarget_intake_parse_job_after_supersede( + *, + cancelled_job: Job, + keep_job: Job, +) -> None: + """ + 旧 running 预解析 Job 被安全同伴取代时,同事务重指 Intake.parse_job_id。 + + 核心逻辑:FOR UPDATE Intake 后复检 keep_job.status—— + keep 仍为 queued:parsing→queued 并清 parse_lease; + keep 已 running:仅在 Intake 已持有其精确 lease 时保留状态,绝不伪造 lease + (否则会踩到已决定 skip+finish 的 Worker,造成永久 parsing)。 + """ + if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")): + return + from app.models import ShippingNoticeIntake + + intake_no = str( + (cancelled_job.payload_json or {}).get("intake_no") + or cancelled_job.business_ref + or "" + ).strip().upper() + if not intake_no: + return + + # 锁内复检同伴状态(调用方应已 FOR UPDATE keep_job) + db.session.refresh(keep_job) + keep_status = str(keep_job.status or "") + if keep_status not in {"queued", "running"}: + return + + locked = ( + db.session.query(ShippingNoticeIntake) + .filter(ShippingNoticeIntake.intake_no == intake_no) + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + if locked is None: + return + current_job_id = int(locked.parse_job_id) if locked.parse_job_id is not None else None + cancelled_id = int(cancelled_job.id) + keep_id = int(keep_job.id) + # 已指向第三方 Job:不抢占 + if current_job_id is not None and current_job_id not in {cancelled_id, keep_id}: + return + now = datetime.utcnow() + current_lease = str(locked.parse_lease or "") or None + status_now = str(locked.parse_status or "") + + if keep_status == "queued": + if current_job_id in {cancelled_id, None}: + locked.parse_job_id = keep_id + # 仅当仍挂旧 Job/旧代次时才打回 queued,避免清掉 keep 新 Worker 的 lease + if status_now == "parsing" and ( + current_job_id == cancelled_id + or current_lease is None + or str(current_lease).startswith(f"{cancelled_id}:") + ): + locked.parse_status = "queued" + locked.parse_lease = None + locked.updated_at = now + return + + # keep 已 running:只保留已真正接管的状态,禁止伪造 lease 转移 + keep_lease = _parse_lease_for_job(keep_job) + if ( + status_now == "parsing" + and current_job_id == keep_id + and current_lease == keep_lease + ): + locked.updated_at = now + return + # 未真正接管:调用方本不应 supersede;此处 no-op 防误伤 + return + + +def _cancel_running_job_superseded( + *, + job_id: int, + now: datetime, + message: str, + owned_attempt: int | None = None, + snap_attempts: int | None = None, +) -> int: + """ + 将仍为 running 的 Job 标为 cancelled(已被新 queued 取代)。 + + Returns: + 条件 UPDATE 影响行数。 + """ + where = [Job.id == int(job_id), Job.status == "running"] + if owned_attempt is not None: + where.append(Job.attempts == int(owned_attempt)) + elif snap_attempts is not None: + where.append(Job.attempts == int(snap_attempts)) + stmt = ( + update(Job) + .where(*where) + .values( + status="cancelled", + progress=100, + message=str(message or "已被新的 queued Job 取代")[:500], + locked_by=None, + locked_at=None, + started_at=None, + finished_at=now, + updated_at=now, + ) + ) + return int(db.session.execute(stmt).rowcount or 0) + + def _worker_id() -> str: """生成当前 worker 标识,用于锁记录和排障。""" try: @@ -103,12 +383,19 @@ def enqueue( max_attempts: int = 3, message: str | None = None, dedupe_active: bool = True, + dedupe_statuses: Sequence[str] | None = None, + commit: bool = True, correlation_id: str | None = None, scheduled_at: Any = None, ) -> int: """ 将任务写入通用 jobs 队列并返回 job id。 + 核心逻辑:先按 domain/type/business_ref + dedupe_statuses 查复用; + 无则 SAVEPOINT 插入。撞上 shipping_notice_parse 的 queued 部分唯一索引时 + IntegrityError 回读已有 Job(并发双插幂等)。commit=False 时不开自动提交, + 由调用方与业务行同事务提交。 + Args: job_type: 任务类型。 payload: JSON payload。 @@ -118,7 +405,10 @@ def enqueue( priority: 优先级,数值越大越先执行。 max_attempts: 最大尝试次数。 message: 初始状态说明。 - dedupe_active: 是否复用 active 状态的同业务任务。 + dedupe_active: 是否复用同业务键下指定状态中的任务。 + dedupe_statuses: 去重匹配的 Job.status 集合;默认 queued+running。 + 重试场景应传仅 queued,避免复用即将结束的 running Job。 + commit: False 时仅 flush,由调用方与业务行同一事务提交。 correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。 scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。 """ @@ -139,20 +429,26 @@ def enqueue( if not isinstance(payload, dict): raise ValueError("payload must be a dict") - if dedupe_active and normalized_ref: - existing = ( + statuses = tuple(dedupe_statuses) if dedupe_statuses is not None else ACTIVE_STATUSES + + def _find_active_dedupe_job() -> Job | None: + if not (dedupe_active and normalized_ref and statuses): + return None + return ( db.session.query(Job) .filter( Job.domain == normalized_domain, Job.job_type == normalized_type, Job.business_ref == normalized_ref, - Job.status.in_(ACTIVE_STATUSES), + Job.status.in_(statuses), ) .order_by(Job.created_at.desc(), Job.id.desc()) .first() ) - if existing: - return int(existing.id) + + existing = _find_active_dedupe_job() + if existing is not None: + return int(existing.id) now = datetime.utcnow() queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now @@ -171,50 +467,207 @@ def enqueue( created_at=queue_at, updated_at=now, ) - db.session.add(job) - db.session.commit() + # [STEP] SAVEPOINT 边界:仅在 begin_nested 内 add+flush。 + # begin_nested 会先 autoflush pending;若 Job 提前进入 Session,冲突会落在 SAVEPOINT 之外, + # 毒化外层事务并在异常分支触发 PendingRollbackError。 + session = _orm_session() + _ensure_outer_dbapi_transaction(session) + try: + with session.begin_nested(): + session.add(job) + session.flush() + except IntegrityError: + # SAVEPOINT 已回滚;确保失败对象不残留为 pending + try: + session.expunge(job) + except Exception: + pass + # 即使 dedupe_active=False,唯一冲突仍须回落已有 queued(索引层幂等) + raced = _find_active_dedupe_job() + if raced is None and normalized_ref: + raced = ( + db.session.query(Job) + .filter( + Job.domain == normalized_domain, + Job.job_type == normalized_type, + Job.business_ref == normalized_ref, + Job.status == "queued", + ) + .order_by(Job.id.asc()) + .first() + ) + if raced is not None: + return int(raced.id) + raise + if commit: + session.commit() return int(job.id) -def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int: - """回收指定业务域内超时 running 的通用任务。""" +def _job_id(job: Job | int) -> int: + """统一解析 Job 主键。""" + return int(job if isinstance(job, int) else job.id) + + +def recover_stale_jobs( + *, + domain: str, + timeout_seconds: float, + job_type: str | JobType | None = None, + on_recovered: Callable[[Job], None] | None = None, +) -> int: + """ + 回收指定业务域内超时 running 的通用任务。 + + 核心逻辑:FOR UPDATE SKIP LOCKED 领取待回收行,再以 + status=running AND attempts=快照 条件 UPDATE;同事务回调 on_recovered。 + 多 Worker 并发回收时不会双写同一 Job,也不会把已被新 Worker 领取的代次打回 queued。 + 若已存在同锚点 queued 同伴(parse 唯一索引),旧 Job 标 cancelled 并重指 Intake, + 每条更新包在 SAVEPOINT 内,避免单行 IntegrityError 毒化整批回收。 + + Args: + on_recovered: 每条 Job 条件更新成功后、统一 commit 前的回调。 + """ cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds)) - query = ( - db.session.query(Job) - .filter( - Job.domain == domain, - Job.status == "running", - Job.started_at.isnot(None), - Job.started_at < cutoff, - ) + query = db.session.query(Job).filter( + Job.domain == domain, + Job.status == "running", + Job.started_at.isnot(None), + Job.started_at < cutoff, ) normalized_type = _normalize_job_type(job_type) if job_type else "" if normalized_type: query = query.filter(Job.job_type == normalized_type) - stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all() + + try: + stale_jobs = ( + query.order_by(Job.started_at.asc(), Job.id.asc()) + .with_for_update(skip_locked=True) + .all() + ) + except OperationalError: + db.session.rollback() + raise + if not stale_jobs: + db.session.rollback() return 0 + session = _orm_session() + _ensure_outer_dbapi_transaction(session) now = datetime.utcnow() + recovered = 0 for job in stale_jobs: - if int(job.attempts or 0) < int(job.max_attempts or 1): - job.status = "queued" - job.message = "任务执行超时,已回收等待重试" - job.locked_by = None - job.locked_at = None - job.started_at = None - job.updated_at = now + # 锁内复检:可能已被他事务终态化(本连接持锁期间一般仍为 running) + if str(job.status or "") != "running": continue - job.status = "failed" - job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)" - job.message = job.error_message - job.progress = 100 - job.locked_by = None - job.locked_at = None - job.finished_at = now - job.updated_at = now + if job.started_at is None or job.started_at >= cutoff: + continue + snap_attempts = int(job.attempts or 0) + max_attempts = int(job.max_attempts or 1) + job_id = int(job.id) + sibling: Job | None = None + rowcount = 0 + + if snap_attempts < max_attempts: + if _subject_to_parse_queued_unique(str(job.job_type or "")): + try: + sibling = _resolve_safe_supersede_sibling( + domain=str(job.domain), + job_type=str(job.job_type), + business_ref=job.business_ref, + exclude_id=job_id, + cancelled_job=job, + ) + except OperationalError: + # 死锁会使整个事务失败;回滚后由下一轮回收重试 + db.session.rollback() + return 0 + # [STEP] SAVEPOINT:queued 唯一冲突不得毁掉整批外层事务 + try: + with session.begin_nested(): + if sibling is not None: + rowcount = _cancel_running_job_superseded( + job_id=job_id, + now=now, + message="超时回收:已存在安全替代解析 Job,旧 Job 已取消", + snap_attempts=snap_attempts, + ) + else: + result = db.session.execute( + update(Job) + .where( + Job.id == job_id, + Job.status == "running", + Job.attempts == snap_attempts, + ) + .values( + status="queued", + message="任务执行超时,已回收等待重试", + locked_by=None, + locked_at=None, + started_at=None, + updated_at=now, + ) + ) + rowcount = int(result.rowcount or 0) + except IntegrityError: + try: + sibling = _resolve_safe_supersede_sibling( + domain=str(job.domain), + job_type=str(job.job_type), + business_ref=job.business_ref, + exclude_id=job_id, + cancelled_job=job, + ) + except OperationalError: + db.session.rollback() + return 0 + if sibling is None: + continue + with session.begin_nested(): + rowcount = _cancel_running_job_superseded( + job_id=job_id, + now=now, + message="超时回收:queued 唯一冲突,旧 Job 已取消", + snap_attempts=snap_attempts, + ) + else: + timeout_msg = f"任务执行超时(超过 {int(timeout_seconds)}s)" + result = db.session.execute( + update(Job) + .where( + Job.id == job_id, + Job.status == "running", + Job.attempts == snap_attempts, + ) + .values( + status="failed", + error_message=timeout_msg, + message=timeout_msg, + progress=100, + locked_by=None, + locked_at=None, + finished_at=now, + updated_at=now, + ) + ) + rowcount = int(result.rowcount or 0) + + if rowcount != 1: + continue + db.session.expire(job) + db.session.refresh(job) + if str(job.status or "") == "cancelled" and sibling is not None: + _retarget_intake_parse_job_after_supersede( + cancelled_job=job, + keep_job=sibling, + ) + if on_recovered is not None: + on_recovered(job) + recovered += 1 db.session.commit() - return len(stale_jobs) + return recovered def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None: @@ -243,7 +696,8 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, return None job.status = "running" - job.started_at = job.started_at or now + # 每次领取刷新 started_at,避免 fail_job requeue 残留旧时间导致立刻被超时回收 + job.started_at = now job.locked_at = now job.locked_by = worker_id or _worker_id() job.attempts = int(job.attempts or 0) + 1 @@ -254,35 +708,235 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, return job -def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None: - """标记任务成功完成。""" - now = datetime.utcnow() - job.status = "success" - job.progress = 100 - job.result_json = result or {} - job.message = message or "任务处理完成" - job.error_message = None - job.locked_by = None - job.locked_at = None - job.finished_at = now - job.updated_at = now - db.session.commit() +def _sync_parse_intake_after_job_mutation(job_id: int) -> None: + """ + shipping_notice_parse Job 状态变更后同步 Intake(同事务、commit 前)。 + + 核心逻辑:委托 sync_intake_after_parse_job_recovery,覆盖 requeue→queued、 + failed→parse_failed、cancelled→安全重指/终态清理,避免 Intake 永久 parsing。 + """ + job = db.session.get(Job, int(job_id)) + if job is None or not _subject_to_parse_queued_unique(str(job.job_type or "")): + return + db.session.expire(job) + db.session.refresh(job) + from app.services.shipping_notice.intake_parse_workflow import ( + sync_intake_after_parse_job_recovery, + ) + + sync_intake_after_parse_job_recovery(job) -def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None: - """标记任务失败;retryable 且未达上限时重新排队。""" +def finish_job( + job: Job | int, + *, + result: dict[str, Any] | None = None, + message: str | None = None, + owned_attempt: int | None = None, +) -> bool: + """ + 条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。 + + Returns: + 是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。 + """ now = datetime.utcnow() - can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1) - job.status = "queued" if can_retry else "failed" - job.progress = 0 if can_retry else 100 - job.result_json = result or {} - job.error_message = str(error or "job failed")[:1000] - job.message = "任务失败,等待重试" if can_retry else job.error_message - job.locked_by = None - job.locked_at = None - job.finished_at = None if can_retry else now - job.updated_at = now + job_id = _job_id(job) + where = [Job.id == job_id, Job.status == "running"] + if owned_attempt is not None: + where.append(Job.attempts == int(owned_attempt)) + stmt = ( + update(Job) + .where(*where) + .values( + status="success", + progress=100, + result_json=result or {}, + message=message or "任务处理完成", + error_message=None, + locked_by=None, + locked_at=None, + finished_at=now, + updated_at=now, + ) + ) + rowcount = int(db.session.execute(stmt).rowcount or 0) db.session.commit() + cached = db.session.get(Job, job_id) + if cached is not None: + db.session.expire(cached) + return rowcount == 1 + + +def fail_job( + job: Job | int, + *, + error: str, + result: dict[str, Any] | None = None, + retryable: bool = False, + owned_attempt: int | None = None, +) -> bool: + """ + 条件收口失败:仅 running(且可选 attempts 匹配)时改 queued/failed/cancelled。 + + 核心逻辑:retryable 且 attempts 未耗尽时,优先安全 supersede,否则 requeue + (清空 started_at)并同步 Intake;唯一冲突窗口消失时保持 running 返回 False, + 禁止误标 failed。attempts 耗尽则 failed 并同步 Intake 离开 parsing。 + + Returns: + 是否实际更新到一行。 + """ + now = datetime.utcnow() + job_id = _job_id(job) + error_text = str(error or "job failed")[:1000] + payload = result or {} + base_where = [Job.id == job_id, Job.status == "running"] + if owned_attempt is not None: + base_where.append(Job.attempts == int(owned_attempt)) + + session = _orm_session() + _ensure_outer_dbapi_transaction(session) + + def _expire_cached() -> None: + cached = db.session.get(Job, job_id) + if cached is not None: + db.session.expire(cached) + + if retryable: + # 先锁住自身 running 行,再锁同伴,缩短无锁窗口且便于复检 attempts + job_row = ( + db.session.query(Job) + .filter(Job.id == job_id, Job.status == "running") + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + sibling: Job | None = None + if job_row is not None and _subject_to_parse_queued_unique(str(job_row.job_type or "")): + try: + sibling = _resolve_safe_supersede_sibling( + domain=str(job_row.domain), + job_type=str(job_row.job_type), + business_ref=job_row.business_ref, + exclude_id=job_id, + cancelled_job=job_row, + ) + except OperationalError: + db.session.rollback() + return False + + attempts_ok = ( + job_row is not None + and int(job_row.attempts or 0) < int(job_row.max_attempts or 1) + ) + if sibling is not None and attempts_ok: + # 仅安全替代者:取消旧 Job(running 且已真正接管 Intake,或仍为 queued) + rowcount = _cancel_running_job_superseded( + job_id=job_id, + now=now, + message="失败重试:已存在安全替代解析 Job,旧 Job 已取消", + owned_attempt=owned_attempt, + ) + if rowcount == 1: + cancelled = db.session.get(Job, job_id) + if cancelled is not None: + _retarget_intake_parse_job_after_supersede( + cancelled_job=cancelled, + keep_job=sibling, + ) + _sync_parse_intake_after_job_mutation(job_id) + db.session.commit() + _expire_cached() + return True + elif sibling is None and attempts_ok: + # 无安全替代(含:同伴 running 但尚未 claim Intake)→ 正常 requeue + requeue_stmt = ( + update(Job) + .where(*base_where, Job.attempts < Job.max_attempts) + .values( + status="queued", + progress=0, + result_json=payload, + error_message=error_text, + message="任务失败,等待重试", + locked_by=None, + locked_at=None, + started_at=None, + finished_at=None, + updated_at=now, + ) + ) + try: + with session.begin_nested(): + rowcount = int(db.session.execute(requeue_stmt).rowcount or 0) + except IntegrityError: + try: + sibling = ( + _resolve_safe_supersede_sibling( + domain=str(job_row.domain), + job_type=str(job_row.job_type), + business_ref=job_row.business_ref, + exclude_id=job_id, + cancelled_job=job_row, + ) + if job_row is not None + else None + ) + except OperationalError: + db.session.rollback() + return False + if sibling is None: + # 唯一冲突窗口已消失:保持 running,勿强行 failed 造成永久 parsing + db.session.rollback() + return False + with session.begin_nested(): + rowcount = _cancel_running_job_superseded( + job_id=job_id, + now=now, + message="失败重试:queued 唯一冲突,旧 Job 已取消", + owned_attempt=owned_attempt, + ) + if rowcount == 1: + cancelled = db.session.get(Job, job_id) + if cancelled is not None: + _retarget_intake_parse_job_after_supersede( + cancelled_job=cancelled, + keep_job=sibling, + ) + _sync_parse_intake_after_job_mutation(job_id) + db.session.commit() + _expire_cached() + return True + else: + if rowcount == 1: + _sync_parse_intake_after_job_mutation(job_id) + db.session.commit() + _expire_cached() + return True + + # 终态 failed:同步 Intake 离开 parsing,避免永久卡住 + fail_stmt = ( + update(Job) + .where(*base_where) + .values( + status="failed", + progress=100, + result_json=payload, + error_message=error_text, + message=error_text, + locked_by=None, + locked_at=None, + started_at=None, + finished_at=now, + updated_at=now, + ) + ) + rowcount = int(db.session.execute(fail_stmt).rowcount or 0) + if rowcount == 1: + _sync_parse_intake_after_job_mutation(job_id) + db.session.commit() + _expire_cached() + return rowcount == 1 def process_next_job( @@ -293,7 +947,12 @@ def process_next_job( timeout_config_key: str | None = None, default_timeout_seconds: float = 300, ) -> tuple[bool, str]: - """领取并分发一条通用任务。""" + """ + 领取并分发一条通用任务。 + + 核心逻辑:超时回收必须与本次允许领取的 job_types 同范围,避免同 domain + 下其他类型被错误阈值或缺少业务回调的入口提前回收;未指定类型时才回收整个 domain。 + """ import app.jobs.handlers # noqa: F401 from app.jobs.registry import get_handler @@ -302,29 +961,54 @@ def process_next_job( if timeout_config_key else default_timeout_seconds ) - recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds) + normalized_types = list( + dict.fromkeys( + _normalize_job_type(item) + for item in (job_types or []) + if _normalize_job_type(item) + ) + ) + if normalized_types: + for normalized_type in normalized_types: + on_recovered = None + if normalized_type == JobType.SHIPPING_NOTICE_PARSE.value: + from app.services.shipping_notice.intake_parse_workflow import ( + sync_intake_after_parse_job_recovery, + ) + + on_recovered = sync_intake_after_parse_job_recovery + recover_stale_jobs( + domain=domain, + timeout_seconds=timeout_seconds, + job_type=normalized_type, + on_recovered=on_recovered, + ) + else: + recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds) job = claim_next_job(domain=domain, job_types=job_types) if not job: return False, "no_job" job_id = int(job.id) + owned_attempt = int(job.attempts or 0) job_type_value = str(job.job_type or "").strip() payload = dict(job.payload_json or {}) payload.setdefault("job_id", job_id) handler = get_handler(JobType(job_type_value)) if handler is None: - fail_job(job, error=f"no handler registered for {job.job_type}") + fail_job( + job_id, + error=f"no handler registered for {job.job_type}", + owned_attempt=owned_attempt, + ) return True, "missing_handler" try: handler(ctx, payload) - refreshed = db.session.get(Job, job_id) - if refreshed and refreshed.status == "running": - finish_job(refreshed, message="任务处理完成") + # 条件收口:Handler 已 finish/fail 或代次失效时 rowcount=0,不覆盖 + finish_job(job_id, message="任务处理完成", owned_attempt=owned_attempt) return True, job_type_value except Exception as exc: db.session.rollback() - refreshed = db.session.get(Job, job_id) - if refreshed: - fail_job(refreshed, error=str(exc), retryable=True) + fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt) raise diff --git a/backend/app/jobs/runner.py b/backend/app/jobs/runner.py index 00f45aec..5cf994fb 100644 --- a/backend/app/jobs/runner.py +++ b/backend/app/jobs/runner.py @@ -43,13 +43,23 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) continue handler = get_handler(job['job_type']) + owned_attempt = job.get('attempts') + owned_attempt_int = int(owned_attempt) if owned_attempt is not None else None if not handler: ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id')) - store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}') + store.mark_failed( + job['id'], + message=f'no handler for {job.get("job_type")}', + owned_attempt=owned_attempt_int, + ) continue try: handler(ctx, job.get('payload') or {}) except Exception as exc: ctx.logger.exception('Handler failed job_id=%s', job.get('id')) - store.mark_failed(job['id'], message=str(exc)) + store.mark_failed( + job['id'], + message=str(exc), + owned_attempt=owned_attempt_int, + ) diff --git a/backend/app/jobs/store.py b/backend/app/jobs/store.py index 4ac9e98f..5fb59e58 100644 --- a/backend/app/jobs/store.py +++ b/backend/app/jobs/store.py @@ -20,6 +20,8 @@ def _normalize_generic_job(job: Job) -> dict[str, Any]: 'id': job.id, 'job_type': JobType(job_type_value), 'raw_job_type': job_type_value, + # 领取时代次,供异常收口条件 UPDATE(勿信 Session 缓存) + 'attempts': int(job.attempts or 0), 'payload': { 'job_id': job.id, **(job.payload_json or {}), @@ -96,21 +98,29 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None: return None -def mark_failed(job_id: int, *, message: str) -> None: +def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None) -> None: """ handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。 + Args: job_id: 任务主键。 message: 失败原因(截断至 1000 字符)。 + owned_attempt: 领取时的 Job.attempts;通用 Job 用条件 UPDATE,避免覆盖新代次。 """ from datetime import datetime from app import db from app.jobs.queue import fail_job - job = db.session.get(Job, job_id) - if job and job.status == 'running': - fail_job(job, error=message[:1000], retryable=True) + # 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op) + generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first() + if generic is not None: + fail_job( + int(job_id), + error=message[:1000], + retryable=True, + owned_attempt=owned_attempt, + ) return kb_job = db.session.get(KbJob, job_id) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index f076f16f..cbf17dc3 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -21,6 +21,8 @@ from app.models.shipping import ( ShippingBatch, ShippingInventoryFile, ShippingInventoryMapping, + ShippingNoticeCandidate, + ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, ShippingTaskEvent, @@ -69,6 +71,8 @@ __all__ = [ 'ShippingTaskInventoryLink', 'ShippingInventoryMapping', 'ShippingNoticeIntake', + 'ShippingNoticeDocument', + 'ShippingNoticeCandidate', 'FileAsset', 'AgentGuide', 'AgentDirectoryMember', diff --git a/backend/app/models/file_asset.py b/backend/app/models/file_asset.py index e74ef2ab..2b2e1058 100644 --- a/backend/app/models/file_asset.py +++ b/backend/app/models/file_asset.py @@ -3,7 +3,9 @@ backend/app/models/file_asset.py 用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。 依赖:models.base.Base。 -逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 等业务通过 asset_id 引用。 +逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 经 asset_id 引用上传根资产; + EML 解析后的订单附件以 parent_asset_id 挂为 derived 子资产(阶段二); + 派生资产对 (parent_asset_id, content_hash) 使用未删除行的部分唯一索引。 """ from __future__ import annotations @@ -11,7 +13,7 @@ from __future__ import annotations from datetime import datetime from typing import Optional -from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint +from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, text from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base @@ -26,12 +28,31 @@ class FileAsset(Base): 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'), + # 仅约束未删除派生资产,避免 soft-delete 永久阻塞同哈希重资产化 + Index( + 'uq_file_assets_parent_content_hash_alive', + 'parent_asset_id', + 'content_hash', + unique=True, + postgresql_where=text('deleted_at IS NULL AND parent_asset_id IS NOT NULL'), + sqlite_where=text('deleted_at IS NULL AND parent_asset_id IS NOT NULL'), + ), + Index('ix_file_assets_parent_attachment_key', 'parent_asset_id', 'source_attachment_key'), ) 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) + # 派生资产:EML 根资产 → 附件 PDF 等子资产 + parent_asset_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('file_assets.id'), + index=True, + nullable=True, + ) + asset_role: Mapped[str] = mapped_column(String(32), default='upload', nullable=False) + # 派生资产首次落库时的 attachment_key;后续复用同哈希时不覆盖(当前来源见 Document.attachment_key) + source_attachment_key: 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) diff --git a/backend/app/models/job.py b/backend/app/models/job.py index 27d80986..f1a978c1 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -11,7 +11,7 @@ from __future__ import annotations from datetime import datetime from typing import Optional -from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text +from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base @@ -29,6 +29,25 @@ class Job(Base): Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'), Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'), Index('ix_jobs_locked_at', 'locked_at'), + # 仅预解析 Job:同业务锚点同时只允许一条 queued + # (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限) + Index( + 'uq_jobs_shipping_parse_queued_ref', + 'domain', + 'job_type', + 'business_ref', + unique=True, + postgresql_where=text( + "job_type = 'shipping_notice_parse' " + "AND status = 'queued' " + "AND business_ref IS NOT NULL" + ), + sqlite_where=text( + "job_type = 'shipping_notice_parse' " + "AND status = 'queued' " + "AND business_ref IS NOT NULL" + ), + ), ) id: Mapped[int] = mapped_column(primary_key=True) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 0705f597..a72d169c 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -1,9 +1,13 @@ """ backend/app/models/shipping.py -用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。 +用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。 依赖:models.base.Base。 -逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等,二者语义分离。 +逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等; + Intake.create_idempotency_key 承载混合/open_existing 确认请求重放; + Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离; + Document/Candidate 承载阶段二「一邮件多订单」识别;ShippingTask.source_candidate_id 预留给建单; + ShippingTask.supersedes_task_id 唯一约束保证修订链线性。 """ from __future__ import annotations @@ -11,7 +15,20 @@ from __future__ import annotations from datetime import datetime from typing import List, Optional -from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy import ( + Boolean, + DateTime, + Float, + ForeignKey, + ForeignKeyConstraint, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, + text, +) from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base @@ -72,6 +89,10 @@ class ShippingTask(Base): Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'), + Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'), + # 线性版本链:同一父任务至多一个后继(NULL 不冲突) + UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'), + Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -89,6 +110,29 @@ class ShippingTask(Base): index=True, nullable=True, ) + # 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter + source_candidate_id: Mapped[Optional[int]] = mapped_column( + ForeignKey( + 'shipping_notice_candidates.id', + name='fk_shipping_tasks_source_candidate_id', + use_alter=True, + ), + index=True, + nullable=True, + ) + business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + supersedes_task_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_tasks.id'), + nullable=True, + ) + duplicate_source_task_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_tasks.id'), + nullable=True, + ) + duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) @@ -301,6 +345,10 @@ class ShippingNoticeIntake(Base): 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'), + Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'), + Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'), + Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'), + Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -315,16 +363,146 @@ class ShippingNoticeIntake(Base): 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) + # 解析执行代次:格式 "{job_id}:{job.attempts}";超时回收清空后旧 Worker 写回被拒绝 + parse_lease: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + duplicate_status: Mapped[str] = mapped_column( + String(32), + default='unchecked', + server_default=text("'unchecked'"), + nullable=False, + ) + duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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) + create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), 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 ShippingNoticeDocument(Base): + """ + 发货通知文档单元:邮件正文或单个附件(阶段二)。 + + 核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。 + """ + + __tablename__ = 'shipping_notice_documents' + __table_args__ = ( + UniqueConstraint( + 'intake_id', + 'attachment_key', + name='uq_shipping_notice_documents_intake_attachment_key', + ), + # 支撑 Candidate (primary_document_id, intake_id) 复合外键 + UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'), + Index('ix_shipping_notice_documents_intake_id', 'intake_id'), + Index('ix_shipping_notice_documents_asset_id', 'asset_id'), + Index('ix_shipping_notice_documents_content_hash', 'content_hash'), + Index('ix_shipping_notice_documents_parse_status', 'parse_status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + intake_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_intakes.id'), + nullable=False, + ) + asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True) + document_type: Mapped[str] = mapped_column(String(32), nullable=False) + attachment_key: Mapped[str] = mapped_column(String(64), nullable=False) + filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + classification: Mapped[str] = mapped_column(String(32), default='unknown', nullable=False) + parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False) + extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, 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 ShippingNoticeCandidate(Base): + """ + 订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。 + + 核心逻辑:通常 1 Document → 1 Candidate;重复检测与决策落在 Candidate 级,互不影响。 + """ + + __tablename__ = 'shipping_notice_candidates' + __table_args__ = ( + UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'), + UniqueConstraint( + 'intake_id', + 'primary_document_id', + name='uq_shipping_notice_candidates_intake_primary_document', + ), + # 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接 + ForeignKeyConstraint( + ['primary_document_id', 'intake_id'], + ['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'], + name='fk_shipping_notice_candidates_document_intake', + ), + Index('ix_shipping_notice_candidates_intake_id', 'intake_id'), + Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'), + Index('ix_shipping_notice_candidates_po_number', 'po_number'), + Index( + 'ix_shipping_notice_candidates_user_fingerprint', + 'business_fingerprint', + ), + Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + candidate_no: Mapped[str] = mapped_column(String(64), nullable=False) + intake_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_intakes.id'), + nullable=False, + ) + primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False) + po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) + validation_status: Mapped[str] = mapped_column( + String(32), + default='pending', + server_default=text("'pending'"), + nullable=False, + ) + conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False) + business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + duplicate_status: Mapped[str] = mapped_column( + String(32), + default='unchecked', + server_default=text("'unchecked'"), + nullable=False, + ) + duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + consumed_task_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_tasks.id'), + 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/models/user.py b/backend/app/models/user.py index 6c85ffd9..d6c24216 100644 --- a/backend/app/models/user.py +++ b/backend/app/models/user.py @@ -89,6 +89,8 @@ class User(Base): """返回当前角色自带的功能权限默认值。""" return { 'training_hr_manage': self.role in {'admin', 'hr'}, + # 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予 + 'shipping_notice_force_create': self.role == 'admin', } def get_feature_permissions(self) -> dict[str, bool]: diff --git a/backend/app/services/file_assets/service.py b/backend/app/services/file_assets/service.py index 4640712e..1de7c862 100644 --- a/backend/app/services/file_assets/service.py +++ b/backend/app/services/file_assets/service.py @@ -3,12 +3,15 @@ backend/app/services/file_assets/service.py 用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。 依赖:file_assets.storage、models.FileAsset、Flask current_app。 -逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回。 +逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回; + create_derived_file_asset_from_bytes 供 EML 附件子资产幂等落库(阶段二); + mark/release 以 SQL 原子 UPDATE 按关联边增减 reference_count;补偿失败写 orphan_cleanup 行。 """ from __future__ import annotations import hashlib +import logging import mimetypes import os import re @@ -17,6 +20,9 @@ from datetime import datetime, timedelta from typing import Any from flask import current_app +from sqlalchemy import case, update +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session from werkzeug.datastructures import FileStorage from werkzeug.utils import secure_filename @@ -26,6 +32,26 @@ from app.core.response import utc_iso from app.models import FileAsset from app.services.file_assets.storage import file_asset_storage +_LOGGER = logging.getLogger(__name__) + + +def _keep_first_source_attachment_key( + asset: FileAsset, + *, + source_attachment_key: str | None, +) -> bool: + """ + 仅在资产尚无来源键时写入首次 source_attachment_key,复用/复活不覆盖。 + + Returns: + 是否实际写入了字段。 + """ + incoming = str(source_attachment_key or '').strip() + if not incoming or str(asset.source_attachment_key or '').strip(): + return False + asset.source_attachment_key = incoming[:64] + return True + _ALLOWED_EXTENSIONS = { 'pdf', 'doc', 'docx', 'txt', 'md', 'log', 'html', 'htm', 'eml', 'csv', 'png', 'jpg', 'jpeg', 'webp', @@ -58,6 +84,21 @@ def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str: return f"temporary/{user_id}/{now:%Y}/{now:%m}/{asset_no}/{safe_name}" +def _build_derived_storage_key( + *, + user_id: int, + parent_asset_no: str, + 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' + parent = re.sub(r'[^\w\-]+', '_', str(parent_asset_no or 'parent'))[:64] or 'parent' + return f"derived/{user_id}/{now:%Y}/{now:%m}/{parent}/{asset_no}/{safe_name}" + + def _serialize_asset(asset: FileAsset) -> dict[str, Any]: return { 'asset_no': asset.asset_no, @@ -67,6 +108,9 @@ def _serialize_asset(asset: FileAsset) -> dict[str, Any]: 'content_hash': asset.content_hash, 'upload_status': asset.upload_status, 'lifecycle_status': asset.lifecycle_status, + 'parent_asset_id': asset.parent_asset_id, + 'asset_role': asset.asset_role, + 'source_attachment_key': asset.source_attachment_key, 'expires_at': utc_iso(asset.expires_at), 'created_at': utc_iso(asset.created_at), } @@ -121,6 +165,9 @@ def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]: asset_no=asset_no, owner_user_id=int(user_id), original_filename=filename, + parent_asset_id=None, + asset_role='upload', + source_attachment_key=None, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, @@ -148,12 +195,398 @@ def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]: 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 +def _find_derived_by_parent_hash( + *, + parent_id: int, + content_hash: str, + include_deleted: bool = False, +) -> FileAsset | None: + """按父资产 + content_hash 查找派生资产(默认可复用活记录)。""" + query = db.session.query(FileAsset).filter( + FileAsset.parent_asset_id == int(parent_id), + FileAsset.content_hash == content_hash, + ) + if not include_deleted: + query = query.filter(FileAsset.deleted_at.is_(None)) + return query.order_by(FileAsset.id.asc()).first() + + +def _revive_soft_deleted_derived_asset( + asset: FileAsset, + *, + data: bytes, + filename: str, + mime_type: str | None, + source_attachment_key: str | None, + uploaded_storage_keys: list[str] | None, +) -> FileAsset: + """ + 恢复被 soft-delete 的派生资产并重新上传对象。 + + 核心逻辑:清理 deleted_at 后复用原 storage_key;失败时保持 expired 供清理。 + """ + resolved_mime = ( + str(mime_type or asset.mime_type or '').strip() + or mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + asset.deleted_at = None + asset.upload_status = 'uploading' + asset.lifecycle_status = 'temporary' + asset.reference_count = 0 + asset.expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours()) + asset.original_filename = str(filename or asset.original_filename or 'attachment.bin')[:255] + asset.mime_type = resolved_mime[:128] + # 复活时仅补写空的首次来源键,不覆盖历史审计值 + _keep_first_source_attachment_key(asset, source_attachment_key=source_attachment_key) asset.updated_at = datetime.utcnow() + db.session.flush() + try: + file_asset_storage.upload_bytes( + storage_key=asset.storage_key, + data=data, + content_type=resolved_mime, + ) + asset.upload_status = 'ready' + if uploaded_storage_keys is not None: + uploaded_storage_keys.append(asset.storage_key) + except Exception: + asset.upload_status = 'failed' + asset.lifecycle_status = 'expired' + asset.updated_at = datetime.utcnow() + raise + return asset + + +def create_derived_file_asset_from_bytes( + *, + user_id: int, + parent: FileAsset, + data: bytes, + filename: str, + mime_type: str | None = None, + source_attachment_key: str | None = None, + asset_role: str = 'derived_attachment', + uploaded_storage_keys: list[str] | None = None, +) -> tuple[FileAsset, bool]: + """ + 从可信内部字节创建(或复用)派生 FileAsset。 + + 核心逻辑:按 parent_asset_id + content_hash 幂等;DB 唯一约束兜底并发; + IntegrityError 时 SAVEPOINT 回滚后回查已有行;新建成功后记录 storage_key 供事务失败补偿。 + source_attachment_key 语义为「首次来源键」:已有值时复用不覆盖。 + + Args: + user_id: 所有者,须与 parent.owner_user_id 一致。 + parent: EML 等根资产。 + data: 附件原始字节(不可为空)。 + filename: 原始文件名。 + mime_type: MIME;缺省按文件名猜测。 + source_attachment_key: 首次资产化时的 att-key(审计);后续复用不改。 + asset_role: 默认 derived_attachment。 + uploaded_storage_keys: 若提供,本函数成功上传的新对象 key 会 append,供调用方失败补偿。 + + Returns: + (已 ready 的 FileAsset, created_new);flush,不 commit。 + + Raises: + ForbiddenError: 非父资产所有者。 + ValidationError: 空内容或超大。 + """ + if int(parent.owner_user_id) != int(user_id): + raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权在该父资产下创建派生文件') + 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().lower() + existing = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash) + if existing is not None: + if _keep_first_source_attachment_key(existing, source_attachment_key=source_attachment_key): + existing.updated_at = datetime.utcnow() + if str(existing.upload_status or '') == 'ready': + return existing, False + try: + file_asset_storage.upload_bytes( + storage_key=existing.storage_key, + data=data, + content_type=existing.mime_type or 'application/octet-stream', + ) + existing.upload_status = 'ready' + existing.updated_at = datetime.utcnow() + if uploaded_storage_keys is not None: + uploaded_storage_keys.append(existing.storage_key) + except Exception: + existing.upload_status = 'failed' + existing.updated_at = datetime.utcnow() + raise + return existing, False + + # 软删除记录挡住同哈希时优先复活,避免孤儿行永久占位 + soft_deleted = _find_derived_by_parent_hash( + parent_id=int(parent.id), + content_hash=content_hash, + include_deleted=True, + ) + if soft_deleted is not None and soft_deleted.deleted_at is not None: + revived = _revive_soft_deleted_derived_asset( + soft_deleted, + data=data, + filename=str(filename or soft_deleted.original_filename or 'attachment.bin'), + mime_type=mime_type, + source_attachment_key=source_attachment_key, + uploaded_storage_keys=uploaded_storage_keys, + ) + return revived, False + + safe_filename = str(filename or '').strip() or 'attachment.bin' + ext = _normalize_extension(safe_filename) + if not ext: + ext = 'bin' + if not os.path.splitext(safe_filename)[1]: + safe_filename = f'{safe_filename}.bin' + + asset_no = generate_asset_no() + storage_key = _build_derived_storage_key( + user_id=int(user_id), + parent_asset_no=str(parent.asset_no or ''), + asset_no=asset_no, + filename=safe_filename, + ) + resolved_mime = ( + str(mime_type or '').strip() + or mimetypes.guess_type(safe_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), + parent_asset_id=int(parent.id), + asset_role=str(asset_role or 'derived_attachment')[:32], + source_attachment_key=(str(source_attachment_key)[:64] if source_attachment_key else None), + original_filename=safe_filename[:255], + storage_provider='minio', + storage_bucket=file_asset_storage.bucket_name, + storage_key=storage_key, + content_hash=content_hash, + file_size=len(data), + mime_type=resolved_mime[:128], + extension=ext[:32] if ext else None, + upload_status='uploading', + lifecycle_status='temporary', + reference_count=0, + expires_at=expires_at, + ) + + # [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务 + try: + with db.session.begin_nested(): + db.session.add(asset) + db.session.flush() + except IntegrityError: + raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash) + if raced is not None: + if _keep_first_source_attachment_key(raced, source_attachment_key=source_attachment_key): + raced.updated_at = datetime.utcnow() + return raced, False + # 冲突落在软删除行(旧全量唯一约束环境)时尝试复活 + raced_deleted = _find_derived_by_parent_hash( + parent_id=int(parent.id), + content_hash=content_hash, + include_deleted=True, + ) + if raced_deleted is None: + raise + revived = _revive_soft_deleted_derived_asset( + raced_deleted, + data=data, + filename=safe_filename, + mime_type=mime_type, + source_attachment_key=source_attachment_key, + uploaded_storage_keys=uploaded_storage_keys, + ) + return revived, False + + try: + file_asset_storage.upload_bytes( + storage_key=storage_key, + data=data, + content_type=resolved_mime, + ) + asset.upload_status = 'ready' + if uploaded_storage_keys is not None: + uploaded_storage_keys.append(storage_key) + except Exception: + asset.upload_status = 'failed' + raise + + return asset, True + + +def mark_asset_referenced(asset: FileAsset) -> None: + """ + 建立一次业务引用:原子 +1,并置 lifecycle=referenced。 + + 核心逻辑:数据库层 `reference_count = reference_count + 1`,避免并发读改写丢失。 + """ + now = datetime.utcnow() + db.session.execute( + update(FileAsset) + .where(FileAsset.id == int(asset.id)) + .values( + reference_count=FileAsset.reference_count + 1, + lifecycle_status='referenced', + expires_at=None, + updated_at=now, + ) + ) + db.session.refresh(asset) + + +def release_asset_reference(asset: FileAsset) -> None: + """ + 原子减少业务引用;派生资产归零后恢复 temporary + TTL,供清理任务回收。 + + 核心逻辑:单条 UPDATE 内用旧值计算新计数与 lifecycle,避免并发少计/多计。 + """ + now = datetime.utcnow() + expires = now + timedelta(hours=_temp_ttl_hours()) + # 不用 GREATEST:SQLite 测试库无该函数;CASE 在 PG/SQLite 均可原子计算新计数 + new_count = case( + (FileAsset.reference_count > 0, FileAsset.reference_count - 1), + else_=0, + ) + db.session.execute( + update(FileAsset) + .where(FileAsset.id == int(asset.id)) + .values( + reference_count=new_count, + lifecycle_status=case( + ( + (FileAsset.reference_count <= 1) + & (FileAsset.asset_role == 'derived_attachment'), + 'temporary', + ), + ( + FileAsset.reference_count > 1, + 'referenced', + ), + else_=FileAsset.lifecycle_status, + ), + expires_at=case( + ( + (FileAsset.reference_count <= 1) + & (FileAsset.asset_role == 'derived_attachment'), + expires, + ), + ( + FileAsset.reference_count > 1, + None, + ), + else_=FileAsset.expires_at, + ), + updated_at=now, + ) + ) + db.session.refresh(asset) + + +def _persist_orphan_storage_key_for_cleanup( + *, + storage_key: str, + owner_user_id: int | None, + storage_bucket: str | None, +) -> None: + """ + 补偿删除失败时写入可被 cleanup 回收的孤儿资产行。 + + 核心逻辑:使用独立 Session,避免污染调用方 Session;标记 expired + orphan_cleanup。 + """ + now = datetime.utcnow() + owner = int(owner_user_id or 0) + if owner <= 0: + # 无可用所有者时仍记录日志即可,不强写无主行 + _LOGGER.error( + 'orphan minio key has no owner_user_id; cannot persist cleanup row key=%s', + storage_key, + ) + return + bind = db.session.get_bind() + if bind is None: + _LOGGER.error('orphan persist skipped: no DB bind for key=%s', storage_key) + return + row = FileAsset( + asset_no=generate_asset_no(), + owner_user_id=owner, + parent_asset_id=None, + asset_role='orphan_cleanup', + source_attachment_key=None, + original_filename='orphan.bin', + storage_provider='minio', + storage_bucket=str(storage_bucket or file_asset_storage.bucket_name)[:128], + storage_key=storage_key[:512], + content_hash=hashlib.sha256(storage_key.encode('utf-8')).hexdigest(), + file_size=0, + mime_type='application/octet-stream', + extension='bin', + upload_status='ready', + lifecycle_status='expired', + reference_count=0, + expires_at=now, + deleted_at=None, + ) + with Session(bind=bind) as orphan_session: + orphan_session.add(row) + orphan_session.commit() + + +def compensate_uploaded_storage_keys( + storage_keys: list[str] | None, + *, + owner_user_id: int | None = None, + storage_bucket: str | None = None, +) -> None: + """ + 事务失败后尽力删除本轮新上传的 MinIO 对象。 + + 核心逻辑:删除失败则 error 日志 + 独立 Session 写入 orphan_cleanup; + 台账写入失败会 rollback 调用方 Session,避免 PendingRollbackError。 + + Args: + storage_keys: create_derived 写入的 storage_key 列表。 + owner_user_id: 孤儿行归属用户;缺省时仅打日志。 + storage_bucket: MinIO bucket;缺省用配置桶。 + """ + for key in storage_keys or []: + normalized = str(key or '').strip() + if not normalized: + continue + try: + file_asset_storage.delete_object(normalized) + except Exception: + _LOGGER.exception('failed to compensate-delete minio object key=%s', normalized) + try: + _persist_orphan_storage_key_for_cleanup( + storage_key=normalized, + owner_user_id=owner_user_id, + storage_bucket=storage_bucket, + ) + except Exception: + _LOGGER.exception( + 'failed to persist orphan cleanup row for minio key=%s', + normalized, + ) + try: + db.session.rollback() + except Exception: + _LOGGER.exception( + 'failed to rollback session after orphan persist error key=%s', + normalized, + ) + def delete_temporary_asset(*, asset_no: str, user_id: int) -> None: diff --git a/backend/app/services/shipping_notice/attachment_integrity.py b/backend/app/services/shipping_notice/attachment_integrity.py new file mode 100644 index 00000000..fc014d61 --- /dev/null +++ b/backend/app/services/shipping_notice/attachment_integrity.py @@ -0,0 +1,82 @@ +""" +services/shipping_notice/attachment_integrity.py + +用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。 +依赖:仅标准库(与 structured_result_json / parse_summary 形状对齐)。 +逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用; + BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致 + (由 tests 校验两端前缀集合)。 +""" + +from __future__ import annotations + +from typing import Any + +# 顶层 / 附件行 warnings 前缀:出现任一即视为不完整(与前端门禁契约对齐) +BLOCKING_WARNING_PREFIXES: tuple[str, ...] = ( + 'eml_nesting_depth_exceeded:', + 'eml_attachment_limit_exceeded:', + 'eml_total_attachment_size_exceeded:', + 'eml_nested_message_unreadable', + 'eml_attachment_text_budget_exhausted:', + 'eml_attachment_text_truncated:', + 'notice_text_truncated:', +) + +_INCOMPLETE_ATTACHMENT_STATUSES = frozenset({'failed', 'empty', 'skipped'}) + + +def is_blocking_warning(text: str) -> bool: + """ + 判定单条 warning 是否为完整性阻断项。 + + Args: + text: warning 原文。 + + Returns: + True 表示该警告会使 Intake 被视为附件解析不完整。 + """ + normalized = str(text or '') + return any(normalized.startswith(prefix) for prefix in BLOCKING_WARNING_PREFIXES) + + +def is_attachment_parse_incomplete(structured: dict[str, Any] | None) -> bool: + """ + 判定 structured_result_json / parse_summary 是否存在未完整解析的附件。 + + 核心逻辑:阻断警告(深度/数量/总大小/不可读嵌套/文本预算或截断)、 + attachment_count > 已登记数、或任一行 parse_status 为 failed/empty/skipped + 均视为不完整;duplicate 仅去重提示,不阻断。 + + Args: + structured: Intake 的 structured_result_json 或 API 下发的 parse_summary。 + + Returns: + True 表示不可用该 Intake 直接建批,应拒绝或允许重试解析。 + """ + if not isinstance(structured, dict): + return False + + warnings = structured.get('warnings') or [] + for item in warnings: + if is_blocking_warning(str(item or '')): + return True + + rows = structured.get('attachments') or [] + if not isinstance(rows, list): + rows = [] + total = int(structured.get('attachment_count') or 0) + if total > len(rows): + return True + + for row in rows: + if not isinstance(row, dict): + continue + status = str(row.get('parse_status') or '').strip().lower() + if status in _INCOMPLETE_ATTACHMENT_STATUSES: + return True + for item in row.get('warnings') or []: + if is_blocking_warning(str(item or '')): + return True + + return False diff --git a/backend/app/services/shipping_notice/batch_create_idempotency.py b/backend/app/services/shipping_notice/batch_create_idempotency.py index 2948a178..f3057bdd 100644 --- a/backend/app/services/shipping_notice/batch_create_idempotency.py +++ b/backend/app/services/shipping_notice/batch_create_idempotency.py @@ -224,6 +224,7 @@ def assert_no_exact_duplicate_notices( 校验跨请求是否存在相同文件内容且仍在进行中的任务。 核心逻辑:须在 acquire_notice_create_locks 之后调用,避免不同幂等键并发重复建单。 + 合法的 duplicate_resolution_type=revision|force_create 跳过哈希阻断(业务 Gate 已授权)。 Raises: ConflictError: SHIPPING.NOTICE_EXACT_DUPLICATE,details 含已有 task_no。 @@ -232,6 +233,10 @@ def assert_no_exact_duplicate_notices( for item in notice_items: if not isinstance(item, dict): continue + resolution_type = str(item.get("duplicate_resolution_type") or "").strip().lower() + # 修订/强制新建:已由 intake Gate 校验决策与权限,允许同 content_hash 再建 + if resolution_type in {"revision", "force_create"}: + continue content_hash = str(item.get("source_content_hash") or "").strip().lower() if not content_hash: continue diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py index 0a8cb81c..eea76dd5 100644 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -2,9 +2,14 @@ backend/app/services/shipping_notice/batch_from_intakes.py 用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。 -依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency。 +依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency、 + attachment_integrity。 逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。 - 先幂等回放;按 content_hash 去重后 FOR UPDATE 预占 consumed;建批失败须 rollback 预占。 + 幂等以 intake.create_idempotency_key 为准(覆盖混合批次 / 纯 open_existing); + 批次 create_idempotency_key + process_summary.request_intake_nos 为兼容回退。 + 建批传 defer_commit,与 consumed 关联 / 摘要 / 审计同事务提交后再启动编排器。 + 按 content_hash 去重后 FOR UPDATE 预占 consumed;建批失败须 rollback 预占。 + parsed 仍须通过附件完整性门禁(与前端 incomplete 规则一致),防止直调 API 绕过。 """ from __future__ import annotations @@ -13,26 +18,30 @@ from datetime import datetime from typing import Any from sqlalchemy import select +from sqlalchemy.orm.attributes import flag_modified from app import db from app.core.errors import ConflictError, ValidationError -from app.models import FileAsset, ShippingNoticeIntake, ShippingTask +from app.models import FileAsset, ShippingBatch, ShippingNoticeIntake, ShippingTask +from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete 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.duplicate_detection import detect_duplicates_for_intake from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item from app.services.shipping_notice.intake_service import mark_intakes_consumed +from app.services.shipping_notice.tool_common import log_task_event def _batch_intake_nos(batch_id: int) -> set[str]: """ 读取批次关联的全部 intake_no 集合。 - 核心逻辑:以 consumed_batch_id 为准(含 content_hash 去重后的附属 intake), - 避免仅按 task.source_intake_id 导致幂等集合校验误报冲突。 + 核心逻辑:以 consumed_batch_id 为准(含 content_hash 去重后的附属 intake)。 + 注意:open_existing 会挂到旧任务批次,不可单独用于混合请求的全量比对。 """ rows = ( db.session.query(ShippingNoticeIntake.intake_no) @@ -42,6 +51,175 @@ def _batch_intake_nos(batch_id: int) -> set[str]: return {str(row[0]).strip().upper() for row in rows if row and row[0]} +def _stamp_intakes_create_idempotency( + intakes: list[ShippingNoticeIntake], + create_idempotency_key: str | None, +) -> None: + """ + 将建单幂等键写回本请求涉及的全部 intake。 + + 核心逻辑:混合批次里 open_existing 不会挂入新建批次,须靠 intake 键闭环重放。 + """ + key = normalize_create_idempotency_key(create_idempotency_key) + if not key: + return + now = datetime.utcnow() + for intake in intakes: + intake.create_idempotency_key = key + intake.updated_at = now + + +def _opened_existing_payload(intake: ShippingNoticeIntake) -> dict[str, Any]: + """从已消费 intake 组装 open_existing 投影。""" + task_no = None + if intake.consumed_task_id: + task = db.session.get(ShippingTask, int(intake.consumed_task_id)) + if task is not None: + task_no = task.task_no + if not task_no: + task_no = str(intake.duplicate_target_task_no or '').strip().upper() or None + return { + 'intake_no': intake.intake_no, + 'task_no': task_no, + 'batch_no': None, + } + + +def _is_open_existing_intake(intake: ShippingNoticeIntake) -> bool: + """判断 intake 是否为打开已有任务决策。""" + return str(intake.duplicate_resolution or '').strip().lower() == 'open_existing' + + +def _resolve_create_batch_for_replay( + *, + user_id: int, + create_intakes: list[ShippingNoticeIntake], + create_idempotency_key: str | None, +) -> ShippingBatch: + """ + 为含建单意图的 intake 解析所属新批次(含断点恢复)。 + + 核心逻辑:优先 consumed_batch_id → 批次幂等键 → 任务 source_intake_id 反查; + 找到后回填缺失的 consumed_*,避免半成品重放成「未创建新批次」。 + """ + batch: ShippingBatch | None = None + for intake in create_intakes: + if intake.consumed_batch_id is None: + continue + candidate = db.session.get(ShippingBatch, int(intake.consumed_batch_id)) + if candidate is not None and int(candidate.user_id or 0) == int(user_id): + batch = candidate + break + + key = normalize_create_idempotency_key(create_idempotency_key) + if batch is None and key: + batch = find_batch_by_create_idempotency(user_id, key) + + if batch is None: + intake_ids = [int(item.id) for item in create_intakes] + task = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(user_id), + ShippingTask.source_intake_id.in_(intake_ids), + ) + .order_by(ShippingTask.id.desc()) + .first() + ) + if task is not None and task.batch_id is not None: + batch = db.session.get(ShippingBatch, int(task.batch_id)) + + if batch is None or int(batch.user_id or 0) != int(user_id): + raise ConflictError( + '建单结果未完整关联,请使用相同幂等键重试', + code='SHIPPING.BATCH_CREATE_INCOMPLETE', + details={ + 'intake_nos': [item.intake_no for item in create_intakes], + 'create_idempotency_key': key, + }, + ) + + tasks = ( + db.session.query(ShippingTask) + .filter(ShippingTask.batch_id == int(batch.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 + } + now = datetime.utcnow() + dirty = False + for intake in create_intakes: + task = task_by_intake_id.get(int(intake.id)) + if task is None: + continue + if intake.consumed_batch_id != int(batch.id) or intake.consumed_task_id != int(task.id): + intake.consumed_batch_id = int(batch.id) + intake.consumed_task_id = int(task.id) + intake.updated_at = now + dirty = True + if intake.parse_status != 'consumed' or intake.consumed_at is None: + intake.parse_status = 'consumed' + intake.consumed_at = intake.consumed_at or now + intake.updated_at = now + dirty = True + if dirty: + db.session.commit() + return batch + + +def _build_replay_from_intakes( + *, + user_id: int, + intakes: list[ShippingNoticeIntake], + create_idempotency_key: str | None = None, +) -> dict[str, Any]: + """ + 依据已打幂等键的 intake 重建确认响应。 + + 核心逻辑:区分 open_existing 与新建批次;建单断点时通过批次/任务反查并回填关联。 + """ + opened: list[dict[str, Any]] = [] + create_intakes: list[ShippingNoticeIntake] = [] + for intake in intakes: + if _is_open_existing_intake(intake): + opened.append(_opened_existing_payload(intake)) + else: + create_intakes.append(intake) + + if create_intakes: + batch = _resolve_create_batch_for_replay( + user_id=user_id, + create_intakes=create_intakes, + create_idempotency_key=create_idempotency_key + or next( + (str(item.create_idempotency_key or '') for item in intakes if item.create_idempotency_key), + None, + ), + ) + result = build_existing_batch_tool_response(batch, user_id=user_id) + result['idempotent_replay'] = True + if opened: + result['opened_existing'] = opened + return result + + focus_task_no = opened[0].get('task_no') if opened else None + return { + 'status': 'ok', + 'batch_no': None, + 'idempotent_replay': True, + 'opened_existing': opened, + 'message': '已打开已有任务,未创建新批次', + 'data': { + 'opened_existing': opened, + 'focus_task': {'task_no': focus_task_no} if focus_task_no else None, + }, + } + + def _try_idempotent_replay( *, user_id: int, @@ -49,23 +227,63 @@ def _try_idempotent_replay( intake_nos: list[str], ) -> dict[str, Any] | None: """ - 按 user_id + create_idempotency_key 查找已有批次,并校验 intake 集合一致。 - Returns: - 幂等重放响应;无匹配批次时返回 None。 + 按 create_idempotency_key 重放确认建单结果。 + + 核心逻辑: + 1. 优先查 intake.create_idempotency_key(混合 / 纯 open_existing); + 2. 回退查 ShippingBatch + process_summary.request_intake_nos(兼容旧数据)。 """ key = normalize_create_idempotency_key(create_idempotency_key) if not key: return None + expected = {str(no).strip().upper() for no in intake_nos} + + stamped = ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.create_idempotency_key == key, + ) + .all() + ) + if stamped: + actual = {str(item.intake_no).strip().upper() for item in stamped} + if actual != expected: + raise ConflictError( + '建单幂等键对应接入集合不一致', + code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT', + details={ + 'expected': sorted(expected), + 'actual': sorted(actual), + 'source': 'intake_create_idempotency_key', + }, + ) + return _build_replay_from_intakes( + user_id=user_id, + intakes=stamped, + create_idempotency_key=key, + ) + 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: + summary = existing.process_summary_json if isinstance(existing.process_summary_json, dict) else {} + stored = summary.get('request_intake_nos') + if isinstance(stored, list) and stored: + actual = {str(item or '').strip().upper() for item in stored if str(item or '').strip()} + else: + # 历史纯建批路径:仅有新建批次上的 intake + actual = _batch_intake_nos(int(existing.id)) + if actual != expected: raise ConflictError( '建单幂等键对应批次的接入集合不一致', code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT', - details={'batch_no': existing.batch_no, 'expected': sorted(expected), 'actual': sorted(actual)}, + details={ + 'batch_no': existing.batch_no, + 'expected': sorted(expected), + 'actual': sorted(actual), + 'source': 'batch_fallback', + }, ) result = build_existing_batch_tool_response(existing, user_id=user_id) result['idempotent_replay'] = True @@ -75,12 +293,7 @@ def _try_idempotent_replay( 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。 - """ + """按 FileAsset.content_hash 去重,保留首次出现的 intake 用于建单。""" seen: set[str] = set() primary: list[tuple[ShippingNoticeIntake, FileAsset]] = [] duplicates_by_hash: dict[str, list[ShippingNoticeIntake]] = {} @@ -97,6 +310,110 @@ def _partition_intakes_by_content_hash( return primary, duplicates_by_hash +def _assert_duplicate_gate( + *, + user_id: int, + intake: ShippingNoticeIntake, + asset: FileAsset, +) -> dict[str, Any]: + """ + 建单前事务内重跑重复检测并校验用户决策。 + + Returns: + 最新 duplicate 结果。 + Raises: + ConflictError: 需决策或目标漂移等。 + """ + 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 + fresh = detect_duplicates_for_intake( + intake=intake, + asset=asset, + business_summary=business_summary, + ) + # 写入最新 matches(不清空已有 resolution,供比对) + intake.business_fingerprint = fresh.get('fingerprint') + intake.fingerprint_version = fresh.get('fingerprint_version') + intake.fingerprint_strength = fresh.get('fingerprint_strength') + intake.duplicate_status = str(fresh.get('status') or 'none') + intake.duplicate_matches_json = list(fresh.get('matches') or []) + intake.duplicate_checked_at = datetime.utcnow() + + blocking = bool(fresh.get('blocking')) + resolution = str(intake.duplicate_resolution or '').strip().lower() + if blocking and not resolution: + raise ConflictError( + '检测到重复发货通知,请先选择处理方式', + code='SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED', + details={'intake_no': intake.intake_no, 'duplicate': fresh}, + ) + if not blocking: + return fresh + + target_no = str(intake.duplicate_target_task_no or '').strip().upper() + matches = list(fresh.get('matches') or []) + if resolution in {'open_existing', 'create_revision', 'force_create'}: + if not target_no or not any(str(m.get('task_no') or '').upper() == target_no for m in matches): + raise ConflictError( + '目标任务状态已变化,请重新确认', + code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED', + details={'intake_no': intake.intake_no}, + ) + target = ( + db.session.query(ShippingTask) + .filter(ShippingTask.task_no == target_no, ShippingTask.user_id == int(user_id)) + .first() + ) + if not target: + raise ConflictError( + '重复目标任务不存在', + code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', + ) + 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('process_status') or '') != str(target.process_status or ''): + raise ConflictError( + '目标任务状态已变化,请重新确认', + code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED', + ) + if resolution == 'create_revision' and not target: + raise ConflictError( + '修订目标无效', + code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', + ) + # 建单时再次校验强制新建权限与原因,防决策后权限被撤或伪造 resolution + if resolution == 'force_create': + from app.models import User + from app.core.errors import ForbiddenError, ValidationError + from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate + + user = 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(intake.duplicate_resolution_reason or '').strip(): + raise ValidationError( + code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED', + message='强制新建必须填写原因', + ) + return fresh + + +def _attach_request_intake_summary( + batch: ShippingBatch, + *, + request_intake_nos: list[str], + open_existing_intake_nos: list[str], +) -> None: + """把本请求完整 intake 集合写入批次摘要,供无 intake 键时的回退重放。""" + summary = dict(batch.process_summary_json) if isinstance(batch.process_summary_json, dict) else {} + summary['request_intake_nos'] = list(request_intake_nos) + summary['open_existing_intake_nos'] = list(open_existing_intake_nos) + batch.process_summary_json = summary + flag_modified(batch, 'process_summary_json') + + def create_shipping_batch_from_intakes( *, user_id: int, @@ -108,17 +425,17 @@ def create_shipping_batch_from_intakes( 根据已解析且未消费的 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 一并关联到同一任务。 + 1. 幂等回放(intake 键优先); + 2. FOR UPDATE 锁定;若已全部消费则再试重放,否则报已消费; + 3. 事务内重跑业务去重并校验决策; + 4. open_existing 仅关联已有任务;其余走建批(含 revision/force 元数据); + 5. 全部 intake 打 create_idempotency_key,content_hash 去重预占后建批。 """ 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 已消费后仍可恢复原批次 + # [STEP 1] 幂等重放优先 replay = _try_idempotent_replay( user_id=user_id, create_idempotency_key=create_idempotency_key, @@ -127,7 +444,7 @@ def create_shipping_batch_from_intakes( if replay is not None: return replay - # [STEP 2] 锁定并校验接入记录 + # [STEP 2] 锁定并校验 stmt = ( select(ShippingNoticeIntake, FileAsset) .join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id) @@ -145,7 +462,6 @@ def create_shipping_batch_from_intakes( code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', ) - # 锁后再查一次幂等键,覆盖 STEP1 与锁定之间的并发窗口 replay = _try_idempotent_replay( user_id=user_id, create_idempotency_key=create_idempotency_key, @@ -156,13 +472,12 @@ def create_shipping_batch_from_intakes( ordered_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = [] now = datetime.utcnow() + consumed_pairs: list[ShippingNoticeIntake] = [] 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', - ) + consumed_pairs.append(intake) + continue if intake.parse_status != 'parsed': raise ConflictError( f'接入记录 {intake.intake_no} 尚未解析完成', @@ -172,6 +487,17 @@ def create_shipping_batch_from_intakes( else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' ), ) + # [STEP] 附件完整性:failed/empty/skipped、超限警告、文本预算耗尽等均不可建批 + structured = ( + intake.structured_result_json + if isinstance(intake.structured_result_json, dict) + else None + ) + if is_attachment_parse_incomplete(structured): + raise ConflictError( + f'接入记录 {intake.intake_no} 附件解析不完整,请重试解析或移除后重新上传', + code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', + ) if intake.expires_at and intake.expires_at < now: raise ConflictError( '接入记录已过期', @@ -179,12 +505,91 @@ def create_shipping_batch_from_intakes( ) ordered_pairs.append((intake, asset)) - # [STEP 3] content_hash 去重:只消费真正用于建单的 primary intake - primary_pairs, duplicates_by_hash = _partition_intakes_by_content_hash(ordered_pairs) + if consumed_pairs: + if len(consumed_pairs) == len(normalized): + # 并发首成功后重试:依赖 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 + raise ConflictError( + f'接入记录 {consumed_pairs[0].intake_no} 已被消费', + code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', + ) + + # [STEP 3] 事务内业务去重 Gate + open_existing_pairs: list[tuple[ShippingNoticeIntake, FileAsset, ShippingTask]] = [] + create_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = [] + for intake, asset in ordered_pairs: + _assert_duplicate_gate(user_id=user_id, intake=intake, asset=asset) + resolution = str(intake.duplicate_resolution or '').strip().lower() + if resolution == 'open_existing': + target = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.task_no == str(intake.duplicate_target_task_no or '').strip().upper(), + ShippingTask.user_id == int(user_id), + ) + .first() + ) + if not target: + raise ConflictError( + '重复目标任务不存在', + code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', + ) + open_existing_pairs.append((intake, asset, target)) + else: + create_pairs.append((intake, asset)) + + all_request_intakes = [intake for intake, _ in ordered_pairs] + _stamp_intakes_create_idempotency(all_request_intakes, create_idempotency_key) + + # [STEP 4] open_existing:关联并 consumed,不新建 + opened: list[dict[str, Any]] = [] + for intake, asset, target in open_existing_pairs: + mark_intakes_consumed( + intakes=[intake], + batch_id=target.batch_id, + task_ids_by_intake={int(intake.id): int(target.id)}, + ) + intake.duplicate_resolution = 'open_existing' + log_task_event( + target, + 'duplicate_opened_existing', + { + 'intake_no': intake.intake_no, + 'matched_task_no': target.task_no, + 'match_type': intake.duplicate_status, + 'fingerprint_version': intake.fingerprint_version, + 'resolution': 'open_existing', + 'operator_user_id': int(user_id), + }, + ) + opened.append({'intake_no': intake.intake_no, 'task_no': target.task_no, 'batch_no': None}) + + if not create_pairs: + db.session.commit() + focus = open_existing_pairs[0][2] if open_existing_pairs else None + return { + 'status': 'ok', + 'batch_no': None, + 'idempotent_replay': False, + 'opened_existing': opened, + 'message': '已打开已有任务,未创建新批次', + 'data': { + 'opened_existing': opened, + 'focus_task': {'task_no': focus.task_no} if focus else None, + }, + } + + # [STEP 5] content_hash 去重后建批 + primary_pairs, duplicates_by_hash = _partition_intakes_by_content_hash(create_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() @@ -194,21 +599,35 @@ def create_shipping_batch_from_intakes( conversation_id=conversation_id, notice_items=notice_items, create_idempotency_key=create_idempotency_key, + defer_commit=True, + start_orchestrator=False, ) 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() + # 下层批次回放成功后,本地预占已回滚;再以 intake 键或批次回放统一出口 + replay = _try_idempotent_replay( + user_id=user_id, + create_idempotency_key=create_idempotency_key, + intake_nos=normalized, + ) + if replay is not None: + if opened: + replay['opened_existing'] = opened + return replay + if opened: + result['opened_existing'] = opened 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: + if opened: + result['opened_existing'] = opened return result from app.services.shipping_notice.query_service import get_batch_for_user @@ -217,6 +636,12 @@ def create_shipping_batch_from_intakes( if not batch_obj: return result + _attach_request_intake_summary( + batch_obj, + request_intake_nos=normalized, + open_existing_intake_nos=[item['intake_no'] for item in opened], + ) + tasks = ( db.session.query(ShippingTask) .filter(ShippingTask.batch_id == batch_obj.id) @@ -239,8 +664,46 @@ def create_shipping_batch_from_intakes( content_hash = str(asset.content_hash or '').strip() if content_hash: hash_to_task_id[content_hash] = int(task.id) + # 审计:修订 / 强制新建 + resolution_type = str(task.duplicate_resolution_type or 'normal') + if resolution_type == 'revision' and task.supersedes_task_id: + prev = db.session.get(ShippingTask, int(task.supersedes_task_id)) + if prev: + log_task_event( + task, + 'duplicate_revision_created', + { + 'intake_no': intake.intake_no, + 'matched_task_no': prev.task_no, + 'fingerprint_version': task.fingerprint_version, + 'resolution': 'create_revision', + 'document_version': task.document_version, + 'operator_user_id': int(user_id), + }, + ) + log_task_event( + prev, + 'task_superseded', + { + 'new_task_no': task.task_no, + 'document_version': task.document_version, + 'operator_user_id': int(user_id), + }, + ) + elif resolution_type == 'force_create': + log_task_event( + task, + 'duplicate_force_created', + { + 'intake_no': intake.intake_no, + 'matched_task_no': intake.duplicate_target_task_no, + 'reason': task.duplicate_override_reason, + 'fingerprint_version': task.fingerprint_version, + 'resolution': 'force_create', + 'operator_user_id': int(user_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) @@ -251,11 +714,27 @@ def create_shipping_batch_from_intakes( dup.consumed_batch_id = int(batch_obj.id) dup.consumed_task_id = int(task_id) if duplicate_intakes: + _stamp_intakes_create_idempotency(duplicate_intakes, create_idempotency_key) 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}, ) + # 与批次创建 / intake 关联 / 审计同事务提交,消除提交断点 db.session.commit() + + from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator + + orchestrator_started = start_batch_orchestrator(batch_no) + if isinstance(data, dict): + data['orchestrator_started'] = orchestrator_started + if orchestrator_started: + base_message = str(result.get('message') or '').strip() + result['message'] = ( + f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。' + ) + + if opened: + result['opened_existing'] = opened return result diff --git a/backend/app/services/shipping_notice/batch_from_notices.py b/backend/app/services/shipping_notice/batch_from_notices.py index 16ed1bba..13a211ac 100644 --- a/backend/app/services/shipping_notice/batch_from_notices.py +++ b/backend/app/services/shipping_notice/batch_from_notices.py @@ -33,11 +33,14 @@ def create_shipping_batch_from_notice_items( notice_items: list[dict[str, Any]], file_summary: dict[str, Any] | None = None, create_idempotency_key: str | None = None, + defer_commit: bool = False, + start_orchestrator: bool | None = None, ) -> dict[str, Any]: """ 根据已抽取的发货通知条目创建批次并可选启动编排器。 核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。 + intake 路径应传 defer_commit=True,避免批次先提交导致上层 ingested 关联/审计断点。 Args: user_id: 当前用户 ID。 @@ -45,6 +48,8 @@ def create_shipping_batch_from_notice_items( notice_items: notice_upload 产出的 notice item 列表。 file_summary: 可选文件预检摘要,写入响应供前端展示。 create_idempotency_key: 建单幂等键(与 ShippingTask.idempotency_key 货代上传幂等分离)。 + defer_commit: True 时下层仅 flush,由调用方最终 commit。 + start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。 Returns: 与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。 @@ -81,6 +86,7 @@ def create_shipping_batch_from_notice_items( "notice_items": notice_items, "defer_parse": True, "create_idempotency_key": normalized_key, + "defer_commit": bool(defer_commit), } try: created = shipping_tools.create_batch_tasks(payload) @@ -101,8 +107,9 @@ def create_shipping_batch_from_notice_items( data = created.get("data") if isinstance(created.get("data"), dict) else {} batch_data = data.get("batch") if isinstance(data.get("batch"), dict) else {} batch_no = str(created.get("batch_no") or batch_data.get("batch_no") or "").strip() + should_start = start_orchestrator if start_orchestrator is not None else (not defer_commit) orchestrator_started = False - if batch_no and not idempotent_replay: + if batch_no and not idempotent_replay and should_start: from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator orchestrator_started = start_batch_orchestrator(batch_no) diff --git a/backend/app/services/shipping_notice/business_fingerprint.py b/backend/app/services/shipping_notice/business_fingerprint.py new file mode 100644 index 00000000..dddf3a1b --- /dev/null +++ b/backend/app/services/shipping_notice/business_fingerprint.py @@ -0,0 +1,173 @@ +""" +backend/app/services/shipping_notice/business_fingerprint.py + +用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。 +依赖:po_number / reservation_id 标准化函数。 +逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;算法版本 shipping-v1。 +""" + +from __future__ import annotations + +import hashlib +import json +from decimal import Decimal, InvalidOperation +from typing import Any + +from app.services.shipping_notice.po_number import normalize_po_number +from app.services.shipping_notice.reservation_id import normalize_reservation_id + +FINGERPRINT_VERSION = 'shipping-v1' + + +def _norm_text(value: Any) -> str: + return str(value or '').strip().upper() + + +def _norm_qty(value: Any) -> str: + if value is None or value == '': + return '' + try: + return format(Decimal(str(value)).quantize(Decimal('0.0001')), 'f') + except (InvalidOperation, ValueError, TypeError): + return _norm_text(value) + + +def _line_digest(lines: list[dict[str, Any]]) -> str: + parts: list[str] = [] + for line in lines: + if not isinstance(line, dict): + continue + sku = _norm_text(line.get('sku')) + rid = normalize_reservation_id(str(line.get('reservation_id') or '')) or '' + qty = _norm_qty(line.get('qty')) + if not sku and not rid and not qty: + continue + parts.append(f'{sku}|{rid}|{qty}') + parts.sort() + return '\n'.join(parts) + + +def _customer_identity(summary: dict[str, Any]) -> tuple[str, str]: + """ + 解析客户身份键。 + + 核心逻辑:优先 customer_code;启发式预解析常只有 customer_name,须回退到名称, + 否则强业务单号(PO/Reservation)也无法生成 usable 指纹。 + Returns: + (identity_value, identity_field) 如 ('ACME', 'customer_name');无则 ('', '')。 + """ + code = _norm_text(summary.get('customer_code')) + if code: + return code, 'customer_code' + name = _norm_text(summary.get('customer_name')) + if name: + return name, 'customer_name' + return '', '' + + +def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[str, Any]: + """ + 由业务摘要生成指纹、强度与组成依据。 + + 核心逻辑(shipping-v1): + - strong:客户身份(code 或 name)+ (PO 或 reservation 集合) + 或:PO + reservation 集合(稳定业务编号,无需客户码) + - medium:客户身份 + 目的地 + required_date + 行 digest + - weak:ship_to 或 仅行 digest(SKU+qty) + - unavailable:不足以可靠去重 + + Args: + business_summary: intake_business_parser 产出。 + + Returns: + {fingerprint, version, strength, components} + """ + summary = business_summary if isinstance(business_summary, dict) else {} + customer_id, customer_field = _customer_identity(summary) + po_number = normalize_po_number(str(summary.get('po_number') or '')) or '' + reservation_ids = sorted( + { + normalize_reservation_id(str(item)) or '' + for item in (summary.get('reservation_ids') or []) + if str(item or '').strip() + } + - {''} + ) + dest = summary.get('destination') if isinstance(summary.get('destination'), dict) else {} + destination_key = '|'.join( + [ + _norm_text(dest.get('code')), + _norm_text(dest.get('city')), + _norm_text(dest.get('country')), + ] + ).strip('|') + required_date = _norm_text(summary.get('required_date')) + ship_to = _norm_text(summary.get('ship_to')) + lines = summary.get('lines') if isinstance(summary.get('lines'), list) else [] + line_digest = _line_digest([item for item in lines if isinstance(item, dict)]) + + strength = 'unavailable' + components: dict[str, Any] = {} + + # [STEP 1] 强指纹:客户身份 + 稳定单号;或仅 PO+Reservation(编号本身足够强) + if customer_id and (po_number or reservation_ids): + strength = 'strong' + components = { + customer_field: customer_id, + 'po_number': po_number or None, + 'reservation_ids': reservation_ids, + } + elif po_number and reservation_ids: + strength = 'strong' + components = { + 'po_number': po_number, + 'reservation_ids': reservation_ids, + } + elif customer_id and destination_key and required_date and line_digest: + strength = 'medium' + components = { + customer_field: customer_id, + 'destination': destination_key, + 'required_date': required_date, + 'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16], + } + elif ship_to and line_digest: + strength = 'weak' + components = { + 'ship_to': ship_to, + 'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16], + } + elif line_digest and (reservation_ids or po_number or customer_id): + # 有行 digest 且至少一项单头标识:弱指纹,可标记 possible + strength = 'weak' + components = { + 'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16], + } + if customer_id: + components[customer_field] = customer_id + if po_number: + components['po_number'] = po_number + if reservation_ids: + components['reservation_ids'] = reservation_ids + else: + return { + 'fingerprint': None, + 'version': FINGERPRINT_VERSION, + 'strength': 'unavailable', + 'components': {}, + } + + payload = { + 'version': FINGERPRINT_VERSION, + 'strength': strength, + 'components': components, + } + digest = hashlib.sha256( + json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') + ).hexdigest() + return { + 'fingerprint': digest, + 'version': FINGERPRINT_VERSION, + 'strength': strength, + 'components': components, + } diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py index 871b5250..80ced5b1 100644 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_handlers.py @@ -181,6 +181,28 @@ class ShippingCreateBatchFromIntakesAction: intake_nos=[str(item) for item in intake_nos], create_idempotency_key=idempotency_key, ) + opened = result.get("opened_existing") if isinstance(result.get("opened_existing"), list) else [] + if opened and not str(result.get("batch_no") or "").strip(): + 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 {} + task_no = str(focus_task.get("task_no") or opened[0].get("task_no") or "").strip() + if task_no: + task = get_task_by_ref(task_no) + if task is not None: + yield _shipping_ui_state_event(task) + content = str(result.get("message") or "已打开已有任务,未创建新批次") + yield from _stream_text_events( + content, + message_type="text", + payload={ + "opened_existing": True, + "task_no": task_no, + "intake_nos": [str(item.get("intake_no") or "") for item in opened], + }, + ) + yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"}) + return + batch_no = str(result.get("batch_no") or "").strip() if batch_no: batch_event = _shipping_batch_ui_state_event(batch_no, user_id) @@ -196,6 +218,9 @@ class ShippingCreateBatchFromIntakesAction: "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")), + "document_version": focus_task.get("document_version"), + "duplicate_resolution_type": focus_task.get("duplicate_resolution_type"), + "supersedes_task_no": focus_task.get("supersedes_task_no"), } yield from _stream_text_events(content, message_type="text", payload=message_payload) yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"}) diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index 60f471ae..fb6efc8e 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -171,6 +171,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: ) ): is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF + # 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。 if ( not is_low_confidence_parse_confirm and ( @@ -182,7 +183,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: return tool_response( status="needs_human", task=task, - message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", + message="库存源尚未确定,请先完成库存源确认。", data=serialize_task_for_tool(task), human_options=ui.human_options, checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py new file mode 100644 index 00000000..9404f175 --- /dev/null +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -0,0 +1,645 @@ +""" +backend/app/services/shipping_notice/document_candidate_persist.py + +用途:阶段二——EML 附件派生 FileAsset、ShippingNoticeDocument / Candidate 幂等落库。 +依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、eml_parse。 +逻辑:由 intake_parse_workflow.run_intake_parse 在文本落库成功后调用;重试按 + (parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。 + Document↔派生资产的引用计数仅在 asset_id 变更时 +1/-1; + Candidate 重复检测可由调用方延后到 SAVEPOINT(run_duplicate_detection=False); + cancel / 阶段二失败可整单释放并清理 structured 投影字段。 +""" + +from __future__ import annotations + +import hashlib +import uuid +from datetime import datetime +from typing import Any + +from app import db +from app.models import ( + FileAsset, + ShippingNoticeCandidate, + ShippingNoticeDocument, + ShippingNoticeIntake, +) +from app.services.file_assets.service import ( + create_derived_file_asset_from_bytes, + mark_asset_referenced, + release_asset_reference, +) +from app.services.shipping_notice.business_fingerprint import build_business_fingerprint +from app.services.shipping_notice.eml_parse import pop_attachment_payload, strip_attachment_payloads +from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary +from app.services.shipping_notice.notice_upload import NoticeIntakeResult + +BODY_ATTACHMENT_KEY = 'body' + + +def generate_candidate_no() -> str: + """生成 SNC-YYYYMMDD-XXXXXXXX 格式候选编号。""" + return f"SNC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def _guess_source_type_for_doc(*, filename: str | None, mime_type: str | None, document_type: str) -> str: + if document_type == 'email_body': + return 'email' + name = str(filename or '').lower() + mime = str(mime_type or '').lower() + if name.endswith('.pdf') or 'pdf' in mime: + return 'pdf' + if name.endswith('.docx') or 'wordprocessingml' in mime: + return 'docx' + if name.endswith('.eml') or mime in {'message/rfc822', 'application/eml'}: + return 'email' + return 'manual' + + +def _has_order_signal(business_summary: dict[str, Any] | None) -> bool: + """是否具备真实业务标识(PO / Reservation / 行项目),禁止用文件名或哈希伪造。""" + summary = business_summary if isinstance(business_summary, dict) else {} + return bool( + str(summary.get('po_number') or '').strip() + or (summary.get('reservation_ids') or []) + or (summary.get('lines') or []) + ) + + +def _classify_document( + *, + document_type: str, + filename: str | None, + mime_type: str | None, + parse_status: str, + business_summary: dict[str, Any] | None, +) -> str: + """ + 文档分类:order_notice / email_context / supporting / unknown。 + + 核心逻辑:仅当业务摘要含真实 PO/Reservation/行项目时标 order_notice; + 邮件正文始终为 email_context(上下文/索引,不生成 Candidate); + 无信号的 parsed PDF/文本归 supporting,保留 Document 但不造假候选。 + """ + has_order_signal = _has_order_signal(business_summary) + status = str(parse_status or '').strip().lower() + name = str(filename or '').lower() + mime = str(mime_type or '').lower() + is_orderish_file = ( + name.endswith(('.pdf', '.docx', '.doc', '.txt', '.csv')) + or 'pdf' in mime + or 'wordprocessingml' in mime + or mime.startswith('text/') + ) + + if document_type == 'email_body': + return 'email_context' + if status == 'parsed' and has_order_signal: + return 'order_notice' + if status == 'parsed' and is_orderish_file: + return 'supporting' + if status in {'failed', 'empty', 'skipped', 'duplicate'}: + return 'supporting' if is_orderish_file else 'unknown' + return 'unknown' + + +def _should_create_candidate(*, document_type: str, classification: str, parse_status: str) -> bool: + """正文永不生成 Candidate;仅 order_notice + parsed 的附件/单文件可生成。""" + if str(document_type or '') == 'email_body': + return False + return classification == 'order_notice' and str(parse_status or '').lower() == 'parsed' + + +def _release_document_asset(asset_id: int | None) -> None: + """Document 不再引用时释放派生资产引用计数。""" + if not asset_id: + return + asset = db.session.get(FileAsset, int(asset_id)) + if asset is None: + return + if str(asset.asset_role or '') != 'derived_attachment': + return + release_asset_reference(asset) + + +def _should_persist_attachment_asset(item: dict[str, Any], payload: bytes) -> bool: + """有效订单附件:有二进制且非重复/纯超限 skip 时可落派生资产。""" + if not payload: + return False + status = str(item.get('parse_status') or '').lower() + if status == 'duplicate': + return False + if status == 'skipped': + # 过大/总量超限仍可不落库;其它 skipped(如超深)有 raw 时尽量保留供下载重试 + warnings = [str(w) for w in (item.get('warnings') or [])] + if any('too_large' in w or 'total_attachment_size_exceeded' in w for w in warnings): + return False + return True + + +def _upsert_document( + *, + intake: ShippingNoticeIntake, + attachment_key: str, + document_type: str, + filename: str | None, + content_hash: str | None, + parse_status: str, + extracted_text: str | None, + warnings: list[str], + asset_id: int | None, + classification: str, +) -> ShippingNoticeDocument: + row = ( + db.session.query(ShippingNoticeDocument) + .filter( + ShippingNoticeDocument.intake_id == int(intake.id), + ShippingNoticeDocument.attachment_key == attachment_key, + ) + .first() + ) + if row is None: + row = ShippingNoticeDocument( + intake_id=int(intake.id), + attachment_key=attachment_key, + document_type=document_type, + ) + db.session.add(row) + previous_asset_id = int(row.asset_id) if row.asset_id else None + row.document_type = document_type + row.filename = (filename or None) + row.content_hash = (content_hash or None) + row.parse_status = parse_status + row.extracted_text = extracted_text + row.parse_warnings_json = list(warnings or []) + row.asset_id = asset_id + row.classification = classification + row.updated_at = datetime.utcnow() + db.session.flush() + # 按 Document→Asset 关联边增减引用,避免「已 referenced」跳过 +1 导致漏计多文档共用 + new_asset_id = int(asset_id) if asset_id else None + if previous_asset_id and previous_asset_id != new_asset_id: + _release_document_asset(previous_asset_id) + if new_asset_id and previous_asset_id != new_asset_id: + new_asset = db.session.get(FileAsset, new_asset_id) + if new_asset is not None and str(new_asset.asset_role or '') == 'derived_attachment': + mark_asset_referenced(new_asset) + return row + + +def _upsert_candidate( + *, + intake: ShippingNoticeIntake, + document: ShippingNoticeDocument, + business_summary: dict[str, Any], + fingerprint: dict[str, Any], + duplicate_result: dict[str, Any], +) -> ShippingNoticeCandidate: + row = ( + db.session.query(ShippingNoticeCandidate) + .filter( + ShippingNoticeCandidate.intake_id == int(intake.id), + ShippingNoticeCandidate.primary_document_id == int(document.id), + ) + .first() + ) + if row is None: + row = ShippingNoticeCandidate( + candidate_no=generate_candidate_no(), + intake_id=int(intake.id), + primary_document_id=int(document.id), + selected=True, + validation_status='pending', + ) + db.session.add(row) + row.po_number = str(business_summary.get('po_number') or '').strip() or None + row.structured_result_json = { + 'business_summary': business_summary, + 'fingerprint_components': fingerprint.get('components') or {}, + } + row.confidence = ( + float(business_summary['confidence']) + if business_summary.get('confidence') is not None + else None + ) + row.business_fingerprint = fingerprint.get('fingerprint') + row.fingerprint_version = fingerprint.get('version') + row.fingerprint_strength = fingerprint.get('strength') + row.duplicate_status = str(duplicate_result.get('status') or 'none') + row.duplicate_matches_json = list(duplicate_result.get('matches') or []) + row.duplicate_checked_at = datetime.utcnow() + # 重解析后清空旧决策,避免陈旧 resolution + row.duplicate_resolution = None + row.duplicate_resolution_reason = None + row.duplicate_target_task_no = None + row.updated_at = datetime.utcnow() + db.session.flush() + return row + + +def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool) -> dict[str, Any]: + asset = db.session.get(FileAsset, int(doc.asset_id)) if doc.asset_id else None + payload: dict[str, Any] = { + 'id': doc.id, + 'document_type': doc.document_type, + 'attachment_key': doc.attachment_key, + 'filename': doc.filename, + 'content_hash': doc.content_hash, + 'classification': doc.classification, + 'parse_status': doc.parse_status, + 'asset_no': asset.asset_no if asset else None, + 'asset_id': doc.asset_id, + 'warnings': list(doc.parse_warnings_json or []), + } + if include_text: + payload['extracted_text'] = doc.extracted_text + else: + payload['text_length'] = len(str(doc.extracted_text or '')) + return payload + + +def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]: + matches = list(cand.duplicate_matches_json or []) + status = str(cand.duplicate_status or 'unchecked') + blocking = status in { + 'exact_file', + 'same_active_task', + 'same_completed_task', + 'possible_duplicate', + } + strength = str(cand.fingerprint_strength or 'unavailable') + if strength == 'unavailable' and status == 'none': + blocking = False + summary = None + if isinstance(cand.structured_result_json, dict): + summary = cand.structured_result_json.get('business_summary') + return { + 'candidate_no': cand.candidate_no, + 'primary_document_id': cand.primary_document_id, + 'po_number': cand.po_number, + 'confidence': cand.confidence, + 'validation_status': cand.validation_status, + 'selected': bool(cand.selected), + 'business_fingerprint': cand.business_fingerprint, + 'fingerprint_strength': cand.fingerprint_strength, + 'fingerprint_version': cand.fingerprint_version, + 'duplicate': { + 'status': status, + 'blocking': blocking, + 'matches': matches, + }, + 'duplicate_resolution': cand.duplicate_resolution, + 'business_summary': summary, + 'consumed_task_id': cand.consumed_task_id, + } + + +def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]: + """列出 Intake 下 Document 摘要。""" + rows = ( + db.session.query(ShippingNoticeDocument) + .filter(ShippingNoticeDocument.intake_id == int(intake_id)) + .order_by(ShippingNoticeDocument.id.asc()) + .all() + ) + return [_serialize_document_brief(row, include_text=include_text) for row in rows] + + +def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]: + """列出 Intake 下 Candidate 摘要。""" + rows = ( + db.session.query(ShippingNoticeCandidate) + .filter(ShippingNoticeCandidate.intake_id == int(intake_id)) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + return [_serialize_candidate_brief(row) for row in rows] + + +_UNCHECKED_DUP: dict[str, Any] = { + 'status': 'unchecked', + 'blocking': False, + 'matches': [], + 'fingerprint': None, + 'fingerprint_version': None, + 'fingerprint_strength': None, + 'components': {}, + 'allowed_actions': [], +} + + +def persist_documents_and_candidates( + *, + intake: ShippingNoticeIntake, + parent_asset: FileAsset, + result: NoticeIntakeResult, + uploaded_storage_keys: list[str] | None = None, + run_duplicate_detection: bool = True, +) -> dict[str, Any]: + """ + 从一次解析结果落派生资产 + Document + Candidate(仅 flush,由调用方统一 commit)。 + + 核心逻辑: + 1. 正文 Document(email_context,永不生成 Candidate); + 2. 附件 → 幂等派生 FileAsset → Document;仅真实订单信号生成 Candidate; + 3. 清理本轮无效 Document 与失效 Candidate;释放孤立派生资产引用; + 4. 剥离 `_payload_bytes`。 + run_duplicate_detection=False 时 Candidate 仅落基础行(duplicate=unchecked), + 供调用方在 SAVEPOINT 内再跑重复检测,避免检测 DB 异常连带回滚阶段二。 + + Returns: + {document_count, candidate_count, linked_asset_count, created_asset_count, documents, candidates} + """ + from app.services.shipping_notice.duplicate_detection import detect_duplicates_for_candidate + + meta = result.meta if isinstance(result.meta, dict) else {} + email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {} + body_text = str(email_meta.get('body_text') or '') + is_eml = str(meta.get('file_type') or '').lower() == 'eml' or bool(email_meta) + + active_keys: set[str] = set() + linked_asset_count = 0 + created_asset_count = 0 + documents: list[ShippingNoticeDocument] = [] + candidates: list[ShippingNoticeCandidate] = [] + active_candidate_doc_ids: set[int] = set() + + # [STEP 1] 正文 Document:仅邮件级上下文,不生成 Candidate + if is_eml: + body_summary = parse_intake_business_summary( + extracted_text=body_text, + source_type='email', + ) + body_class = _classify_document( + document_type='email_body', + filename=parent_asset.original_filename, + mime_type=parent_asset.mime_type, + parse_status='parsed' if body_text.strip() else 'empty', + business_summary=body_summary, + ) + body_hash = hashlib.sha256(body_text.encode('utf-8')).hexdigest().lower() if body_text else None + body_doc = _upsert_document( + intake=intake, + attachment_key=BODY_ATTACHMENT_KEY, + document_type='email_body', + filename=parent_asset.original_filename, + content_hash=body_hash or str(parent_asset.content_hash or '') or None, + parse_status='parsed' if body_text.strip() else 'empty', + extracted_text=body_text or None, + warnings=[], + asset_id=None, + classification=body_class, + ) + active_keys.add(BODY_ATTACHMENT_KEY) + documents.append(body_doc) + + # [STEP 2] 附件派生资产 + Document + Candidate(需真实业务信号) + raw_attachments = list(meta.get('attachments') or []) + for item in raw_attachments: + if not isinstance(item, dict): + continue + key = str(item.get('attachment_key') or '').strip() + if not key: + continue + payload = pop_attachment_payload(item) + asset_id: int | None = None + if _should_persist_attachment_asset(item, payload): + child, created_new = create_derived_file_asset_from_bytes( + user_id=int(intake.user_id), + parent=parent_asset, + data=payload, + filename=str(item.get('filename') or f'{key}.bin'), + mime_type=str(item.get('mime_type') or '') or None, + source_attachment_key=key, + uploaded_storage_keys=uploaded_storage_keys, + ) + asset_id = int(child.id) + linked_asset_count += 1 + if created_new: + created_asset_count += 1 + item['asset_no'] = child.asset_no + item['asset_id'] = child.id + + att_text = str(item.get('extracted_text') or '') + att_status = str(item.get('parse_status') or 'empty') + att_summary = parse_intake_business_summary( + extracted_text=att_text, + source_type=_guess_source_type_for_doc( + filename=str(item.get('filename') or ''), + mime_type=str(item.get('mime_type') or ''), + document_type='attachment', + ), + ) + classification = _classify_document( + document_type='attachment', + filename=str(item.get('filename') or ''), + mime_type=str(item.get('mime_type') or ''), + parse_status=att_status, + business_summary=att_summary, + ) + + doc = _upsert_document( + intake=intake, + attachment_key=key, + document_type='attachment', + filename=str(item.get('filename') or '') or None, + content_hash=str(item.get('content_hash') or '') or None, + parse_status=att_status, + extracted_text=att_text or None, + warnings=[str(w) for w in (item.get('warnings') or [])], + asset_id=asset_id, + classification=classification, + ) + item['document_id'] = doc.id + active_keys.add(key) + documents.append(doc) + + if _should_create_candidate( + document_type='attachment', + classification=classification, + parse_status=att_status, + ): + fp = build_business_fingerprint(att_summary) + if run_duplicate_detection: + child_asset = db.session.get(FileAsset, int(asset_id)) if asset_id else parent_asset + dup = detect_duplicates_for_candidate( + intake=intake, + asset=child_asset or parent_asset, + document=doc, + business_summary=att_summary, + fingerprint_result=fp, + ) + else: + dup = dict(_UNCHECKED_DUP) + cand = _upsert_candidate( + intake=intake, + document=doc, + business_summary=att_summary, + fingerprint=fp, + duplicate_result=dup, + ) + candidates.append(cand) + active_candidate_doc_ids.add(int(doc.id)) + + # [STEP 3] 非 EML 单文件:有真实订单信号才生成 Candidate + if not is_eml: + file_summary = parse_intake_business_summary( + extracted_text=str(result.text or ''), + source_type=str(result.source_type or 'manual'), + ) + file_class = _classify_document( + document_type='attachment', + filename=result.filename, + mime_type=result.source_file_type, + parse_status='parsed', + business_summary=file_summary, + ) + file_doc = _upsert_document( + intake=intake, + attachment_key='file', + document_type='attachment', + filename=result.filename, + content_hash=str(result.content_hash or parent_asset.content_hash or '') or None, + parse_status='parsed', + extracted_text=str(result.text or '') or None, + warnings=list(result.warnings or []), + asset_id=int(parent_asset.id), + classification=file_class, + ) + active_keys.add('file') + documents.append(file_doc) + if _should_create_candidate( + document_type='attachment', + classification=file_class, + parse_status='parsed', + ): + fp = build_business_fingerprint(file_summary) + if run_duplicate_detection: + dup = detect_duplicates_for_candidate( + intake=intake, + asset=parent_asset, + document=file_doc, + business_summary=file_summary, + fingerprint_result=fp, + ) + else: + dup = dict(_UNCHECKED_DUP) + cand = _upsert_candidate( + intake=intake, + document=file_doc, + business_summary=file_summary, + fingerprint=fp, + duplicate_result=dup, + ) + candidates.append(cand) + active_candidate_doc_ids.add(int(file_doc.id)) + + # [STEP 4] 清理消失的 Document,并释放其派生资产 + stale_docs = ( + db.session.query(ShippingNoticeDocument) + .filter( + ShippingNoticeDocument.intake_id == int(intake.id), + ShippingNoticeDocument.attachment_key.notin_(tuple(active_keys) or ('__none__',)), + ) + .all() + ) + stale_ids = {int(d.id) for d in stale_docs} + if stale_ids: + db.session.query(ShippingNoticeCandidate).filter( + ShippingNoticeCandidate.intake_id == int(intake.id), + ShippingNoticeCandidate.primary_document_id.in_(tuple(stale_ids)), + ).delete(synchronize_session=False) + for doc in stale_docs: + _release_document_asset(int(doc.asset_id) if doc.asset_id else None) + db.session.delete(doc) + + # [STEP 5] 清理本轮不再具备候选资格的旧 Candidate(Document 仍在但 classification 变了) + stale_cand_q = db.session.query(ShippingNoticeCandidate).filter( + ShippingNoticeCandidate.intake_id == int(intake.id), + ) + if active_candidate_doc_ids: + stale_cand_q = stale_cand_q.filter( + ShippingNoticeCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)), + ) + stale_cand_q.delete(synchronize_session=False) + + # [STEP 6] 剥离 payload,防止后续 structured_result 泄漏 + strip_attachment_payloads(meta) + + db.session.flush() + return { + 'document_count': len(documents), + 'candidate_count': len(candidates), + 'linked_asset_count': linked_asset_count, + 'created_asset_count': created_asset_count, + 'documents': [_serialize_document_brief(d, include_text=False) for d in documents], + 'candidates': [_serialize_candidate_brief(c) for c in candidates], + } + + +def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> None: + """ + 清理 structured_result_json 中的阶段二投影(document/candidate 计数与附件资产标识)。 + + 核心逻辑:取消或阶段二失败后,避免摘要仍指向已删除的 Document/Asset。 + """ + structured = ( + dict(intake.structured_result_json) + if isinstance(intake.structured_result_json, dict) + else {} + ) + structured.pop('document_count', None) + structured.pop('candidate_count', None) + attachments = structured.get('attachments') + if isinstance(attachments, list): + cleaned: list[dict[str, Any]] = [] + for item in attachments: + if not isinstance(item, dict): + continue + row = dict(item) + row.pop('asset_no', None) + row.pop('asset_id', None) + row.pop('document_id', None) + cleaned.append(row) + structured['attachments'] = cleaned + intake.structured_result_json = structured + intake.updated_at = datetime.utcnow() + + +def release_unconsumed_intake_stage2(*, intake: ShippingNoticeIntake) -> dict[str, int]: + """ + 删除未消费 Intake 的 Document/Candidate,并释放派生资产引用。 + + 核心逻辑:用于 cancel / 阶段二重试失败清理;已 consumed 的 Intake 不得调用。 + Candidate 先删(FK 指向 Document),再逐项 release 派生资产后删 Document。 + + Args: + intake: 目标接入记录(须已锁定或处于独占写路径)。 + + Returns: + 删除的 candidate/document 数量及释放的 asset 次数。 + """ + candidates = ( + db.session.query(ShippingNoticeCandidate) + .filter(ShippingNoticeCandidate.intake_id == int(intake.id)) + .all() + ) + documents = ( + db.session.query(ShippingNoticeDocument) + .filter(ShippingNoticeDocument.intake_id == int(intake.id)) + .all() + ) + for cand in candidates: + db.session.delete(cand) + released_assets = 0 + for doc in documents: + if doc.asset_id: + _release_document_asset(int(doc.asset_id)) + released_assets += 1 + db.session.delete(doc) + db.session.flush() + return { + 'deleted_candidates': len(candidates), + 'deleted_documents': len(documents), + 'released_assets': released_assets, + } diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py new file mode 100644 index 00000000..4e1bdb71 --- /dev/null +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -0,0 +1,609 @@ +""" +backend/app/services/shipping_notice/duplicate_detection.py + +用途:发货通知业务重复检测(文件哈希 + 业务指纹),产出统一 duplicate 结果。 +依赖:models.ShippingTask/FileAsset/Document/Candidate、business_fingerprint、core.response.utc_iso。 +逻辑:Intake 级与 Candidate 级共用匹配规则;候选 A 重复只写回 A,不连带阻断同信其它候选; + 刷新入口按 Candidate 重检再聚合到 Intake;检测异常可 clear 为 unchecked; + 范围限定当前 user_id,不跨用户泄露。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.core.response import utc_iso +from app.models import ( + FileAsset, + ShippingNoticeCandidate, + ShippingNoticeDocument, + ShippingNoticeIntake, + ShippingTask, +) +from app.services.shipping_notice.business_fingerprint import FINGERPRINT_VERSION, build_business_fingerprint + +# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态) +_ACTIVE_PROCESS_STATUSES = frozenset( + { + 'created', + 'parsed', + 'pending_review', + 'inventory_ready', + 'waiting_inventory', + 'matched', + 'waiting_upload', + 'upload_failed', + } +) +_COMPLETED_PROCESS_STATUSES = frozenset({'uploaded', 'completed'}) +_CLOSED_PROCESS_STATUSES = frozenset({'closed', 'rejected'}) +_IRREVERSIBLE_PROCESS_STATUSES = frozenset({'uploaded', 'completed', 'closed', 'rejected'}) + + +def classify_task_lifecycle(process_status: str | None) -> str: + """将 process_status 归类为 active / completed / closed / unknown。""" + status = str(process_status or '').strip().lower() + if status in _ACTIVE_PROCESS_STATUSES: + return 'active' + if status in _COMPLETED_PROCESS_STATUSES: + return 'completed' + if status in _CLOSED_PROCESS_STATUSES: + return 'closed' + return 'unknown' + + +def is_irreversible_task(task: ShippingTask) -> bool: + """已 uploaded 或终态任务不可原地覆盖源文件。""" + status = str(task.process_status or '').strip().lower() + if status in _IRREVERSIBLE_PROCESS_STATUSES: + return True + upload_status = str(task.upload_status or '').strip().lower() + return upload_status in {'uploaded', 'succeeded', 'success'} + + +def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]: + return { + 'task_no': task.task_no, + 'process_status': task.process_status, + 'document_version': int(task.document_version or 1), + 'match_type': match_type, + 'matched_fields': list(matched_fields), + 'lifecycle': classify_task_lifecycle(task.process_status), + 'created_at': utc_iso(task.created_at), + } + + +def _allowed_actions_for( + *, + status: str, + fingerprint_strength: str, + matches: list[dict[str, Any]], +) -> list[str]: + if status in {'none', 'unchecked'} or not matches: + return [] + actions = ['open_existing'] + primary = matches[0] + lifecycle = str(primary.get('lifecycle') or '') + if lifecycle in {'active', 'completed', 'closed'}: + actions.append('create_revision') + if fingerprint_strength in {'strong', 'medium', 'weak', 'unavailable'}: + actions.append('force_create') + return actions + + +def detect_duplicates_for_intake( + *, + intake: ShippingNoticeIntake, + asset: FileAsset | None = None, + business_summary: dict[str, Any] | None = None, + fingerprint_result: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 对已解析 intake 执行重复检测。 + + 核心逻辑: + 1. 同用户同 content_hash 且已有未关闭任务 → exact_file; + 2. 同业务指纹任务 → same_active_task / same_completed_task; + 3. 弱指纹仅可能标记 possible_duplicate; + 4. strength=unavailable 不阻断。 + + Returns: + {status, blocking, fingerprint_strength, fingerprint, fingerprint_version, matches, allowed_actions, components} + """ + summary = business_summary if isinstance(business_summary, dict) else ( + intake.structured_result_json.get('business_summary') + if isinstance(intake.structured_result_json, dict) + else None + ) + fp = fingerprint_result or build_business_fingerprint(summary if isinstance(summary, dict) else {}) + strength = str(fp.get('strength') or 'unavailable') + fingerprint = fp.get('fingerprint') + version = str(fp.get('version') or FINGERPRINT_VERSION) + components = fp.get('components') if isinstance(fp.get('components'), dict) else {} + + if asset is None: + asset = db.session.get(FileAsset, int(intake.asset_id)) + + matches: list[dict[str, Any]] = [] + status = 'none' + + # [STEP 1] 精确文件哈希 + content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower() + if content_hash: + hash_tasks = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(intake.user_id), + ShippingTask.source_content_hash == content_hash, + ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)), + ) + .order_by(ShippingTask.id.desc()) + .limit(10) + .all() + ) + for task in hash_tasks: + matches.append( + _match_payload( + task, + match_type='exact_file', + matched_fields=['source_content_hash'], + ) + ) + if matches: + status = 'exact_file' + + # [STEP 2] 业务指纹 + if fingerprint and strength in {'strong', 'medium'}: + fp_tasks = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(intake.user_id), + ShippingTask.business_fingerprint == fingerprint, + ShippingTask.fingerprint_version == version, + ) + .order_by(ShippingTask.id.desc()) + .limit(20) + .all() + ) + matched_fields = list(components.keys()) + for task in fp_tasks: + # 跳过已被当前 exact_file 命中过的同一 task + if any(m.get('task_no') == task.task_no for m in matches): + continue + matches.append( + _match_payload( + task, + match_type='business_fingerprint', + matched_fields=matched_fields, + ) + ) + if matches and status == 'none': + primary_life = classify_task_lifecycle(matches[0].get('process_status')) + if primary_life == 'active': + status = 'same_active_task' + elif primary_life == 'completed': + status = 'same_completed_task' + else: + status = 'possible_duplicate' + elif matches and status == 'exact_file': + # 同文件命中优先;保留 status=exact_file + pass + elif fingerprint and strength == 'weak' and status == 'none': + # 弱指纹:仅标记疑似,不按 active 强阻断 + fp_tasks = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(intake.user_id), + ShippingTask.business_fingerprint == fingerprint, + ShippingTask.fingerprint_version == version, + ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)), + ) + .order_by(ShippingTask.id.desc()) + .limit(5) + .all() + ) + for task in fp_tasks: + matches.append( + _match_payload( + task, + match_type='weak_fingerprint', + matched_fields=list(components.keys()), + ) + ) + if matches: + status = 'possible_duplicate' + + blocking = status in { + 'exact_file', + 'same_active_task', + 'same_completed_task', + 'possible_duplicate', # 疑似重复须用户确认,不可静默建单 + } + if strength == 'unavailable' and status == 'none': + blocking = False + + return { + 'status': status, + 'blocking': blocking, + 'fingerprint_strength': strength, + 'fingerprint': fingerprint, + 'fingerprint_version': version, + 'components': components, + 'matches': matches, + 'allowed_actions': _allowed_actions_for( + status=status, + fingerprint_strength=strength, + matches=matches, + ), + 'checked_at': utc_iso(datetime.utcnow()), + } + + +def apply_duplicate_result_to_intake( + intake: ShippingNoticeIntake, + result: dict[str, Any], +) -> None: + """将检测结果写回 intake ORM 字段(不 commit)。""" + intake.business_fingerprint = result.get('fingerprint') + intake.fingerprint_version = result.get('fingerprint_version') + intake.fingerprint_strength = result.get('fingerprint_strength') + intake.duplicate_status = str(result.get('status') or 'none') + intake.duplicate_matches_json = list(result.get('matches') or []) + intake.duplicate_checked_at = datetime.utcnow() + # 重新检测后清空旧决策,避免陈旧 resolution + intake.duplicate_resolution = None + intake.duplicate_resolution_reason = None + intake.duplicate_target_task_no = None + intake.duplicate_resolved_by_id = None + intake.duplicate_resolved_at = None + intake.updated_at = datetime.utcnow() + + +def clear_duplicate_state_to_unchecked(*, intake: ShippingNoticeIntake) -> None: + """ + 将 Intake 与其 Candidate 的重复结果/决策统一清空为 unchecked。 + + 核心逻辑:重复检测 SAVEPOINT 回滚后调用,避免 partial 写回与陈旧 resolution 并存。 + """ + now = datetime.utcnow() + intake.duplicate_status = 'unchecked' + intake.duplicate_matches_json = [] + intake.business_fingerprint = None + intake.fingerprint_version = None + intake.fingerprint_strength = None + intake.duplicate_checked_at = now + intake.duplicate_resolution = None + intake.duplicate_resolution_reason = None + intake.duplicate_target_task_no = None + intake.duplicate_resolved_by_id = None + intake.duplicate_resolved_at = None + intake.updated_at = now + candidates = ( + db.session.query(ShippingNoticeCandidate) + .filter(ShippingNoticeCandidate.intake_id == int(intake.id)) + .all() + ) + for candidate in candidates: + candidate.duplicate_status = 'unchecked' + candidate.duplicate_matches_json = [] + candidate.duplicate_checked_at = now + candidate.duplicate_resolution = None + candidate.duplicate_resolution_reason = None + candidate.duplicate_target_task_no = None + candidate.updated_at = now + + +def apply_duplicate_result_to_candidate( + candidate: ShippingNoticeCandidate, + result: dict[str, Any], + *, + clear_resolution: bool = True, +) -> None: + """ + 将检测结果写回 Candidate ORM 字段(不 commit)。 + + 核心逻辑:刷新/重解析后同步 duplicate_* 与指纹概要;默认清空旧决策。 + """ + candidate.duplicate_status = str(result.get('status') or 'none') + candidate.duplicate_matches_json = list(result.get('matches') or []) + candidate.duplicate_checked_at = datetime.utcnow() + if result.get('fingerprint') is not None: + candidate.business_fingerprint = result.get('fingerprint') + if result.get('fingerprint_version') is not None: + candidate.fingerprint_version = result.get('fingerprint_version') + if result.get('fingerprint_strength') is not None: + candidate.fingerprint_strength = result.get('fingerprint_strength') + if clear_resolution: + candidate.duplicate_resolution = None + candidate.duplicate_resolution_reason = None + candidate.duplicate_target_task_no = None + candidate.updated_at = datetime.utcnow() + + +def refresh_candidates_and_aggregate_intake( + *, + intake: ShippingNoticeIntake, + parent_asset: FileAsset | None = None, +) -> dict[str, Any]: + """ + 逐 Candidate 重跑重复检测,写回各候选后聚合 Intake 概览。 + + 核心逻辑:有 Candidate 时必须走候选级路径,避免仅刷新 Intake 造成数据分裂; + 无候选时回退扁平 Intake 级检测。 + 调用方须已对 Intake FOR UPDATE,并确认仍为 parsed 且未消费。 + + Returns: + 聚合后的 duplicate 结果(已 apply 到 Intake;Candidate 已写回)。 + """ + candidates = ( + db.session.query(ShippingNoticeCandidate) + .filter(ShippingNoticeCandidate.intake_id == int(intake.id)) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + if not candidates: + summary = ( + intake.structured_result_json.get('business_summary') + if isinstance(intake.structured_result_json, dict) + else None + ) + summary = summary if isinstance(summary, dict) else {} + fingerprint = build_business_fingerprint(summary) + result = detect_duplicates_for_intake( + intake=intake, + asset=parent_asset, + business_summary=summary, + fingerprint_result=fingerprint, + ) + apply_duplicate_result_to_intake(intake, result) + return result + + candidate_results: list[dict[str, Any]] = [] + for candidate in candidates: + document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id)) + structured = ( + candidate.structured_result_json + if isinstance(candidate.structured_result_json, dict) + else {} + ) + summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {} + fingerprint = build_business_fingerprint(summary) + child_asset = None + if document is not None and document.asset_id: + child_asset = db.session.get(FileAsset, int(document.asset_id)) + dup = detect_duplicates_for_candidate( + intake=intake, + asset=child_asset or parent_asset, + document=document, + business_summary=summary, + fingerprint_result=fingerprint, + ) + apply_duplicate_result_to_candidate(candidate, dup) + candidate_results.append(dup) + + aggregated = aggregate_intake_duplicate_from_candidates(intake, candidate_results) + # 概览指纹不足时用扁平摘要补强列表展示 + structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} + flat_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {} + if flat_summary and not aggregated.get('fingerprint'): + flat_fp = build_business_fingerprint(flat_summary) + if flat_fp.get('fingerprint'): + aggregated = { + **aggregated, + 'fingerprint': flat_fp.get('fingerprint'), + 'fingerprint_version': flat_fp.get('version'), + 'fingerprint_strength': flat_fp.get('strength'), + 'components': flat_fp.get('components') or {}, + } + apply_duplicate_result_to_intake(intake, aggregated) + return aggregated + + +def detect_duplicates_for_candidate( + *, + intake: ShippingNoticeIntake, + asset: FileAsset | None = None, + document: ShippingNoticeDocument | None = None, + business_summary: dict[str, Any] | None = None, + fingerprint_result: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 对单个订单候选执行重复检测(不写 Intake,不影响同信其它候选)。 + + 核心逻辑:与 detect_duplicates_for_intake 同源规则,但 exact_file 优先用 + Document/派生资产 content_hash(单 PDF),避免整封 EML 哈希误伤其它订单。 + + Returns: + 与 intake 检测相同结构的结果字典。 + """ + summary = business_summary if isinstance(business_summary, dict) else {} + fp = fingerprint_result or build_business_fingerprint(summary) + strength = str(fp.get('strength') or 'unavailable') + fingerprint = fp.get('fingerprint') + version = str(fp.get('version') or FINGERPRINT_VERSION) + components = fp.get('components') if isinstance(fp.get('components'), dict) else {} + + content_hash = '' + if document is not None and str(document.content_hash or '').strip(): + content_hash = str(document.content_hash).strip().lower() + if not content_hash and asset is not None: + content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower() + + matches: list[dict[str, Any]] = [] + status = 'none' + + # [STEP 1] 精确文件哈希(附件级) + if content_hash: + hash_tasks = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(intake.user_id), + ShippingTask.source_content_hash == content_hash, + ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)), + ) + .order_by(ShippingTask.id.desc()) + .limit(10) + .all() + ) + for task in hash_tasks: + matches.append( + _match_payload( + task, + match_type='exact_file', + matched_fields=['source_content_hash'], + ) + ) + if matches: + status = 'exact_file' + + # [STEP 2] 业务指纹 + if fingerprint and strength in {'strong', 'medium'}: + fp_tasks = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(intake.user_id), + ShippingTask.business_fingerprint == fingerprint, + ShippingTask.fingerprint_version == version, + ) + .order_by(ShippingTask.id.desc()) + .limit(20) + .all() + ) + matched_fields = list(components.keys()) + for task in fp_tasks: + if any(m.get('task_no') == task.task_no for m in matches): + continue + matches.append( + _match_payload( + task, + match_type='business_fingerprint', + matched_fields=matched_fields, + ) + ) + if matches and status == 'none': + primary_life = classify_task_lifecycle(matches[0].get('process_status')) + if primary_life == 'active': + status = 'same_active_task' + elif primary_life == 'completed': + status = 'same_completed_task' + else: + status = 'possible_duplicate' + elif fingerprint and strength == 'weak' and status == 'none': + fp_tasks = ( + db.session.query(ShippingTask) + .filter( + ShippingTask.user_id == int(intake.user_id), + ShippingTask.business_fingerprint == fingerprint, + ShippingTask.fingerprint_version == version, + ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)), + ) + .order_by(ShippingTask.id.desc()) + .limit(5) + .all() + ) + for task in fp_tasks: + matches.append( + _match_payload( + task, + match_type='weak_fingerprint', + matched_fields=list(components.keys()), + ) + ) + if matches: + status = 'possible_duplicate' + + blocking = status in { + 'exact_file', + 'same_active_task', + 'same_completed_task', + 'possible_duplicate', + } + if strength == 'unavailable' and status == 'none': + blocking = False + + return { + 'status': status, + 'blocking': blocking, + 'fingerprint_strength': strength, + 'fingerprint': fingerprint, + 'fingerprint_version': version, + 'components': components, + 'matches': matches, + 'allowed_actions': _allowed_actions_for( + status=status, + fingerprint_strength=strength, + matches=matches, + ), + 'checked_at': utc_iso(datetime.utcnow()), + } + + +def aggregate_intake_duplicate_from_candidates( + intake: ShippingNoticeIntake, + candidate_results: list[dict[str, Any]], +) -> dict[str, Any]: + """ + 将多个 Candidate 检测结果汇总到 Intake(仅概览,不抹平单候选独立性)。 + + 核心逻辑:全部 none → none;部分阻断 → partial_duplicate;全部同态则透传该状态。 + """ + if not candidate_results: + return { + 'status': 'none', + 'blocking': False, + 'fingerprint_strength': 'unavailable', + 'fingerprint': None, + 'fingerprint_version': FINGERPRINT_VERSION, + 'components': {}, + 'matches': [], + 'allowed_actions': [], + 'checked_at': utc_iso(datetime.utcnow()), + } + + statuses = [str(item.get('status') or 'none') for item in candidate_results] + blocking_items = [item for item in candidate_results if item.get('blocking')] + unique_blocking = {str(item.get('status') or 'none') for item in blocking_items} + + if not blocking_items: + status = 'none' + blocking = False + elif len(unique_blocking) == 1 and len(blocking_items) == len(candidate_results): + status = next(iter(unique_blocking)) + blocking = True + else: + status = 'partial_duplicate' + blocking = True + + # 概览指纹:取首个强/中指纹候选;否则首个候选 + primary = next( + ( + item + for item in candidate_results + if str(item.get('fingerprint_strength') or '') in {'strong', 'medium'} + ), + candidate_results[0], + ) + matches: list[dict[str, Any]] = [] + for item in blocking_items: + for match in item.get('matches') or []: + if isinstance(match, dict) and match not in matches: + matches.append(match) + + return { + 'status': status, + 'blocking': blocking, + 'fingerprint_strength': primary.get('fingerprint_strength'), + 'fingerprint': primary.get('fingerprint'), + 'fingerprint_version': primary.get('fingerprint_version') or FINGERPRINT_VERSION, + 'components': primary.get('components') or {}, + 'matches': matches, + 'allowed_actions': _allowed_actions_for( + status=status, + fingerprint_strength=str(primary.get('fingerprint_strength') or 'unavailable'), + matches=matches, + ), + 'checked_at': utc_iso(datetime.utcnow()), + 'candidate_statuses': statuses, + } diff --git a/backend/app/services/shipping_notice/eml_parse.py b/backend/app/services/shipping_notice/eml_parse.py new file mode 100644 index 00000000..25d5bb2d --- /dev/null +++ b/backend/app/services/shipping_notice/eml_parse.py @@ -0,0 +1,1195 @@ +""" +services/shipping_notice/eml_parse.py + +用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。 +依赖:标准库 email/html;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。 +逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图; + 嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件; + 外层 body 不穿透 rfc822 / 附件型 multipart,避免订单文本误入正文或重复; + 单附件失败不影响其余附件;总大小:顶层容器计费,展开子内容不计费; + 附件摘要内存字段 `_payload_bytes` 供阶段二派生 FileAsset,写库/API 前须剥离。 +""" + +from __future__ import annotations + +import hashlib +import html as html_lib +import re +import tempfile +from dataclasses import dataclass, field +from email import policy +from email.message import Message +from email.parser import BytesParser +from email.utils import parsedate_to_datetime +from pathlib import Path +from typing import Any, Callable + +# 签名/Logo 文件名启发式(仅对 image/* 生效) +_SIGNATURE_LOGO_NAME_RE = re.compile( + r"(?:^|[_.\-])(logo|signature|sig|banner|icon|spacer|pixel|footer|header)(?:[_.\-]|$)", + re.IGNORECASE, +) + + +@dataclass +class EmlLimits: + """EML 解析安全上限。""" + + max_attachments: int = 20 + max_attachment_bytes: int = 20 * 1024 * 1024 + max_total_attachment_bytes: int = 50 * 1024 * 1024 + max_nesting_depth: int = 3 + + +def load_eml_limits() -> EmlLimits: + """ + 从 Flask 配置读取 EML 安全上限;无应用上下文时回退默认值。 + + Returns: + EmlLimits: 附件数量/大小/总大小/嵌套深度上限。 + """ + defaults = EmlLimits() + try: + from flask import current_app + + cfg = current_app.config + except RuntimeError: + return defaults + + def _int(key: str, fallback: int) -> int: + raw = cfg.get(key) + try: + value = int(raw) if raw is not None and str(raw).strip() != "" else fallback + except (TypeError, ValueError): + return fallback + return value if value > 0 else fallback + + return EmlLimits( + max_attachments=_int("SHIPPING_NOTICE_EML_MAX_ATTACHMENTS", defaults.max_attachments), + max_attachment_bytes=_int( + "SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES", defaults.max_attachment_bytes + ), + max_total_attachment_bytes=_int( + "SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES", + defaults.max_total_attachment_bytes, + ), + max_nesting_depth=_int("SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH", defaults.max_nesting_depth), + ) + + +def _header_str(msg: Message, name: str) -> str: + """读取并规范化邮件头为单行字符串。""" + raw = msg.get(name) + if raw is None: + return "" + return " ".join(str(raw).split()) + + +def _decode_part_text(part: Message | None, data: bytes) -> str: + """ + 按 MIME 声明的 charset 优先解码文本字节。 + + 核心逻辑:先试 part.get_content_charset(),再回退 utf-8/GB/latin-1,避免欧洲邮件乱码。 + """ + if not data: + return "" + candidates: list[str] = [] + charset = "" + if part is not None: + try: + charset = str(part.get_content_charset() or "").strip() + except Exception: + charset = "" + if charset: + candidates.append(charset) + candidates.extend(("utf-8", "utf-8-sig", "gb18030", "gbk", "latin-1", "cp1252")) + seen: set[str] = set() + for enc in candidates: + key = enc.lower().replace("_", "-") + if key in seen: + continue + seen.add(key) + try: + return data.decode(enc) + except Exception: + continue + return data.decode("utf-8", errors="replace") + + +def _html_to_text(raw_html: str) -> str: + """ + 简易 HTML 转文本:去脚本样式、保留表格行列边界、解码实体;不执行脚本。 + + 核心逻辑:→换行、|→制表符;压缩空格时不得吞掉制表符。 + """ + s = re.sub(r"(?is)<(script|style).*?>.*?", "", raw_html or "") + s = re.sub(r"(?is)", "\n", s) + s = re.sub(r"(?is)", "\n", s) + s = re.sub(r"(?is)", "\n", s) + s = re.sub(r"(?is)", "\n", s) + s = re.sub(r"(?is)", "\t", s) + s = re.sub(r"(?is)<[^>]+>", " ", s) + s = html_lib.unescape(s) + # 只压缩空格,保留 \t 作为列分隔 + s = re.sub(r" +", " ", s) + s = re.sub(r" *\t *", "\t", s) + s = re.sub(r"\n\s*\n+", "\n\n", s) + return s.strip() + + +def _normalize_message_id(value: str) -> str: + text = str(value or "").strip() + if not text: + return "" + return text + + +def _format_date(msg: Message) -> str: + raw = _header_str(msg, "Date") + if not raw: + return "" + try: + dt = parsedate_to_datetime(raw) + if dt is not None: + return dt.isoformat() + except Exception: + pass + return raw + + +def _looks_like_signature_or_logo(filename: str) -> bool: + name = Path(str(filename or "")).name + return bool(_SIGNATURE_LOGO_NAME_RE.search(name)) + + +def _part_filename(part: Message, fallback: str = "attachment.bin") -> str: + name = str(part.get_filename() or "").strip() + if name: + return name + ctype = str(part.get_content_type() or "application/octet-stream") + subtype = ctype.split("/", 1)[-1] if "/" in ctype else "bin" + return f"{fallback}.{subtype}" + + +def _is_body_text_part(part: Message) -> bool: + """ + 判定是否为邮件正文部件。 + + 核心逻辑:text/plain|html 且非 attachment;带 filename/name 的文本部件视为附件而非正文。 + """ + ctype = str(part.get_content_type() or "") + if ctype not in {"text/plain", "text/html"}: + return False + if part.get_content_disposition() == "attachment": + return False + if str(part.get_filename() or "").strip(): + return False + return True + + +def _is_inline_or_embedded_resource(part: Message) -> bool: + """ + 判定应忽略的内嵌资源 / 签名图 / Logo。 + + 核心逻辑:仅跳过图片类 inline/CID/签名文件名;inline PDF 等可下载内容仍视为真实附件。 + """ + ctype = str(part.get_content_type() or "").lower() + disp = part.get_content_disposition() + content_id = str(part.get("Content-ID") or "").strip() + filename = str(part.get_filename() or "").strip() + + if not ctype.startswith("image/"): + return False + if disp == "attachment": + return False + if disp == "inline" or content_id: + return True + if filename and _looks_like_signature_or_logo(filename): + return True + return False + + +def _is_real_attachment(part: Message) -> bool: + """判定是否为真实附件(排除 multipart、正文、内嵌图片、嵌套 rfc822 容器)。""" + if part.is_multipart(): + return False + ctype = str(part.get_content_type() or "").lower() + if ctype == "message/rfc822": + return False + if _is_body_text_part(part): + return False + if _is_inline_or_embedded_resource(part): + return False + disp = part.get_content_disposition() + if disp == "attachment": + return True + if part.get_filename(): + return True + # inline 的非图片可下载内容(如 PDF)按真实附件处理 + if disp == "inline" and not ctype.startswith("image/"): + return True + if not ctype.startswith("text/") and ctype not in {"message/delivery-status", "text/calendar"}: + if disp is None and ctype.startswith("application/"): + return True + return False + + +def _read_part_payload(part: Message) -> bytes: + """读取 MIME 部件解码后的原始字节;失败返回空。""" + try: + payload = part.get_payload(decode=True) + except Exception: + return b"" + if isinstance(payload, bytes): + return payload + if isinstance(payload, str): + return payload.encode("utf-8", errors="ignore") + return b"" + + +def _part_as_text(part: Message) -> str: + """将文本部件按 charset 解码并在需要时做 HTML 清洗。""" + raw = _read_part_payload(part) + text = _decode_part_text(part, raw) + if str(part.get_content_type() or "") == "text/html": + return _html_to_text(text) + return text.strip() + + +def _is_attached_multipart(part: Message) -> bool: + """ + 判定 multipart 是否应视为「文件附件容器」(而非可选正文结构)。 + + 核心逻辑:Content-Disposition=attachment 或带 filename/name 的 multipart/* + (如 bundle.mime)须登记为独立附件,禁止当外层正文树展开。 + """ + if not isinstance(part, Message) or not part.is_multipart(): + return False + ctype = str(part.get_content_type() or "").lower() + if ctype == "message/rfc822": + return False + if part.get_content_disposition() == "attachment": + return True + if str(part.get_filename() or "").strip(): + return True + try: + name_param = str(part.get_param("name") or "").strip() + except Exception: + name_param = "" + return bool(name_param) + + +def _iter_local_body_candidates(msg: Message, *, root: bool = True): + """ + 遍历可作为「当前容器正文」的 text 部件。 + + 核心逻辑:不穿透 message/rfc822 与附件型 multipart(二者由独立附件登记), + 避免外层 body_text 吞掉附件内订单文本。 + """ + ctype = str(msg.get_content_type() or "").lower() + if ctype == "message/rfc822": + return + if msg.is_multipart(): + # 根若本身是附件型 multipart,正文候选应为空(由附件路径提取) + if not root and _is_attached_multipart(msg): + return + if root and _is_attached_multipart(msg): + return + parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or []) + for part in parts: + if not isinstance(part, Message): + continue + if _is_attached_multipart(part): + continue + yield from _iter_local_body_candidates(part, root=False) + return + # 根级单部件邮件放宽到 text/*;multipart 内仅认真正无 filename 的正文部件 + if root: + if _is_body_text_part(msg) or ctype in {"text/plain", "text/html"}: + yield msg + elif _is_body_text_part(msg): + yield msg + + +def _extract_body_text(msg: Message) -> str: + """ + 提取清洗后的邮件正文(仅当前消息容器,不穿透 rfc822 / 附件型 multipart)。 + + 核心逻辑:优先 text/plain,其次 text/html;带 filename 的部件不算正文; + 转发/附件容器内订单文本只出现在独立附件行,供扁平正文单次拼接。 + """ + plain = "" + html = "" + for part in _iter_local_body_candidates(msg): + ctype = str(part.get_content_type() or "") + text = _part_as_text(part) + if ctype == "text/plain" and not plain: + plain = text + elif ctype == "text/html" and not html: + html = text + return plain or html + + +def _is_collectible_text_leaf(msg: Message) -> bool: + """判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。""" + ctype = str(msg.get_content_type() or "").lower() + if ctype not in {"text/plain", "text/html"}: + return False + if not _is_body_text_part(msg) and str(msg.get_filename() or "").strip(): + return False + if not _is_body_text_part(msg) and msg.get_content_disposition() == "attachment": + return False + return True + + +def _extract_alternative_part_text(alt: Message) -> str: + """ + 从 multipart/alternative 选取单一表达:plain 优先于 html。 + + 核心逻辑:根节点即使带 disposition=attachment 也须进入子树; + 仅跳过嵌套 rfc822 / 再套一层附件型 multipart;子树内 plain 优先。 + """ + plain = "" + html = "" + + def _walk(msg: Message, *, is_root: bool) -> None: + nonlocal plain, html + ctype = str(msg.get_content_type() or "").lower() + if ctype == "message/rfc822": + return + # 根 alternative 本身常为附件型 multipart,不得在此处直接 return + if not is_root and _is_attached_multipart(msg): + return + if msg.is_multipart(): + parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or []) + for part in parts: + if isinstance(part, Message): + _walk(part, is_root=False) + return + if not _is_collectible_text_leaf(msg): + return + text = _part_as_text(msg).strip() + if not text: + return + if ctype == "text/plain" and not plain: + plain = text + elif ctype == "text/html" and not html: + html = text + + _walk(alt, is_root=True) + return plain or html + + +def _extract_text_inside_attached_multipart(root: Message) -> str: + """ + 从附件型 multipart 内部抽取可落库文本。 + + 核心逻辑: + - multipart/mixed(及非 alternative 容器):独立 text/plain 与 text/html 段全部拼接保留; + - multipart/alternative(含根即为附件型 alternative):plain 优先取一份等价表达; + - 不穿透嵌套 rfc822 / 再套附件型 multipart(留给 _walk_message 按 depth 展开)。 + """ + chunks: list[str] = [] + + def _walk(msg: Message, *, is_root: bool) -> None: + ctype = str(msg.get_content_type() or "").lower() + if ctype == "message/rfc822": + return + if not is_root and _is_attached_multipart(msg): + return + if msg.is_multipart(): + if ctype == "multipart/alternative": + text = _extract_alternative_part_text(msg).strip() + if text: + chunks.append(text) + return + parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or []) + for part in parts: + if isinstance(part, Message): + _walk(part, is_root=False) + return + if not _is_collectible_text_leaf(msg): + return + text = _part_as_text(msg).strip() + if text: + chunks.append(text) + + _walk(root, is_root=True) + return "\n\n".join(chunks) + + +def _register_skipped_attached_multipart( + state: _ParseState, + part: Message, + *, + reason: str, +) -> None: + """超深/超限的附件型 multipart 登记为 skipped,供完整性门禁感知。""" + state.discovered_attachment_count += 1 + if reason.startswith("eml_total_attachment_size_exceeded"): + if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings): + state.warnings.append(reason) + elif reason.startswith("eml_nesting_depth_exceeded"): + if not any(str(w).startswith("eml_nesting_depth_exceeded") for w in state.warnings): + state.warnings.append(reason) + elif reason not in state.warnings: + state.warnings.append(reason) + if len(state.attachments) >= state.limits.max_attachments: + _note_attachment_limit_exceeded(state) + return + filename = _part_filename(part, fallback="bundle") + try: + raw = part.as_bytes() + except Exception: + raw = b"" + key = _next_attachment_key(state) + state.attachments.append( + { + "attachment_key": key, + "filename": filename, + "mime_type": str(part.get_content_type() or "multipart/mixed"), + "size": len(raw or b""), + "content_hash": hashlib.sha256(raw).hexdigest().lower() if raw else "", + "parse_status": "skipped", + "extracted_text": "", + "warnings": [reason], + } + ) + + +def _register_and_expand_attached_multipart( + state: _ParseState, + part: Message, + *, + depth: int, + count_toward_total: bool, +) -> None: + """ + 将 disposition=attachment / 带文件名的 multipart/* 登记为独立附件并展开内层。 + + 核心逻辑:容器计费后子内容 count_toward_total=False;容器 extracted_text 拼接内层 + 全部正文段;再以 depth+1 walk 子树(嵌套容器计入深度上限)。 + + Args: + depth: 当前容器所在深度;展开子内容使用 depth+1。 + """ + state.discovered_attachment_count += 1 + if len(state.attachments) >= state.limits.max_attachments: + _note_attachment_limit_exceeded(state) + return + + try: + raw = part.as_bytes() + except Exception: + raw = b"" + size = len(raw or b"") + filename = _part_filename(part, fallback="bundle") + content_hash = hashlib.sha256(raw or b"").hexdigest().lower() if raw else "" + key = _next_attachment_key(state) + item: dict[str, Any] = { + "attachment_key": key, + "filename": filename, + "mime_type": str(part.get_content_type() or "multipart/mixed"), + "size": size, + "content_hash": content_hash, + "parse_status": "skipped", + "extracted_text": "", + "warnings": [], + "_payload_bytes": raw or b"", + } + + if size > state.limits.max_attachment_bytes: + item["parse_status"] = "skipped" + item["warnings"].append(f"eml_attachment_too_large:{size}") + state.warnings.append(f"eml_attachment_too_large:{filename}:{size}") + state.attachments.append(item) + return + if count_toward_total: + if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes: + item["parse_status"] = "skipped" + item["warnings"].append("eml_total_attachment_size_exceeded") + if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings): + state.warnings.append( + f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}" + ) + state.attachments.append(item) + return + state.total_attachment_bytes += size + + if content_hash and content_hash in state.seen_hashes: + item["parse_status"] = "duplicate" + item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}") + state.warnings.append(f"eml_attachment_duplicate:{filename}") + state.attachments.append(item) + return + if content_hash: + state.seen_hashes[content_hash] = key + + text = _extract_text_inside_attached_multipart(part).strip() + state.attachments.append(item) + before_child_count = len(state.attachments) + # [STEP] 子内容深度 +1,与 rfc822 / 嵌套 .eml 对齐 + _walk_message(part, state, depth=depth + 1, count_toward_total=False) + if text: + item["parse_status"] = "parsed" + item["extracted_text"] = text + elif len(state.attachments) > before_child_count: + # 仅含二进制子附件:容器本身无正文,仍视为成功登记 + item["parse_status"] = "parsed" + item["extracted_text"] = "" + else: + item["parse_status"] = "empty" + item["warnings"].append("eml_attachment_empty_text") + + +def _unwrap_rfc822(part: Message) -> Message | None: + """从 message/rfc822 部件取出内嵌 Message。""" + payload = part.get_payload() + if isinstance(payload, list) and payload: + inner = payload[0] + if isinstance(inner, Message): + return inner + if isinstance(payload, Message): + return payload + raw = _read_part_payload(part) + if not raw: + if isinstance(payload, str) and payload.strip(): + raw = payload.encode("utf-8", errors="ignore") + elif isinstance(payload, bytes): + raw = payload + if not raw: + return None + try: + return BytesParser(policy=policy.default).parsebytes(raw) + except Exception: + return None + + +def _rfc822_container_bytes(part: Message, nested: Message | None = None) -> bytes: + """ + 估算 message/rfc822 容器输入字节。 + + 核心逻辑:优先 decode 后的 part payload;若为空(内层以 Message 对象挂载), + 则用 nested.as_bytes(),以便对原生转发邮件执行单附件/总量上限。 + """ + raw = _read_part_payload(part) + if raw: + return raw + target = nested + if target is None: + target = _unwrap_rfc822(part) + if target is None: + return b"" + try: + return target.as_bytes() + except Exception: + return b"" + + +def _guess_suffix(filename: str, mime_type: str) -> str: + suffix = Path(filename).suffix.lower() + if suffix: + return suffix + mime = (mime_type or "").lower() + mapping = { + "application/pdf": ".pdf", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", + "text/csv": ".csv", + "text/plain": ".txt", + "text/html": ".html", + "message/rfc822": ".eml", + "image/png": ".png", + "image/jpeg": ".jpg", + "image/webp": ".webp", + } + return mapping.get(mime, ".bin") + + +ExtractTextFn = Callable[[Path], tuple[str, dict[str, Any]]] + + +@dataclass +class _ParseState: + limits: EmlLimits + extract_text: ExtractTextFn + warnings: list[str] = field(default_factory=list) + attachments: list[dict[str, Any]] = field(default_factory=list) + nested_bodies: list[str] = field(default_factory=list) # 兼容保留;v3 起 rfc822 改走 attachments,不再写入 + seen_hashes: dict[str, str] = field(default_factory=dict) + total_attachment_bytes: int = 0 + attachment_seq: int = 0 + skipped_inline: int = 0 + # 发现的真实附件总数(含因上限未登记的),用于 attachment_count + discovered_attachment_count: int = 0 + + +def _next_attachment_key(state: _ParseState) -> str: + state.attachment_seq += 1 + return f"att-{state.attachment_seq:03d}" + + +def _is_eml_payload(*, filename: str, mime_type: str) -> bool: + """判定附件是否为可递归的 .eml / rfc822 载荷。""" + suffix = Path(filename or "").suffix.lower() + mime = (mime_type or "").lower() + return suffix == ".eml" or mime in {"message/rfc822", "application/eml"} + + +def _expand_eml_file_attachment( + *, + state: _ParseState, + payload: bytes, + depth: int, +) -> tuple[str, str, list[str]]: + """ + 在共享 _ParseState 下展开 .eml 文件附件。 + + 核心逻辑:深度 +1 后复用同一 attachments/限额/哈希,避免重新 parse_eml_bytes(depth=0) + 绕过嵌套与附件总数限制;容器项自身只保留内层主题+正文。 + 容器字节已在登记时计入 total_attachment_bytes,子内容 count_toward_total=False + 避免与容器双重计费,同时封死「多个近似空壳大 EML」绕过总量上限。 + + Returns: + (parse_status, extracted_text, warnings) + """ + next_depth = depth + 1 + if next_depth > state.limits.max_nesting_depth: + warn = f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}" + if warn not in state.warnings: + state.warnings.append(warn) + return "skipped", "", [warn] + try: + nested = BytesParser(policy=policy.default).parsebytes(payload or b"") + except Exception as exc: + return "failed", "", [f"eml_attachment_extract_failed:{exc}"] + + subject = _header_str(nested, "Subject") + body = _extract_body_text(nested) + chunks: list[str] = [] + if subject: + chunks.append(f"Subject: {subject}") + if body: + chunks.append(body) + # 子附件计入同一 state;大小已由容器计费,不再对子 payload 累加总字节 + _walk_message(nested, state, depth=next_depth, count_toward_total=False) + text = "\n\n".join(chunks).strip() + if not text: + return "empty", "", ["eml_attachment_empty_text"] + return "parsed", text, [] + + +def _extract_attachment_text( + *, + state: _ParseState, + filename: str, + mime_type: str, + payload: bytes, + depth: int, +) -> tuple[str, str, list[str]]: + """ + 抽取单个附件文本。 + + 核心逻辑:.eml 走共享状态展开;其他类型写临时文件调用 extract_text(PDF/DOCX 等)。 + + Returns: + (parse_status, extracted_text, warnings) + """ + if _is_eml_payload(filename=filename, mime_type=mime_type): + return _expand_eml_file_attachment(state=state, payload=payload or b"", depth=depth) + + suffix = _guess_suffix(filename, mime_type) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: + tmp.write(payload) + tmp_path = Path(tmp.name) + text, meta = state.extract_text(tmp_path) + warn = list(meta.get("warnings") or []) if isinstance(meta, dict) else [] + if not str(text or "").strip(): + return "empty", "", warn or ["eml_attachment_empty_text"] + return "parsed", str(text).strip(), warn + except Exception as exc: + return "failed", "", [f"eml_attachment_extract_failed:{exc}"] + finally: + if tmp_path is not None: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + + +def _note_attachment_limit_exceeded(state: _ParseState) -> None: + """刷新「附件数量超限」警告,带上当前 discovered 总数。""" + prefix = "eml_attachment_limit_exceeded:" + state.warnings = [w for w in state.warnings if not str(w).startswith(prefix)] + state.warnings.append( + f"{prefix}{state.limits.max_attachments}:discovered={state.discovered_attachment_count}" + ) + + +def _append_attachment( + state: _ParseState, + *, + filename: str, + mime_type: str, + payload: bytes, + depth: int, + count_toward_total: bool = True, +) -> None: + """ + 在安全上限内登记并抽取单个真实附件。 + + Args: + count_toward_total: True 时把本附件 payload 计入总大小配额。 + 由 .eml 容器展开出的子附件传 False(容器已计费,避免双重计费)。 + """ + state.discovered_attachment_count += 1 + + # [STEP 1] 数量上限:仍计入 discovered,但不登记抽正文 + if len(state.attachments) >= state.limits.max_attachments: + _note_attachment_limit_exceeded(state) + return + + size = len(payload or b"") + content_hash = hashlib.sha256(payload or b"").hexdigest().lower() + key = _next_attachment_key(state) + item: dict[str, Any] = { + "attachment_key": key, + "filename": filename, + "mime_type": mime_type or "application/octet-stream", + "size": size, + "content_hash": content_hash, + "parse_status": "skipped", + "extracted_text": "", + "warnings": [], + # 仅内存保留供阶段二派生资产;写 structured_result / 对外 API 前必须剥离 + "_payload_bytes": payload or b"", + } + + # [STEP 2] 单附件 / 总大小上限 + # 计费规则:顶层真实附件(含 .eml 容器)计入总量;从已计费 .eml 展开的子内容不计。 + if size > state.limits.max_attachment_bytes: + item["parse_status"] = "skipped" + item["warnings"].append(f"eml_attachment_too_large:{size}") + state.warnings.append(f"eml_attachment_too_large:{filename}:{size}") + state.attachments.append(item) + return + if count_toward_total: + if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes: + item["parse_status"] = "skipped" + item["warnings"].append("eml_total_attachment_size_exceeded") + if not any( + str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings + ): + state.warnings.append( + f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}" + ) + state.attachments.append(item) + return + state.total_attachment_bytes += size + + # [STEP 3] 同信内内容哈希去重(含嵌套 .eml 展开后的子附件) + if content_hash in state.seen_hashes: + item["parse_status"] = "duplicate" + item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}") + state.warnings.append(f"eml_attachment_duplicate:{filename}") + state.attachments.append(item) + return + state.seen_hashes[content_hash] = key + + # [STEP 4] 先占位登记,再抽取/展开,确保 .eml 递归子附件计入同一数量上限 + state.attachments.append(item) + status, text, warn = _extract_attachment_text( + state=state, + filename=filename, + mime_type=mime_type, + payload=payload or b"", + depth=depth, + ) + item["parse_status"] = status + item["extracted_text"] = text + item["warnings"].extend(warn) + if status == "failed": + state.warnings.append(f"eml_attachment_extract_failed:{filename}") + + +def _register_and_expand_rfc822( + state: _ParseState, + part: Message, + nested: Message, + *, + depth: int, +) -> None: + """ + 将原生 message/rfc822 登记为独立附件,并展开内层正文附件。 + + 核心逻辑:与 .eml 文件附件对齐——容器行保存主题+正文;子附件 count_toward_total=False; + 不写入 nested_bodies,避免与 attachment.extracted_text / 扁平正文双重拼接。 + + Args: + state: 共享解析状态(容器字节须已由调用方计费或无需计费)。 + part: 外层 message/rfc822 MIME 部件。 + nested: 已 unwrap 的内层 Message。 + depth: 当前外层深度;内层 walk 使用 depth+1。 + """ + state.discovered_attachment_count += 1 + if len(state.attachments) >= state.limits.max_attachments: + _note_attachment_limit_exceeded(state) + return + + raw = _rfc822_container_bytes(part, nested) + filename = str(part.get_filename() or "").strip() or "forwarded-message.eml" + content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else "" + key = _next_attachment_key(state) + item: dict[str, Any] = { + "attachment_key": key, + "filename": filename, + "mime_type": "message/rfc822", + "size": len(raw), + "content_hash": content_hash, + "parse_status": "empty", + "extracted_text": "", + "warnings": [], + "_payload_bytes": raw or b"", + } + + if content_hash and content_hash in state.seen_hashes: + item["parse_status"] = "duplicate" + item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}") + state.warnings.append(f"eml_attachment_duplicate:{filename}") + state.attachments.append(item) + return + if content_hash: + state.seen_hashes[content_hash] = key + + subject = _header_str(nested, "Subject") + body = _extract_body_text(nested) + chunks: list[str] = [] + if subject: + chunks.append(f"Subject: {subject}") + if body: + chunks.append(body) + text = "\n\n".join(chunks).strip() + state.attachments.append(item) + # [STEP] 先占位再展开,使内层子附件与容器共享数量上限 + _walk_message(nested, state, depth=depth + 1, count_toward_total=False) + if text: + item["parse_status"] = "parsed" + item["extracted_text"] = text + else: + item["parse_status"] = "empty" + item["warnings"].append("eml_attachment_empty_text") + + +def _register_skipped_nested_rfc822(state: _ParseState, part: Message, *, reason: str) -> None: + """ + 超深/不可读/超限的 message/rfc822 登记为 skipped 附件行,供前端徽标感知「不完整」。 + + Args: + state: 共享解析状态。 + part: 被跳过的 rfc822 部件。 + reason: 警告码(如 eml_nesting_depth_exceeded:N / eml_attachment_too_large:N)。 + """ + state.discovered_attachment_count += 1 + # [STEP] 总量超限只保留一条顶层 warning;其它 reason 按原文去重 + if reason.startswith("eml_total_attachment_size_exceeded"): + if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings): + state.warnings.append(reason) + elif reason not in state.warnings: + state.warnings.append(reason) + if len(state.attachments) >= state.limits.max_attachments: + _note_attachment_limit_exceeded(state) + return + filename = str(part.get_filename() or "").strip() or "forwarded-message.eml" + raw = _rfc822_container_bytes(part) + key = _next_attachment_key(state) + state.attachments.append( + { + "attachment_key": key, + "filename": filename, + "mime_type": "message/rfc822", + "size": len(raw), + "content_hash": hashlib.sha256(raw).hexdigest().lower() if raw else "", + "parse_status": "skipped", + "extracted_text": "", + "warnings": [reason], + } + ) + + +def _maybe_charge_rfc822_container( + state: _ParseState, + part: Message, + nested: Message, + *, + count_toward_total: bool, +) -> bool: + """ + 对原生 message/rfc822 转发容器执行单附件/总量上限并计费。 + + 核心逻辑:与 .eml 文件附件一致——容器字节计入配额后,内层展开 count_toward_total=False。 + + Returns: + True 表示可通过并已计费(或无需计费);False 表示已登记 skipped,调用方勿再展开。 + """ + if not count_toward_total: + return True + raw = _rfc822_container_bytes(part, nested) + size = len(raw) + filename = str(part.get_filename() or "").strip() or "forwarded-message.eml" + if size > state.limits.max_attachment_bytes: + reason = f"eml_attachment_too_large:{size}" + state.warnings.append(f"eml_attachment_too_large:{filename}:{size}") + _register_skipped_nested_rfc822(state, part, reason=reason) + return False + if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes: + reason = f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}" + _register_skipped_nested_rfc822(state, part, reason=reason) + return False + state.total_attachment_bytes += size + return True + + +def _walk_message( + msg: Message, + state: _ParseState, + *, + depth: int, + count_toward_total: bool = True, +) -> None: + """ + 递归遍历 MIME 树:收集真实附件,展开 message/rfc822(含内层正文),跳过内嵌图片。 + + Args: + msg: 当前邮件 Message。 + state: 共享解析状态。 + depth: 当前嵌套深度(顶层为 0)。 + count_toward_total: 本层登记的附件是否计入总大小配额。 + """ + if depth > state.limits.max_nesting_depth: + state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}") + return + + if not msg.is_multipart(): + if _is_real_attachment(msg): + _append_attachment( + state, + filename=_part_filename(msg), + mime_type=str(msg.get_content_type() or "application/octet-stream"), + payload=_read_part_payload(msg), + depth=depth, + count_toward_total=count_toward_total, + ) + return + + parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or []) + for part in parts: + if not isinstance(part, Message): + continue + ctype = str(part.get_content_type() or "").lower() + + if ctype == "message/rfc822": + if depth + 1 > state.limits.max_nesting_depth: + _register_skipped_nested_rfc822( + state, + part, + reason=f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}", + ) + continue + nested = _unwrap_rfc822(part) + if nested is None: + _register_skipped_nested_rfc822( + state, + part, + reason="eml_nested_message_unreadable", + ) + continue + # [STEP] 原生转发容器须计费,防止绕过单附件/总量上限 + if not _maybe_charge_rfc822_container( + state, + part, + nested, + count_toward_total=count_toward_total, + ): + continue + # 成功路径登记为独立附件(与 .eml 文件附件一致),再展开内层 + _register_and_expand_rfc822(state, part, nested, depth=depth) + continue + + if part.is_multipart(): + # 附件型 multipart(filename / disposition=attachment)须独立登记,禁止当正文树展开 + if _is_attached_multipart(part): + next_depth = depth + 1 + if next_depth > state.limits.max_nesting_depth: + _register_skipped_attached_multipart( + state, + part, + reason=f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}", + ) + continue + _register_and_expand_attached_multipart( + state, + part, + depth=depth, + count_toward_total=count_toward_total, + ) + continue + _walk_message( + part, + state, + depth=depth, + count_toward_total=count_toward_total, + ) + continue + + if _is_inline_or_embedded_resource(part): + state.skipped_inline += 1 + continue + + if _is_body_text_part(part): + continue + + if _is_real_attachment(part): + _append_attachment( + state, + filename=_part_filename(part), + mime_type=str(part.get_content_type() or "application/octet-stream"), + payload=_read_part_payload(part), + depth=depth, + count_toward_total=count_toward_total, + ) + + +def _compose_flat_text( + *, + subject: str, + body_text: str, + attachments: list[dict[str, Any]], +) -> str: + """将主题、正文(含转发段)与各附件文本拼成下游订单解析用的扁平正文。""" + parts: list[str] = [] + if subject: + parts.append(f"Subject: {subject}") + if body_text: + parts.append(body_text) + for item in attachments: + if item.get("parse_status") != "parsed": + continue + text = str(item.get("extracted_text") or "").strip() + if not text: + continue + name = str(item.get("filename") or item.get("attachment_key") or "attachment") + parts.append(f"--- attachment: {name} ---\n{text}") + return "\n\n".join(parts) + + +def parse_eml_bytes( + data: bytes, + *, + extract_text: ExtractTextFn, + limits: EmlLimits | None = None, + depth: int = 0, + retain_payloads: bool = False, +) -> tuple[str, dict[str, Any]]: + """ + 结构化解析 EML 字节流。 + + 核心逻辑:提取邮件头与清洗正文 → 区分真实附件与内嵌图片 → 对附件调用 extract_text; + 嵌套 rfc822 登记为独立附件并展开内层;不执行宏、脚本或嵌入对象。 + + Args: + data: .eml 原始字节。 + extract_text: 叶附件文本抽取函数,签名与 extract_notice_text 一致。 + limits: 安全上限;为空时从配置/默认加载。 + depth: 当前嵌套深度(供嵌套 .eml 附件复用)。 + retain_payloads: True 时在 attachments[*]._payload_bytes 保留二进制供派生资产; + 默认 False,返回前剥离,避免测试/JSON 路径泄漏。 + + Returns: + tuple[str, dict]: (扁平拼接文本, meta含 email/attachments/attachment_count/warnings)。 + """ + limits = limits or load_eml_limits() + if depth > limits.max_nesting_depth: + return "", { + "file_type": "eml", + "warnings": [f"eml_nesting_depth_exceeded:{limits.max_nesting_depth}"], + "email": {}, + "attachments": [], + "attachment_count": 0, + "attachment_registered_count": 0, + } + + msg = BytesParser(policy=policy.default).parsebytes(data or b"") + subject = _header_str(msg, "Subject") + from_addr = _header_str(msg, "From") + to_addr = _header_str(msg, "To") + date_val = _format_date(msg) + message_id = _normalize_message_id(_header_str(msg, "Message-ID") or _header_str(msg, "Message-Id")) + body_text = _extract_body_text(msg) + + state = _ParseState(limits=limits, extract_text=extract_text) + _walk_message(msg, state, depth=depth) + + if state.skipped_inline: + state.warnings.append(f"eml_inline_resources_skipped:{state.skipped_inline}") + + body_segments = [body_text, *state.nested_bodies] + combined_body = "\n\n".join(segment for segment in body_segments if segment) + + email_meta = { + "message_id": message_id, + "subject": subject, + "from": from_addr, + "to": to_addr, + "date": date_val, + "body_text": combined_body, + } + flat = _compose_flat_text( + subject=subject, + body_text=combined_body, + attachments=state.attachments, + ) + meta: dict[str, Any] = { + "file_type": "eml", + "warnings": list(state.warnings), + "email": email_meta, + "attachments": list(state.attachments), + # attachment_count = 发现的真实附件总数(含因上限未登记的) + "attachment_count": int(state.discovered_attachment_count), + "attachment_registered_count": len(state.attachments), + } + # 注意:attachments[*]._payload_bytes 仅供同进程持久化派生资产,不得序列化进 DB/API + if not retain_payloads: + strip_attachment_payloads(meta) + return flat, meta + + +def pop_attachment_payload(item: dict[str, Any]) -> bytes: + """ + 取出并移除附件上的内存 payload。 + + Args: + item: parse_eml_bytes 产出的单条 attachment 摘要。 + + Returns: + 原始字节;无则 b""。 + """ + if not isinstance(item, dict): + return b"" + raw = item.pop("_payload_bytes", None) + return raw if isinstance(raw, (bytes, bytearray)) else b"" + + +def strip_attachment_payloads(meta: dict[str, Any] | None) -> dict[str, Any]: + """ + 就地剥除 meta.attachments 中的 `_payload_bytes`,防止二进制泄漏到摘要/API。 + + Returns: + 同一 meta 引用(或空 dict)。 + """ + if not isinstance(meta, dict): + return {} + for item in meta.get("attachments") or []: + if isinstance(item, dict): + item.pop("_payload_bytes", None) + return meta diff --git a/backend/app/services/shipping_notice/intake_business_parser.py b/backend/app/services/shipping_notice/intake_business_parser.py new file mode 100644 index 00000000..0f521e0f --- /dev/null +++ b/backend/app/services/shipping_notice/intake_business_parser.py @@ -0,0 +1,76 @@ +""" +backend/app/services/shipping_notice/intake_business_parser.py + +用途:从发货通知抽取文本产出稳定业务摘要(预解析阶段,不创建 ShippingTask)。 +依赖:extract.extract_notice_fields、notice_lines。 +逻辑:由 intake_parse_workflow 在文本抽取成功后调用;与正式 parse_notice 共用字段口径。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.shipping_notice.extract import extract_notice_fields + + +def parse_intake_business_summary( + *, + extracted_text: str, + source_type: str = 'manual', +) -> dict[str, Any]: + """ + 将预解析文本转为可序列化业务摘要。 + + 核心逻辑:调用 extract_notice_fields(无 Dify structured,走启发式兜底), + 提取单头/行项目/置信度;不写库。 + + Args: + extracted_text: 文本抽取结果。 + source_type: 来源类型(pdf/email/manual 等)。 + + Returns: + 含 customer/po/reservation/lines/confidence/parse_source 的摘要字典。 + """ + parsed, confidence, warnings = extract_notice_fields( + raw_text=str(extracted_text or ''), + source_type=str(source_type or 'manual'), + structured=None, + ) + lines = parsed.get('lines') if isinstance(parsed.get('lines'), list) else [] + reservation_ids: list[str] = [] + for line in lines: + if not isinstance(line, dict): + continue + rid = str(line.get('reservation_id') or '').strip() + if rid and rid not in reservation_ids: + reservation_ids.append(rid) + doc_rid = str(parsed.get('reservation_id') or '').strip() + if doc_rid and doc_rid not in reservation_ids: + reservation_ids.insert(0, doc_rid) + + return { + 'customer_name': str(parsed.get('customer_name') or '').strip() or None, + 'customer_code': str(parsed.get('customer_code') or '').strip() or None, + 'po_number': str(parsed.get('po_number') or '').strip() or None, + 'reservation_ids': reservation_ids, + 'ship_to': str(parsed.get('ship_to') or '').strip() or None, + 'destination': { + 'code': str(parsed.get('destination_code') or '').strip() or None, + 'city': str(parsed.get('destination_city') or '').strip() or None, + 'country': str(parsed.get('destination_country') or '').strip() or None, + }, + 'required_date': str(parsed.get('required_date') or '').strip() or None, + 'lines': [ + { + 'sku': str(line.get('sku') or '').strip() or None, + 'reservation_id': str(line.get('reservation_id') or '').strip() or None, + 'qty': line.get('qty'), + 'uom': str(line.get('uom') or '').strip() or None, + } + for line in lines + if isinstance(line, dict) + ], + 'confidence': float(confidence or 0.0), + 'parse_source': str(parsed.get('parse_source') or 'heuristic'), + 'warnings': list(warnings), + } diff --git a/backend/app/services/shipping_notice/intake_parse_workflow.py b/backend/app/services/shipping_notice/intake_parse_workflow.py index 65d5bcc6..db227784 100644 --- a/backend/app/services/shipping_notice/intake_parse_workflow.py +++ b/backend/app/services/shipping_notice/intake_parse_workflow.py @@ -1,34 +1,198 @@ """ backend/app/services/shipping_notice/intake_parse_workflow.py -用途:发货通知接入记录的文本抽取与预解析编排。 -依赖:notice_upload、file_assets.service、models.ShippingNoticeIntake。 -逻辑:由 shipping_notice_parse Job handler 调用;不写 API 路由。 +用途:发货通知接入记录的文本抽取与预解析编排;intake 转 notice_item(含修订行锁)。 +依赖:notice_upload、file_assets.service、document_candidate_persist、duplicate_detection、models。 +逻辑:由 shipping_notice_parse Job handler 调用;EML 结构化 meta(email/attachments)写入 + structured_result_json;解析成功后先落 Document/Candidate 基础行,再在 SAVEPOINT 内 + 做 Candidate/Intake 重复检测;失败清理 clear_duplicate_state_to_unchecked; + 超时 Job 回收经 sync_intake_after_parse_job_recovery 同步 Intake 并清空 parse_lease; + 写回须匹配 parse_lease,拒绝过期 Worker。 """ from __future__ import annotations import tempfile +from datetime import datetime 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.core.errors import ConflictError +from app.models import FileAsset, ShippingNoticeIntake, ShippingTask 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, + max_notice_chars, truncate_notice_text, ) def _parser_version() -> str: - return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip() + return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v6') or 'v6').strip() + + +def _truncate_meta_text(text: str, *, limit: int | None = None) -> tuple[str, bool]: + """ + 截断写入 structured_result_json 的长文本字段。 + + Returns: + (截断后文本, 是否发生截断) + """ + if limit is not None: + cap = int(limit) + else: + try: + cap = max_notice_chars() + except RuntimeError: + cap = 200000 + if cap <= 0: + return str(text or ''), False + value = str(text or '') + if len(value) <= cap: + return value, False + return value[:cap], True + + +def _eml_stored_attachment_chars_budget() -> int: + """EML 全部附件落库文本合计上限;无应用上下文时回退 500000。""" + try: + raw = current_app.config.get('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS') + value = int(raw) if raw is not None and str(raw).strip() != '' else 500_000 + except (RuntimeError, TypeError, ValueError): + return 500_000 + return value if value > 0 else 500_000 + + +def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]: + """ + 从 EML 抽取 meta 生成可写入 structured_result_json 的附件摘要。 + + 核心逻辑:单附件按 NOTICE_TEXT_MAX_CHARS 截断;全部附件再共享 + SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS 总预算。 + + Returns: + (附件摘要列表, 汇总级 warnings) + """ + rows: list[dict[str, Any]] = [] + extra_warnings: list[str] = [] + try: + per_limit = max_notice_chars() + except RuntimeError: + per_limit = 200000 + budget = _eml_stored_attachment_chars_budget() + remaining = budget + for item in meta.get('attachments') or []: + if not isinstance(item, dict): + continue + original = str(item.get('extracted_text') or '') + text, truncated = _truncate_meta_text(original, limit=per_limit) + warn = list(item.get('warnings') or []) + if truncated: + warn = [*warn, f'eml_attachment_text_truncated:{per_limit}'] + if remaining <= 0: + if text: + text = '' + warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}'] + elif len(text) > remaining: + text = text[:remaining] + warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}'] + remaining = 0 + else: + remaining -= len(text) + row: dict[str, Any] = { + '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'), + 'extracted_text': text, + 'text_length': len(original), + 'stored_text_length': len(text), + 'warnings': warn, + } + if item.get('asset_no'): + row['asset_no'] = item.get('asset_no') + if item.get('asset_id') is not None: + row['asset_id'] = item.get('asset_id') + if item.get('document_id') is not None: + row['document_id'] = item.get('document_id') + rows.append(row) + if any( + any(str(w).startswith('eml_attachment_text_budget_exhausted:') for w in (row.get('warnings') or [])) + for row in rows + ): + extra_warnings.append(f'eml_attachment_text_budget_exhausted:{budget}') + return rows, extra_warnings + + +def intake_result_to_structured_summary( + result: NoticeIntakeResult, + *, + business_summary: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 生成前端可展示的预解析摘要(技术摘要 + 可选业务摘要)。 + + 核心逻辑:普通文件仅写文件级统计;EML 额外写入 email 元数据、attachment_count 与附件摘要 + (含各附件独立 extracted_text);email.body_text 按 notice 文本上限截断; + 截断警告统一为 `eml_*_truncated:{limit}`(N=上限字符数)。 + """ + line_count = 0 + for line in str(result.text or '').splitlines(): + if line.strip(): + line_count += 1 + payload: dict[str, Any] = { + '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(), + } + meta = result.meta if isinstance(result.meta, dict) else {} + email_meta = meta.get('email') + if isinstance(email_meta, dict) and email_meta: + original_body = str(email_meta.get('body_text') or '') + try: + body_limit = max_notice_chars() + except RuntimeError: + body_limit = 200000 + body_text, body_truncated = _truncate_meta_text(original_body, limit=body_limit) + payload['email'] = { + 'message_id': email_meta.get('message_id') or '', + 'subject': email_meta.get('subject') or '', + 'from': email_meta.get('from') or '', + 'to': email_meta.get('to') or '', + 'date': email_meta.get('date') or '', + 'body_text': body_text, + 'body_text_length': len(original_body), + 'stored_body_text_length': len(body_text), + } + if body_truncated: + payload['warnings'] = [ + *payload['warnings'], + f'eml_body_text_truncated:{body_limit}', + ] + if 'attachment_count' in meta: + payload['attachment_count'] = int(meta.get('attachment_count') or 0) + if 'attachment_registered_count' in meta: + payload['attachment_registered_count'] = int(meta.get('attachment_registered_count') or 0) + attachments, attach_extra_warnings = _attachment_summaries_for_structured(meta) + if attach_extra_warnings: + payload['warnings'] = [*payload['warnings'], *attach_extra_warnings] + if attachments: + payload['attachments'] = attachments + if isinstance(business_summary, dict): + payload['business_summary'] = business_summary + payload['confidence'] = business_summary.get('confidence') + payload['parse_source'] = business_summary.get('parse_source') + return payload def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: @@ -44,7 +208,8 @@ def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: tmp.write(raw) tmp_path = Path(tmp.name) try: - text, meta = extract_notice_text(tmp_path) + # EML 须保留附件二进制,供阶段二幂等创建派生 FileAsset + text, meta = extract_notice_text(tmp_path, retain_payloads=True) warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] except Exception as exc: return NoticeIntakeResult( @@ -94,23 +259,9 @@ def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: ) -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'}) +# 与 cancel 同序写路径:解析写回 / 失败清理允许的状态 +_WRITABLE_PARSE_STATUSES = frozenset({'parsing', 'queued', 'created'}) def _db_parse_status(intake_id: int) -> str | None: @@ -127,121 +278,492 @@ def _db_parse_status(intake_id: int) -> str | None: return str(obj.parse_status or '') -def _commit_parse_result_if_writable( +def _lock_intake_row(intake_id: int) -> ShippingNoticeIntake | None: + """ + FOR UPDATE 锁定 Intake 行(与 cancel / refresh / retry 同序之首)。 + + 核心逻辑:先 expire 本地缓存并以 populate_existing 重读,避免抽取窗口内他事务 + 已 cancel 而身份映射仍返回 parsing。 + """ + cached = db.session.get(ShippingNoticeIntake, int(intake_id)) + if cached is not None: + db.session.expire(cached) + return ( + db.session.query(ShippingNoticeIntake) + .filter(ShippingNoticeIntake.id == int(intake_id)) + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + + +def _strip_stage2_keys_from_summary(summary: dict[str, Any]) -> dict[str, Any]: + """从 structured_result 摘要中剥离阶段二投影字段。""" + summary.pop('document_count', None) + summary.pop('candidate_count', None) + attachments = summary.get('attachments') + if isinstance(attachments, list): + for item in attachments: + if isinstance(item, dict): + item.pop('asset_no', None) + item.pop('asset_id', None) + item.pop('document_id', None) + return summary + + +def _parse_lease_matches( + locked: ShippingNoticeIntake, + *, + required_lease: str | None, +) -> bool: + """ + 校验写回是否仍持有当前执行代次。 + + 核心逻辑:双方均为空(直连单测未发 lease)放行;否则必须精确相等。 + 超时回收会清空 parse_lease,旧 Worker 持旧 lease 写回将被拒绝。 + """ + current = str(getattr(locked, 'parse_lease', None) or '').strip() or None + expected = str(required_lease or '').strip() or None + if expected is None and current is None: + return True + return expected is not None and current == expected + + +def _fail_intake_with_stage2_cleanup( *, intake_id: int, - values: dict[str, Any], -) -> ShippingNoticeIntake | None: + intake_no: str, + parser_version: str, + error_code: str, + error_message: str, + extracted_text: str | None, + structured_result_json: dict[str, Any] | None, + parse_warnings_json: list[str] | None, + allowed_statuses: frozenset[str] | None = None, + commit: bool = True, + locked_intake: ShippingNoticeIntake | None = None, + required_lease: str | None = None, +) -> dict[str, Any]: """ - 条件更新解析结果:仅当库中状态仍非 cancelled/expired/consumed 时写回。 + 持 Intake 锁清理阶段二并写 parse_failed。 + + 核心逻辑:与 cancel 同序(先 Intake 再 Document/资产);释放阶段二后完整清空 + Intake 重复字段(matches/指纹/决策)。structured_result_json / parse_warnings_json + 为 None 时保留锁内现有值并仅剥离阶段二投影。commit=False 供 Job 回收同事务调用。 + required_lease 不匹配时跳过(旧 Worker),避免覆盖新执行。 + """ + from app.services.shipping_notice.document_candidate_persist import ( + release_unconsumed_intake_stage2, + ) + from app.services.shipping_notice.duplicate_detection import ( + clear_duplicate_state_to_unchecked, + ) + + allowed = allowed_statuses or _WRITABLE_PARSE_STATUSES + locked = locked_intake if locked_intake is not None else _lock_intake_row(intake_id) + if locked is None: + return {'status': 'skipped', 'intake_no': intake_no, 'parse_status': None} + status_now = str(locked.parse_status or '') + if status_now in _ABORT_WRITE_STATUSES or status_now not in allowed: + if commit: + db.session.rollback() + return {'status': 'skipped', 'intake_no': intake_no, 'parse_status': status_now} + if not _parse_lease_matches(locked, required_lease=required_lease): + if commit: + db.session.rollback() + return { + 'status': 'skipped', + 'intake_no': intake_no, + 'parse_status': status_now, + 'reason': 'stale_parse_lease', + } + + release_unconsumed_intake_stage2(intake=locked) + clear_duplicate_state_to_unchecked(intake=locked) + base_summary = ( + dict(structured_result_json) + if isinstance(structured_result_json, dict) + else dict(locked.structured_result_json or {}) + ) + summary = _strip_stage2_keys_from_summary(base_summary) + locked.parser_version = parser_version or locked.parser_version + locked.parse_status = 'parse_failed' + locked.parse_lease = None + locked.error_code = error_code + locked.error_message = str(error_message or '')[:1000] + # extracted_text=None 表示清空(抽取失败);Handler 路径应传入上一轮值以保留 + locked.extracted_text = extracted_text + locked.structured_result_json = summary + if parse_warnings_json is not None: + locked.parse_warnings_json = list(parse_warnings_json) + locked.updated_at = datetime.utcnow() + if commit: + db.session.commit() + return { + 'status': 'parse_failed', + 'intake_no': intake_no, + 'error_message': locked.error_message, + } + + +def fail_intake_with_stage2_cleanup(**kwargs: Any) -> dict[str, Any]: + """ + 公开入口:领取后 Handler/回收路径写 parse_failed 并清理阶段二。 + + 核心逻辑:委托 _fail_intake_with_stage2_cleanup,保证资产缺失与超时失败同口径。 + """ + return _fail_intake_with_stage2_cleanup(**kwargs) + + +def sync_intake_after_parse_job_recovery(job: Any) -> None: + """ + 预解析 Job 超时回收后同步 Intake(须在 recover_stale_jobs 同事务、commit 前调用)。 + + 核心逻辑:仅当 parse_job_id 仍指向本 Job时处理;通常要求 Intake=parsing, + 但 Job→queued 还允许本轮 Handler 已先提交的 parse_failed,并恢复为 queued; + Job→queued 清空 parse_lease/错误(使旧 Worker 写回失效); + Job→cancelled 则 FOR UPDATE 锁定替代 Job 后按 queued/running 安全重指; + Job→failed 则持锁阶段二清理并 parse_failed。 + """ + from app.models import Job as JobModel + + if not isinstance(job, JobModel): + return + if str(job.job_type or '') != 'shipping_notice_parse': + return + intake_no = str( + (job.payload_json or {}).get('intake_no') or job.business_ref or '' + ).strip().upper() + if not intake_no: + return + + locked = ( + db.session.query(ShippingNoticeIntake) + .filter(ShippingNoticeIntake.intake_no == intake_no) + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + if locked is None: + return + if locked.parse_job_id is None or int(locked.parse_job_id) != int(job.id): + return + + now = datetime.utcnow() + job_status = str(job.status or '') + intake_status = str(locked.parse_status or '') + if job_status == 'queued': + if intake_status not in {'parsing', 'parse_failed'}: + return + # Handler 可能已先提交 parse_failed;Job 自动重试时恢复为 queued 同一语义 + locked.parse_status = 'queued' + locked.parse_lease = None + locked.error_code = None + locked.error_message = None + locked.updated_at = now + return + if intake_status != 'parsing': + return + if job_status == 'cancelled': + # 安全替代者重指;若无替代且仍挂本 Job,终态清理以免永久 parsing + from app.jobs.queue import ( + _resolve_safe_supersede_sibling, + _retarget_intake_parse_job_after_supersede, + ) + + sibling = _resolve_safe_supersede_sibling( + domain=str(job.domain or ''), + job_type='shipping_notice_parse', + business_ref=job.business_ref, + exclude_id=int(job.id), + cancelled_job=job, + ) + if sibling is not None: + _retarget_intake_parse_job_after_supersede( + cancelled_job=job, + keep_job=sibling, + ) + return + current_lease = str(locked.parse_lease or '') or None + _fail_intake_with_stage2_cleanup( + intake_id=int(locked.id), + intake_no=intake_no, + parser_version=str(locked.parser_version or _parser_version()), + error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED', + error_message=str(job.message or job.error_message or '预解析 Job 已取消')[:1000], + extracted_text=locked.extracted_text, + structured_result_json=None, + parse_warnings_json=None, + allowed_statuses=frozenset({'parsing'}), + commit=False, + locked_intake=locked, + required_lease=current_lease, + ) + return + if job_status == 'failed': + # 超时/终态失败清理:不校验 lease(当前仍是持锁的活跃解析代次) + current_lease = str(locked.parse_lease or '') or None + error_code = ( + 'SHIPPING_NOTICE.INTAKE_PARSE_TIMEOUT' + if '超时' in str(job.error_message or job.message or '') + else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' + ) + _fail_intake_with_stage2_cleanup( + intake_id=int(locked.id), + intake_no=intake_no, + parser_version=str(locked.parser_version or _parser_version()), + error_code=error_code, + error_message=str(job.error_message or '预解析任务失败')[:1000], + extracted_text=locked.extracted_text, + structured_result_json=None, + parse_warnings_json=None, + allowed_statuses=frozenset({'parsing'}), + commit=False, + locked_intake=locked, + required_lease=current_lease, + ) + + +def _run_business_dedup_after_parse( + intake: ShippingNoticeIntake, + asset: FileAsset, + *, + extracted_text: str, + source_type: str, + candidate_dup_results: list[dict[str, Any]] | None = None, + commit: bool = True, +) -> dict[str, Any]: + """ + 解析成功后:候选级汇总 / 扁平文本回退 → 指纹 → 写回 intake。 + + 核心逻辑:若已有 Candidate 检测结果则聚合为 Intake 概览(partial_duplicate 表示部分阻断); + 否则回退到扁平文本 Intake 级检测。commit=False 时由调用方在同一 Intake 锁事务中提交。 Returns: - 写成功后的 ORM 对象;被取消/过期/消费则返回 None。 + duplicate 检测结果字典。 """ - # [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) + from app.services.shipping_notice.business_fingerprint import build_business_fingerprint + from app.services.shipping_notice.duplicate_detection import ( + aggregate_intake_duplicate_from_candidates, + apply_duplicate_result_to_intake, + detect_duplicates_for_intake, ) - 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)) + from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary + + business_summary = parse_intake_business_summary( + extracted_text=extracted_text, + source_type=source_type, + ) + if candidate_dup_results: + dup = aggregate_intake_duplicate_from_candidates(intake, candidate_dup_results) + # 概览指纹仍保留扁平摘要强度供列表展示 + flat_fp = build_business_fingerprint(business_summary) + if not dup.get('fingerprint') and flat_fp.get('fingerprint'): + dup = { + **dup, + 'fingerprint': flat_fp.get('fingerprint'), + 'fingerprint_version': flat_fp.get('version'), + 'fingerprint_strength': flat_fp.get('strength'), + 'components': flat_fp.get('components') or {}, + } + else: + fingerprint = build_business_fingerprint(business_summary) + dup = detect_duplicates_for_intake( + intake=intake, + asset=asset, + business_summary=business_summary, + fingerprint_result=fingerprint, + ) + # 合并业务摘要进 structured_result_json + structured = dict(intake.structured_result_json or {}) + structured['business_summary'] = business_summary + structured['confidence'] = business_summary.get('confidence') + structured['parse_source'] = business_summary.get('parse_source') + intake.structured_result_json = structured + apply_duplicate_result_to_intake(intake, dup) + if commit: + db.session.commit() + return dup -def run_intake_parse(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]: +def run_intake_parse( + intake: ShippingNoticeIntake, + asset: FileAsset, + *, + parse_lease: str | None = None, +) -> dict[str, Any]: """ 执行单条接入记录的预解析并更新 ORM 状态。 - 核心逻辑:抽取文本后强制刷新并条件 UPDATE;抽取期间被取消则 status=skipped,不覆盖 cancelled。 + 核心逻辑:抽取文本(无锁)→ FOR UPDATE Intake → 校验 parse_lease → + 同事务落阶段二基础行 + parsed;重复检测在 SAVEPOINT;失败出口持锁清理。 + parse_lease 不匹配(超时后被新 Worker 接替)则 skipped,防止旧结果覆盖。 Returns: - 解析结果摘要字典;若期间被取消/过期则 status=skipped。 + 解析结果摘要字典;若期间被取消/过期/租约失效则 status=skipped。 """ + from app.services.file_assets.service import compensate_uploaded_storage_keys + from app.services.shipping_notice.document_candidate_persist import ( + persist_documents_and_candidates, + ) + from app.services.shipping_notice.eml_parse import strip_attachment_payloads + 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) + owner_user_id = int(getattr(asset, 'owner_user_id', None) or getattr(intake, 'user_id', 0) or 0) + storage_bucket = str(getattr(asset, 'storage_bucket', '') or '') or None - 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 result.status in {'extract_failed', 'empty_text'}: + strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) + summary = intake_result_to_structured_summary(result) + error_message = ( + '; '.join(warnings)[:1000] or '文本抽取失败' + if result.status == 'extract_failed' + else '未提取到有效文本' ) - 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( + return _fail_intake_with_stage2_cleanup( 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, - }, + intake_no=intake_no, + parser_version=parser_version, + error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED', + error_message=error_message, + extracted_text=None, + structured_result_json=summary, + parse_warnings_json=warnings, + required_lease=parse_lease, ) - 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: + # [STEP 1] 与 cancel 同序:先锁 Intake,确认仍可写且 lease 仍有效 + locked = _lock_intake_row(intake_id) + if locked is None: + strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) + return {'status': 'skipped', 'intake_no': intake_no, 'parse_status': None} + status_now = str(locked.parse_status or '') + if status_now in _ABORT_WRITE_STATUSES or status_now not in _WRITABLE_PARSE_STATUSES: + db.session.rollback() + strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) return { 'status': 'skipped', 'intake_no': intake_no, - 'parse_status': _db_parse_status(intake_id), + 'parse_status': status_now, } - return {'status': 'parsed', 'intake_no': intake_no} + if not _parse_lease_matches(locked, required_lease=parse_lease): + db.session.rollback() + strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) + return { + 'status': 'skipped', + 'intake_no': intake_no, + 'parse_status': status_now, + 'reason': 'stale_parse_lease', + } + + persist_info: dict[str, Any] = {} + uploaded_storage_keys: list[str] = [] + try: + # [STEP 2] 阶段二基础落库(重复检测延后到 SAVEPOINT,避免检测异常回滚 Document/资产) + persist_info = persist_documents_and_candidates( + intake=locked, + parent_asset=asset, + result=result, + uploaded_storage_keys=uploaded_storage_keys, + run_duplicate_detection=False, + ) + + tech_summary = intake_result_to_structured_summary(result) + tech_summary['document_count'] = persist_info.get('document_count') + tech_summary['candidate_count'] = persist_info.get('candidate_count') + locked.parser_version = parser_version + locked.parse_status = 'parsed' + locked.parse_lease = None + locked.error_code = None + locked.error_message = None + locked.extracted_text = result.text + locked.structured_result_json = tech_summary + locked.parse_warnings_json = warnings + locked.updated_at = datetime.utcnow() + + # SAVEPOINT:写业务摘要 + Candidate/Intake 重复检测;失败降级 unchecked + from app.services.shipping_notice.duplicate_detection import ( + clear_duplicate_state_to_unchecked, + refresh_candidates_and_aggregate_intake, + ) + from app.services.shipping_notice.intake_business_parser import ( + parse_intake_business_summary, + ) + + try: + with db.session.begin_nested(): + business_summary = parse_intake_business_summary( + extracted_text=str(result.text or ''), + source_type=str(result.source_type or 'manual'), + ) + structured = dict(locked.structured_result_json or {}) + structured['business_summary'] = business_summary + structured['confidence'] = business_summary.get('confidence') + structured['parse_source'] = business_summary.get('parse_source') + locked.structured_result_json = structured + dup = refresh_candidates_and_aggregate_intake( + intake=locked, + parent_asset=asset, + ) + except Exception: + clear_duplicate_state_to_unchecked(intake=locked) + dup = { + 'status': 'unchecked', + 'fingerprint_strength': None, + } + + strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) + db.session.commit() + return { + 'status': 'parsed', + 'intake_no': intake_no, + 'duplicate_status': dup.get('status'), + 'fingerprint_strength': dup.get('fingerprint_strength'), + 'document_count': persist_info.get('document_count'), + 'candidate_count': persist_info.get('candidate_count'), + } + except Exception as exc: + db.session.rollback() + compensate_uploaded_storage_keys( + uploaded_storage_keys, + owner_user_id=owner_user_id, + storage_bucket=storage_bucket, + ) + strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) + fail_summary = intake_result_to_structured_summary(result) + fail_warnings = [ + *warnings, + f'document_candidate_persist_failed:{type(exc).__name__}:{str(exc)[:200]}', + ] + fail_summary['warnings'] = list(fail_summary.get('warnings') or []) + [ + f'document_candidate_persist_failed:{type(exc).__name__}', + ] + return _fail_intake_with_stage2_cleanup( + intake_id=intake_id, + intake_no=intake_no, + parser_version=parser_version, + error_code='SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED', + error_message=( + f'附件资产化或候选识别失败: {type(exc).__name__}: {str(exc)[:400]}' + ), + extracted_text=result.text, + structured_result_json=fail_summary, + parse_warnings_json=fail_warnings, + required_lease=parse_lease, + ) def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]: - """将已解析 intake 转为兼容 create_batch 的 notice_item。""" - return { + """ + 将已解析 intake 转为兼容 create_batch 的 notice_item(含业务指纹与重复决策元数据)。 + + 核心逻辑:create_revision 时对目标任务 FOR UPDATE,并拒绝已有后继,防止并发打出两个 v2。 + """ + item = { 'source_type': guess_source_type(asset.original_filename), 'source_file_name': asset.original_filename, 'source_file_type': asset.mime_type, @@ -251,4 +773,51 @@ def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dic 'warnings': list(intake.parse_warnings_json or []), 'source_asset_id': asset.id, 'source_intake_id': intake.id, + 'business_fingerprint': intake.business_fingerprint, + 'fingerprint_version': intake.fingerprint_version, + 'document_version': 1, + 'duplicate_resolution_type': 'normal', + 'supersedes_task_id': None, + 'duplicate_source_task_id': None, + 'duplicate_override_reason': None, } + resolution = str(intake.duplicate_resolution or '').strip().lower() + target_no = str(intake.duplicate_target_task_no or '').strip().upper() + if resolution == 'create_revision' and target_no: + target = ( + db.session.query(ShippingTask) + .filter(ShippingTask.task_no == target_no) + .with_for_update() + .first() + ) + if not target: + raise ConflictError( + '修订目标任务不存在', + code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', + details={'target_task_no': target_no}, + ) + existing_successor = ( + db.session.query(ShippingTask.id) + .filter(ShippingTask.supersedes_task_id == int(target.id)) + .first() + ) + if existing_successor is not None: + raise ConflictError( + '目标任务已有修订版本,请打开已有修订或重新检测', + code='SHIPPING_NOTICE.REVISION_CONFLICT', + details={'target_task_no': target.task_no, 'document_version': int(target.document_version or 1)}, + ) + item['supersedes_task_id'] = int(target.id) + item['document_version'] = int(target.document_version or 1) + 1 + item['duplicate_resolution_type'] = 'revision' + elif resolution == 'force_create' and target_no: + target = ( + db.session.query(ShippingTask) + .filter(ShippingTask.task_no == target_no) + .first() + ) + if target: + item['duplicate_source_task_id'] = int(target.id) + item['duplicate_override_reason'] = intake.duplicate_resolution_reason + item['duplicate_resolution_type'] = 'force_create' + return item diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py index e68190d4..c63a1cd3 100644 --- a/backend/app/services/shipping_notice/intake_service.py +++ b/backend/app/services/shipping_notice/intake_service.py @@ -1,9 +1,13 @@ """ 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 执行。 +用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。 +依赖:file_assets.service、intake_parse_workflow、jobs.queue、models、duplicate_detection、 + attachment_integrity。 +逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行; + 创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE; + cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径); + 状态轮询用瘦身 parse_summary。 """ from __future__ import annotations @@ -13,20 +17,37 @@ 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, NotFoundError, ValidationError +from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.core.response import utc_iso -from app.jobs.queue import enqueue +from app.jobs.queue import QUEUED_ONLY_STATUSES, enqueue from app.jobs.types import JobType -from app.models import FileAsset, ShippingNoticeIntake +from app.models import FileAsset, ShippingNoticeIntake, ShippingTask, 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.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'}) + def _parser_version() -> str: - return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip() + return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v6') or 'v6').strip() def _intake_ttl_hours() -> int: @@ -38,15 +59,141 @@ def generate_intake_no() -> str: 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]: - """对外序列化接入记录。""" +def _duplicate_payload_from_intake(intake: ShippingNoticeIntake) -> 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', + } + 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 '')) + ), + } + 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 []), + } + 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: ShippingNoticeIntake, + *, + asset: FileAsset | None = None, + include_parse_texts: bool = False, +) -> dict[str, Any]: + """ + 对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。 + + Args: + include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口), + 并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。 + """ + 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)) 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, + '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), 'warnings': list(intake.parse_warnings_json or []), 'error_code': intake.error_code, 'error_message': intake.error_message, @@ -76,12 +223,12 @@ def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake: 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) + return serialize_intake(intake, asset=asset, include_parse_texts=True) def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset: @@ -91,6 +238,31 @@ def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset: return asset +def _lock_intake_for_asset_purpose_parser( + *, + asset_id: int, + purpose: str, + parser_version: str, +) -> ShippingNoticeIntake | None: + """ + FOR UPDATE 锁定同一资产目的+解析器版本下的 Intake(创建/重投入口串行化)。 + + Returns: + 锁定的 Intake;不存在则 None。 + """ + return ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.asset_id == int(asset_id), + ShippingNoticeIntake.purpose == purpose, + ShippingNoticeIntake.parser_version == parser_version, + ) + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + + def create_shipping_notice_intake( *, user_id: int, @@ -99,7 +271,13 @@ def create_shipping_notice_intake( ) -> dict[str, Any]: """ 基于已上传 FileAsset 创建接入记录并投递解析 Job。 - 核心逻辑:校验资产 ready → 复用同 parser 版本 intake → 入队 shipping_notice_parse。 + + 核心逻辑: + 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。 """ asset = get_asset_for_user(asset_no, user_id) if str(asset.upload_status or '') != 'ready': @@ -108,41 +286,82 @@ def create_shipping_notice_intake( 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) + purpose = 'shipping_notice' + conv = str(conversation_id or '').strip() or None - if not intake: - intake = ShippingNoticeIntake( + # [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: + candidate = ShippingNoticeIntake( intake_no=generate_intake_no(), - asset_id=asset.id, + asset_id=int(asset.id), user_id=int(user_id), - conversation_id=str(conversation_id or '').strip() or None, - purpose='shipping_notice', + conversation_id=conv, + purpose=purpose, parse_status='created', parser_version=parser_version, expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()), ) - db.session.add(intake) - db.session.flush() + 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 intake.parse_status in {'queued', 'parsing'}: + # [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 = str(conversation_id or intake.conversation_id or '').strip() or None + intake.conversation_id = conv or intake.conversation_id intake.error_code = None intake.error_message = None - intake.updated_at = datetime.utcnow() + intake.parse_lease = None + intake.updated_at = now + # 与 retry 一致:仅复用 queued,不复用残留 running,避免挂到僵尸 Job job_id = enqueue( JobType.SHIPPING_NOTICE_PARSE, {'intake_no': intake.intake_no}, @@ -151,6 +370,9 @@ def create_shipping_notice_intake( 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() @@ -191,9 +413,46 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str 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'}: + """ + 重试解析: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(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.intake_no == normalized, + ShippingNoticeIntake.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='当前状态不允许重试解析', @@ -202,6 +461,8 @@ def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: 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}, @@ -210,7 +471,9 @@ def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: created_by_id=user_id, message='等待重试预解析发货通知', max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3), - dedupe_active=False, + dedupe_active=True, + dedupe_statuses=QUEUED_ONLY_STATUSES, + commit=False, ) intake.parse_job_id = job_id db.session.commit() @@ -218,15 +481,196 @@ def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: def cancel_intake(*, user_id: int, intake_no: str) -> None: - """取消未消费的接入记录。""" - intake = get_intake_for_user(intake_no, user_id) + """ + 取消未消费的接入记录。 + + 核心逻辑: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(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.intake_no == normalized, + ShippingNoticeIntake.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 + if str(getattr(user, 'role', '') or '') == 'admin': + return True + 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 ( + 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(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.intake_no == normalized, + ShippingNoticeIntake.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: + business_summary = parse_intake_business_summary( + extracted_text=str(intake.extracted_text or ''), + source_type='manual', + ) + 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(ShippingTask) + .filter(ShippingTask.task_no == target_no, ShippingTask.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('process_status') or '') != str(target_task.process_status or ''): + 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[ShippingNoticeIntake], diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index f22ed008..67ae31b8 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -879,7 +879,9 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: """ 确认当前任务的库存 RPA 来源,并在门禁通过后继续触发库存导出。 - 【AI 触发时机】:当用户在订单解析阶段库存源检查点选择一个 source_code 后调用。 + + 【AI 触发时机】:当用户在库存源检查点(通常已先完成解析确认)选择 source_code 后调用。 + 兼容:存量任务若仍带 pending_parse_review_after_source,确认源后会回到 parse_review。 """ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -929,6 +931,7 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: }, ) + # 存量兼容:旧顺序先确认库存源时延后的低置信度解析复核。 if task_needs_parse_review(task): step_payload = dict(task.step_payload_json or {}) step_payload.pop("pending_parse_review_after_source", None) diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index a8b88bdf..022e5ac2 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -3,7 +3,8 @@ services/shipping_notice/inventory_source_gate.py 用途:库存源稳定性门禁、独立字段写入与路由指纹管理。 依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。 -逻辑:订单解析与后续 RPA/库存/匹配/导出流程统一调用本模块,禁止散落判断。 +逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review; + RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。 """ from __future__ import annotations @@ -249,24 +250,17 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource def task_needs_parse_review(task: ShippingTask) -> bool: """ 判断任务是否仍需完成低置信度解析人工确认。 - 核心逻辑:优先看 review/pending 标记;库存源先确认时依赖 step_payload 或 parse_confidence 兜底。 - """ - from flask import current_app + 核心逻辑:仅认显式标记——review/pending 为 parse_review / low_confidence, + 或存量 pending_parse_review_after_source。禁止仅凭 parse_confidence 兜底, + 否则「解析已确认 → 再确认库存源」会被误判回解析复核。 + """ from app.services.shipping_notice.constants import PH_LOW_CONF, RS_PARSE_REVIEW if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF: return True payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - if payload.get("pending_parse_review_after_source"): - return True - threshold = float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) - try: - confidence = float(task.parse_confidence) if task.parse_confidence is not None else 1.0 - except (TypeError, ValueError): - confidence = 1.0 - lines = task.lines_json if isinstance(task.lines_json, list) else [] - return confidence < threshold and bool(lines) + return bool(payload.get("pending_parse_review_after_source")) def transition_task_to_inventory_source_review( @@ -278,7 +272,10 @@ def transition_task_to_inventory_source_review( ) -> None: """ 将任务持久化到库存源人工复核检查点,并写入候选裁决信息。 + 核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。 + mark_pending_parse_review 仅用于存量/兼容路径(旧顺序先源后解析); + 新路径应先完成 parse_review,再进入本检查点,通常不传 True。 """ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -304,8 +301,11 @@ def transition_task_to_inventory_source_review( def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceAdjudication: """ - 对已进入后续阶段但库存源不稳定的任务补做裁决并落库到 inventory_source_review。 - 【AI 触发时机】:auto_progress / ensure_inventory 等入口发现门禁未通过时调用。 + 对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。 + + 【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。 + 核心逻辑:新业务顺序是先解析后库存源;仅当仍检测到待解析复核(含存量延后标记)时, + 才写入 pending_parse_review_after_source 以兼容旧任务。 """ adjudication = adjudicate_and_apply_inventory_source(task) if not is_inventory_source_stable(task): diff --git a/backend/app/services/shipping_notice/notice_upload.py b/backend/app/services/shipping_notice/notice_upload.py index 9ae36c89..d077a708 100644 --- a/backend/app/services/shipping_notice/notice_upload.py +++ b/backend/app/services/shipping_notice/notice_upload.py @@ -2,9 +2,9 @@ services/shipping_notice/notice_upload.py 用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。 -依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。 +依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、eml_parse、export._storage_root、Flask current_app 配置。 逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads - 收敛抽取与失败分流;下游 extract/task_workflow 只消费 NoticeIntakeResult。 + 收敛抽取与失败分流;.eml 走结构化解析(正文/内嵌资源/真实附件);下游只消费 NoticeIntakeResult。 """ from __future__ import annotations @@ -14,8 +14,6 @@ import hashlib import re import shutil from dataclasses import dataclass, field -from email import policy -from email.parser import BytesParser from pathlib import Path from typing import Any, Literal, Sequence @@ -24,6 +22,7 @@ from flask import current_app from edkb_system.contracts import Block, Context from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr from app.services.shipping_notice.export import _storage_root +from app.services.shipping_notice.eml_parse import parse_eml_bytes def task_notice_upload_path(task_no: str, filename: str) -> Path: @@ -112,32 +111,6 @@ def _html_to_text(html: str) -> str: return s.strip() -def _eml_to_text(data: bytes) -> str: - msg = BytesParser(policy=policy.default).parsebytes(data) - parts: list[str] = [] - subject = str(msg.get("subject") or "").strip() - if subject: - parts.append(f"Subject: {subject}") - if msg.is_multipart(): - for part in msg.walk(): - if part.is_multipart(): - continue - ctype = str(part.get_content_type() or "") - payload = part.get_payload(decode=True) or b"" - if ctype == "text/plain": - parts.append(_decode_text(payload).strip()) - elif ctype == "text/html": - parts.append(_html_to_text(_decode_text(payload)).strip()) - else: - payload = msg.get_payload(decode=True) or b"" - ctype = str(msg.get_content_type() or "") - if ctype == "text/html": - parts.append(_html_to_text(_decode_text(payload)).strip()) - else: - parts.append(_decode_text(payload).strip()) - return "\n\n".join(x for x in parts if x) - - def _image_bytes_to_blocks(raw: bytes) -> list[Block]: if not raw: return [] @@ -172,12 +145,23 @@ def _blocks_to_text(blocks: list[Block]) -> str: return text -def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]: +def extract_notice_text( + file_path: Path, + *, + retain_payloads: bool = False, +) -> tuple[str, dict[str, Any]]: """ 从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。 + 核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析(元数据 + 真实附件独立抽取), + 内嵌 Logo/签名图不进入附件列表,也不参与订单文本拼接。 + + Args: + file_path: 已落盘的通知文件路径。 + retain_payloads: 仅 EML;True 时保留 attachments[*]._payload_bytes 供 Intake 派生资产。 + Returns: - tuple[str, dict]: (抽取文本, meta 含 warnings 与 file_type)。 + tuple[str, dict]: (抽取文本, meta 含 warnings、file_type;eml 另含 email/attachments/attachment_count)。 """ path = Path(file_path) ext = path.suffix.lower().lstrip(".") @@ -189,7 +173,12 @@ def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]: if ext in {"html", "htm"}: return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext} if ext in {"eml"}: - return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext} + # 叶附件递归抽取时复用本函数;eml_parse 通过嵌套深度上限防止 bom 炸弹式嵌套 + return parse_eml_bytes( + path.read_bytes(), + extract_text=extract_notice_text, + retain_payloads=retain_payloads, + ) blocks: list[Block] = [] if ext in {"pdf"}: diff --git a/backend/app/services/shipping_notice/parse_summary.py b/backend/app/services/shipping_notice/parse_summary.py index b58b48f8..fcb426df 100644 --- a/backend/app/services/shipping_notice/parse_summary.py +++ b/backend/app/services/shipping_notice/parse_summary.py @@ -4,6 +4,7 @@ services/shipping_notice/parse_summary.py 用途:把发货通知解析结果格式化成适合聊天区展示的摘要文本。 依赖:shipping_notice.i18n 中的语言解析与文案函数、订单行格式化辅助函数。 逻辑:由 task_workflow.parse_notice 在解析完成后调用本文件,向前端或 Agent 返回可直接展示的解析总结。 + 库存源门禁路径不经本模块,由 parse_notice 直接拼接 issues 列表文案。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 0bd82718..4a0b3f98 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -1,10 +1,11 @@ """ services/shipping_notice/query_service.py -用途:发货通知读模型 — 任务/批次查询、排序与序列化投影。 +用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。 依赖:models.ShippingBatch、ShippingTask、ShippingTaskEvent。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; - tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉。 + tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉; + SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*。 """ from __future__ import annotations @@ -293,6 +294,40 @@ def _serialize_inventory_snapshot(task: ShippingTask) -> dict[str, Any] | None: return serialize_inventory_snapshot_link(task) +def _task_version_chain_fields(task: ShippingTask) -> dict[str, Any]: + """ + 组装任务版本链与重复决策投影字段。 + + 核心逻辑:查 supersedes / 被谁 supersede / duplicate_source,供工作台与 Chat 导航。 + """ + supersedes_task_no = None + if task.supersedes_task_id: + prev = db.session.get(ShippingTask, int(task.supersedes_task_id)) + if prev is not None: + supersedes_task_no = prev.task_no + superseded_by = ( + db.session.query(ShippingTask) + .filter(ShippingTask.supersedes_task_id == int(task.id)) + .order_by(ShippingTask.document_version.desc(), ShippingTask.id.desc()) + .first() + ) + duplicate_source_task_no = None + if task.duplicate_source_task_id: + src = db.session.get(ShippingTask, int(task.duplicate_source_task_id)) + if src is not None: + duplicate_source_task_no = src.task_no + return { + 'document_version': int(task.document_version or 1), + 'supersedes_task_no': supersedes_task_no, + 'superseded_by_task_no': superseded_by.task_no if superseded_by else None, + 'duplicate_source_task_no': duplicate_source_task_no, + 'duplicate_resolution_type': task.duplicate_resolution_type, + 'duplicate_override_reason': task.duplicate_override_reason, + 'business_fingerprint': task.business_fingerprint, + 'fingerprint_version': task.fingerprint_version, + } + + def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]: """按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。""" from app.services.shipping_notice.rpa import rpa_runtime_mode @@ -305,7 +340,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, return _task_tool_payload(task) if projection == TaskProjection.SUMMARY: step_payload = task.step_payload_json or {} - return { + data = { "id": task.id, "task_no": task.task_no, "batch_no": _task_batch_no(task), @@ -351,6 +386,8 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, "created_at": task.created_at.isoformat() if task.created_at else None, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } + data.update(_task_version_chain_fields(task)) + return data if projection == TaskProjection.DETAIL: data = serialize_task(task, TaskProjection.SUMMARY) data.update({ diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index adabd0e6..1812a4f7 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -2,8 +2,9 @@ services/shipping_notice/queue_service.py 用途:货代发货后台任务队列适配层。 -依赖:app.jobs.queue、jobs.types、shipping_notice.batch_orchestrator。 -逻辑:发货通知只写入通用 jobs 表,worker 通过 Job Runner 消费后执行单票编排。 +依赖:app.jobs.queue、jobs.types、batch_orchestrator、intake_parse_workflow。 +逻辑:发货通知写入通用 jobs;worker 领取 RUN/PARSE;超时回收时 PARSE Job + 经 sync_intake_after_parse_job_recovery 同步 Intake,避免永久 parsing。 """ from __future__ import annotations @@ -110,19 +111,48 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: def recover_stale_shipping_notice_jobs() -> tuple[int, str]: - """兼容旧调用:回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。""" + """ + 回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。 + + 核心逻辑:单票编排与预解析分超时配置回收;预解析 Job 回收同事务同步 Intake, + 避免 Job 已 requeue/failed 而 Intake 永久 parsing。 + """ from app.jobs.queue import recover_stale_jobs + from app.services.shipping_notice.intake_parse_workflow import ( + sync_intake_after_parse_job_recovery, + ) from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( recover_pending_rpa_callback_cleanup_jobs, ) - timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300)) - count = recover_stale_jobs(domain=SHIPPING_NOTICE_JOB_DOMAIN, timeout_seconds=timeout_sec) + run_timeout = float( + current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300) or 300 + ) + parse_timeout = float( + current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300) or 300 + ) + run_count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=run_timeout, + job_type=JobType.SHIPPING_NOTICE_RUN, + ) + parse_count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=parse_timeout, + job_type=JobType.SHIPPING_NOTICE_PARSE, + on_recovered=sync_intake_after_parse_job_recovery, + ) + count = int(run_count) + int(parse_count) cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs() if cleanup_warnings: logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5])) if count: - logger.warning('recovered %s stale shipping_notice job(s)', count) + logger.warning( + 'recovered %s stale shipping_notice job(s) (run=%s parse=%s)', + count, + run_count, + parse_count, + ) if cleanup_count: logger.info('processed %s rpa callback cleanup job(s)', cleanup_count) parts = [] diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index c6a44b03..f2aff878 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -277,7 +277,8 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: 核心逻辑:先创建批次,再逐个创建任务;若 notice_item 已带 structured 或 auto_parse=true 则立即 parse_notice,否则仅保存 raw_text 待 Dify 续办。 Args: - payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据。 + payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据; + defer_commit=True 时仅 flush,由调用方与 intake 回写同事务提交。 Returns: dict[str, Any]: Tool 标准响应,包含批次摘要和每个任务的解析状态。 @@ -285,10 +286,15 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: notice_items = payload.get("notice_items") user_id = payload.get("user_id") idem_key = normalize_create_idempotency_key(payload.get("create_idempotency_key")) + # intake 建批路径可 defer_commit,由上层一次提交(consumed 关联 / 摘要 / 审计同事务) + defer_commit = bool(payload.get("defer_commit")) if not isinstance(notice_items, list) or not notice_items: batch, _created = create_batch(payload) try: - db.session.commit() + if defer_commit: + db.session.flush() + else: + db.session.commit() except IntegrityError as exc: replay = handle_batch_create_integrity_error( user_id=int(payload.get("user_id") or 0), @@ -362,6 +368,13 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: source_content_hash=content_hash, source_asset_id=item.get("source_asset_id"), source_intake_id=item.get("source_intake_id"), + business_fingerprint=str(item.get("business_fingerprint") or "").strip() or None, + fingerprint_version=str(item.get("fingerprint_version") or "").strip() or None, + document_version=int(item.get("document_version") or 1), + supersedes_task_id=item.get("supersedes_task_id"), + duplicate_source_task_id=item.get("duplicate_source_task_id"), + duplicate_override_reason=str(item.get("duplicate_override_reason") or "").strip() or None, + duplicate_resolution_type=str(item.get("duplicate_resolution_type") or "normal").strip() or "normal", batch_index=idx, batch_total=total, raw_content=str(item.get("raw_text") or "").strip() or None, @@ -369,7 +382,26 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: ) db.session.add(task) log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no}) - db.session.flush() + try: + db.session.flush() + except IntegrityError as exc: + db.session.rollback() + # 修订链唯一约束竞争:并发两个 create_revision 指向同一父任务 + orig = str(getattr(exc, "orig", "") or exc) + if "supersedes" in orig.lower() or "uq_shipping_tasks_supersedes" in orig.lower(): + raise ConflictError( + "目标任务已有修订版本,请打开已有修订或重新检测", + code="SHIPPING_NOTICE.REVISION_CONFLICT", + details={"supersedes_task_id": item.get("supersedes_task_id")}, + ) from exc + replay = handle_batch_create_integrity_error( + user_id=int(payload.get("user_id") or 0), + create_idempotency_key=idem_key, + exc=exc, + ) + if replay is not None: + return replay + raise parse_payload: dict[str, Any] = { "task_id": task.task_no, "user_id": payload.get("user_id"), @@ -405,7 +437,10 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: recompute_batch_summary(batch) try: - db.session.commit() + if defer_commit: + db.session.flush() + else: + db.session.commit() except IntegrityError as exc: replay = handle_batch_create_integrity_error( user_id=int(payload.get("user_id") or 0), @@ -689,17 +724,57 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, ) - # [STEP 5] 库存源硬门禁:订单解析阶段必须先完成库存源裁决(先于低置信度人工确认)。 + # [STEP 5] 先裁决库存源线索(写入 destination / 候选),但低置信度必须先走解析复核。 + # 业务顺序:确认解析正确 → 再人工确认库存源 → 才允许库存/RPA。 low_confidence = confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) adjudication = adjudicate_and_apply_inventory_source(task) - if not is_inventory_source_stable(task): + source_stable = is_inventory_source_stable(task) + + if low_confidence: + apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) + log_task_event( + task, + "parse_needs_review", + { + "confidence": confidence, + "warnings": warnings, + "inventory_source_status": adjudication.status, + "inventory_source_stable": source_stable, + }, + ) + _upsert_parse_review_chat_message(task) + db.session.commit() + summary_text = format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload) + if not source_stable: + summary_text = ( + f"{summary_text}\n\n" + "解析确认通过后,若库存源仍无法唯一命中,将再请你选择正式库存源;" + "站点与库位将由系统根据配置自动填充。" + ) + return tool_response( + status="needs_human", + task=task, + message=summary_text, + data={ + **serialize_task_for_tool(task), + "warnings": warnings, + "inventory_source_candidates": adjudication.candidates, + "inventory_source_status": adjudication.status, + "inventory_source_reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + }, + stop_agent_turn=True, + forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], + ) + + # [STEP 6] 解析已自动接受(高置信度);库存源未稳定时才进入库存源人工确认。 + if not source_stable: from app.services.shipping_notice.inventory_source_gate import transition_task_to_inventory_source_review transition_task_to_inventory_source_review( task, adjudication, error_message="无法根据发货通知唯一确定库存查询来源", - mark_pending_parse_review=low_confidence, ) set_task_step_progress( task, @@ -708,7 +783,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: status="needs_human", message="库存源待确认", progress_percent=100, - detail="请确认本票应使用哪个库存源后继续。", + detail="解析已通过,请确认本票应使用哪个库存源后继续。", extra={"warnings": warnings, "inventory_source_status": adjudication.status}, ) log_task_event( @@ -719,16 +794,28 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: "reason": adjudication.reason, "destination_candidates": adjudication.destination_candidates, "candidate_source_codes": [item.get("source_code") for item in adjudication.candidates], + "warnings": warnings, }, ) db.session.commit() + message_parts = [ + "订单解析已通过,但库存源仍待确认:", + "- 无法根据发货通知唯一确定库存查询来源", + ] + for warning in warnings: + text = str(warning or "").strip() + if text: + message_parts.append(f"- {text}") + message_parts.extend( + [ + "", + "请选择正式库存源后继续;站点与库位将由系统根据配置自动填充。", + ] + ) return tool_response( status="needs_human", task=task, - message=( - "订单字段已解析,但库存源尚未唯一确定。" - "请选择正式库存源后继续;站点与库位将由系统根据配置自动填充。" - ), + message="\n".join(message_parts), data={ **serialize_task_for_tool(task), "warnings": warnings, @@ -742,19 +829,6 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], ) - # [STEP 6] 低置信度停待人审;库存源已稳定后才进入解析内容复核。 - if low_confidence: - apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) - log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings}) - _upsert_parse_review_chat_message(task) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload), - data={**serialize_task_for_tool(task), "warnings": warnings}, - ) - apply_task_transition(task, TaskTransition.PARSED) log_task_event(task, "parsed", {"confidence": confidence, "warnings": warnings}) db.session.commit() @@ -767,8 +841,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: include_confirmation_hint=not should_auto_continue, ) - # [STEP 4] 高置信度解析后不在当前请求线程里继续串行推进。 - # 统一把后续库存/匹配/导出链路交给后台 worker,避免请求线程兼任主调度器。 + # [STEP 7] 高置信度且库存源稳定:后续库存/匹配/导出交给后台 worker。 if should_auto_continue: orchestrator_started = start_task_orchestrator(task.task_no) merged_message = ( diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 57cec357..55860e91 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -2,8 +2,9 @@ services/shipping_notice/ui_state.py 用途:发货通知任务/批次 UI 状态读模型,作为 Chat 按钮、步骤条与工作台的统一状态来源。 -依赖:models.ShippingTask/ShippingBatch、state_machine、query_service。 -逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要。 +依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants。 +逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要; + 文件解析阶段额外汇总 summary.issues(解析复核 / RSV / 库存源门禁 + parse warnings)。 """ from __future__ import annotations @@ -40,6 +41,7 @@ from app.services.shipping_notice.constants import ( RS_PARSE_REVIEW, RS_SHORTAGE_REVIEW, ) +from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable from app.services.shipping_notice.query_service import ( compute_batch_process_summary, list_sorted_batch_tasks, @@ -179,7 +181,88 @@ def _action_buttons_for_task(task: ShippingTask) -> list[dict[str, str]]: return ui.action_buttons -def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, str | None]: +_PARSE_STAGE_CHECKPOINTS = { + CP_PARSE_REVIEW, + CP_RSV_REQ, + CP_INVENTORY_SOURCE_REVIEW, + CP_NOTICE_TEXT_EXTRACTION_FAILED, +} + +_WARNING_DISPLAY_ALIASES: dict[str, str] = { + "parse_fallback_heuristic": "解析引擎回退到启发式规则,请人工核对字段。", + "heuristic_no_lines_detected": "启发式解析未识别到订单行,请核对通知内容。", +} + + +def _normalize_issue_text(raw: Any) -> str: + """将 warnings / error 原文规范化为可展示短文案,过滤空值。""" + text = str(raw or "").strip() + if not text: + return "" + return _WARNING_DISPLAY_ALIASES.get(text, text) + + +def _append_unique_issue(issues: list[str], raw: Any) -> None: + """追加去重后的问题文案,保持首次出现顺序。""" + text = _normalize_issue_text(raw) + if text and text not in issues: + issues.append(text) + + +def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> list[str]: + """ + 汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。 + + 核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发; + 以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。 + 新顺序为先解析复核再库存源;存量 pending_parse_review_after_source 仍提示延后复核。 + """ + checkpoint_value = str(checkpoint or "").strip() + if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS: + return [] + + issues: list[str] = [] + if checkpoint_value == CP_INVENTORY_SOURCE_REVIEW: + _append_unique_issue( + issues, + task.error_message or "无法根据发货通知唯一确定库存查询来源", + ) + elif checkpoint_value == CP_RSV_REQ: + _append_unique_issue( + issues, + task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)", + ) + elif checkpoint_value == CP_NOTICE_TEXT_EXTRACTION_FAILED: + _append_unique_issue( + issues, + task.error_message or "未能从发货通知中解析到可审核内容", + ) + elif checkpoint_value == CP_PARSE_REVIEW: + _append_unique_issue(issues, "通知单解析置信度不足,需要复核单头或明细。") + if not is_inventory_source_stable(task): + _append_unique_issue( + issues, + "解析确认通过后,若库存源仍无法唯一命中,还需选择正式库存源。", + ) + + payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + progress = payload.get("current_step_progress") if isinstance(payload, dict) else None + extra = progress.get("extra") if isinstance(progress, dict) else None + warnings = extra.get("warnings") if isinstance(extra, dict) else None + if isinstance(warnings, list): + for item in warnings: + _append_unique_issue(issues, item) + + # 存量兼容:旧顺序「先库存源后解析」延后的低置信度提示。 + if payload.get("pending_parse_review_after_source") or ( + checkpoint_value == CP_INVENTORY_SOURCE_REVIEW and task.review_status == RS_PARSE_REVIEW + ): + _append_unique_issue(issues, "解析置信度不足,确认库存源后仍需复核解析结果。") + + return issues + + +def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, Any]: """输出用户可读任务摘要,供 Chat 文案与工作台卡片复用。""" title = user_facing_task_stage(task) message_by_checkpoint: dict[str, str] = { @@ -200,10 +283,12 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, CP_UPLOADED: "任务已完成上传。", CP_COMPLETED: "任务已关闭。", } + issues = _collect_parse_stage_issues(task, checkpoint) return { "title": title, "message": message_by_checkpoint.get(str(checkpoint or ""), title), "error_message": task.error_message or task.upload_error_message, + "issues": issues, } diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml index 13d847a7..9d21a02b 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/shipping_inventory_sources.yaml @@ -625,6 +625,7 @@ sources: - SINGAPORE HUB - SINGAPORE - SG + - VMI-SIN - source_code: CRANE enabled: true source_type: crane_footprint diff --git a/backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py b/backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py new file mode 100644 index 00000000..b31a4368 --- /dev/null +++ b/backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py @@ -0,0 +1,136 @@ +""" +backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py + +用途:发货通知第三阶段业务去重字段、任务版本链与相关索引。 +依赖:Alembic revision c9d0e1f2a3b5。 +逻辑:为 shipping_notice_intakes / shipping_tasks 增加指纹与重复决策列;历史 document_version 回填为 1。 + +Revision ID: a2b3c4d5e6f7 +Revises: c9d0e1f2a3b5 +Create Date: 2026-07-14 09:35:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "a2b3c4d5e6f7" +down_revision = "c9d0e1f2a3b5" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op: + batch_op.add_column(sa.Column("business_fingerprint", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("fingerprint_version", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("fingerprint_strength", sa.String(length=32), nullable=True)) + batch_op.add_column( + sa.Column( + "duplicate_status", + sa.String(length=32), + server_default="unchecked", + nullable=False, + ) + ) + batch_op.add_column(sa.Column("duplicate_matches_json", sa.JSON(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_checked_at", sa.DateTime(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_resolution", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("duplicate_resolution_reason", sa.Text(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_target_task_no", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("duplicate_resolved_by_id", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_resolved_at", sa.DateTime(), nullable=True)) + batch_op.create_foreign_key( + "fk_shipping_notice_intakes_duplicate_resolved_by_id_users", + "users", + ["duplicate_resolved_by_id"], + ["id"], + ) + batch_op.create_index( + "ix_shipping_notice_intakes_user_business_fingerprint", + ["user_id", "business_fingerprint"], + unique=False, + ) + batch_op.create_index( + "ix_shipping_notice_intakes_duplicate_status_created", + ["duplicate_status", "created_at"], + unique=False, + ) + batch_op.create_index( + "ix_shipping_notice_intakes_fp_version_fingerprint", + ["fingerprint_version", "business_fingerprint"], + unique=False, + ) + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("business_fingerprint", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("fingerprint_version", sa.String(length=32), nullable=True)) + batch_op.add_column( + sa.Column("document_version", sa.Integer(), server_default="1", nullable=False) + ) + batch_op.add_column(sa.Column("supersedes_task_id", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_source_task_id", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_override_reason", sa.Text(), nullable=True)) + batch_op.add_column(sa.Column("duplicate_resolution_type", sa.String(length=32), nullable=True)) + batch_op.create_foreign_key( + "fk_shipping_tasks_supersedes_task_id", + "shipping_tasks", + ["supersedes_task_id"], + ["id"], + ) + batch_op.create_foreign_key( + "fk_shipping_tasks_duplicate_source_task_id", + "shipping_tasks", + ["duplicate_source_task_id"], + ["id"], + ) + batch_op.create_index( + "ix_shipping_tasks_user_business_fingerprint", + ["user_id", "business_fingerprint"], + unique=False, + ) + batch_op.create_index("ix_shipping_tasks_supersedes_task_id", ["supersedes_task_id"], unique=False) + batch_op.create_index( + "ix_shipping_tasks_duplicate_source_task_id", + ["duplicate_source_task_id"], + unique=False, + ) + + op.execute("UPDATE shipping_tasks SET document_version = 1 WHERE document_version IS NULL") + + +def downgrade() -> None: + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_tasks_duplicate_source_task_id") + batch_op.drop_index("ix_shipping_tasks_supersedes_task_id") + batch_op.drop_index("ix_shipping_tasks_user_business_fingerprint") + batch_op.drop_constraint("fk_shipping_tasks_duplicate_source_task_id", type_="foreignkey") + batch_op.drop_constraint("fk_shipping_tasks_supersedes_task_id", type_="foreignkey") + batch_op.drop_column("duplicate_resolution_type") + batch_op.drop_column("duplicate_override_reason") + batch_op.drop_column("duplicate_source_task_id") + batch_op.drop_column("supersedes_task_id") + batch_op.drop_column("document_version") + batch_op.drop_column("fingerprint_version") + batch_op.drop_column("business_fingerprint") + + with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_notice_intakes_fp_version_fingerprint") + batch_op.drop_index("ix_shipping_notice_intakes_duplicate_status_created") + batch_op.drop_index("ix_shipping_notice_intakes_user_business_fingerprint") + batch_op.drop_constraint( + "fk_shipping_notice_intakes_duplicate_resolved_by_id_users", + type_="foreignkey", + ) + batch_op.drop_column("duplicate_resolved_at") + batch_op.drop_column("duplicate_resolved_by_id") + batch_op.drop_column("duplicate_target_task_no") + batch_op.drop_column("duplicate_resolution_reason") + batch_op.drop_column("duplicate_resolution") + batch_op.drop_column("duplicate_checked_at") + batch_op.drop_column("duplicate_matches_json") + batch_op.drop_column("duplicate_status") + batch_op.drop_column("fingerprint_strength") + batch_op.drop_column("fingerprint_version") + batch_op.drop_column("business_fingerprint") diff --git a/backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py b/backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py new file mode 100644 index 00000000..bf7a93f8 --- /dev/null +++ b/backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py @@ -0,0 +1,34 @@ +""" +backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py + +用途:为 ShippingNoticeIntake 增加 parse_lease,隔离超时回收前后的解析执行代次。 +依赖:Alembic revision f5a6b7c8d9e0。 +逻辑:upgrade 增加可空 parse_lease;downgrade 删除该列。 + +Revision ID: a6b7c8d9e0f1 +Revises: f5a6b7c8d9e0 +Create Date: 2026-07-14 19:40:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "a6b7c8d9e0f1" +down_revision = "f5a6b7c8d9e0" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """增加 parse_lease 列。""" + op.add_column( + "shipping_notice_intakes", + sa.Column("parse_lease", sa.String(length=64), nullable=True), + ) + + +def downgrade() -> None: + """删除 parse_lease 列。""" + op.drop_column("shipping_notice_intakes", "parse_lease") diff --git a/backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py b/backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py new file mode 100644 index 00000000..cd6950b4 --- /dev/null +++ b/backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py @@ -0,0 +1,145 @@ +""" +backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py + +用途:为 shipping_notice_parse 的 queued Job 增加部分唯一索引,防止并发双插。 +依赖:Alembic revision a6b7c8d9e0f1。 +逻辑:先合并历史重复 queued 预解析 Job,将 Intake.parse_job_id 重指 keep_id, + 再取消其余重复行;最后创建 uq_jobs_shipping_parse_queued_ref。 + 故意不含 running,以便 retry 在旧 running 残留时可另建 queued。 + +Revision ID: b7c8d9e0f1a2 +Revises: a6b7c8d9e0f1 +Create Date: 2026-07-14 20:00:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "b7c8d9e0f1a2" +down_revision = "a6b7c8d9e0f1" +branch_labels = None +depends_on = None + + +def _index_names(table: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {str(ix.get("name") or "") for ix in inspector.get_indexes(table)} + + +def _retarget_intake_parse_job_ids(bind, *, keep_id: int, drop_ids: list[int]) -> None: + """ + 将被取消 Job 上的 Intake.parse_job_id 重指向保留的 queued Job。 + + 须在取消 drop 行之前调用,避免升级后出现 queued 状态挂着 cancelled job_id。 + """ + for drop_id in drop_ids: + bind.execute( + sa.text( + """ + UPDATE shipping_notice_intakes + SET parse_job_id = :keep_id, + updated_at = CURRENT_TIMESTAMP + WHERE parse_job_id = :drop_id + """ + ), + {"keep_id": int(keep_id), "drop_id": int(drop_id)}, + ) + + +def _dedupe_queued_parse_jobs() -> None: + """同 domain/business_ref 的多条 queued 预解析 Job:保留最小 id,其余标 cancelled。""" + bind = op.get_bind() + groups = bind.execute( + sa.text( + """ + SELECT domain, business_ref + FROM jobs + WHERE job_type = 'shipping_notice_parse' + AND status = 'queued' + AND business_ref IS NOT NULL + GROUP BY domain, business_ref + HAVING COUNT(*) > 1 + """ + ) + ).fetchall() + for domain, business_ref in groups: + ids = [ + int(row[0]) + for row in bind.execute( + sa.text( + """ + SELECT id + FROM jobs + WHERE domain = :domain + AND job_type = 'shipping_notice_parse' + AND business_ref = :business_ref + AND status = 'queued' + ORDER BY id ASC + """ + ), + {"domain": str(domain), "business_ref": str(business_ref)}, + ).fetchall() + ] + if len(ids) < 2: + continue + keep_id = ids[0] + drop_ids = ids[1:] + # [STEP 1] 先重指 Intake,再取消重复 Job,避免 parse_job_id 悬空 + _retarget_intake_parse_job_ids(bind, keep_id=keep_id, drop_ids=drop_ids) + for drop_id in drop_ids: + bind.execute( + sa.text( + """ + UPDATE jobs + SET status = 'cancelled', + message = '并发去重:合并 queued shipping_notice_parse', + progress = 100, + locked_by = NULL, + locked_at = NULL, + finished_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE id = :drop_id + AND id <> :keep_id + AND status = 'queued' + """ + ), + {"drop_id": drop_id, "keep_id": keep_id}, + ) + + +def upgrade() -> None: + """去重后创建 shipping_notice_parse queued 部分唯一索引。""" + _dedupe_queued_parse_jobs() + # 兼容误建的旧名 + for obsolete in ("uq_jobs_shipping_parse_active_ref", "uq_jobs_shipping_parse_queued_ref"): + if obsolete == "uq_jobs_shipping_parse_queued_ref": + continue + if obsolete in _index_names("jobs"): + op.drop_index(obsolete, table_name="jobs") + if "uq_jobs_shipping_parse_queued_ref" in _index_names("jobs"): + return + op.create_index( + "uq_jobs_shipping_parse_queued_ref", + "jobs", + ["domain", "job_type", "business_ref"], + unique=True, + postgresql_where=sa.text( + "job_type = 'shipping_notice_parse' " + "AND status = 'queued' " + "AND business_ref IS NOT NULL" + ), + sqlite_where=sa.text( + "job_type = 'shipping_notice_parse' " + "AND status = 'queued' " + "AND business_ref IS NOT NULL" + ), + ) + + +def downgrade() -> None: + """删除部分唯一索引。""" + if "uq_jobs_shipping_parse_queued_ref" in _index_names("jobs"): + op.drop_index("uq_jobs_shipping_parse_queued_ref", table_name="jobs") diff --git a/backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py b/backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py new file mode 100644 index 00000000..05b6cd67 --- /dev/null +++ b/backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py @@ -0,0 +1,51 @@ +""" +backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py + +用途:intake 建单幂等键落库;任务 supersedes 唯一约束防并发双修订。 +依赖:Alembic revision a2b3c4d5e6f7。 +逻辑:shipping_notice_intakes.create_idempotency_key 支撑混合批次 / + 纯 open_existing 重放;shipping_tasks.supersedes_task_id 唯一保证线性版本链。 + +Revision ID: c2d3e4f5a6b7 +Revises: a2b3c4d5e6f7 +Create Date: 2026-07-14 11:00:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "c2d3e4f5a6b7" +down_revision = "a2b3c4d5e6f7" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op: + batch_op.add_column(sa.Column("create_idempotency_key", sa.String(length=128), nullable=True)) + batch_op.create_index( + "ix_shipping_notice_intakes_user_create_idempotency", + ["user_id", "create_idempotency_key"], + unique=False, + ) + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_tasks_supersedes_task_id") + # PostgreSQL/SQLite:UNIQUE 允许多个 NULL,非空时每任务至多一个后继修订 + batch_op.create_index( + "uq_shipping_tasks_supersedes_task_id", + ["supersedes_task_id"], + unique=True, + ) + + +def downgrade() -> None: + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("uq_shipping_tasks_supersedes_task_id") + batch_op.create_index("ix_shipping_tasks_supersedes_task_id", ["supersedes_task_id"], unique=False) + + with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_notice_intakes_user_create_idempotency") + batch_op.drop_column("create_idempotency_key") diff --git a/backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py b/backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py new file mode 100644 index 00000000..3c99d96d --- /dev/null +++ b/backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py @@ -0,0 +1,76 @@ +""" +backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py + +用途:修复已执行 b7c8d9e0f1a2 但未重指 parse_job_id 的环境。 +依赖:Alembic revision b7c8d9e0f1a2。 +逻辑:若 Intake.parse_job_id 指向已取消的 shipping_notice_parse Job, + 且同 (domain, business_ref) 仍有 queued 同伴,则重指到最小 queued id。 + +Revision ID: c8d9e0f1a2b3 +Revises: b7c8d9e0f1a2 +Create Date: 2026-07-14 20:10:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "c8d9e0f1a2b3" +down_revision = "b7c8d9e0f1a2" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """将指向 cancelled 预解析 Job 的 Intake.parse_job_id 重指到同 domain 的 queued Job。""" + bind = op.get_bind() + rows = bind.execute( + sa.text( + """ + SELECT i.id AS intake_id, + j.domain AS domain, + j.business_ref AS business_ref + FROM shipping_notice_intakes AS i + INNER JOIN jobs AS j ON j.id = i.parse_job_id + WHERE j.job_type = 'shipping_notice_parse' + AND j.status = 'cancelled' + AND j.business_ref IS NOT NULL + """ + ) + ).fetchall() + for intake_id, domain, business_ref in rows: + keep = bind.execute( + sa.text( + """ + SELECT id + FROM jobs + WHERE domain = :domain + AND job_type = 'shipping_notice_parse' + AND status = 'queued' + AND business_ref = :business_ref + ORDER BY id ASC + LIMIT 1 + """ + ), + {"domain": str(domain), "business_ref": str(business_ref)}, + ).fetchone() + if keep is None: + continue + bind.execute( + sa.text( + """ + UPDATE shipping_notice_intakes + SET parse_job_id = :keep_id, + updated_at = CURRENT_TIMESTAMP + WHERE id = :intake_id + AND parse_job_id IS NOT NULL + """ + ), + {"keep_id": int(keep[0]), "intake_id": int(intake_id)}, + ) + + +def downgrade() -> None: + """数据修复不可逆。""" + pass diff --git a/backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py b/backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py new file mode 100644 index 00000000..e28c43ee --- /dev/null +++ b/backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py @@ -0,0 +1,238 @@ +""" +backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py + +用途:阶段二——FileAsset 派生字段、ShippingNoticeDocument/Candidate 表、Task.source_candidate_id。 +依赖:Alembic revision c2d3e4f5a6b7。 +逻辑:EML 附件子资产挂 parent_asset_id;文档/候选支撑「一邮件多订单」识别(不创建 Task)。 + +Revision ID: d3e4f5a6b7c8 +Revises: c2d3e4f5a6b7 +Create Date: 2026-07-14 17:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "d3e4f5a6b7c8" +down_revision = "c2d3e4f5a6b7" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("file_assets", schema=None) as batch_op: + batch_op.add_column(sa.Column("parent_asset_id", sa.Integer(), nullable=True)) + batch_op.add_column( + sa.Column("asset_role", sa.String(length=32), server_default="upload", nullable=False) + ) + batch_op.add_column(sa.Column("source_attachment_key", sa.String(length=64), nullable=True)) + batch_op.create_foreign_key( + "fk_file_assets_parent_asset_id", + "file_assets", + ["parent_asset_id"], + ["id"], + ) + batch_op.create_index("ix_file_assets_parent_asset_id", ["parent_asset_id"], unique=False) + batch_op.create_index( + "ix_file_assets_parent_content_hash", + ["parent_asset_id", "content_hash"], + unique=False, + ) + batch_op.create_index( + "ix_file_assets_parent_attachment_key", + ["parent_asset_id", "source_attachment_key"], + unique=False, + ) + + op.create_table( + "shipping_notice_documents", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("intake_id", sa.Integer(), nullable=False), + sa.Column("asset_id", sa.Integer(), nullable=True), + sa.Column("document_type", sa.String(length=32), nullable=False), + sa.Column("attachment_key", sa.String(length=64), nullable=False), + sa.Column("filename", sa.String(length=255), nullable=True), + sa.Column("content_hash", sa.String(length=64), nullable=True), + sa.Column("classification", sa.String(length=32), nullable=False), + sa.Column("parse_status", sa.String(length=32), nullable=False), + sa.Column("extracted_text", sa.Text(), nullable=True), + sa.Column("parse_warnings_json", sa.JSON(), 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(["intake_id"], ["shipping_notice_intakes.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint( + "intake_id", + "attachment_key", + name="uq_shipping_notice_documents_intake_attachment_key", + ), + ) + op.create_index( + "ix_shipping_notice_documents_intake_id", + "shipping_notice_documents", + ["intake_id"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_documents_asset_id", + "shipping_notice_documents", + ["asset_id"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_documents_content_hash", + "shipping_notice_documents", + ["content_hash"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_documents_parse_status", + "shipping_notice_documents", + ["parse_status"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_documents_created_at", + "shipping_notice_documents", + ["created_at"], + unique=False, + ) + + op.create_table( + "shipping_notice_candidates", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("candidate_no", sa.String(length=64), nullable=False), + sa.Column("intake_id", sa.Integer(), nullable=False), + sa.Column("primary_document_id", sa.Integer(), nullable=False), + sa.Column("po_number", sa.String(length=128), nullable=True), + sa.Column("structured_result_json", sa.JSON(), nullable=True), + sa.Column("confidence", sa.Float(), nullable=True), + sa.Column( + "validation_status", + sa.String(length=32), + server_default="pending", + nullable=False, + ), + sa.Column("conflicts_json", sa.JSON(), nullable=True), + sa.Column("selected", sa.Boolean(), server_default=sa.text("true"), nullable=False), + sa.Column("business_fingerprint", sa.String(length=64), nullable=True), + sa.Column("fingerprint_version", sa.String(length=32), nullable=True), + sa.Column("fingerprint_strength", sa.String(length=32), nullable=True), + sa.Column( + "duplicate_status", + sa.String(length=32), + server_default="unchecked", + nullable=False, + ), + sa.Column("duplicate_matches_json", sa.JSON(), nullable=True), + sa.Column("duplicate_resolution", sa.String(length=32), nullable=True), + sa.Column("duplicate_resolution_reason", sa.Text(), nullable=True), + sa.Column("duplicate_target_task_no", sa.String(length=64), nullable=True), + sa.Column("duplicate_checked_at", sa.DateTime(), nullable=True), + sa.Column("consumed_task_id", sa.Integer(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]), + sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]), + sa.ForeignKeyConstraint(["primary_document_id"], ["shipping_notice_documents.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("candidate_no", name="uq_shipping_notice_candidates_candidate_no"), + sa.UniqueConstraint( + "intake_id", + "primary_document_id", + name="uq_shipping_notice_candidates_intake_primary_document", + ), + ) + op.create_index( + "ix_shipping_notice_candidates_intake_id", + "shipping_notice_candidates", + ["intake_id"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_candidates_primary_document_id", + "shipping_notice_candidates", + ["primary_document_id"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_candidates_po_number", + "shipping_notice_candidates", + ["po_number"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_candidates_user_fingerprint", + "shipping_notice_candidates", + ["business_fingerprint"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_candidates_duplicate_status", + "shipping_notice_candidates", + ["duplicate_status"], + unique=False, + ) + op.create_index( + "ix_shipping_notice_candidates_created_at", + "shipping_notice_candidates", + ["created_at"], + unique=False, + ) + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("source_candidate_id", sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + "fk_shipping_tasks_source_candidate_id", + "shipping_notice_candidates", + ["source_candidate_id"], + ["id"], + ) + batch_op.create_index( + "ix_shipping_tasks_source_candidate_id", + ["source_candidate_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_candidate_id") + batch_op.drop_constraint("fk_shipping_tasks_source_candidate_id", type_="foreignkey") + batch_op.drop_column("source_candidate_id") + + op.drop_index("ix_shipping_notice_candidates_created_at", table_name="shipping_notice_candidates") + op.drop_index( + "ix_shipping_notice_candidates_duplicate_status", + table_name="shipping_notice_candidates", + ) + op.drop_index( + "ix_shipping_notice_candidates_user_fingerprint", + table_name="shipping_notice_candidates", + ) + op.drop_index("ix_shipping_notice_candidates_po_number", table_name="shipping_notice_candidates") + op.drop_index( + "ix_shipping_notice_candidates_primary_document_id", + table_name="shipping_notice_candidates", + ) + op.drop_index("ix_shipping_notice_candidates_intake_id", table_name="shipping_notice_candidates") + op.drop_table("shipping_notice_candidates") + + op.drop_index("ix_shipping_notice_documents_created_at", table_name="shipping_notice_documents") + op.drop_index("ix_shipping_notice_documents_parse_status", table_name="shipping_notice_documents") + op.drop_index("ix_shipping_notice_documents_content_hash", table_name="shipping_notice_documents") + op.drop_index("ix_shipping_notice_documents_asset_id", table_name="shipping_notice_documents") + op.drop_index("ix_shipping_notice_documents_intake_id", table_name="shipping_notice_documents") + op.drop_table("shipping_notice_documents") + + with op.batch_alter_table("file_assets", schema=None) as batch_op: + batch_op.drop_index("ix_file_assets_parent_attachment_key") + batch_op.drop_index("ix_file_assets_parent_content_hash") + batch_op.drop_index("ix_file_assets_parent_asset_id") + batch_op.drop_constraint("fk_file_assets_parent_asset_id", type_="foreignkey") + batch_op.drop_column("source_attachment_key") + batch_op.drop_column("asset_role") + batch_op.drop_column("parent_asset_id") diff --git a/backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py b/backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py new file mode 100644 index 00000000..2422874e --- /dev/null +++ b/backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py @@ -0,0 +1,225 @@ +""" +backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py + +用途:阶段二并发幂等与 Candidate/Document intake 一致性约束。 +依赖:Alembic revision d3e4f5a6b7c8。 +逻辑:合并重复派生资产 → 按 Document.asset_id 重算 reference_count/lifecycle → + 建立「未删除」部分唯一索引;Candidate 复合外键保证主文档同属该 Intake。 + +Revision ID: e4f5a6b7c8d9 +Revises: d3e4f5a6b7c8 +Create Date: 2026-07-14 18:15:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "e4f5a6b7c8d9" +down_revision = "d3e4f5a6b7c8" +branch_labels = None +depends_on = None + + +def _drop_document_fk_on_candidates() -> None: + """删除 Candidate → Document 的旧单列外键(名称因库而异)。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + for fk in inspector.get_foreign_keys("shipping_notice_candidates"): + cols = list(fk.get("constrained_columns") or []) + referred = str(fk.get("referred_table") or "") + if referred == "shipping_notice_documents" and cols == ["primary_document_id"]: + op.drop_constraint(fk["name"], "shipping_notice_candidates", type_="foreignkey") + return + + +def _dedupe_derived_file_assets() -> None: + """ + 合并同父同哈希的活派生资产,再建立唯一约束。 + + 核心逻辑:保留最小 id;Document.asset_id 重指向保留行;多余行 soft-delete。 + """ + bind = op.get_bind() + rows = bind.execute( + sa.text( + """ + SELECT parent_asset_id, content_hash + FROM file_assets + WHERE parent_asset_id IS NOT NULL + AND deleted_at IS NULL + AND content_hash IS NOT NULL + GROUP BY parent_asset_id, content_hash + HAVING COUNT(*) > 1 + """ + ) + ).fetchall() + for parent_asset_id, content_hash in rows: + ids = [ + int(r[0]) + for r in bind.execute( + sa.text( + """ + SELECT id + FROM file_assets + WHERE parent_asset_id = :parent_id + AND content_hash = :content_hash + AND deleted_at IS NULL + ORDER BY id ASC + """ + ), + {"parent_id": int(parent_asset_id), "content_hash": str(content_hash)}, + ).fetchall() + ] + if len(ids) < 2: + continue + keep_id = ids[0] + for drop_id in ids[1:]: + bind.execute( + sa.text( + """ + UPDATE shipping_notice_documents + SET asset_id = :keep_id + WHERE asset_id = :drop_id + """ + ), + {"keep_id": keep_id, "drop_id": drop_id}, + ) + # 转为 orphan_cleanup + expired(deleted_at 保持 NULL),交给 cleanup 删 MinIO + bind.execute( + sa.text( + """ + UPDATE file_assets + SET parent_asset_id = NULL, + asset_role = 'orphan_cleanup', + source_attachment_key = NULL, + lifecycle_status = 'expired', + reference_count = 0, + expires_at = CURRENT_TIMESTAMP, + deleted_at = NULL, + updated_at = CURRENT_TIMESTAMP + WHERE id = :drop_id + """ + ), + {"drop_id": drop_id}, + ) + + +def _recompute_derived_reference_counts() -> None: + """ + 按 shipping_notice_documents.asset_id 重算活派生资产的引用数与生命周期。 + + 核心逻辑:合并后保留行可能仍残留旧 reference_count;以 Document 关联边为准校正。 + """ + bind = op.get_bind() + dialect = str(getattr(bind.dialect, "name", "") or "") + expires_expr = ( + "CURRENT_TIMESTAMP + INTERVAL '72 hours'" + if dialect == "postgresql" + else "datetime('now', '+72 hours')" + ) + bind.execute( + sa.text( + f""" + UPDATE file_assets + SET + reference_count = ( + SELECT COUNT(*) + FROM shipping_notice_documents AS d + WHERE d.asset_id = file_assets.id + ), + lifecycle_status = CASE + WHEN ( + SELECT COUNT(*) + FROM shipping_notice_documents AS d + WHERE d.asset_id = file_assets.id + ) > 0 THEN 'referenced' + ELSE 'temporary' + END, + expires_at = CASE + WHEN ( + SELECT COUNT(*) + FROM shipping_notice_documents AS d + WHERE d.asset_id = file_assets.id + ) > 0 THEN NULL + ELSE {expires_expr} + END, + updated_at = CURRENT_TIMESTAMP + WHERE parent_asset_id IS NOT NULL + AND deleted_at IS NULL + AND asset_role = 'derived_attachment' + """ + ) + ) + + +def _index_names(table: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {str(ix.get("name") or "") for ix in inspector.get_indexes(table)} + + +def upgrade() -> None: + names = _index_names("file_assets") + with op.batch_alter_table("file_assets", schema=None) as batch_op: + if "ix_file_assets_parent_content_hash" in names: + batch_op.drop_index("ix_file_assets_parent_content_hash") + if "uq_file_assets_parent_content_hash" in names: + batch_op.drop_index("uq_file_assets_parent_content_hash") + + _dedupe_derived_file_assets() + _recompute_derived_reference_counts() + + # PostgreSQL:仅未删除派生资产唯一;SQLite 同步 sqlite_where + names = _index_names("file_assets") + if "uq_file_assets_parent_content_hash_alive" not in names: + op.create_index( + "uq_file_assets_parent_content_hash_alive", + "file_assets", + ["parent_asset_id", "content_hash"], + unique=True, + postgresql_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"), + sqlite_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"), + ) + + with op.batch_alter_table("shipping_notice_documents", schema=None) as batch_op: + batch_op.create_unique_constraint( + "uq_shipping_notice_documents_id_intake", + ["id", "intake_id"], + ) + + _drop_document_fk_on_candidates() + with op.batch_alter_table("shipping_notice_candidates", schema=None) as batch_op: + batch_op.create_foreign_key( + "fk_shipping_notice_candidates_document_intake", + "shipping_notice_documents", + ["primary_document_id", "intake_id"], + ["id", "intake_id"], + ) + + +def downgrade() -> None: + with op.batch_alter_table("shipping_notice_candidates", schema=None) as batch_op: + batch_op.drop_constraint( + "fk_shipping_notice_candidates_document_intake", + type_="foreignkey", + ) + batch_op.create_foreign_key( + "fk_shipping_notice_candidates_primary_document_id", + "shipping_notice_documents", + ["primary_document_id"], + ["id"], + ) + + with op.batch_alter_table("shipping_notice_documents", schema=None) as batch_op: + batch_op.drop_constraint("uq_shipping_notice_documents_id_intake", type_="unique") + + names = _index_names("file_assets") + if "uq_file_assets_parent_content_hash_alive" in names: + op.drop_index("uq_file_assets_parent_content_hash_alive", table_name="file_assets") + with op.batch_alter_table("file_assets", schema=None) as batch_op: + batch_op.create_index( + "ix_file_assets_parent_content_hash", + ["parent_asset_id", "content_hash"], + unique=False, + ) diff --git a/backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py b/backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py new file mode 100644 index 00000000..0c7faddf --- /dev/null +++ b/backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py @@ -0,0 +1,181 @@ +""" +backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py + +用途:将派生资产全量唯一索引改为「未删除」部分唯一,并合并历史重复行。 +依赖:Alembic revision e4f5a6b7c8d9。 +逻辑:兼容已执行旧版 e4(创建 uq_file_assets_parent_content_hash)的环境; + 去重后按 Document 重算 reference_count;新装库若 e4 已建 partial index 则索引创建 no-op。 + downgrade 恢复非唯一普通索引,避免软删除同键冲突。 + +Revision ID: f5a6b7c8d9e0 +Revises: e4f5a6b7c8d9 +Create Date: 2026-07-14 19:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "f5a6b7c8d9e0" +down_revision = "e4f5a6b7c8d9" +branch_labels = None +depends_on = None + + +def _index_names(table: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {str(ix.get("name") or "") for ix in inspector.get_indexes(table)} + + +def _dedupe_derived_file_assets() -> None: + """合并同父同哈希活记录:保留最小 id,重指向 Document,软删其余。""" + bind = op.get_bind() + rows = bind.execute( + sa.text( + """ + SELECT parent_asset_id, content_hash + FROM file_assets + WHERE parent_asset_id IS NOT NULL + AND deleted_at IS NULL + AND content_hash IS NOT NULL + GROUP BY parent_asset_id, content_hash + HAVING COUNT(*) > 1 + """ + ) + ).fetchall() + for parent_asset_id, content_hash in rows: + ids = [ + int(r[0]) + for r in bind.execute( + sa.text( + """ + SELECT id + FROM file_assets + WHERE parent_asset_id = :parent_id + AND content_hash = :content_hash + AND deleted_at IS NULL + ORDER BY id ASC + """ + ), + {"parent_id": int(parent_asset_id), "content_hash": str(content_hash)}, + ).fetchall() + ] + if len(ids) < 2: + continue + keep_id = ids[0] + for drop_id in ids[1:]: + bind.execute( + sa.text( + """ + UPDATE shipping_notice_documents + SET asset_id = :keep_id + WHERE asset_id = :drop_id + """ + ), + {"keep_id": keep_id, "drop_id": drop_id}, + ) + # 转为 orphan_cleanup + expired(deleted_at 保持 NULL),交给 cleanup 删 MinIO + bind.execute( + sa.text( + """ + UPDATE file_assets + SET parent_asset_id = NULL, + asset_role = 'orphan_cleanup', + source_attachment_key = NULL, + lifecycle_status = 'expired', + reference_count = 0, + expires_at = CURRENT_TIMESTAMP, + deleted_at = NULL, + updated_at = CURRENT_TIMESTAMP + WHERE id = :drop_id + """ + ), + {"drop_id": drop_id}, + ) + + +def _recompute_derived_reference_counts() -> None: + """按 Document.asset_id 重算活派生资产引用数与 lifecycle/expires_at。""" + bind = op.get_bind() + dialect = str(getattr(bind.dialect, "name", "") or "") + expires_expr = ( + "CURRENT_TIMESTAMP + INTERVAL '72 hours'" + if dialect == "postgresql" + else "datetime('now', '+72 hours')" + ) + bind.execute( + sa.text( + f""" + UPDATE file_assets + SET + reference_count = ( + SELECT COUNT(*) + FROM shipping_notice_documents AS d + WHERE d.asset_id = file_assets.id + ), + lifecycle_status = CASE + WHEN ( + SELECT COUNT(*) + FROM shipping_notice_documents AS d + WHERE d.asset_id = file_assets.id + ) > 0 THEN 'referenced' + ELSE 'temporary' + END, + expires_at = CASE + WHEN ( + SELECT COUNT(*) + FROM shipping_notice_documents AS d + WHERE d.asset_id = file_assets.id + ) > 0 THEN NULL + ELSE {expires_expr} + END, + updated_at = CURRENT_TIMESTAMP + WHERE parent_asset_id IS NOT NULL + AND deleted_at IS NULL + AND asset_role = 'derived_attachment' + """ + ) + ) + + +def upgrade() -> None: + names = _index_names("file_assets") + if "uq_file_assets_parent_content_hash" in names: + op.drop_index("uq_file_assets_parent_content_hash", table_name="file_assets") + + _dedupe_derived_file_assets() + _recompute_derived_reference_counts() + + names = _index_names("file_assets") + if "uq_file_assets_parent_content_hash_alive" not in names: + op.create_index( + "uq_file_assets_parent_content_hash_alive", + "file_assets", + ["parent_asset_id", "content_hash"], + unique=True, + postgresql_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"), + sqlite_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"), + ) + + +def downgrade() -> None: + """ + 降级:去掉部分唯一索引,恢复非唯一普通索引。 + + 核心逻辑:不恢复全量唯一——软删除与活记录可共享 (parent, hash),全量唯一会冲突。 + """ + names = _index_names("file_assets") + if "uq_file_assets_parent_content_hash_alive" in names: + op.drop_index("uq_file_assets_parent_content_hash_alive", table_name="file_assets") + if "uq_file_assets_parent_content_hash" in names: + op.drop_index("uq_file_assets_parent_content_hash", table_name="file_assets") + names = _index_names("file_assets") + if "ix_file_assets_parent_content_hash" not in names: + op.create_index( + "ix_file_assets_parent_content_hash", + "file_assets", + ["parent_asset_id", "content_hash"], + unique=False, + ) diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py index ff393479..a9e06c4d 100644 --- a/backend/tests/test_shipping_notice_batches.py +++ b/backend/tests/test_shipping_notice_batches.py @@ -894,6 +894,43 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app): ] +def test_parse_stage_ui_state_lists_all_issues(app): + """文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。""" + from app.services.shipping_notice.ui_state import build_task_ui_state + + with app.app_context(): + task = ShippingTask( + task_no="SN-PARSE-ISSUES-LIST", + source_type="pdf", + process_status="pending_review", + pending_human_reason="inventory_source_unresolved", + error_message="无法根据发货通知唯一确定库存查询来源", + parse_confidence=0.4, + step_payload_json={ + "pending_parse_review_after_source": True, + "inventory_source_resolution": {"status": "unresolved", "candidates": []}, + "current_step_progress": { + "extra": { + "warnings": [ + "部分订单行缺少 Reservation ID,可能影响精确匹配。", + "parse_fallback_heuristic", + ] + } + }, + }, + ) + + ui_state = build_task_ui_state(task) + issues = ui_state["summary"]["issues"] + + assert ui_state["checkpoint"] == "inventory_source_review" + assert issues[0] == "无法根据发货通知唯一确定库存查询来源" + assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues + assert "解析引擎回退到启发式规则,请人工核对字段。" in issues + assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues + assert len(issues) == 4 + + def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client): """任务/批次工作台读接口直接返回 UI State,Chat 和工作台不再各自推导状态。""" headers = _workspace_headers(app) diff --git a/backend/tests/test_shipping_notice_business_dedup.py b/backend/tests/test_shipping_notice_business_dedup.py new file mode 100644 index 00000000..5a6cf10d --- /dev/null +++ b/backend/tests/test_shipping_notice_business_dedup.py @@ -0,0 +1,750 @@ +""" +backend/tests/test_shipping_notice_business_dedup.py + +用途:第三阶段业务指纹、重复检测与决策门闩核心用例。 +依赖:pytest、business_fingerprint、duplicate_detection、batch_from_intakes。 +逻辑:覆盖指纹稳定性、阻断门闩、open_existing / create_revision 分流。 +""" + +from __future__ import annotations + +from datetime import datetime +from unittest.mock import patch + +import pytest + +from app import db +from app.core.errors import ConflictError +from app.models import ( + FileAsset, + ShippingBatch, + ShippingNoticeCandidate, + ShippingNoticeDocument, + ShippingNoticeIntake, + ShippingTask, + User, +) +from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes +from app.services.shipping_notice.business_fingerprint import build_business_fingerprint +from app.services.shipping_notice.duplicate_detection import ( + detect_duplicates_for_candidate, + detect_duplicates_for_intake, +) +from app.services.shipping_notice.intake_service import resolve_intake_duplicate + + +@pytest.fixture +def dedup_user(app): + with app.app_context(): + user = User(username='dedup-user', email='dedup@example.com', password_hash='x', role='user') + db.session.add(user) + db.session.commit() + yield user + + +def _seed_parsed_intake( + user_id: int, + *, + intake_no: str, + hash_value: str, + business_summary: dict, + fingerprint: dict, +): + 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', + structured_result_json={'business_summary': business_summary}, + business_fingerprint=fingerprint.get('fingerprint'), + fingerprint_version=fingerprint.get('version'), + fingerprint_strength=fingerprint.get('strength'), + duplicate_status='none', + duplicate_matches_json=[], + ) + db.session.add(intake) + db.session.commit() + return asset, intake + + +def test_fingerprint_stable_across_line_order(): + base = { + 'customer_code': 'C1', + 'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'}, + 'required_date': '2026-01-01', + 'lines': [ + {'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'}, + {'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}, + ], + } + swapped = { + **base, + 'lines': [ + {'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}, + {'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'}, + ], + } + a = build_business_fingerprint(base) + b = build_business_fingerprint(swapped) + assert a['strength'] == 'medium' + assert a['fingerprint'] == b['fingerprint'] + + +def test_fingerprint_changes_with_qty(): + base = { + 'customer_code': 'C1', + 'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'}, + 'required_date': '2026-01-01', + 'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}], + } + changed = {**base, 'lines': [{'sku': 'A', 'qty': 9, 'reservation_id': '1000000002'}]} + assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint'] + + +def test_blocking_create_requires_resolution(app, dedup_user): + with app.app_context(): + summary = { + 'customer_code': 'C1', + 'po_number': 'PO-9', + 'reservation_ids': ['1000140351'], + 'lines': [], + } + fp = build_business_fingerprint(summary) + asset, intake = _seed_parsed_intake( + dedup_user.id, + intake_no='SNI-DEDUP-BLOCK', + hash_value='hash-block-1', + business_summary=summary, + fingerprint=fp, + ) + batch = ShippingBatch(batch_no='SB-DEDUP-OLD', user_id=dedup_user.id, file_count=1) + db.session.add(batch) + db.session.flush() + existing = ShippingTask( + task_no='SN-DEDUP-OLD', + batch_id=batch.id, + user_id=dedup_user.id, + source_type='manual', + process_status='waiting_inventory', + business_fingerprint=fp['fingerprint'], + fingerprint_version=fp['version'], + document_version=1, + ) + db.session.add(existing) + db.session.commit() + + result = detect_duplicates_for_intake(intake=intake, asset=asset, business_summary=summary, fingerprint_result=fp) + assert result['blocking'] is True + assert result['status'] == 'same_active_task' + + with pytest.raises(ConflictError) as excinfo: + create_shipping_batch_from_intakes( + user_id=dedup_user.id, + conversation_id='conv-dedup', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-block', + ) + assert excinfo.value.code == 'SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED' + + +def test_open_existing_does_not_create_batch(app, dedup_user): + with app.app_context(): + summary = { + 'customer_code': 'C1', + 'po_number': 'PO-OPEN', + 'reservation_ids': ['1000140352'], + 'lines': [], + } + fp = build_business_fingerprint(summary) + asset, intake = _seed_parsed_intake( + dedup_user.id, + intake_no='SNI-DEDUP-OPEN', + hash_value='hash-open-1', + business_summary=summary, + fingerprint=fp, + ) + batch = ShippingBatch(batch_no='SB-OPEN-OLD', user_id=dedup_user.id, file_count=1) + db.session.add(batch) + db.session.flush() + existing = ShippingTask( + task_no='SN-OPEN-OLD', + batch_id=batch.id, + user_id=dedup_user.id, + source_type='manual', + process_status='waiting_inventory', + business_fingerprint=fp['fingerprint'], + fingerprint_version=fp['version'], + document_version=1, + ) + db.session.add(existing) + db.session.commit() + + # 模拟前端已决策:写入 resolution,避免 resolve 内 refresh 对 SQLite 时间敏感 + intake.duplicate_status = 'same_active_task' + intake.duplicate_matches_json = [ + { + 'task_no': existing.task_no, + 'process_status': existing.process_status, + 'document_version': 1, + 'match_type': 'business_fingerprint', + 'matched_fields': ['customer_code', 'po_number'], + 'lifecycle': 'active', + } + ] + intake.duplicate_resolution = 'open_existing' + intake.duplicate_target_task_no = existing.task_no + intake.duplicate_resolved_by_id = dedup_user.id + intake.duplicate_resolved_at = datetime.utcnow() + db.session.commit() + + with patch( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items' + ) as create_mock: + result = create_shipping_batch_from_intakes( + user_id=dedup_user.id, + conversation_id='conv-open', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-open', + ) + create_mock.assert_not_called() + + assert result.get('batch_no') in (None, '') + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'consumed' + assert refreshed.consumed_task_id == existing.id + + +def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatch): + """create_revision 应写入 supersedes_task_id 与 document_version+1。""" + with app.app_context(): + summary = { + 'customer_code': 'C1', + 'po_number': 'PO-REV-1', + 'reservation_ids': ['12345678'], + 'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '12345678'}], + } + fp = build_business_fingerprint(summary) + asset, intake = _seed_parsed_intake( + dedup_user.id, + intake_no='SNI-REV-1', + hash_value='hash-rev-1', + business_summary=summary, + fingerprint=fp, + ) + existing = ShippingTask( + task_no='SN-REV-BASE', + user_id=dedup_user.id, + source_type='manual', + process_status='uploaded', + business_fingerprint=fp.get('fingerprint'), + fingerprint_version=fp.get('version'), + document_version=1, + ) + db.session.add(existing) + db.session.commit() + + intake.duplicate_status = 'same_completed_task' + intake.duplicate_matches_json = [ + { + 'task_no': existing.task_no, + 'process_status': 'uploaded', + 'document_version': 1, + 'match_type': 'business_fingerprint', + 'matched_fields': ['customer_code', 'po_number'], + } + ] + intake.duplicate_resolution = 'create_revision' + intake.duplicate_target_task_no = existing.task_no + intake.duplicate_resolved_by_id = dedup_user.id + intake.duplicate_resolved_at = datetime.utcnow() + db.session.commit() + + def _fake_create(**kwargs): + notice_items = kwargs['notice_items'] + item = notice_items[0] + batch = ShippingBatch( + batch_no='SB-REV-1', + user_id=dedup_user.id, + file_count=1, + create_idempotency_key=kwargs.get('create_idempotency_key'), + ) + db.session.add(batch) + db.session.flush() + task = ShippingTask( + task_no='SN-REV-NEW', + batch_id=batch.id, + user_id=dedup_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'), + business_fingerprint=item.get('business_fingerprint'), + fingerprint_version=item.get('fingerprint_version'), + document_version=int(item.get('document_version') or 1), + supersedes_task_id=item.get('supersedes_task_id'), + duplicate_resolution_type=item.get('duplicate_resolution_type'), + 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}], + 'focus_task': { + 'task_no': task.task_no, + 'document_version': task.document_version, + 'duplicate_resolution_type': task.duplicate_resolution_type, + 'supersedes_task_no': existing.task_no, + }, + }, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _fake_create, + ) + # 确保 detect 仍命中 + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake', + lambda **kwargs: { + 'status': 'same_completed_task', + 'blocking': True, + 'fingerprint': fp.get('fingerprint'), + 'fingerprint_version': fp.get('version'), + 'fingerprint_strength': fp.get('strength'), + 'matches': intake.duplicate_matches_json, + 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], + }, + ) + + result = create_shipping_batch_from_intakes( + user_id=dedup_user.id, + conversation_id='conv-rev', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-rev', + ) + assert result['batch_no'] == 'SB-REV-1' + created = db.session.query(ShippingTask).filter_by(task_no='SN-REV-NEW').one() + assert created.supersedes_task_id == existing.id + assert int(created.document_version) == 2 + assert created.duplicate_resolution_type == 'revision' + + +def test_fingerprint_strong_with_customer_name_po_reservation(): + """启发式常只有客户名:客户名 + PO + Reservation 应产出 strong 指纹。""" + summary = { + 'customer_name': 'ACME', + 'customer_code': None, + 'po_number': 'PO-20260714', + 'reservation_ids': ['1000140351'], + 'lines': [{'sku': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}], + } + fp = build_business_fingerprint(summary) + assert fp['strength'] == 'strong' + assert fp['fingerprint'] + assert fp['components'].get('customer_name') == 'ACME' + + +def test_pending_review_hit_is_same_active_blocking(app, dedup_user): + """pending_review 属活跃态:业务指纹命中应为 same_active_task 且 blocking。""" + with app.app_context(): + summary = { + 'customer_code': 'C1', + 'po_number': 'PO-PENDING', + 'reservation_ids': ['1000140399'], + 'lines': [], + } + fp = build_business_fingerprint(summary) + asset, intake = _seed_parsed_intake( + dedup_user.id, + intake_no='SNI-PENDING-ACTIVE', + hash_value='hash-pending-1', + business_summary=summary, + fingerprint=fp, + ) + existing = ShippingTask( + task_no='SN-PENDING-1', + user_id=dedup_user.id, + source_type='manual', + process_status='pending_review', + business_fingerprint=fp['fingerprint'], + fingerprint_version=fp['version'], + document_version=1, + ) + db.session.add(existing) + db.session.commit() + + result = detect_duplicates_for_intake( + intake=intake, + asset=asset, + business_summary=summary, + fingerprint_result=fp, + ) + assert result['status'] == 'same_active_task' + assert result['blocking'] is True + + +def test_assert_no_exact_duplicate_allows_revision_and_force(app, dedup_user): + """revision/force_create 可越过同 content_hash 的旧门闩;无决议仍阻断。""" + from app.services.shipping_notice.batch_create_idempotency import assert_no_exact_duplicate_notices + + with app.app_context(): + existing = ShippingTask( + task_no='SN-HASH-GATE', + user_id=dedup_user.id, + source_type='manual', + source_content_hash='samehashabc', + process_status='pending_review', + ) + db.session.add(existing) + db.session.commit() + + assert_no_exact_duplicate_notices( + dedup_user.id, + [ + { + 'source_content_hash': 'samehashabc', + 'source_file_name': 'same.xlsx', + 'duplicate_resolution_type': 'revision', + } + ], + ) + assert_no_exact_duplicate_notices( + dedup_user.id, + [ + { + 'source_content_hash': 'samehashabc', + 'source_file_name': 'same.xlsx', + 'duplicate_resolution_type': 'force_create', + } + ], + ) + with pytest.raises(ConflictError) as excinfo: + assert_no_exact_duplicate_notices( + dedup_user.id, + [ + { + 'source_content_hash': 'samehashabc', + 'source_file_name': 'same.xlsx', + } + ], + ) + assert excinfo.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE' + + +def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user): + """API 投影:possible_duplicate 必须 blocking,供前端弹窗确认。""" + from app.services.shipping_notice.intake_service import serialize_intake + + with app.app_context(): + asset, intake = _seed_parsed_intake( + dedup_user.id, + intake_no='SNI-POSSIBLE-1', + hash_value='hash-possible-1', + business_summary={'customer_name': 'X', 'lines': [{'sku': 'A', 'qty': 1}]}, + fingerprint={'fingerprint': 'weakfp', 'version': 'shipping-v1', 'strength': 'weak'}, + ) + intake.duplicate_status = 'possible_duplicate' + intake.fingerprint_strength = 'weak' + intake.duplicate_matches_json = [ + { + 'task_no': 'SN-OLD', + 'process_status': 'waiting_inventory', + 'document_version': 1, + 'match_type': 'weak_fingerprint', + 'matched_fields': ['line_digest'], + } + ] + db.session.commit() + payload = serialize_intake(intake, asset=asset) + assert payload['duplicate']['status'] == 'possible_duplicate' + assert payload['duplicate']['blocking'] is True + assert 'force_create' in payload['duplicate']['allowed_actions'] + + +def test_task_summary_includes_version_chain(app, dedup_user): + """query_service SUMMARY 须暴露版本链与 duplicate 决策字段。""" + from app.services.shipping_notice.query_service import TaskProjection, serialize_task + + with app.app_context(): + base = ShippingTask( + task_no='SN-VER-BASE', + user_id=dedup_user.id, + source_type='manual', + process_status='uploaded', + document_version=1, + ) + db.session.add(base) + db.session.flush() + rev = ShippingTask( + task_no='SN-VER-REV', + user_id=dedup_user.id, + source_type='manual', + process_status='pending_review', + document_version=2, + supersedes_task_id=base.id, + duplicate_resolution_type='revision', + duplicate_source_task_id=base.id, + duplicate_override_reason=None, + business_fingerprint='fp-x', + fingerprint_version='shipping-v1', + ) + db.session.add(rev) + db.session.commit() + + data = serialize_task(rev, TaskProjection.SUMMARY) + assert data['document_version'] == 2 + assert data['supersedes_task_no'] == 'SN-VER-BASE' + assert data['duplicate_source_task_no'] == 'SN-VER-BASE' + assert data['duplicate_resolution_type'] == 'revision' + assert data['business_fingerprint'] == 'fp-x' + + base_data = serialize_task(base, TaskProjection.SUMMARY) + assert base_data['superseded_by_task_no'] == 'SN-VER-REV' + + +def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user): + """ + 阶段二:同一邮件中候选 A 与已有任务重复时,仅 A 被阻断;B/C 仍可为 none。 + """ + with app.app_context(): + existing_fp = build_business_fingerprint( + { + 'customer_code': 'C1', + 'po_number': '4510039227', + 'reservation_ids': ['1000140351'], + 'lines': [], + } + ) + existing = ShippingTask( + task_no='SN-EXISTING-PO-A', + user_id=dedup_user.id, + source_type='manual', + process_status='pending_review', + business_fingerprint=existing_fp['fingerprint'], + fingerprint_version=existing_fp['version'], + source_content_hash='hash-other-file', + ) + db.session.add(existing) + + parent = FileAsset( + asset_no='FA-STAGE2-DEDUP-EML', + owner_user_id=dedup_user.id, + original_filename='multi.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{dedup_user.id}/stage2.eml', + content_hash='eml-parent-hash', + file_size=100, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-DEDUP', + asset_id=parent.id, + user_id=dedup_user.id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + extracted_text='multi', + duplicate_status='unchecked', + ) + db.session.add(intake) + db.session.flush() + + docs = [] + for idx, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1): + doc = ShippingNoticeDocument( + intake_id=intake.id, + attachment_key=f'att-00{idx}', + document_type='attachment', + filename=f'{po}.pdf', + content_hash=f'pdf-hash-{po}', + classification='order_notice', + parse_status='parsed', + extracted_text=f'PO {po}', + ) + db.session.add(doc) + docs.append(doc) + db.session.flush() + + results = [] + for doc, po in zip(docs, ('4510039227', '4510039228', '4510039229')): + summary = { + 'customer_code': 'C1', + 'po_number': po, + 'reservation_ids': ['1000140351'] if po == '4510039227' else [], + 'lines': [], + } + if po != '4510039227': + summary['reservation_ids'] = [f'100014035{po[-1]}'] + fp = build_business_fingerprint(summary) + dup = detect_duplicates_for_candidate( + intake=intake, + document=doc, + business_summary=summary, + fingerprint_result=fp, + ) + cand = ShippingNoticeCandidate( + candidate_no=f'SNC-{po}', + intake_id=intake.id, + primary_document_id=doc.id, + po_number=po, + structured_result_json={'business_summary': summary}, + business_fingerprint=fp.get('fingerprint'), + fingerprint_version=fp.get('version'), + fingerprint_strength=fp.get('strength'), + duplicate_status=str(dup.get('status') or 'none'), + duplicate_matches_json=list(dup.get('matches') or []), + selected=True, + validation_status='pending', + ) + db.session.add(cand) + results.append(dup) + db.session.commit() + + assert results[0]['blocking'] is True + assert results[0]['status'] in {'same_active_task', 'exact_file', 'possible_duplicate'} + assert results[1]['blocking'] is False + assert results[1]['status'] == 'none' + assert results[2]['blocking'] is False + assert results[2]['status'] == 'none' + + refreshed = ( + db.session.query(ShippingNoticeCandidate) + .filter_by(intake_id=intake.id) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + assert refreshed[0].duplicate_status != 'none' + assert refreshed[1].duplicate_status == 'none' + assert refreshed[2].duplicate_status == 'none' + + +def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user): + """刷新重复检测须重写各 Candidate.duplicate_status,再聚合到 Intake。""" + from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection + + with app.app_context(): + existing_fp = build_business_fingerprint( + { + 'customer_code': 'C1', + 'po_number': '4510099999', + 'reservation_ids': ['1000199999'], + 'lines': [], + } + ) + existing = ShippingTask( + task_no='SN-REFRESH-EXISTING', + user_id=dedup_user.id, + source_type='manual', + process_status='pending_review', + business_fingerprint=existing_fp['fingerprint'], + fingerprint_version=existing_fp['version'], + source_content_hash='hash-refresh-other', + ) + db.session.add(existing) + + parent = FileAsset( + asset_no='FA-REFRESH-DEDUP', + owner_user_id=dedup_user.id, + original_filename='refresh.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{dedup_user.id}/refresh.eml', + content_hash='eml-refresh-hash', + file_size=100, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-REFRESH-DEDUP', + asset_id=parent.id, + user_id=dedup_user.id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + extracted_text='refresh', + duplicate_status='none', + structured_result_json={'business_summary': {'customer_code': 'C1'}}, + ) + db.session.add(intake) + db.session.flush() + + summary = { + 'customer_code': 'C1', + 'po_number': '4510099999', + 'reservation_ids': ['1000199999'], + 'lines': [], + } + fp = build_business_fingerprint(summary) + doc = ShippingNoticeDocument( + intake_id=intake.id, + attachment_key='att-001', + document_type='attachment', + filename='dup.pdf', + content_hash='pdf-refresh-1', + classification='order_notice', + parse_status='parsed', + extracted_text='PO 4510099999', + ) + db.session.add(doc) + db.session.flush() + cand = ShippingNoticeCandidate( + candidate_no='SNC-REFRESH-1', + intake_id=intake.id, + primary_document_id=doc.id, + po_number='4510099999', + structured_result_json={'business_summary': summary}, + business_fingerprint=fp.get('fingerprint'), + fingerprint_version=fp.get('version'), + fingerprint_strength=fp.get('strength'), + # 模拟解析后任务尚未存在时的旧结果;刷新时应变为阻断 + duplicate_status='none', + duplicate_matches_json=[], + selected=True, + validation_status='pending', + ) + db.session.add(cand) + db.session.commit() + + payload = refresh_intake_duplicate_detection( + user_id=dedup_user.id, + intake_no='SNI-REFRESH-DEDUP', + ) + assert payload['duplicate']['blocking'] is True + db.session.expire_all() + cand2 = db.session.query(ShippingNoticeCandidate).filter_by(candidate_no='SNC-REFRESH-1').one() + assert cand2.duplicate_status != 'none' + assert list(cand2.duplicate_matches_json or []) diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index 9edc5cdb..3fcaca71 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -1,3 +1,6 @@ +from email.message import EmailMessage +from pathlib import Path + from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract from app.services.shipping_notice.notice_lines import ( normalize_notice_line, @@ -13,10 +16,105 @@ from app.services.shipping_notice.reservation_id import ( ) +def _minimal_pdf_bytes(marker: str) -> bytes: + """ + 构造含可见文本的最小 PDF,供 EML 附件抽取测试使用。 + + 核心逻辑:手写 PDF 对象流并嵌入 Helvetica 文本;extract_notice_text 应能读出 marker。 + """ + safe = ( + str(marker) + .replace("\\", "\\\\") + .replace("(", "\\(") + .replace(")", "\\)") + ) + stream = f"BT /F1 24 Tf 72 720 Td ({safe}) Tj ET".encode("latin-1") + objects = [ + b"1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n", + b"2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n", + ( + b"3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " + b"/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n" + ), + f"4 0 obj<< /Length {len(stream)} >>stream\n".encode("latin-1") + + stream + + b"\nendstream\nendobj\n", + b"5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n", + ] + out = bytearray(b"%PDF-1.4\n") + offsets = [0] + for obj in objects: + offsets.append(len(out)) + out.extend(obj) + xref_pos = len(out) + out.extend(f"xref\n0 {len(offsets)}\n".encode("latin-1")) + out.extend(b"0000000000 65535 f \n") + for off in offsets[1:]: + out.extend(f"{off:010d} 00000 n \n".encode("latin-1")) + out.extend( + f"trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode( + "latin-1" + ) + ) + return bytes(out) + + +_TINY_PNG = ( + b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01" + b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00" + b"\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82" +) + + +def _build_eml( + *, + subject: str, + body: str, + attachments: list[tuple[str, str, bytes]], + inline_images: list[tuple[str, str, bytes]] | None = None, + message_id: str = "", +) -> bytes: + """ + 组装 multipart/mixed 测试邮件。 + + Args: + subject: 邮件主题。 + body: text/plain 正文。 + attachments: (filename, mime, payload) 真实附件列表。 + inline_images: (filename, content_id, payload) 内嵌签名图。 + message_id: Message-ID 头。 + """ + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = "laszlo.fussy@example.com" + msg["To"] = "freight@example.com" + msg["Date"] = "Mon, 13 Jul 2026 10:00:00 +0800" + msg["Message-ID"] = message_id + msg.set_content(body) + + for filename, content_id, payload in inline_images or []: + msg.add_attachment( + payload, + maintype="image", + subtype="png", + filename=filename, + cid=content_id, + disposition="inline", + ) + + for filename, mime, payload in attachments: + maintype, _, subtype = mime.partition("/") + msg.add_attachment( + payload, + maintype=maintype or "application", + subtype=subtype or "octet-stream", + filename=filename, + ) + return msg.as_bytes() + + def test_extract_notice_text_reads_xfa_pdf_datasets(): """XFA 表单型 PO 的订单字段应进入 raw_text,避免只抽页面文本漏明细。""" - from pathlib import Path - from app.services.shipping_notice.notice_upload import extract_notice_text pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf" @@ -31,6 +129,1006 @@ def test_extract_notice_text_reads_xfa_pdf_datasets(): assert "EINDT=2026-06-23" in text +def test_extract_eml_with_three_pdf_attachments(tmp_path): + """带 3 个 PDF 附件的 EML:attachment_count=3,且各附件独立抽到文本。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + markers = ("PO-MARKER-AAA", "PO-MARKER-BBB", "PO-MARKER-CCC") + attachments = [ + (f"{marker}.pdf", "application/pdf", _minimal_pdf_bytes(marker)) for marker in markers + ] + raw = _build_eml( + subject="PO 4510039227, 4510039228, 4510039229", + body="Please find POs attached.", + attachments=attachments, + ) + path = tmp_path / "multi-po.eml" + path.write_bytes(raw) + + text, meta = extract_notice_text(path) + + assert meta["file_type"] == "eml" + assert meta["attachment_count"] == 3 + assert meta["email"]["subject"] == "PO 4510039227, 4510039228, 4510039229" + assert meta["email"]["from"] == "laszlo.fussy@example.com" + assert meta["email"]["message_id"] == "" + assert "Please find POs attached." in meta["email"]["body_text"] + + parsed_atts = meta["attachments"] + assert len(parsed_atts) == 3 + for marker, item in zip(markers, parsed_atts): + assert item["filename"] == f"{marker}.pdf" + assert item["mime_type"] == "application/pdf" + assert item["parse_status"] == "parsed" + assert len(item["content_hash"]) == 64 + assert marker in item["extracted_text"] + assert marker in text + + +def test_extract_eml_skips_signature_inline_image(tmp_path): + """邮件签名图片(inline + Content-ID)不得进入 attachments,也不进入订单文本。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + pdf = _minimal_pdf_bytes("PO-ONLY-ORDER") + raw = _build_eml( + subject="Single PO", + body="Body with one PO attachment.", + attachments=[("order.pdf", "application/pdf", pdf)], + inline_images=[("signature.png", "", _TINY_PNG)], + ) + path = tmp_path / "with-signature.eml" + path.write_bytes(raw) + + text, meta = extract_notice_text(path) + + assert meta["attachment_count"] == 1 + assert meta["attachments"][0]["filename"] == "order.pdf" + assert all(item["filename"] != "signature.png" for item in meta["attachments"]) + assert any(str(w).startswith("eml_inline_resources_skipped:") for w in meta["warnings"]) + assert "PO-ONLY-ORDER" in text + # 签名图文件名不应出现在扁平正文附件区 + assert "--- attachment: signature.png ---" not in text + + +def test_extract_eml_duplicate_attachments(tmp_path): + """同信内重复内容哈希的附件标记 duplicate,不重复抽取。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + pdf = _minimal_pdf_bytes("PO-DUP-SAME") + raw = _build_eml( + subject="Dup attachments", + body="Two copies of the same PDF.", + attachments=[ + ("a.pdf", "application/pdf", pdf), + ("a-copy.pdf", "application/pdf", pdf), + ], + ) + path = tmp_path / "dup.eml" + path.write_bytes(raw) + + _, meta = extract_notice_text(path) + + assert meta["attachment_count"] == 2 + assert meta["attachments"][0]["parse_status"] == "parsed" + assert meta["attachments"][1]["parse_status"] == "duplicate" + assert any(str(w).startswith("eml_attachment_duplicate:") for w in meta["warnings"]) + + +def test_extract_eml_corrupt_attachment_does_not_block_others(tmp_path): + """某一个附件损坏时,其他附件仍正常解析。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + good = _minimal_pdf_bytes("PO-GOOD-OK") + bad = b"%PDF-1.4\nthis is not a valid pdf stream{{{{" + raw = _build_eml( + subject="One bad attachment", + body="Mixed attachments.", + attachments=[ + ("good.pdf", "application/pdf", good), + ("broken.pdf", "application/pdf", bad), + ("also-good.pdf", "application/pdf", _minimal_pdf_bytes("PO-ALSO-GOOD")), + ], + ) + path = tmp_path / "partial-fail.eml" + path.write_bytes(raw) + + text, meta = extract_notice_text(path) + + assert meta["attachment_count"] == 3 + statuses = {item["filename"]: item["parse_status"] for item in meta["attachments"]} + assert statuses["good.pdf"] == "parsed" + assert statuses["also-good.pdf"] == "parsed" + # 损坏附件:extract 可能 empty 或 failed,均不得拖垮其余 + assert statuses["broken.pdf"] in {"failed", "empty"} + assert "PO-GOOD-OK" in text + assert "PO-ALSO-GOOD" in text + + +def test_intake_structured_summary_includes_eml_fields(tmp_path): + """EML 预解析摘要应带上 email / attachment_count / attachments(含独立 extracted_text)。""" + from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary + from app.services.shipping_notice.notice_upload import extract_notice_text, NoticeIntakeResult + + raw = _build_eml( + subject="Summary PO", + body="Summary body.", + attachments=[("one.pdf", "application/pdf", _minimal_pdf_bytes("PO-SUM-1"))], + ) + path = tmp_path / "summary.eml" + path.write_bytes(raw) + text, meta = extract_notice_text(path) + result = NoticeIntakeResult( + filename="summary.eml", + source_type="email", + source_file_type="message/rfc822", + text=text, + warnings=list(meta.get("warnings") or []), + meta=meta, + content_hash="abc", + file_size=len(raw), + status="accepted", + ) + summary = intake_result_to_structured_summary(result) + assert summary["attachment_count"] == 1 + assert summary["email"]["subject"] == "Summary PO" + assert summary["attachments"][0]["filename"] == "one.pdf" + assert summary["attachments"][0]["parse_status"] == "parsed" + assert "PO-SUM-1" in str(summary["attachments"][0].get("extracted_text") or "") + assert summary["attachments"][0]["text_length"] > 0 + + +def test_extract_eml_named_text_part_is_attachment(tmp_path): + """带 filename 的 text/plain 不得当正文丢弃,应进入 attachments。""" + from email.message import EmailMessage + + from app.services.shipping_notice.notice_upload import extract_notice_text + + msg = EmailMessage() + msg["Subject"] = "Named text attach" + msg["From"] = "a@example.com" + msg["To"] = "b@example.com" + msg.set_content("Cover note only.") + msg.add_attachment( + b"PO-LINE-TXT-001 qty 2", + maintype="text", + subtype="plain", + filename="order.txt", + ) + path = tmp_path / "named-text.eml" + path.write_bytes(msg.as_bytes()) + + text, meta = extract_notice_text(path) + assert meta["attachment_count"] == 1 + assert meta["attachments"][0]["filename"] == "order.txt" + assert meta["attachments"][0]["parse_status"] == "parsed" + assert "PO-LINE-TXT-001" in meta["attachments"][0]["extracted_text"] + assert "PO-LINE-TXT-001" in text + + +def test_extract_eml_respects_declared_charset(tmp_path): + """正文解码须尊重 Content-Type charset(ISO-8859-1 café résumé)。""" + from email.message import EmailMessage + + from app.services.shipping_notice.notice_upload import extract_notice_text + + body = "Please ship café résumé to Lille" + msg = EmailMessage() + msg["Subject"] = "Charset test" + msg["From"] = "eu@example.com" + msg["To"] = "freight@example.com" + msg.set_content(body, charset="iso-8859-1") + path = tmp_path / "charset.eml" + path.write_bytes(msg.as_bytes()) + + _, meta = extract_notice_text(path) + assert "café" in meta["email"]["body_text"] + assert "résumé" in meta["email"]["body_text"] + + +def test_extract_eml_nested_rfc822_registers_independent_attachment(tmp_path): + """成功 message/rfc822 须登记独立附件行(含正文文本)并计入 attachment_count。""" + from email.message import EmailMessage + + from app.services.shipping_notice.notice_upload import extract_notice_text + + inner = EmailMessage() + inner["Subject"] = "Inner PO Only In Body" + inner["From"] = "buyer@example.com" + inner["To"] = "vendor@example.com" + inner.set_content("INNER-ORDER-PO-4510039999 please ship") + + outer = EmailMessage() + outer["Subject"] = "FW: order" + outer["From"] = "relay@example.com" + outer["To"] = "freight@example.com" + outer.set_content("Please see forwarded message.") + # set_content(EmailMessage) → message/rfc822 部件 + outer.add_attachment(inner) + + path = tmp_path / "forwarded.eml" + path.write_bytes(outer.as_bytes()) + + text, meta = extract_notice_text(path) + assert meta["attachment_count"] == 1 + assert meta["attachment_registered_count"] == 1 + assert len(meta["attachments"]) == 1 + rfc822_rows = [ + row + for row in meta["attachments"] + if str(row.get("mime_type") or "") == "message/rfc822" + or str(row.get("filename") or "").endswith(".eml") + ] + assert rfc822_rows, "native message/rfc822 must appear as an attachment row" + row = rfc822_rows[0] + assert row["filename"] == "forwarded-message.eml" or row["mime_type"] == "message/rfc822" + assert row["parse_status"] == "parsed" + assert "INNER-ORDER-PO-4510039999" in str(row.get("extracted_text") or "") + assert "Inner PO Only In Body" in str(row.get("extracted_text") or "") + # 扁平正文经 attachment 段拼接仍可下游解析 + assert "INNER-ORDER-PO-4510039999" in text + assert "Inner PO Only In Body" in text + # 不得只剩封面正文(attachment_count=0)却把订单塞进合并正文 + assert "Please see forwarded message." in text or "Please see forwarded message" in meta.get("email", {}).get("body_text", "") + # 有外层正文时,内层订单只应在扁平文本中出现一次(封面 + 附件段各一处主题/订单不重复计数订单号) + assert text.count("INNER-ORDER-PO-4510039999") == 1 + + +def test_extract_eml_forward_only_no_outer_body_dedupes_inner_order(tmp_path): + """无外层正文、仅含 message/rfc822 附件时,内层订单不得在扁平文本出现两次。""" + from email.message import EmailMessage + + from app.services.shipping_notice.notice_upload import extract_notice_text + + inner = EmailMessage() + inner["Subject"] = "Forward Only PO" + inner["From"] = "buyer@example.com" + inner["To"] = "vendor@example.com" + inner.set_content("INNER-PO-777 please ship") + + outer = EmailMessage() + outer["Subject"] = "FW: bare forward" + outer["From"] = "relay@example.com" + outer["To"] = "freight@example.com" + # 常见场景:外层无 set_content,仅挂载转发附件 + outer.add_attachment(inner) + + path = tmp_path / "forward-only.eml" + path.write_bytes(outer.as_bytes()) + + text, meta = extract_notice_text(path) + body = str((meta.get("email") or {}).get("body_text") or "") + assert "INNER-PO-777" not in body, "outer body must not absorb inner rfc822 text" + assert meta["attachment_count"] == 1 + assert meta["attachments"][0]["parse_status"] == "parsed" + assert "INNER-PO-777" in str(meta["attachments"][0].get("extracted_text") or "") + assert text.count("INNER-PO-777") == 1 + + +def test_extract_eml_attached_multipart_registers_independent_attachment(tmp_path): + """disposition=attachment 的 multipart/* 须登记为独立附件,不得把订单吞进外层 body。""" + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.services.shipping_notice.notice_upload import extract_notice_text + + bundle = MIMEMultipart("mixed") + bundle.set_param("name", "bundle.mime") + bundle.add_header("Content-Disposition", "attachment", filename="bundle.mime") + bundle.attach(MIMEText("BUNDLE-PO-888 please ship", "plain", "utf-8")) + + outer = MIMEMultipart("mixed") + outer["Subject"] = "Has MIME bundle" + outer["From"] = "a@example.com" + outer["To"] = "b@example.com" + outer.attach(MIMEText("Outer cover only.", "plain", "utf-8")) + outer.attach(bundle) + + path = tmp_path / "attached-multipart.eml" + path.write_bytes(outer.as_bytes()) + + text, meta = extract_notice_text(path) + body = str((meta.get("email") or {}).get("body_text") or "") + assert "BUNDLE-PO-888" not in body + assert "Outer cover only." in body + assert meta["attachment_count"] >= 1 + bundles = [ + row + for row in meta["attachments"] + if str(row.get("filename") or "") == "bundle.mime" + or str(row.get("mime_type") or "").startswith("multipart/") + ] + assert bundles, "attached multipart must appear as an attachment row" + assert bundles[0]["parse_status"] == "parsed" + assert "BUNDLE-PO-888" in str(bundles[0].get("extracted_text") or "") + assert text.count("BUNDLE-PO-888") == 1 + + +def test_extract_eml_attached_multipart_keeps_all_plain_parts(tmp_path): + """附件型 multipart 内多个 text/plain 须全部拼入 extracted_text,不得只留第一段。""" + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.services.shipping_notice.notice_upload import extract_notice_text + + bundle = MIMEMultipart("mixed") + bundle.add_header("Content-Disposition", "attachment", filename="multi-po.mime") + bundle.attach(MIMEText("PO-A-111 please ship", "plain", "utf-8")) + bundle.attach(MIMEText("PO-B-222 please ship", "plain", "utf-8")) + + outer = MIMEMultipart("mixed") + outer["Subject"] = "Multi plain bundle" + outer["From"] = "a@example.com" + outer["To"] = "b@example.com" + outer.attach(MIMEText("cover", "plain", "utf-8")) + outer.attach(bundle) + + path = tmp_path / "multi-plain-bundle.eml" + path.write_bytes(outer.as_bytes()) + text, meta = extract_notice_text(path) + row = next(r for r in meta["attachments"] if r.get("filename") == "multi-po.mime") + extracted = str(row.get("extracted_text") or "") + assert "PO-A-111" in extracted + assert "PO-B-222" in extracted + assert text.count("PO-A-111") == 1 + assert text.count("PO-B-222") == 1 + + +def test_extract_eml_attached_multipart_mixed_keeps_plain_and_html(tmp_path): + """multipart/mixed 附件内独立 plain 与 HTML 订单段须全部保留(非 alternative 的 plain 优先)。""" + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.services.shipping_notice.notice_upload import extract_notice_text + + bundle = MIMEMultipart("mixed") + bundle.add_header("Content-Disposition", "attachment", filename="plain-html.mime") + bundle.attach(MIMEText("PLAIN-PO-101 please ship", "plain", "utf-8")) + bundle.attach(MIMEText("

HTML-PO-202 please ship

", "html", "utf-8")) + + outer = MIMEMultipart("mixed") + outer["Subject"] = "Plain+HTML mixed bundle" + outer["From"] = "a@example.com" + outer["To"] = "b@example.com" + outer.attach(MIMEText("cover", "plain", "utf-8")) + outer.attach(bundle) + + path = tmp_path / "plain-html-mixed.eml" + path.write_bytes(outer.as_bytes()) + text, meta = extract_notice_text(path) + row = next(r for r in meta["attachments"] if r.get("filename") == "plain-html.mime") + extracted = str(row.get("extracted_text") or "") + assert "PLAIN-PO-101" in extracted + assert "HTML-PO-202" in extracted + assert text.count("PLAIN-PO-101") == 1 + assert text.count("HTML-PO-202") == 1 + + +def test_extract_eml_attached_multipart_alternative_prefers_plain(tmp_path): + """multipart/alternative 附件内仍 plain 优先,避免同一订单 plain/html 双份。""" + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.services.shipping_notice.notice_upload import extract_notice_text + + alt = MIMEMultipart("alternative") + alt.attach(MIMEText("ALT-PO-PLAIN-303", "plain", "utf-8")) + alt.attach(MIMEText("ALT-PO-HTML-303", "html", "utf-8")) + + bundle = MIMEMultipart("mixed") + bundle.add_header("Content-Disposition", "attachment", filename="alt.mime") + bundle.attach(alt) + + outer = MIMEMultipart("mixed") + outer["Subject"] = "Alternative bundle" + outer["From"] = "a@example.com" + outer.attach(MIMEText("cover", "plain", "utf-8")) + outer.attach(bundle) + + path = tmp_path / "alt-bundle.eml" + path.write_bytes(outer.as_bytes()) + text, meta = extract_notice_text(path) + row = next(r for r in meta["attachments"] if r.get("filename") == "alt.mime") + extracted = str(row.get("extracted_text") or "") + assert "ALT-PO-PLAIN-303" in extracted + assert "ALT-PO-HTML-303" not in extracted + assert text.count("ALT-PO-PLAIN-303") == 1 + + +def test_extract_eml_attached_alternative_root_extracts_plain(tmp_path): + """根部件即为 disposition=attachment 的 multipart/alternative 时须提取 plain,不得 empty。""" + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.services.shipping_notice.notice_upload import extract_notice_text + + alt = MIMEMultipart("alternative") + alt.add_header("Content-Disposition", "attachment", filename="order-alt.mime") + alt.attach(MIMEText("ROOT-ALT-PO-404 please ship", "plain", "utf-8")) + alt.attach(MIMEText("

ROOT-ALT-HTML-404

", "html", "utf-8")) + + outer = MIMEMultipart("mixed") + outer["Subject"] = "Attached alternative root" + outer["From"] = "a@example.com" + outer["To"] = "b@example.com" + outer.attach(MIMEText("cover", "plain", "utf-8")) + outer.attach(alt) + + path = tmp_path / "alt-root-attached.eml" + path.write_bytes(outer.as_bytes()) + text, meta = extract_notice_text(path) + row = next(r for r in meta["attachments"] if r.get("filename") == "order-alt.mime") + assert row["parse_status"] == "parsed" + extracted = str(row.get("extracted_text") or "") + assert "ROOT-ALT-PO-404" in extracted + assert "ROOT-ALT-HTML-404" not in extracted + assert text.count("ROOT-ALT-PO-404") == 1 + assert "ROOT-ALT-PO-404" not in str((meta.get("email") or {}).get("body_text") or "") + + +def test_extract_eml_nested_attached_multipart_respects_depth(tmp_path): + """嵌套附件型 multipart 须累加 depth,超限时 skipped 并打 eml_nesting_depth_exceeded。""" + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + inner = MIMEMultipart("mixed") + inner.add_header("Content-Disposition", "attachment", filename="inner.mime") + inner.attach(MIMEText("INNER-NESTED-PO-999", "plain", "utf-8")) + + outer_bundle = MIMEMultipart("mixed") + outer_bundle.add_header("Content-Disposition", "attachment", filename="outer.mime") + outer_bundle.attach(MIMEText("OUTER-BUNDLE-PO", "plain", "utf-8")) + outer_bundle.attach(inner) + + root = MIMEMultipart("mixed") + root["Subject"] = "Nested attached multipart" + root["From"] = "a@example.com" + root.attach(MIMEText("cover", "plain", "utf-8")) + root.attach(outer_bundle) + + _, meta = parse_eml_bytes( + root.as_bytes(), + extract_text=extract_notice_text, + limits=EmlLimits(max_attachments=10, max_nesting_depth=1), + depth=0, + ) + by_name = {row["filename"]: row for row in meta["attachments"]} + assert by_name["outer.mime"]["parse_status"] == "parsed" + assert "OUTER-BUNDLE-PO" in str(by_name["outer.mime"].get("extracted_text") or "") + assert by_name["inner.mime"]["parse_status"] == "skipped" + assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"]) + assert "INNER-NESTED-PO-999" not in str(by_name["inner.mime"].get("extracted_text") or "") + + +def test_extract_eml_html_table_keeps_row_boundaries(tmp_path): + """HTML-only 邮件表格应保留行列边界(换行+制表符),且解码 HTML 实体。""" + from email.message import EmailMessage + + from app.services.shipping_notice.notice_upload import extract_notice_text + + html = ( + "" + "" + "" + "" + "" + "
POQty
451003922730
45100392282
A&B3
" + ) + msg = EmailMessage() + msg["Subject"] = "HTML table" + msg["From"] = "a@example.com" + msg["To"] = "b@example.com" + msg.set_content(html, subtype="html") + path = tmp_path / "html-table.eml" + path.write_bytes(msg.as_bytes()) + + _, meta = extract_notice_text(path) + body = meta["email"]["body_text"] + assert "4510039227" in body + assert "4510039228" in body + assert "A&B" in body + assert body.count("\n") >= 2 + assert "\t" in body + assert "4510039227\t30" in body.replace(" ", "") + + +def test_extract_eml_nested_eml_file_respects_depth(tmp_path): + """嵌套 .eml 文件附件须共享深度/限额,不得重置 depth=0 无限展开。""" + from email.message import EmailMessage + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + leaf = EmailMessage() + leaf["Subject"] = "Leaf" + leaf["From"] = "leaf@example.com" + leaf.set_content("LEAF-MARKER-DEPTH") + leaf_bytes = leaf.as_bytes() + + def wrap_as_eml_file(payload: bytes, filename: str, subject: str) -> bytes: + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = "a@example.com" + msg["To"] = "b@example.com" + msg.set_content(f"see {filename}") + msg.add_attachment( + payload, + maintype="application", + subtype="octet-stream", + filename=filename, + ) + return msg.as_bytes() + + l1 = wrap_as_eml_file(leaf_bytes, "l1.eml", "L1") + l2 = wrap_as_eml_file(l1, "l2.eml", "L2") + root = wrap_as_eml_file(l2, "l3.eml", "Root") + + text, meta = parse_eml_bytes( + root, + extract_text=extract_notice_text, + limits=EmlLimits(max_attachments=20, max_nesting_depth=1), + depth=0, + ) + assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"]) + # depth=1 只允许再展开一层;更深的 LEAF 不应进入正文 + assert "LEAF-MARKER-DEPTH" not in text + assert "LEAF-MARKER-DEPTH" not in str(meta.get("email", {}).get("body_text") or "") + + +def test_extract_eml_attachment_count_includes_overflow(tmp_path): + """超限未登记的附件仍计入 attachment_count。""" + from email.message import EmailMessage + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + msg = EmailMessage() + msg["Subject"] = "Three attaches" + msg["From"] = "a@example.com" + msg["To"] = "b@example.com" + msg.set_content("cover") + for idx in range(3): + msg.add_attachment( + f"PO-LINE-{idx}".encode("utf-8"), + maintype="text", + subtype="plain", + filename=f"order-{idx}.txt", + ) + _, meta = parse_eml_bytes( + msg.as_bytes(), + extract_text=extract_notice_text, + limits=EmlLimits(max_attachments=2, max_nesting_depth=3), + ) + assert meta["attachment_count"] == 3 + assert meta["attachment_registered_count"] == 2 + assert len(meta["attachments"]) == 2 + assert any("eml_attachment_limit_exceeded:2:discovered=3" in str(w) for w in meta["warnings"]) + + +def test_extract_eml_container_does_not_double_count_total_bytes(tmp_path): + """嵌套 .eml 容器计费后,内层子附件不得再计,避免双重计费导致误 skip。""" + from email.message import EmailMessage + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + inner = EmailMessage() + inner["Subject"] = "Inner" + inner["From"] = "inner@example.com" + inner.set_content("cover") + inner.add_attachment( + b"INNER-PO-TINY", + maintype="text", + subtype="plain", + filename="inner.txt", + ) + inner_bytes = inner.as_bytes() + + outer = EmailMessage() + outer["Subject"] = "Outer" + outer["From"] = "outer@example.com" + outer.set_content("see nested") + outer.add_attachment( + inner_bytes, + maintype="application", + subtype="octet-stream", + filename="nested.eml", + ) + outer_bytes = outer.as_bytes() + # 上限略大于容器;若对子内容再计一次,则可能误 skip + tight_total = len(inner_bytes) + 10 + assert tight_total < len(outer_bytes) + len(b"INNER-PO-TINY") + + _, meta = parse_eml_bytes( + outer_bytes, + extract_text=extract_notice_text, + limits=EmlLimits( + max_attachments=10, + max_attachment_bytes=10 * 1024 * 1024, + max_total_attachment_bytes=tight_total, + max_nesting_depth=3, + ), + ) + by_name = {row["filename"]: row for row in meta["attachments"]} + assert "nested.eml" in by_name + assert by_name["inner.txt"]["parse_status"] == "parsed" + assert "INNER-PO-TINY" in by_name["inner.txt"]["extracted_text"] + + +def test_extract_eml_large_containers_count_toward_total(): + """多个近似空壳大 .eml 容器须计入总量,不能仅靠跳过叶子附件绕过。""" + from email.message import EmailMessage + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + def _shell_eml(name: str, pad: bytes) -> bytes: + msg = EmailMessage() + msg["Subject"] = name + msg["From"] = "shell@example.com" + msg.set_content("pad-only") + # 用文本附件撑大容器体积(容器整体计费) + msg.add_attachment(pad, maintype="text", subtype="plain", filename=f"{name}-pad.txt") + return msg.as_bytes() + + pad = b"X" * 8000 + shell_a = _shell_eml("A", pad) + shell_b = _shell_eml("B", pad) + shell_c = _shell_eml("C", pad) + + root = EmailMessage() + root["Subject"] = "Many shells" + root["From"] = "root@example.com" + root.set_content("holders") + for name, payload in (("a.eml", shell_a), ("b.eml", shell_b), ("c.eml", shell_c)): + root.add_attachment( + payload, + maintype="application", + subtype="octet-stream", + filename=name, + ) + + # 只够放两个容器;第三个须 skipped 并打总量警告 + two_shells = len(shell_a) + len(shell_b) + _, meta = parse_eml_bytes( + root.as_bytes(), + extract_text=extract_notice_text, + limits=EmlLimits( + max_attachments=20, + max_attachment_bytes=10 * 1024 * 1024, + max_total_attachment_bytes=two_shells + 50, + max_nesting_depth=3, + ), + ) + by_name = {row["filename"]: row for row in meta["attachments"]} + assert by_name["a.eml"]["parse_status"] in {"parsed", "empty"} + assert by_name["b.eml"]["parse_status"] in {"parsed", "empty"} + assert by_name["c.eml"]["parse_status"] == "skipped" + assert any(str(w).startswith("eml_total_attachment_size_exceeded:") for w in meta["warnings"]) + + +def test_attachment_integrity_flags_budget_and_failed_status(): + """完整性助手须覆盖预算耗尽、文本截断与 failed/empty/skipped。""" + from app.services.shipping_notice.attachment_integrity import ( + BLOCKING_WARNING_PREFIXES, + is_attachment_parse_incomplete, + ) + + assert not is_attachment_parse_incomplete( + { + "attachment_count": 1, + "attachments": [{"parse_status": "parsed", "warnings": []}], + "warnings": [], + } + ) + assert is_attachment_parse_incomplete( + { + "attachment_count": 1, + "attachments": [{"parse_status": "failed", "warnings": []}], + "warnings": [], + } + ) + assert is_attachment_parse_incomplete( + { + "attachment_count": 2, + "attachments": [{"parse_status": "parsed", "warnings": []}], + "warnings": [], + } + ) + assert is_attachment_parse_incomplete( + { + "attachment_count": 1, + "attachments": [ + { + "parse_status": "parsed", + "warnings": ["eml_attachment_text_budget_exhausted:100"], + } + ], + "warnings": [], + } + ) + assert is_attachment_parse_incomplete( + { + "attachment_count": 1, + "attachments": [{"parse_status": "parsed", "warnings": []}], + "warnings": ["eml_attachment_text_budget_exhausted:100"], + } + ) + assert is_attachment_parse_incomplete( + { + "attachment_count": 1, + "attachments": [ + { + "parse_status": "parsed", + "warnings": ["eml_attachment_text_truncated:10"], + } + ], + "warnings": [], + } + ) + assert is_attachment_parse_incomplete( + { + "attachment_count": 0, + "attachments": [], + "warnings": ["notice_text_truncated:100"], + } + ) + # 契约:每个阻断前缀都须能触发 incomplete + for prefix in BLOCKING_WARNING_PREFIXES: + assert is_attachment_parse_incomplete({"warnings": [f"{prefix}demo"], "attachments": []}) + + +def test_frontend_blocking_warning_prefixes_match_backend(): + """前后端阻断 warning 前缀契约须一致,防止再漏截断类码。""" + import ast + import re + from pathlib import Path + + from app.services.shipping_notice.attachment_integrity import BLOCKING_WARNING_PREFIXES + + ts_path = ( + Path(__file__).resolve().parents[2] + / "frontend" + / "src" + / "features" + / "chat" + / "shipping" + / "shippingNoticeAttachmentIntegrity.ts" + ) + assert ts_path.is_file(), f"missing frontend contract file: {ts_path}" + text = ts_path.read_text(encoding="utf-8") + match = re.search( + r"export const BLOCKING_WARNING_PREFIXES\s*=\s*\[(.*?)]\s*as const", + text, + flags=re.S, + ) + assert match, "frontend BLOCKING_WARNING_PREFIXES array not found" + literal = "[" + match.group(1) + "]" + literal = literal.replace("'", '"') + fe_prefixes = ast.literal_eval(literal) + assert sorted(fe_prefixes) == sorted(BLOCKING_WARNING_PREFIXES) + + +def test_intake_structured_summary_per_attachment_text_truncated(app): + """单附件文本超 NOTICE_TEXT_MAX_CHARS 须投影 truncated warning 并阻断完整性。""" + from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete + from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + with app.app_context(): + app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 10 + app.config["SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS"] = 1_000_000 + result = NoticeIntakeResult( + filename="trunc.eml", + source_type="email", + source_file_type="message/rfc822", + text="cover", + warnings=[], + meta={ + "email": {"subject": "Trunc", "body_text": "cover"}, + "attachment_count": 1, + "attachments": [ + { + "attachment_key": "att-001", + "filename": "long.txt", + "mime_type": "text/plain", + "size": 20, + "content_hash": "h1", + "parse_status": "parsed", + "extracted_text": "ABCDEFGHIJKLMNOP", # 16 chars → 截断为 10 + "warnings": [], + } + ], + }, + content_hash="trunc-hash", + file_size=100, + status="accepted", + ) + summary = intake_result_to_structured_summary(result) + row = summary["attachments"][0] + assert row["parse_status"] == "parsed" + assert row["stored_text_length"] == 10 + assert any(str(w).startswith("eml_attachment_text_truncated:") for w in row["warnings"]) + assert is_attachment_parse_incomplete(summary) + + +def test_notice_text_truncated_blocks_integrity(app): + """扁平正文 notice_text_truncated 须进入完整性门禁。""" + from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete + from app.services.shipping_notice.notice_upload import truncate_notice_text + + with app.app_context(): + app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 20 + text, warnings = truncate_notice_text("X" * 50, []) + assert len(text) == 20 + assert any(str(w).startswith("notice_text_truncated:") for w in warnings) + assert is_attachment_parse_incomplete( + { + "warnings": warnings, + "attachment_count": 0, + "attachments": [], + } + ) + + +def test_extract_eml_rfc822_forward_respects_size_limits(): + """原生 message/rfc822 转发须受单附件/总量上限约束,不可静默完整展开。""" + from email.message import EmailMessage + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + forwarded = EmailMessage() + forwarded["Subject"] = "Huge forward" + forwarded["From"] = "inner@example.com" + forwarded.set_content("Y" * 5000) + + root = EmailMessage() + root["Subject"] = "Wrapper" + root["From"] = "outer@example.com" + root.set_content("see forward") + root.add_attachment(forwarded) + + _, meta = parse_eml_bytes( + root.as_bytes(), + extract_text=extract_notice_text, + limits=EmlLimits( + max_attachments=10, + max_attachment_bytes=100, + max_total_attachment_bytes=100, + max_nesting_depth=3, + ), + ) + assert any( + str(w).startswith("eml_attachment_too_large:") + or str(w).startswith("eml_total_attachment_size_exceeded:") + for w in meta["warnings"] + ) + assert any(row.get("parse_status") == "skipped" for row in meta["attachments"]) + flat_body = str((meta.get("email") or {}).get("body_text") or "") + assert ("Y" * 200) not in flat_body + + +def test_intake_structured_summary_attachment_text_budget(app): + """附件文本总预算部分/完全耗尽时须投影 warning,且第二附件文本可被截断或清空。""" + from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete + + with app.app_context(): + app.config["SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS"] = 30 + result = NoticeIntakeResult( + filename="budget.eml", + source_type="email", + source_file_type="message/rfc822", + text="cover", + warnings=[], + meta={ + "email": {"subject": "Budget", "body_text": "cover"}, + "attachment_count": 2, + "attachments": [ + { + "attachment_key": "att-001", + "filename": "a.txt", + "mime_type": "text/plain", + "size": 20, + "content_hash": "h1", + "parse_status": "parsed", + "extracted_text": "AAAAAAAAAA" * 3, # 30 chars + "warnings": [], + }, + { + "attachment_key": "att-002", + "filename": "b.txt", + "mime_type": "text/plain", + "size": 20, + "content_hash": "h2", + "parse_status": "parsed", + "extracted_text": "BBBBBBBBBB" * 3, + "warnings": [], + }, + ], + }, + content_hash="budget-hash", + file_size=100, + status="accepted", + ) + summary = intake_result_to_structured_summary(result) + assert any( + str(w).startswith("eml_attachment_text_budget_exhausted:") for w in summary["warnings"] + ) + assert summary["attachments"][0]["stored_text_length"] == 30 + assert summary["attachments"][1]["stored_text_length"] == 0 + assert is_attachment_parse_incomplete(summary) + + +def test_extract_eml_rfc822_depth_registers_skipped_row(tmp_path): + """超深 message/rfc822 应登记 skipped 附件行,便于前端感知不完整。""" + from email.message import EmailMessage + + from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes + from app.services.shipping_notice.notice_upload import extract_notice_text + + deepest = EmailMessage() + deepest["Subject"] = "Deep" + deepest.set_content("DEEP-ORDER-SHOULD-SKIP") + + mid = EmailMessage() + mid["Subject"] = "Mid" + mid.set_content("mid") + mid.add_attachment(deepest) + + root = EmailMessage() + root["Subject"] = "Root" + root["From"] = "a@example.com" + root.set_content("root") + root.add_attachment(mid) + + _, meta = parse_eml_bytes( + root.as_bytes(), + extract_text=extract_notice_text, + limits=EmlLimits(max_attachments=10, max_nesting_depth=0), + depth=0, + ) + assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"]) + skipped = [row for row in meta["attachments"] if row.get("parse_status") == "skipped"] + assert skipped + assert any( + any(str(w).startswith("eml_nesting_depth_exceeded:") for w in (row.get("warnings") or [])) + for row in skipped + ) + + +def test_extract_eml_keeps_inline_pdf_attachment(tmp_path): + """Content-Disposition: inline 的 PDF 不得被当成签名图丢弃。""" + from email.message import EmailMessage + + from app.services.shipping_notice.notice_upload import extract_notice_text + + msg = EmailMessage() + msg["Subject"] = "Inline PDF" + msg["From"] = "a@example.com" + msg["To"] = "b@example.com" + msg.set_content("See PDF.") + msg.add_attachment( + _minimal_pdf_bytes("PO-INLINE-PDF"), + maintype="application", + subtype="pdf", + filename="inline-order.pdf", + disposition="inline", + ) + path = tmp_path / "inline-pdf.eml" + path.write_bytes(msg.as_bytes()) + + text, meta = extract_notice_text(path) + assert meta["attachment_count"] == 1 + assert meta["attachments"][0]["filename"] == "inline-order.pdf" + assert meta["attachments"][0]["parse_status"] == "parsed" + assert "PO-INLINE-PDF" in text + + def test_extract_reservation_id_from_pr_number(): assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351" assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351" diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py index d7be1af9..1fc2d20f 100644 --- a/backend/tests/test_shipping_notice_intakes.py +++ b/backend/tests/test_shipping_notice_intakes.py @@ -17,7 +17,15 @@ 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.models import ( + FileAsset, + ShippingBatch, + ShippingNoticeCandidate, + ShippingNoticeDocument, + 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 @@ -59,10 +67,160 @@ def test_create_intake_queues_parse_job(app, shipping_user): ) assert intake_data['parse_status'] == 'queued' enqueue_mock.assert_called_once() + assert enqueue_mock.call_args.kwargs.get('commit') is False intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_data['intake_no']).one() assert intake.parse_job_id == 101 +def test_create_intake_integrity_race_returns_existing(app, shipping_user, monkeypatch): + """并发首次插入撞唯一约束时须回落已有 Intake,不得 500。""" + with app.app_context(): + from sqlalchemy.exc import IntegrityError + + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'race-intake')) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + winner = ShippingNoticeIntake( + intake_no='SNI-RACE-WIN', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='queued', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + parse_job_id=555, + ) + db.session.add(winner) + db.session.commit() + + calls = {'n': 0} + + def _lock_side_effect(*, asset_id, purpose, parser_version): + calls['n'] += 1 + if calls['n'] == 1: + return None + return ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-RACE-WIN') + .execution_options(populate_existing=True) + .with_for_update() + .first() + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_service._lock_intake_for_asset_purpose_parser', + _lock_side_effect, + ) + + def _boom_nested(): + class _CM: + def __enter__(self): + raise IntegrityError('stmt', {}, Exception('uq')) + + def __exit__(self, *args): + return False + + return _CM() + + monkeypatch.setattr(db.session, 'begin_nested', _boom_nested) + + payload = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=asset.asset_no, + conversation_id='conv-race', + ) + assert payload['intake_no'] == 'SNI-RACE-WIN' + assert payload['parse_status'] == 'queued' + assert db.session.query(ShippingNoticeIntake).filter_by(asset_id=asset.id).count() == 1 + + +def test_create_parse_failed_twice_reuses_single_parse_job(app, shipping_user): + """parse_failed 并发式连续创建须串行持锁并复用同一 active Job。""" + with app.app_context(): + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'parse-failed-reuse'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-FAIL-REUSE', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parse_failed', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED', + ) + db.session.add(intake) + db.session.commit() + + first = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=asset.asset_no, + ) + second = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=asset.asset_no, + ) + assert first['intake_no'] == second['intake_no'] == 'SNI-FAIL-REUSE' + assert first['parse_status'] == second['parse_status'] == 'queued' + jobs = ( + db.session.query(Job) + .filter( + Job.domain == SHIPPING_NOTICE_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_NOTICE_PARSE.value, + Job.business_ref == 'SNI-FAIL-REUSE', + Job.status.in_(('queued', 'running')), + ) + .all() + ) + assert len(jobs) == 1 + refreshed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-FAIL-REUSE').one() + assert refreshed.parse_job_id == jobs[0].id + + +def test_create_intake_ignores_old_parser_version_reuse(app, shipping_user): + """同一 FileAsset 上旧 parser_version 的 parsed Intake 不得被新版本直接复用。""" + with app.app_context(): + app.config['SHIPPING_NOTICE_PARSER_VERSION'] = 'v6' + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'legacy-v5-body')) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + # 覆盖本次升级:v5 仅有 JSON 附件摘要,无 Document/Candidate/派生资产,须强制重解析 + old = ShippingNoticeIntake( + intake_no='SNI-OLD-PARSER-V5', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v5', + extracted_text='stale without documents candidates or derived assets', + structured_result_json={'attachment_count': 0, 'attachments': [], 'warnings': []}, + ) + db.session.add(old) + db.session.commit() + + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=909) as enq: + payload = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=asset.asset_no, + conversation_id='conv-parser-bump', + ) + enq.assert_called_once() + assert payload['intake_no'] != old.intake_no + assert payload['parse_status'] == 'queued' + assert payload['parser_version'] == 'v6' + created = db.session.query(ShippingNoticeIntake).filter_by(intake_no=payload['intake_no']).one() + assert created.parser_version == 'v6' + assert created.asset_id == asset.id + # 旧版行仍在,但未被返回/复用 + assert db.session.get(ShippingNoticeIntake, old.id).parse_status == 'parsed' + + def test_error_classes_accept_custom_code_kwargs(app): """业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。""" with app.app_context(): @@ -220,6 +378,259 @@ def test_create_batch_from_intakes_idempotent_replay_after_consumed(app, shippin assert called['count'] == 0 +def test_mixed_open_existing_and_create_idempotent_replay(app, shipping_user, monkeypatch): + """混合批次:open_existing 挂旧批次时,同幂等键重试须成功回放而非集合冲突。""" + with app.app_context(): + # 旧任务(open_existing 目标) + old_batch = ShippingBatch(batch_no='SB-MIX-OLD', user_id=shipping_user.id, file_count=1) + db.session.add(old_batch) + db.session.flush() + old_task = ShippingTask( + task_no='SN-MIX-OLD', + batch_id=old_batch.id, + user_id=shipping_user.id, + source_type='manual', + process_status='waiting_inventory', + document_version=1, + ) + db.session.add(old_task) + db.session.flush() + + asset_a, intake_a = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-MIX-A', hash_value='hash-mix-a' + ) + asset_b, intake_b = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-MIX-B', hash_value='hash-mix-b' + ) + intake_a.duplicate_resolution = 'open_existing' + intake_a.duplicate_target_task_no = old_task.task_no + intake_a.duplicate_status = 'same_active_task' + intake_a.duplicate_matches_json = [ + { + 'task_no': old_task.task_no, + 'process_status': old_task.process_status, + 'document_version': 1, + 'match_type': 'business_fingerprint', + 'matched_fields': ['po_number'], + 'lifecycle': 'active', + } + ] + db.session.commit() + + def _fake_create(**kwargs): + batch = ShippingBatch( + batch_no='SB-MIX-NEW', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key=kwargs.get('create_idempotency_key'), + process_summary_json={'request_intake_nos': ['SNI-MIX-A', 'SNI-MIX-B']}, + ) + db.session.add(batch) + db.session.flush() + item = kwargs['notice_items'][0] + task = ShippingTask( + task_no='SN-MIX-NEW', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_intake_id=item.get('source_intake_id'), + source_asset_id=item.get('source_asset_id'), + 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}], + 'focus_task': {'task_no': task.task_no}, + }, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _fake_create, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake', + lambda **kwargs: { + 'status': kwargs['intake'].duplicate_status or 'none', + 'blocking': kwargs['intake'].duplicate_resolution == 'open_existing', + 'fingerprint': None, + 'fingerprint_version': 'shipping-v1', + 'fingerprint_strength': 'strong', + 'matches': list(kwargs['intake'].duplicate_matches_json or []), + 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], + }, + ) + + first = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-mix', + intake_nos=['SNI-MIX-A', 'SNI-MIX-B'], + create_idempotency_key='idem-mix-1', + ) + assert first.get('batch_no') == 'SB-MIX-NEW' + assert first.get('idempotent_replay') is not True + assert any(x.get('task_no') == 'SN-MIX-OLD' for x in (first.get('opened_existing') or [])) + + second = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-mix', + intake_nos=['SNI-MIX-A', 'SNI-MIX-B'], + create_idempotency_key='idem-mix-1', + ) + assert second.get('idempotent_replay') is True + assert second.get('batch_no') == 'SB-MIX-NEW' + assert any(x.get('task_no') == 'SN-MIX-OLD' for x in (second.get('opened_existing') or [])) + + +def test_pure_open_existing_idempotent_replay(app, shipping_user, monkeypatch): + """纯 open_existing:无新批次时凭 intake 幂等键重放,不报已消费。""" + with app.app_context(): + old_batch = ShippingBatch(batch_no='SB-OPEN-ONLY', user_id=shipping_user.id, file_count=1) + db.session.add(old_batch) + db.session.flush() + old_task = ShippingTask( + task_no='SN-OPEN-ONLY', + batch_id=old_batch.id, + user_id=shipping_user.id, + source_type='manual', + process_status='pending_review', + ) + db.session.add(old_task) + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-OPEN-ONLY', hash_value='hash-open-only') + intake.duplicate_resolution = 'open_existing' + intake.duplicate_target_task_no = old_task.task_no + intake.duplicate_status = 'same_active_task' + intake.duplicate_matches_json = [ + { + 'task_no': old_task.task_no, + 'process_status': 'pending_review', + 'document_version': 1, + 'match_type': 'business_fingerprint', + 'matched_fields': ['po_number'], + 'lifecycle': 'active', + } + ] + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake', + lambda **kwargs: { + 'status': 'same_active_task', + 'blocking': True, + 'fingerprint': 'fp', + 'fingerprint_version': 'shipping-v1', + 'fingerprint_strength': 'strong', + 'matches': list(intake.duplicate_matches_json or []), + 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], + }, + ) + + first = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-open-only', + intake_nos=['SNI-OPEN-ONLY'], + create_idempotency_key='idem-open-only', + ) + assert first.get('batch_no') in (None, '') + assert first.get('idempotent_replay') is False + + second = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-open-only', + intake_nos=['SNI-OPEN-ONLY'], + create_idempotency_key='idem-open-only', + ) + assert second.get('idempotent_replay') is True + assert (second.get('opened_existing') or [])[0].get('task_no') == 'SN-OPEN-ONLY' + + +def test_intake_replay_heals_missing_consumed_batch_id(app, shipping_user): + """批次已创建但 intake.consumed_batch_id 未回填时,重放须恢复批次而非「未创建新批次」。""" + with app.app_context(): + asset, intake = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-HEAL-1', hash_value='hash-heal-1' + ) + batch = ShippingBatch( + batch_no='SB-HEAL-1', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key='idem-heal-1', + ) + db.session.add(batch) + db.session.flush() + task = ShippingTask( + task_no='SN-HEAL-1', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_intake_id=intake.id, + source_asset_id=asset.id, + process_status='created', + ) + db.session.add(task) + # 模拟提交断点:已 stamp + consumed,但尚未回填 consumed_batch_id + intake.parse_status = 'consumed' + intake.consumed_at = datetime.utcnow() + intake.create_idempotency_key = 'idem-heal-1' + intake.consumed_batch_id = None + intake.consumed_task_id = None + db.session.commit() + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-heal', + intake_nos=['SNI-HEAL-1'], + create_idempotency_key='idem-heal-1', + ) + assert result.get('idempotent_replay') is True + assert result.get('batch_no') == 'SB-HEAL-1' + assert '未创建新批次' not in str(result.get('message') or '') + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.consumed_batch_id == batch.id + assert refreshed.consumed_task_id == task.id + + +def test_revision_conflict_when_successor_exists(app, shipping_user): + """已有后继修订时,再次 create_revision 应冲突。""" + from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item + + with app.app_context(): + base = ShippingTask( + task_no='SN-REV-LOCK-BASE', + user_id=shipping_user.id, + source_type='manual', + process_status='uploaded', + document_version=1, + ) + db.session.add(base) + db.session.flush() + successor = ShippingTask( + task_no='SN-REV-LOCK-V2', + user_id=shipping_user.id, + source_type='manual', + process_status='pending_review', + document_version=2, + supersedes_task_id=base.id, + duplicate_resolution_type='revision', + ) + db.session.add(successor) + asset, intake = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-REV-LOCK', hash_value='hash-rev-lock' + ) + intake.duplicate_resolution = 'create_revision' + intake.duplicate_target_task_no = base.task_no + db.session.commit() + + with pytest.raises(ConflictError) as excinfo: + intake_to_notice_item(intake, asset) + assert excinfo.value.code == 'SHIPPING_NOTICE.REVISION_CONFLICT' + + 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') @@ -238,6 +649,917 @@ def test_queued_intake_cannot_create_batch(app, shipping_user): assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' +def test_incomplete_attachments_cannot_create_batch(app, shipping_user): + """顶层 parsed 但附件不完整时,建批须被后端门禁拒绝。""" + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-INCOMPLETE-ATT') + intake.structured_result_json = { + 'filename': 'mail.eml', + 'source_type': 'email', + 'attachment_count': 2, + 'attachments': [ + {'filename': 'ok.pdf', 'parse_status': 'parsed', 'warnings': []}, + {'filename': 'bad.pdf', 'parse_status': 'failed', 'warnings': []}, + ], + 'warnings': [], + } + db.session.commit() + with pytest.raises(ConflictError) as excinfo: + create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id=None, + intake_nos=[intake.intake_no], + create_idempotency_key='idem-incomplete-att', + ) + assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE' + + +def test_text_budget_exhausted_cannot_create_batch(app, shipping_user): + """文本预算耗尽警告须进入建批完整性门禁。""" + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-BUDGET-BLOCK') + intake.structured_result_json = { + 'filename': 'mail.eml', + 'source_type': 'email', + 'attachment_count': 1, + 'attachments': [ + { + 'filename': 'big.txt', + 'parse_status': 'parsed', + 'warnings': ['eml_attachment_text_budget_exhausted:500000'], + } + ], + 'warnings': ['eml_attachment_text_budget_exhausted:500000'], + } + db.session.commit() + with pytest.raises(ConflictError) as excinfo: + create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id=None, + intake_nos=[intake.intake_no], + create_idempotency_key='idem-budget-block', + ) + assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE' + + +def test_retry_parse_allows_incomplete_parsed_intake(app, shipping_user): + """附件不完整但顶层 parsed 时须允许重试解析。""" + from app.services.shipping_notice.intake_service import retry_intake_parse + + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-INCOMPLETE') + intake.structured_result_json = { + 'attachment_count': 1, + 'attachments': [{'filename': 'x.pdf', 'parse_status': 'failed', 'warnings': []}], + 'warnings': [], + } + db.session.commit() + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=4242) as enq: + payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no) + enq.assert_called_once() + kwargs = enq.call_args.kwargs + assert kwargs.get('commit') is False + assert kwargs.get('dedupe_statuses') == ('queued',) + assert payload['parse_status'] == 'queued' + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'queued' + assert refreshed.parse_job_id == 4242 + + +def test_retry_parse_does_not_reuse_running_job(app, shipping_user): + """重试不得复用仍为 running 的原 Job,须新建 queued Job。""" + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.intake_service import retry_intake_parse + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-RUNNING') + intake.parse_status = 'parse_failed' + db.session.flush() + running = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + progress=50, + message='running old parse', + attempts=1, + max_attempts=3, + created_by_id=shipping_user.id, + ) + db.session.add(running) + db.session.commit() + old_id = int(running.id) + + payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no) + assert payload['parse_status'] == 'queued' + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert int(refreshed.parse_job_id or 0) != old_id + new_job = db.session.get(Job, int(refreshed.parse_job_id)) + assert new_job is not None + assert new_job.status == 'queued' + assert db.session.get(Job, old_id).status == 'running' + + +def test_enqueue_commit_false_keeps_job_uncommitted_until_outer_commit(app, shipping_user): + """enqueue(commit=False) 仅 flush,外层 rollback 后 Job 不得残留。""" + from app.jobs.queue import enqueue + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + job_id = enqueue( + JobType.SHIPPING_NOTICE_PARSE, + {'intake_no': 'SNI-ENQ-FLUSH'}, + domain=SHIPPING_NOTICE_JOB_DOMAIN, + business_ref='SNI-ENQ-FLUSH', + created_by_id=shipping_user.id, + commit=False, + dedupe_active=False, + ) + assert int(job_id) > 0 + assert db.session.get(Job, job_id) is not None + db.session.rollback() + assert db.session.get(Job, job_id) is None + + +def test_enqueue_unique_conflict_does_not_poison_outer_transaction(app, shipping_user): + """ + 唯一冲突必须落在 SAVEPOINT 内:外层 Intake 修改不得因 PendingRollbackError 丢失。 + """ + from app.jobs.queue import enqueue + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'enq-savepoint'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-ENQ-SAVEPOINT', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parse_failed', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + existing = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + priority=0, + business_ref='SNI-ENQ-SAVEPOINT', + payload_json={'intake_no': 'SNI-ENQ-SAVEPOINT'}, + progress=0, + message='winner', + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + db.session.add(intake) + db.session.add(existing) + db.session.commit() + keep_id = int(existing.id) + + # 外层事务:先改 Intake,再强制插入撞唯一(dedupe 关闭) + locked = ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-ENQ-SAVEPOINT') + .with_for_update() + .one() + ) + locked.parse_status = 'queued' + locked.error_message = None + returned_id = enqueue( + JobType.SHIPPING_NOTICE_PARSE, + {'intake_no': 'SNI-ENQ-SAVEPOINT'}, + domain=SHIPPING_NOTICE_JOB_DOMAIN, + business_ref='SNI-ENQ-SAVEPOINT', + created_by_id=shipping_user.id, + dedupe_active=False, + commit=False, + ) + assert returned_id == keep_id + locked.parse_job_id = returned_id + db.session.commit() + + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-ENQ-SAVEPOINT' + ).one() + assert refreshed.parse_status == 'queued' + assert refreshed.parse_job_id == keep_id + assert ( + db.session.query(Job) + .filter( + Job.business_ref == 'SNI-ENQ-SAVEPOINT', + Job.status == 'queued', + ) + .count() + == 1 + ) + + +def test_fail_job_supersedes_running_when_queued_sibling_exists(app, shipping_user): + """旧 running 失败重试时若已有 queued 同伴,须 cancelled 并重指 parse_job_id。""" + from datetime import datetime, timedelta + + from app.jobs.queue import fail_job + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'fail-supersede'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-FAIL-SUPERSEDE', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + parse_lease='1:1', + ) + running = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-FAIL-SUPERSEDE', + payload_json={'intake_no': 'SNI-FAIL-SUPERSEDE'}, + progress=50, + message='old running', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(minutes=10), + created_by_id=shipping_user.id, + ) + queued = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + priority=0, + business_ref='SNI-FAIL-SUPERSEDE', + payload_json={'intake_no': 'SNI-FAIL-SUPERSEDE'}, + progress=0, + message='new queued', + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, running, queued]) + db.session.flush() + intake.parse_job_id = int(running.id) + db.session.commit() + old_id = int(running.id) + keep_id = int(queued.id) + + ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1) + assert ok is True + assert db.session.get(Job, old_id).status == 'cancelled' + assert db.session.get(Job, keep_id).status == 'queued' + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-FAIL-SUPERSEDE' + ).one() + assert refreshed.parse_job_id == keep_id + assert refreshed.parse_status == 'queued' + assert refreshed.parse_lease is None + + +def test_fail_job_retarget_preserves_running_sibling_lease(app, shipping_user): + """替代 Job 已真正 claim Intake(精确 lease)时,supersede 须保留 parsing/lease。""" + from datetime import datetime, timedelta + + from app.jobs.queue import fail_job + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'fail-preserve-lease'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-PRESERVE-LEASE', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + old = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-PRESERVE-LEASE', + payload_json={'intake_no': 'SNI-PRESERVE-LEASE'}, + progress=50, + message='old', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(minutes=10), + created_by_id=shipping_user.id, + ) + keep = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-PRESERVE-LEASE', + payload_json={'intake_no': 'SNI-PRESERVE-LEASE'}, + progress=20, + message='new worker', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow(), + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, old, keep]) + db.session.flush() + keep_id = int(keep.id) + intake.parse_job_id = keep_id + intake.parse_lease = f'{keep_id}:1' + db.session.commit() + old_id = int(old.id) + + ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1) + assert ok is True + assert db.session.get(Job, old_id).status == 'cancelled' + assert db.session.get(Job, keep_id).status == 'running' + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-PRESERVE-LEASE' + ).one() + assert refreshed.parse_job_id == keep_id + assert refreshed.parse_status == 'parsing' + assert refreshed.parse_lease == f'{keep_id}:1' + + +def test_fail_job_does_not_supersede_unowned_running_sibling(app, shipping_user): + """ + 同伴仅 Job.running、尚未 claim Intake 时不得 supersede。 + + 模拟:新 Worker 已读到旧 parse_job_id 将决定 skip+finish;若旧失败线程把 lease + 伪造给新 Job,会导致 Intake 永久 parsing。此时旧 Job 应正常 requeue。 + """ + from datetime import datetime, timedelta + + from app.jobs.queue import fail_job + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'fail-unowned-running'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-UNOWNED-RUNNING', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + old = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-UNOWNED-RUNNING', + payload_json={'intake_no': 'SNI-UNOWNED-RUNNING'}, + progress=50, + message='old still owns intake', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(minutes=10), + created_by_id=shipping_user.id, + ) + peer = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-UNOWNED-RUNNING', + payload_json={'intake_no': 'SNI-UNOWNED-RUNNING'}, + progress=10, + message='claimed job but not intake yet', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow(), + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, old, peer]) + db.session.flush() + old_id = int(old.id) + peer_id = int(peer.id) + # Intake 仍属旧 Job(新 Worker 预检会看到非本 Job 并 skip) + intake.parse_job_id = old_id + intake.parse_lease = f'{old_id}:1' + db.session.commit() + + ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1) + assert ok is True + refreshed_old = db.session.get(Job, old_id) + assert refreshed_old is not None + # 不得 cancelled + 伪造 lease;应 requeue 旧 Job,并同步 Intake 离开 parsing + assert refreshed_old.status == 'queued' + assert refreshed_old.started_at is None + assert db.session.get(Job, peer_id).status == 'running' + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-UNOWNED-RUNNING' + ).one() + assert refreshed.parse_job_id == old_id + assert refreshed.parse_status == 'queued' + assert refreshed.parse_lease is None + + +def test_fail_job_requeue_clears_started_at_so_recover_does_not_demote(app, shipping_user): + """fail_job requeue 必须清空 started_at,否则 claim 后会被超时回收立刻打回。""" + from datetime import datetime, timedelta + + from app.jobs.queue import claim_next_job, fail_job, recover_stale_jobs + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'fail-started-at'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STARTED-AT', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + job = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-STARTED-AT', + payload_json={'intake_no': 'SNI-STARTED-AT'}, + progress=50, + message='long running', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=2), + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, job]) + db.session.flush() + job_id = int(job.id) + intake.parse_job_id = job_id + intake.parse_lease = f'{job_id}:1' + db.session.commit() + + assert fail_job(job_id, error='retryable', retryable=True, owned_attempt=1) is True + queued = db.session.get(Job, job_id) + assert queued is not None and queued.status == 'queued' + assert queued.started_at is None + + claimed = claim_next_job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_types=[JobType.SHIPPING_NOTICE_PARSE], + ) + assert claimed is not None and int(claimed.id) == job_id + claim_started = claimed.started_at + assert claim_started is not None + + recovered = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=60, + job_type=JobType.SHIPPING_NOTICE_PARSE, + ) + assert recovered == 0 + still = db.session.get(Job, job_id) + assert still is not None + assert still.status == 'running' + assert still.started_at == claim_started + + +def test_fail_job_prefers_queued_over_lower_id_unowned_running(app, shipping_user): + """不安全 running id 更小时,仍须选择后面的 queued 替代旧 Job。""" + from datetime import datetime, timedelta + + from app.jobs.queue import fail_job + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'fail-prefer-queued'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-FAIL-PREFER-QUEUED', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + old = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-FAIL-PREFER-QUEUED', + payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(minutes=10), + created_by_id=shipping_user.id, + ) + unowned = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-FAIL-PREFER-QUEUED', + payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow(), + created_by_id=shipping_user.id, + ) + queued = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + priority=0, + business_ref='SNI-FAIL-PREFER-QUEUED', + payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'}, + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, old, unowned, queued]) + db.session.flush() + old_id = int(old.id) + unowned_id = int(unowned.id) + queued_id = int(queued.id) + assert unowned_id < queued_id + intake.parse_job_id = old_id + intake.parse_lease = f'{old_id}:1' + db.session.commit() + + ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1) + assert ok is True + assert db.session.get(Job, old_id).status == 'cancelled' + assert db.session.get(Job, unowned_id).status == 'running' + assert db.session.get(Job, queued_id).status == 'queued' + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-FAIL-PREFER-QUEUED' + ).one() + assert refreshed.parse_job_id == queued_id + assert refreshed.parse_status == 'queued' + assert refreshed.parse_lease is None + + +def test_create_intake_rejects_cancelled_and_expired(app, shipping_user): + """创建入口不得复活 cancelled/expired;过期须落 expired 并 CONFLICT。""" + from datetime import datetime, timedelta + + from app.core.errors import ConflictError + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_cancelled = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'create-cancel'), + ) + asset_expired = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'create-expire'), + ) + a1 = db.session.query(FileAsset).filter_by(asset_no=asset_cancelled['asset_no']).one() + a2 = db.session.query(FileAsset).filter_by(asset_no=asset_expired['asset_no']).one() + cancelled = ShippingNoticeIntake( + intake_no='SNI-CREATE-CANCELLED', + asset_id=a1.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='cancelled', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + expired = ShippingNoticeIntake( + intake_no='SNI-CREATE-EXPIRED', + asset_id=a2.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parse_failed', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + expires_at=datetime.utcnow() - timedelta(hours=1), + ) + db.session.add_all([cancelled, expired]) + db.session.commit() + + with pytest.raises(ConflictError) as cancelled_exc: + create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=a1.asset_no, + ) + assert cancelled_exc.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS' + assert ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-CREATE-CANCELLED') + .one() + .parse_status + == 'cancelled' + ) + + with pytest.raises(ConflictError) as expired_exc: + create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=a2.asset_no, + ) + assert expired_exc.value.code == 'SHIPPING_NOTICE.INTAKE_EXPIRED' + assert ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-CREATE-EXPIRED') + .one() + .parse_status + == 'expired' + ) + + +def test_recover_stale_supersedes_running_when_queued_sibling_exists(app, shipping_user): + """超时回收旧 running 时若已有 queued 同伴,须 cancelled 并重指 Intake。""" + from datetime import datetime, timedelta + + from app.jobs.queue import recover_stale_jobs + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.intake_parse_workflow import ( + sync_intake_after_parse_job_recovery, + ) + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'recover-supersede'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-RECOVER-SUPERSEDE', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + parse_lease='9:1', + ) + running = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-RECOVER-SUPERSEDE', + payload_json={'intake_no': 'SNI-RECOVER-SUPERSEDE'}, + progress=50, + message='stale running', + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=1), + created_by_id=shipping_user.id, + ) + queued = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + priority=0, + business_ref='SNI-RECOVER-SUPERSEDE', + payload_json={'intake_no': 'SNI-RECOVER-SUPERSEDE'}, + progress=0, + message='replacement', + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, running, queued]) + db.session.flush() + intake.parse_job_id = int(running.id) + db.session.commit() + old_id = int(running.id) + keep_id = int(queued.id) + + count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=60, + job_type=JobType.SHIPPING_NOTICE_PARSE, + on_recovered=sync_intake_after_parse_job_recovery, + ) + assert count == 1 + assert db.session.get(Job, old_id).status == 'cancelled' + assert db.session.get(Job, keep_id).status == 'queued' + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-RECOVER-SUPERSEDE' + ).one() + assert refreshed.parse_job_id == keep_id + assert refreshed.parse_status == 'queued' + assert refreshed.parse_lease is None + + +def test_recover_stale_prefers_queued_over_lower_id_unowned_running(app, shipping_user): + """回收时不得让较小 id 的不安全 running 遮挡 queued 替代者。""" + from datetime import datetime, timedelta + + from app.jobs.queue import recover_stale_jobs + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.intake_parse_workflow import ( + sync_intake_after_parse_job_recovery, + ) + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'recover-prefer-queued'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-RECOVER-PREFER-QUEUED', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + old = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-RECOVER-PREFER-QUEUED', + payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=2), + created_by_id=shipping_user.id, + ) + unowned = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + priority=0, + business_ref='SNI-RECOVER-PREFER-QUEUED', + payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow(), + created_by_id=shipping_user.id, + ) + queued = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + priority=0, + business_ref='SNI-RECOVER-PREFER-QUEUED', + payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'}, + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + db.session.add_all([intake, old, unowned, queued]) + db.session.flush() + old_id = int(old.id) + unowned_id = int(unowned.id) + queued_id = int(queued.id) + assert unowned_id < queued_id + intake.parse_job_id = old_id + intake.parse_lease = f'{old_id}:1' + db.session.commit() + + count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=60, + job_type=JobType.SHIPPING_NOTICE_PARSE, + on_recovered=sync_intake_after_parse_job_recovery, + ) + assert count == 1 + assert db.session.get(Job, old_id).status == 'cancelled' + assert db.session.get(Job, unowned_id).status == 'running' + assert db.session.get(Job, queued_id).status == 'queued' + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-RECOVER-PREFER-QUEUED' + ).one() + assert refreshed.parse_job_id == queued_id + assert refreshed.parse_status == 'queued' + assert refreshed.parse_lease is None + + +def test_migration_retarget_helper_updates_intake_parse_job_id(app, shipping_user): + """迁移去重辅助:取消重复 Job 前须把 Intake.parse_job_id 重指 keep_id。""" + import importlib.util + from pathlib import Path + + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=_make_upload(b'mig-retarget'), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + keep = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + priority=0, + business_ref='SNI-MIG-RETARGET', + payload_json={'intake_no': 'SNI-MIG-RETARGET'}, + progress=0, + message='keep', + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + drop = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='cancelled', + priority=0, + business_ref='SNI-MIG-RETARGET', + payload_json={'intake_no': 'SNI-MIG-RETARGET'}, + progress=100, + message='drop', + attempts=0, + max_attempts=3, + created_by_id=shipping_user.id, + ) + intake = ShippingNoticeIntake( + intake_no='SNI-MIG-RETARGET', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='queued', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + db.session.add_all([keep, drop, intake]) + db.session.flush() + intake.parse_job_id = int(drop.id) + db.session.commit() + keep_id = int(keep.id) + drop_id = int(drop.id) + + mig_path = ( + Path(__file__).resolve().parents[1] + / 'migrations' + / 'versions' + / 'b7c8d9e0f1a2_jobs_parse_active_unique.py' + ) + spec = importlib.util.spec_from_file_location('mig_b7_parse_uq', mig_path) + assert spec and spec.loader + mig = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mig) + mig._retarget_intake_parse_job_ids( + db.session.connection(), + keep_id=keep_id, + drop_ids=[drop_id], + ) + db.session.commit() + + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-MIG-RETARGET' + ).one() + assert refreshed.parse_job_id == keep_id + + def test_create_batch_failure_rolls_back_preconsume(app, shipping_user, monkeypatch): """建批业务异常后预占 consumed 须回滚,否则用户无法重试。""" with app.app_context(): @@ -363,6 +1685,576 @@ def test_parse_worker_skips_cancelled_intake(app, shipping_user): assert refreshed.parse_status == 'cancelled' +def test_parse_worker_marks_parse_failed_when_asset_missing(app, shipping_user): + """资产已删除时领取后须写 parse_failed(不抛出),避免永久 parsing 且可用户重试。""" + with app.app_context(): + import logging + + from app.jobs.context import JobContext + from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.intake_service import retry_intake_parse + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-ASSET-GONE') + intake.parse_status = 'queued' + asset.deleted_at = datetime.utcnow() + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=1, + max_attempts=3, + ) + db.session.add(job) + db.session.flush() + intake.parse_job_id = job.id + db.session.commit() + + ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) + run_shipping_notice_parse(ctx, {'job_id': job.id, 'intake_no': intake.intake_no}) + + db.session.expire_all() + failed = db.session.get(ShippingNoticeIntake, intake.id) + assert failed is not None + assert failed.parse_status == 'parse_failed' + assert failed.error_code == 'FILE_ASSET.NOT_FOUND' + refreshed_job = db.session.get(Job, job.id) + assert refreshed_job is not None + assert refreshed_job.status == 'failed' + + asset.deleted_at = None + db.session.commit() + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=801): + retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-ASSET-GONE') + assert retried['parse_status'] == 'queued' + + +def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user): + """超时回收预解析 Job 时须把 Intake 从 parsing 同步为 queued,且同 Job 可再领取。""" + with app.app_context(): + import logging + from datetime import timedelta + + from app.jobs.context import JobContext + from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-STALE-PARSE') + intake.parse_status = 'parsing' + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=1), + locked_at=datetime.utcnow() - timedelta(hours=1), + locked_by='dead-worker', + ) + db.session.add(job) + db.session.flush() + intake.parse_job_id = job.id + db.session.commit() + + count, _ = recover_stale_shipping_notice_jobs() + assert count >= 1 + db.session.expire_all() + recovered_job = db.session.get(Job, job.id) + recovered_intake = db.session.get(ShippingNoticeIntake, intake.id) + assert recovered_job is not None and recovered_job.status == 'queued' + assert recovered_intake is not None and recovered_intake.parse_status == 'queued' + + # 再次执行:即使仍短暂为 parsing,同 parse_job_id 也应可领取(防御路径) + recovered_intake.parse_status = 'parsing' + recovered_job.status = 'running' + recovered_job.attempts = 2 + db.session.commit() + monkey_asset = db.session.get(FileAsset, asset.id) + assert monkey_asset is not None + with patch( + 'app.jobs.handlers.shipping_notice_parse.run_intake_parse', + return_value={'status': 'parsed', 'intake_no': intake.intake_no}, + ): + ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) + run_shipping_notice_parse( + ctx, {'job_id': recovered_job.id, 'intake_no': intake.intake_no} + ) + db.session.expire_all() + finished = db.session.get(Job, job.id) + assert finished is not None + assert finished.status == 'success' + + +def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2( + app, shipping_user, +): + """预解析 Job 超时耗尽须 parse_failed,并清理上一轮 Document/Candidate。""" + with app.app_context(): + from datetime import timedelta + + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-STALE-EXHAUST') + intake.parse_status = 'parsing' + intake.duplicate_status = 'soft_duplicate' + intake.duplicate_matches_json = [{'task_no': 'ST-X'}] + intake.duplicate_resolution = 'force_create' + doc = ShippingNoticeDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='a.pdf', + classification='order_notice', + parse_status='parsed', + content_hash='hash-stale-exhaust', + ) + db.session.add(doc) + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=3, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=1), + ) + db.session.add(job) + db.session.flush() + intake.parse_job_id = job.id + db.session.commit() + + recover_stale_shipping_notice_jobs() + db.session.expire_all() + failed_job = db.session.get(Job, job.id) + failed_intake = db.session.get(ShippingNoticeIntake, intake.id) + assert failed_job is not None and failed_job.status == 'failed' + assert failed_intake is not None + assert failed_intake.parse_status == 'parse_failed' + assert failed_intake.error_code == 'SHIPPING_NOTICE.INTAKE_PARSE_TIMEOUT' + assert failed_intake.duplicate_status == 'unchecked' + assert failed_intake.duplicate_matches_json in (None, []) + assert failed_intake.duplicate_resolution is None + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed_intake.id).count() == 0 + + +def test_process_next_job_does_not_override_handler_non_retryable_fail(app, shipping_user): + """Handler 已以 retryable=False 收口后,process_next_job 不得再强制 requeue。""" + with app.app_context(): + from app.jobs.context import JobContext + from app.jobs.queue import process_next_job + from app.jobs.types import JobType + from app.models import Job + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-NO-OVERRIDE') + intake.parse_status = 'queued' + asset.deleted_at = datetime.utcnow() + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='queued', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=0, + max_attempts=3, + ) + db.session.add(job) + db.session.flush() + intake.parse_job_id = job.id + db.session.commit() + job_id = job.id + + ctx = JobContext(config=dict(app.config), logger=app.logger, extras={'queues': ['shipping']}) + processed, job_type = process_next_job( + ctx=ctx, + domain='shipping_notice', + job_types=[JobType.SHIPPING_NOTICE_PARSE], + timeout_config_key='SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', + ) + assert processed is True + assert job_type == JobType.SHIPPING_NOTICE_PARSE.value + db.session.expire_all() + refreshed = db.session.get(Job, job_id) + assert refreshed is not None + assert refreshed.status == 'failed' + failed_intake = db.session.get(ShippingNoticeIntake, intake.id) + assert failed_intake is not None + assert failed_intake.parse_status == 'parse_failed' + + +def test_run_worker_entry_does_not_recover_parse_job(app, shipping_user): + """RUN单步入口只能回收RUN,不得按RUN阈值触碰PARSE Job或Intake lease。""" + from datetime import timedelta + + from app.jobs.context import JobContext + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import process_next_shipping_notice_job + + with app.app_context(): + asset, intake = _seed_parsed_intake( + shipping_user.id, + intake_no='SNI-RUN-ENTRY-PARSE-ISOLATION', + ) + intake.parse_status = 'parsing' + parse_job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=2), + locked_at=datetime.utcnow() - timedelta(hours=2), + locked_by='parse-worker', + ) + db.session.add(parse_job) + db.session.flush() + parse_job_id = int(parse_job.id) + intake.parse_job_id = parse_job_id + intake.parse_lease = f'{parse_job_id}:1' + db.session.commit() + + ctx = JobContext(config=dict(app.config), logger=app.logger, extras={'queues': ['shipping']}) + processed, reason = process_next_shipping_notice_job(ctx) + assert processed is False + assert reason == 'no_job' + + db.session.expire_all() + untouched_job = db.session.get(Job, parse_job_id) + untouched_intake = db.session.get(ShippingNoticeIntake, intake.id) + assert untouched_job is not None and untouched_job.status == 'running' + assert untouched_intake is not None and untouched_intake.parse_status == 'parsing' + assert untouched_intake.parse_lease == f'{parse_job_id}:1' + + +def test_retryable_handler_failure_requeues_job_and_intake(app, shipping_user): + """Handler可重试异常即使先写parse_failed,最终也须统一回到Job/Intake queued。""" + import logging + + from app.jobs.context import JobContext + from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse + from app.jobs.types import JobType + from app.models import Job + + with app.app_context(): + _, intake = _seed_parsed_intake( + shipping_user.id, + intake_no='SNI-HANDLER-RETRY-SYNC', + ) + intake.parse_status = 'queued' + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow(), + ) + db.session.add(job) + db.session.flush() + job_id = int(job.id) + intake.parse_job_id = job_id + db.session.commit() + + ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) + with patch( + 'app.jobs.handlers.shipping_notice_parse.run_intake_parse', + side_effect=RuntimeError('temporary parser outage'), + ): + with pytest.raises(RuntimeError, match='temporary parser outage'): + run_shipping_notice_parse( + ctx, + {'job_id': job_id, 'intake_no': intake.intake_no}, + ) + + db.session.expire_all() + queued_job = db.session.get(Job, job_id) + queued_intake = db.session.get(ShippingNoticeIntake, intake.id) + assert queued_job is not None and queued_job.status == 'queued' + assert queued_job.started_at is None + assert queued_intake is not None and queued_intake.parse_status == 'queued' + assert queued_intake.parse_job_id == job_id + assert queued_intake.parse_lease is None + assert queued_intake.error_code is None + assert queued_intake.error_message is None + + +def test_finish_job_owned_attempt_mismatch_is_noop(app, shipping_user): + """旧代次 finish_job 不得覆盖新 attempts 的 running Job(根治 Session 缓存误判)。""" + with app.app_context(): + from app.jobs.queue import finish_job + from app.jobs.types import JobType + from app.models import Job + + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref='SNI-OWNED-ATTEMPT', + payload_json={'intake_no': 'SNI-OWNED-ATTEMPT'}, + attempts=2, + max_attempts=3, + started_at=datetime.utcnow(), + ) + db.session.add(job) + db.session.commit() + job_id = int(job.id) + + # 故意不 expire:模拟 Handler Session 里仍缓存 attempts=1 的旧视图 + assert finish_job(job_id, message='stale gen', owned_attempt=1) is False + db.session.expire_all() + still = db.session.get(Job, job_id) + assert still is not None + assert still.status == 'running' + assert int(still.attempts or 0) == 2 + + assert finish_job(job_id, message='current gen', owned_attempt=2) is True + db.session.expire_all() + done = db.session.get(Job, job_id) + assert done is not None + assert done.status == 'success' + + +def test_recover_stale_jobs_does_not_demote_new_attempt(app, shipping_user): + """回收条件 UPDATE 绑定 attempts 快照,不能把已被新 Worker 领取的代次打回 queued。""" + with app.app_context(): + from datetime import timedelta + + from app.jobs.queue import recover_stale_jobs + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + job = Job( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref='SNI-RECOVER-SNAP', + payload_json={'intake_no': 'SNI-RECOVER-SNAP'}, + attempts=2, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=1), + locked_at=datetime.utcnow() - timedelta(hours=1), + ) + db.session.add(job) + db.session.commit() + job_id = int(job.id) + + # 模拟:陈旧回收器持有 attempts=1 的过期视图,直接条件 UPDATE 应失败 + from sqlalchemy import update as sa_update + + from app.models import Job as JobModel + + now = datetime.utcnow() + rc = db.session.execute( + sa_update(JobModel) + .where( + JobModel.id == job_id, + JobModel.status == 'running', + JobModel.attempts == 1, + ) + .values(status='queued', started_at=None, updated_at=now) + ) + assert int(rc.rowcount or 0) == 0 + db.session.rollback() + + # 正常回收:当前 attempts=2 仍超时 → queued + count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=60, + job_type=JobType.SHIPPING_NOTICE_PARSE, + ) + assert count == 1 + db.session.expire_all() + recovered = db.session.get(Job, job_id) + assert recovered is not None + assert recovered.status == 'queued' + assert int(recovered.attempts or 0) == 2 + + +def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, monkeypatch): + """超时回收清空 lease 后,旧 Worker 持旧 lease 写回须 skipped,不得覆盖新租约。""" + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-LEASE-STALE') + intake.parse_status = 'parsing' + intake.parse_lease = '99:1' + intake.parse_job_id = 99 + db.session.commit() + + # 模拟回收:清空 lease,随后新 Worker 领取 99:2 + intake.parse_status = 'queued' + intake.parse_lease = None + db.session.commit() + intake.parse_status = 'parsing' + intake.parse_lease = '99:2' + db.session.commit() + + 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='PO Number: LEASE001\nSKU X qty 1', + warnings=[], + meta={}, + content_hash=str(asset.content_hash or ''), + file_size=12, + status='accepted', + saved_path=None, + ), + ) + result = run_intake_parse(intake, asset, parse_lease='99:1') + assert result['status'] == 'skipped' + assert result.get('reason') == 'stale_parse_lease' + db.session.expire_all() + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed is not None + assert refreshed.parse_status == 'parsing' + assert refreshed.parse_lease == '99:2' + + +def test_recover_clears_parse_lease_so_old_worker_fail_is_noop(app, shipping_user): + """回收为 queued 后必须清空 parse_lease;旧 lease 的失败清理不得写 parse_failed。""" + with app.app_context(): + from datetime import timedelta + + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.intake_parse_workflow import ( + fail_intake_with_stage2_cleanup, + ) + from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-LEASE-RECOVER') + intake.parse_status = 'parsing' + intake.parse_lease = '55:1' + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=1), + ) + db.session.add(job) + db.session.flush() + intake.parse_job_id = job.id + db.session.commit() + + recover_stale_shipping_notice_jobs() + db.session.expire_all() + recovered = db.session.get(ShippingNoticeIntake, intake.id) + assert recovered is not None + assert recovered.parse_status == 'queued' + assert recovered.parse_lease is None + + stale = fail_intake_with_stage2_cleanup( + intake_id=int(recovered.id), + intake_no=recovered.intake_no, + parser_version='v6', + error_code='FILE_ASSET.NOT_FOUND', + error_message='stale worker', + extracted_text=None, + structured_result_json={}, + parse_warnings_json=[], + required_lease='55:1', + ) + assert stale['status'] == 'skipped' + assert stale.get('reason') == 'stale_parse_lease' + db.session.expire_all() + still = db.session.get(ShippingNoticeIntake, intake.id) + assert still is not None + assert still.parse_status == 'queued' + + +def test_asset_missing_on_retry_clears_prior_stage2(app, shipping_user, monkeypatch): + """不完整 parsed 重试时父资产被删:须清理 Document/Candidate 与重复决策后再 parse_failed。""" + with app.app_context(): + import logging + + from app.jobs.context import JobContext + from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.intake_service import serialize_intake + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-ASSET-GONE-S2') + intake.parse_status = 'queued' + intake.duplicate_status = 'soft_duplicate' + intake.duplicate_matches_json = [{'task_no': 'ST-KEEP'}] + intake.duplicate_resolution = 'open_existing' + intake.duplicate_target_task_no = 'ST-KEEP' + intake.structured_result_json = { + 'document_count': 1, + 'candidate_count': 1, + 'attachments': [{'filename': 'x.pdf', 'asset_no': 'FA-X'}], + } + doc = ShippingNoticeDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='x.pdf', + classification='order_notice', + parse_status='parsed', + content_hash='hash-gone-s2', + ) + db.session.add(doc) + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_NOTICE_PARSE.value, + status='running', + business_ref=intake.intake_no, + payload_json={'intake_no': intake.intake_no}, + attempts=1, + max_attempts=3, + ) + db.session.add(job) + db.session.flush() + intake.parse_job_id = job.id + asset.deleted_at = datetime.utcnow() + db.session.commit() + + ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) + run_shipping_notice_parse(ctx, {'job_id': job.id, 'intake_no': intake.intake_no}) + + db.session.expire_all() + failed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-ASSET-GONE-S2' + ).one() + assert failed.parse_status == 'parse_failed' + assert failed.error_code == 'FILE_ASSET.NOT_FOUND' + assert failed.duplicate_status == 'unchecked' + assert failed.duplicate_matches_json in (None, []) + assert failed.duplicate_resolution is None + assert failed.duplicate_target_task_no is None + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0 + payload = serialize_intake(failed, asset=None) + assert (payload.get('duplicate') or {}).get('matches') in (None, []) + structured = failed.structured_result_json or {} + assert 'document_count' not in structured + assert not any( + isinstance(row, dict) and row.get('asset_no') + for row in (structured.get('attachments') or []) + ) + + def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeypatch): """抽取期间他事务取消后,即使 Session 缓存仍为 parsing,也不得覆盖为 parsed。""" with app.app_context(): @@ -413,6 +2305,343 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp assert refreshed.parse_status == 'cancelled' +def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch): + """ + FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。 + + 核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。 + """ + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + + msg = EmailMessage() + msg['Subject'] = 'Intake EML Persist' + msg['From'] = 'shipper@example.com' + msg['To'] = 'freight@example.com' + msg['Message-ID'] = '' + msg.set_content('Cover letter.') + msg.add_attachment( + b'PO-PERSIST-LINE-001 qty 5', + maintype='text', + subtype='plain', + filename='order-a.txt', + ) + msg.add_attachment( + b'PO-PERSIST-LINE-002 qty 3', + maintype='text', + subtype='plain', + filename='order-b.txt', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='multi.eml', + content_type='message/rfc822', + ), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-EML-PERSIST-001', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + db.session.add(intake) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _asset: eml_bytes, + ) + # 跳过重复检测,专注结构化落库 + monkeypatch.setattr( + 'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake', + lambda **kwargs: {'status': 'none', 'fingerprint_strength': None}, + ) + + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, asset) + assert result['status'] == 'parsed' + + db.session.expire_all() + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-EML-PERSIST-001' + ).one() + structured = refreshed.structured_result_json or {} + assert structured.get('attachment_count') == 2 + assert structured.get('email', {}).get('subject') == 'Intake EML Persist' + attachments = structured.get('attachments') or [] + assert len(attachments) == 2 + texts = {row['filename']: row.get('extracted_text') for row in attachments} + assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '') + assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '') + assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '') + expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6') + assert refreshed.parser_version == expected_parser + assert all('_payload_bytes' not in row for row in attachments) + assert all(row.get('asset_no') for row in attachments) + + from app.services.shipping_notice.intake_service import serialize_intake + + lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False) + lean_atts = (lean.get('parse_summary') or {}).get('attachments') or [] + assert lean_atts and 'extracted_text' not in lean_atts[0] + assert 'body_text' not in ((lean.get('parse_summary') or {}).get('email') or {}) + + full = serialize_intake(refreshed, asset=asset, include_parse_texts=True) + full_atts = (full.get('parse_summary') or {}).get('attachments') or [] + assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '') + + +def test_run_intake_parse_persists_attached_multipart_and_detail_api( + app, client, shipping_user, monkeypatch, +): + """ + FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。 + + 核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning; + status 瘦身、详情含全文。 + """ + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + from app.core.auth.jwt import issue_local_access_token + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.intake_service import serialize_intake + + inner = MIMEMultipart('mixed') + inner.add_header('Content-Disposition', 'attachment', filename='inner-depth.mime') + inner.attach(MIMEText('INNER-DEPTH-PO-999', 'plain', 'utf-8')) + + bundle = MIMEMultipart('mixed') + bundle.add_header('Content-Disposition', 'attachment', filename='bundle-persist.mime') + bundle.attach(MIMEText('PLAIN-PO-101 please ship', 'plain', 'utf-8')) + bundle.attach(MIMEText('

HTML-PO-202 please ship

', 'html', 'utf-8')) + bundle.attach(inner) + + root = MIMEMultipart('mixed') + root['Subject'] = 'Intake multipart persist' + root['From'] = 'shipper@example.com' + root['To'] = 'freight@example.com' + root['Message-ID'] = '' + root.attach(MIMEText('Outer cover.', 'plain', 'utf-8')) + root.attach(bundle) + eml_bytes = root.as_bytes() + + with app.app_context(): + app.config['SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH'] = 1 + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='multipart-persist.eml', + content_type='message/rfc822', + ), + ) + asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-EML-MP-PERSIST-001', + asset_id=asset.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'), + ) + db.session.add(intake) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _asset: eml_bytes, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake', + lambda **kwargs: {'status': 'none', 'fingerprint_strength': None}, + ) + + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, asset) + assert result['status'] == 'parsed' + + db.session.expire_all() + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-EML-MP-PERSIST-001' + ).one() + structured = refreshed.structured_result_json or {} + by_name = { + str(row.get('filename') or ''): row + for row in (structured.get('attachments') or []) + } + assert 'bundle-persist.mime' in by_name + assert 'inner-depth.mime' in by_name + bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '') + assert 'PLAIN-PO-101' in bundle_text + assert 'HTML-PO-202' in bundle_text + assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed' + assert by_name['inner-depth.mime'].get('parse_status') == 'skipped' + warnings = list(structured.get('warnings') or []) + list( + by_name['inner-depth.mime'].get('warnings') or [] + ) + assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings) + assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '') + assert 'HTML-PO-202' in str(refreshed.extracted_text or '') + + lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False) + lean_bundle = next( + row + for row in ((lean.get('parse_summary') or {}).get('attachments') or []) + if row.get('filename') == 'bundle-persist.mime' + ) + assert 'extracted_text' not in lean_bundle + + full = serialize_intake(refreshed, asset=asset, include_parse_texts=True) + full_bundle = next( + row + for row in ((full.get('parse_summary') or {}).get('attachments') or []) + if row.get('filename') == 'bundle-persist.mime' + ) + assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '') + assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '') + + headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'} + + status_res = client.post( + '/api/workspace/shipping-notice/intakes/status', + json={'intake_nos': ['SNI-EML-MP-PERSIST-001']}, + headers=headers, + ) + assert status_res.status_code == 200 + status_item = status_res.get_json()['data']['items'][0] + status_atts = (status_item.get('parse_summary') or {}).get('attachments') or [] + status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime') + assert 'extracted_text' not in status_bundle + status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime') + assert status_inner.get('parse_status') == 'skipped' + + detail_res = client.get( + '/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001', + headers=headers, + ) + assert detail_res.status_code == 200 + detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or [] + detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime') + assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '') + assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '') + detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime') + assert detail_inner.get('parse_status') == 'skipped' + + +def test_intake_status_api_strips_texts_detail_returns_full(app, client): + """ + Flask 路由:POST /intakes/status 不返回附件全文;GET 详情返回全文;越权 404。 + """ + from datetime import datetime, timedelta + + from app.core.auth.jwt import issue_local_access_token + from app.models import FileAsset, ShippingNoticeIntake, User + + with app.app_context(): + owner = User(username='intake-api-owner', email='intake-api-owner@example.com', password_hash='x') + other = User(username='intake-api-other', email='intake-api-other@example.com', password_hash='x') + db.session.add_all([owner, other]) + db.session.commit() + owner_id = owner.id + other_id = other.id + owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'} + other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'} + + asset = FileAsset( + asset_no='FA-EML-API-001', + owner_user_id=owner_id, + original_filename='multi.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{owner_id}/test/multi.eml', + content_hash='hash-eml-api-001', + file_size=12, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-EML-API-001', + asset_id=asset.id, + user_id=owner_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v2', + extracted_text='flat body', + structured_result_json={ + 'email': { + 'subject': 'API EML', + 'body_text': 'SECRET-BODY-TEXT', + 'body_text_length': 16, + 'stored_body_text_length': 16, + }, + 'attachment_count': 1, + 'attachment_registered_count': 1, + 'attachments': [ + { + 'attachment_key': 'att-001', + 'filename': 'order.txt', + 'parse_status': 'parsed', + 'extracted_text': 'SECRET-ATTACHMENT-TEXT', + 'text_length': 22, + 'stored_text_length': 22, + } + ], + 'warnings': [], + }, + expires_at=datetime.utcnow() + timedelta(hours=24), + ) + db.session.add(intake) + db.session.commit() + + status_res = client.post( + '/api/workspace/shipping-notice/intakes/status', + json={'intake_nos': ['SNI-EML-API-001']}, + headers=owner_headers, + ) + assert status_res.status_code == 200 + status_payload = status_res.get_json() + assert status_payload['success'] is True + item = status_payload['data']['items'][0] + summary = item['parse_summary'] + assert 'extracted_text' not in (summary.get('attachments') or [{}])[0] + assert 'body_text' not in (summary.get('email') or {}) + + detail_res = client.get( + '/api/workspace/shipping-notice/intakes/SNI-EML-API-001', + headers=owner_headers, + ) + assert detail_res.status_code == 200 + detail = detail_res.get_json()['data'] + detail_summary = detail['parse_summary'] + assert detail_summary['email']['body_text'] == 'SECRET-BODY-TEXT' + assert detail_summary['attachments'][0]['extracted_text'] == 'SECRET-ATTACHMENT-TEXT' + + forbidden = client.get( + '/api/workspace/shipping-notice/intakes/SNI-EML-API-001', + headers=other_headers, + ) + assert forbidden.status_code in {403, 404} + assert forbidden.get_json().get('success') is False + # 避免未使用变量告警 + assert other_id != owner_id + + def test_ensure_default_file_asset_cleanup_schedule(app, shipping_user): """有用户时可幂等补建默认 TTL 清理排程。""" with app.app_context(): @@ -475,3 +2704,1226 @@ def test_user_insert_hook_seeds_cleanup_schedule(app): assert expected is not None # 钩子执行时刻与断言时刻可能跨整点边界,允许在同一小时窗口内 assert abs((task.next_run_at - expected).total_seconds()) < 3700 + + +def _minimal_pdf_bytes(marker: str) -> bytes: + """构造含可见文本的最小 PDF(与 extract 测试口径一致)。""" + safe = str(marker).replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)') + stream = f'BT /F1 24 Tf 72 720 Td ({safe}) Tj ET'.encode('latin-1') + objects = [ + b'1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n', + b'2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n', + ( + b'3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] ' + b'/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n' + ), + f'4 0 obj<< /Length {len(stream)} >>stream\n'.encode('latin-1') + + stream + + b'\nendstream\nendobj\n', + b'5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n', + ] + out = bytearray(b'%PDF-1.4\n') + offsets = [0] + for obj in objects: + offsets.append(len(out)) + out.extend(obj) + xref_pos = len(out) + out.extend(f'xref\n0 {len(offsets)}\n'.encode('latin-1')) + out.extend(b'0000000000 65535 f \n') + for off in offsets[1:]: + out.extend(f'{off:010d} 00000 n \n'.encode('latin-1')) + out.extend( + f'trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n'.encode( + 'latin-1' + ) + ) + return bytes(out) + + +def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets( + app, shipping_user, monkeypatch, +): + """ + 阶段二验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document + 3 Candidate; + 正文订单表不额外生成第 4 候选;各 PDF 独立 FileAsset;重试不膨胀。 + """ + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.intake_service import serialize_intake + + markers = ('4510039227', '4510039228', '4510039229') + msg = EmailMessage() + msg['Subject'] = 'PO 4510039227, 4510039228, 4510039229' + msg['From'] = 'laszlo.fussy@example.com' + msg['To'] = 'freight@example.com' + msg['Message-ID'] = '' + msg.set_content( + 'Please find POs attached.\n' + 'PO Number: 4510039227 qty 10\n' + 'PO Number: 4510039228 qty 20\n' + 'PO Number: 4510039229 qty 30\n' + ) + for po in markers: + msg.add_attachment( + _minimal_pdf_bytes(f'PO Number: {po} SKU-A qty 1'), + maintype='application', + subtype='pdf', + filename=f'{po}.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='three-po.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-3PDF', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _asset: eml_bytes, + ) + + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + first = run_intake_parse(intake, parent) + assert first['status'] == 'parsed' + db.session.expire_all() + refreshed_intake = ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-STAGE2-3PDF') + .one() + ) + persist_warns = [ + str(w) + for w in (refreshed_intake.parse_warnings_json or []) + if str(w).startswith('document_candidate_persist_failed') + ] + assert not persist_warns, persist_warns + assert first.get('document_count') == 4, first + docs = ( + db.session.query(ShippingNoticeDocument) + .filter_by(intake_id=refreshed_intake.id) + .order_by(ShippingNoticeDocument.id.asc()) + .all() + ) + cands = ( + db.session.query(ShippingNoticeCandidate) + .filter_by(intake_id=refreshed_intake.id) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + children = ( + db.session.query(FileAsset) + .filter( + FileAsset.parent_asset_id == parent.id, + FileAsset.deleted_at.is_(None), + ) + .all() + ) + + assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json) + body_docs = [d for d in docs if d.document_type == 'email_body'] + assert len(body_docs) == 1 + assert body_docs[0].classification == 'email_context' + pdf_docs = [d for d in docs if d.document_type == 'attachment'] + assert len(pdf_docs) == 3 + assert all(d.classification == 'order_notice' for d in pdf_docs) + assert all(d.asset_id for d in pdf_docs) + assert len(cands) == 3 + assert all(c.primary_document_id != body_docs[0].id for c in cands) + assert len(children) == 3 + assert len({c.content_hash for c in children}) == 3 + + detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True) + assert detail['document_count'] == 4 + assert detail['candidate_count'] == 3 + + intake2 = ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-STAGE2-3PDF') + .one() + ) + intake2.parse_status = 'parsing' + db.session.commit() + second = run_intake_parse(intake2, parent) + assert second['status'] == 'parsed' + db.session.expire_all() + intake_id = ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-STAGE2-3PDF') + .one() + .id + ) + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4 + assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 3 + assert ( + db.session.query(FileAsset) + .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None)) + .count() + == 3 + ) + + +def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate( + app, shipping_user, monkeypatch, +): + """无 PO/行项目的 PDF 仅落 Document(supporting),不伪造 Candidate。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + + msg = EmailMessage() + msg['Subject'] = 'Packing list only' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('See packing list.') + msg.add_attachment( + _minimal_pdf_bytes('This is packing list page 1'), + maintype='application', + subtype='pdf', + filename='packing.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='packing.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-SUPPORT', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, parent) + assert result['status'] == 'parsed' + att = ( + db.session.query(ShippingNoticeDocument) + .filter_by(intake_id=intake.id, document_type='attachment') + .one() + ) + assert att.classification == 'supporting' + assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake.id).count() == 0 + + +def test_stage2_persist_failure_marks_parse_failed_and_allows_retry( + app, shipping_user, monkeypatch, +): + """阶段二持久化失败须 parse_failed,且可 retry_intake_parse。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.intake_service import retry_intake_parse + + msg = EmailMessage() + msg['Subject'] = 'fail stage2' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('body') + msg.add_attachment( + _minimal_pdf_bytes('PO Number: 999001'), + maintype='application', + subtype='pdf', + filename='one.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='fail.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-FAIL', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', + lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')), + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, parent) + assert result['status'] == 'parse_failed' + db.session.expire_all() + failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one() + assert failed.parse_status == 'parse_failed' + assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED' + + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777): + retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL') + assert retried['parse_status'] == 'queued' + + +def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked( + app, shipping_user, monkeypatch, +): + """Candidate 重复检测异常仅 SAVEPOINT 回滚:Document/Candidate 保留,去重为 unchecked。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + + msg = EmailMessage() + msg['Subject'] = 'dedup savepoint' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('body') + msg.add_attachment( + _minimal_pdf_bytes('PO Number: DEDUPSP001\nSKU: X qty 1'), + maintype='application', + subtype='pdf', + filename='order.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='dedup-sp.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-DEDUP-SAVEPOINT', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake', + lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-candidate-dedup')), + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, parent) + assert result['status'] == 'parsed' + assert result.get('duplicate_status') == 'unchecked' + db.session.expire_all() + refreshed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-DEDUP-SAVEPOINT' + ).one() + assert refreshed.parse_status == 'parsed' + assert refreshed.duplicate_status == 'unchecked' + assert refreshed.duplicate_matches_json in (None, []) + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=refreshed.id).count() >= 1 + assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() >= 1 + + +def test_stage2_fail_cleanup_clears_prior_duplicate_resolution( + app, shipping_user, monkeypatch, +): + """阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.intake_service import serialize_intake + + msg = EmailMessage() + msg['Subject'] = 'fail clear dup' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('body') + msg.add_attachment( + _minimal_pdf_bytes('PO Number: FAILCLEARDUP1\nSKU: X qty 1'), + maintype='application', + subtype='pdf', + filename='one.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='fail-clear-dup.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-CLEAR-DUP', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + duplicate_status='soft_duplicate', + duplicate_matches_json=[{'task_no': 'ST-OLD', 'match_type': 'po_number'}], + business_fingerprint='fp-old', + fingerprint_version='shipping-v1', + fingerprint_strength='strong', + duplicate_resolution='force_create', + duplicate_resolution_reason='prev', + duplicate_target_task_no='ST-OLD', + duplicate_resolved_at=datetime.utcnow(), + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', + lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-clear-dup')), + ) + intake.parse_status = 'parsing' + db.session.commit() + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, parent) + assert result['status'] == 'parse_failed' + db.session.expire_all() + failed = db.session.query(ShippingNoticeIntake).filter_by( + intake_no='SNI-STAGE2-CLEAR-DUP' + ).one() + assert failed.parse_status == 'parse_failed' + assert failed.duplicate_status == 'unchecked' + assert failed.duplicate_matches_json in (None, []) + assert failed.business_fingerprint is None + assert failed.fingerprint_version is None + assert failed.fingerprint_strength is None + assert failed.duplicate_resolution is None + assert failed.duplicate_resolution_reason is None + assert failed.duplicate_target_task_no is None + assert failed.duplicate_resolved_at is None + payload = serialize_intake(failed, asset=parent) + dup = payload.get('duplicate') or {} + assert (dup.get('matches') or []) == [] + assert payload.get('duplicate_resolution') is None + + +def test_derived_asset_refcount_increments_per_document_link(app, shipping_user): + """多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。""" + from app.services.shipping_notice.document_candidate_persist import _upsert_document + + with app.app_context(): + parents = [] + for suffix in ('A', 'B'): + parent = FileAsset( + asset_no=f'FA-REF-PARENT-{suffix}', + owner_user_id=shipping_user.id, + original_filename=f'root-{suffix}.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/ref/parent-{suffix}.eml', + content_hash=f'parenthash-{suffix}', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + parents.append(parent) + db.session.flush() + child = FileAsset( + asset_no='FA-REF-CHILD', + owner_user_id=shipping_user.id, + parent_asset_id=parents[0].id, + asset_role='derived_attachment', + source_attachment_key='att-a', + original_filename='a.pdf', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/ref/a.pdf', + content_hash='samehash', + file_size=20, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(child) + db.session.flush() + intakes = [] + for idx, suffix in enumerate(('A', 'B')): + intake = ShippingNoticeIntake( + intake_no=f'SNI-REF-{suffix}', + asset_id=parents[idx].id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + ) + db.session.add(intake) + intakes.append(intake) + db.session.commit() + + _upsert_document( + intake=intakes[0], + attachment_key='att-a', + document_type='attachment', + filename='a.pdf', + content_hash='samehash', + parse_status='parsed', + extracted_text='PO Number: 1', + warnings=[], + asset_id=int(child.id), + classification='order_notice', + ) + _upsert_document( + intake=intakes[1], + attachment_key='att-a', + document_type='attachment', + filename='a.pdf', + content_hash='samehash', + parse_status='parsed', + extracted_text='PO Number: 1', + warnings=[], + asset_id=int(child.id), + classification='order_notice', + ) + db.session.commit() + db.session.refresh(child) + assert int(child.reference_count or 0) == 2 + assert child.lifecycle_status == 'referenced' + + _upsert_document( + intake=intakes[0], + attachment_key='att-a', + document_type='attachment', + filename='a.pdf', + content_hash='samehash', + parse_status='parsed', + extracted_text='PO Number: 1', + warnings=[], + asset_id=None, + classification='supporting', + ) + db.session.commit() + db.session.refresh(child) + assert int(child.reference_count or 0) == 1 + assert child.lifecycle_status == 'referenced' + + +def test_soft_deleted_derived_asset_can_be_revived(app, shipping_user): + """软删除派生资产后同哈希应可复活,不被全量唯一约束永久挡死。""" + from datetime import datetime + + from app.services.file_assets.service import create_derived_file_asset_from_bytes + + with app.app_context(): + parent = FileAsset( + asset_no='FA-REVIVE-PARENT', + owner_user_id=shipping_user.id, + original_filename='root.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/revive/parent.eml', + content_hash='revive-parent', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + payload = b'%PDF-1.4 revive-payload' + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + child, created = create_derived_file_asset_from_bytes( + user_id=shipping_user.id, + parent=parent, + data=payload, + filename='revive.pdf', + mime_type='application/pdf', + source_attachment_key='att-1', + ) + assert created is True + child.deleted_at = datetime.utcnow() + child.lifecycle_status = 'expired' + child.reference_count = 0 + db.session.commit() + revived, created_again = create_derived_file_asset_from_bytes( + user_id=shipping_user.id, + parent=parent, + data=payload, + filename='revive.pdf', + mime_type='application/pdf', + source_attachment_key='att-1', + ) + assert created_again is False + assert revived.id == child.id + assert revived.deleted_at is None + assert revived.upload_status == 'ready' + + +def test_reuse_derived_asset_keeps_first_source_attachment_key(app, shipping_user): + """同哈希复用时 source_attachment_key 保持首次来源键,不被后续 att-key 覆盖。""" + from app.services.file_assets.service import create_derived_file_asset_from_bytes + + with app.app_context(): + parent = FileAsset( + asset_no='FA-KEY-PARENT', + owner_user_id=shipping_user.id, + original_filename='root.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/key/parent.eml', + content_hash='key-parent', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + db.session.commit() + payload = b'%PDF-1.4 shared-key-payload' + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + first, created = create_derived_file_asset_from_bytes( + user_id=shipping_user.id, + parent=parent, + data=payload, + filename='shared.pdf', + mime_type='application/pdf', + source_attachment_key='att-001', + ) + assert created is True + second, created_again = create_derived_file_asset_from_bytes( + user_id=shipping_user.id, + parent=parent, + data=payload, + filename='shared.pdf', + mime_type='application/pdf', + source_attachment_key='att-009', + ) + assert created_again is False + assert second.id == first.id + assert second.source_attachment_key == 'att-001' + + +def test_compensate_orphan_persist_failure_rollbacks_caller_session(app, shipping_user): + """orphan 台账写入失败后须 rollback,调用方 Session 不应卡在 failed。""" + from app.services.file_assets.service import compensate_uploaded_storage_keys + + with app.app_context(): + with patch( + 'app.services.file_assets.service.file_asset_storage.delete_object', + side_effect=RuntimeError('minio down'), + ), patch( + 'app.services.file_assets.service._persist_orphan_storage_key_for_cleanup', + side_effect=RuntimeError('orphan write failed'), + ): + compensate_uploaded_storage_keys( + ['temporary/orphan-fail-session.bin'], + owner_user_id=shipping_user.id, + ) + # Session 已恢复:可正常查询,不会 PendingRollbackError + assert db.session.query(FileAsset).count() >= 0 + + +def test_mark_and_release_asset_reference_are_atomic(app, shipping_user): + """引用计数须走原子 UPDATE,并发读改写不能丢增减。""" + from app.services.file_assets.service import mark_asset_referenced, release_asset_reference + + with app.app_context(): + asset = FileAsset( + asset_no='FA-ATOMIC-REF', + owner_user_id=shipping_user.id, + parent_asset_id=None, + asset_role='derived_attachment', + original_filename='a.pdf', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/atomic/a.pdf', + content_hash='atomic-hash', + file_size=10, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(asset) + db.session.commit() + + mark_asset_referenced(asset) + mark_asset_referenced(asset) + db.session.commit() + db.session.refresh(asset) + assert int(asset.reference_count or 0) == 2 + assert asset.lifecycle_status == 'referenced' + + release_asset_reference(asset) + db.session.commit() + db.session.refresh(asset) + assert int(asset.reference_count or 0) == 1 + assert asset.lifecycle_status == 'referenced' + + release_asset_reference(asset) + db.session.commit() + db.session.refresh(asset) + assert int(asset.reference_count or 0) == 0 + assert asset.lifecycle_status == 'temporary' + + +def test_cancel_intake_is_idempotent_and_clears_stage2_projection(app, shipping_user): + """二次取消不得再释放引用;并清理 parse_summary 阶段二投影。""" + from app.services.file_assets.service import mark_asset_referenced + from app.services.shipping_notice.intake_service import cancel_intake + + with app.app_context(): + parent = FileAsset( + asset_no='FA-CANCEL-IDEMP-PARENT', + owner_user_id=shipping_user.id, + original_filename='c.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/cancel-idemp/parent.eml', + content_hash='cancel-idemp-parent', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + child = FileAsset( + asset_no='FA-CANCEL-IDEMP-CHILD', + owner_user_id=shipping_user.id, + parent_asset_id=parent.id, + asset_role='derived_attachment', + original_filename='c.pdf', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/cancel-idemp/c.pdf', + content_hash='cancel-idemp-child', + file_size=20, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(child) + db.session.flush() + mark_asset_referenced(child) + intake = ShippingNoticeIntake( + intake_no='SNI-CANCEL-IDEMP', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + structured_result_json={ + 'document_count': 2, + 'candidate_count': 1, + 'attachments': [ + { + 'attachment_key': 'att-001', + 'filename': 'c.pdf', + 'asset_no': child.asset_no, + 'document_id': 99, + } + ], + }, + ) + db.session.add(intake) + db.session.flush() + doc = ShippingNoticeDocument( + intake_id=intake.id, + attachment_key='att-001', + document_type='attachment', + filename='c.pdf', + asset_id=child.id, + classification='order_notice', + parse_status='parsed', + ) + db.session.add(doc) + db.session.commit() + + cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP') + cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP') + db.session.expire_all() + child2 = db.session.get(FileAsset, child.id) + intake2 = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-CANCEL-IDEMP').one() + assert int(child2.reference_count or 0) == 0 + assert intake2.parse_status == 'cancelled' + summary = intake2.structured_result_json or {} + assert 'document_count' not in summary + assert 'candidate_count' not in summary + att0 = (summary.get('attachments') or [{}])[0] + assert 'asset_no' not in att0 + assert 'document_id' not in att0 + + +def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeypatch): + """文本抽取失败写 parse_failed 时须清理上一轮 Document/Candidate。""" + from app.services.file_assets.service import mark_asset_referenced + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + with app.app_context(): + parent = FileAsset( + asset_no='FA-EXTRACT-CLEAR', + owner_user_id=shipping_user.id, + original_filename='clear.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/extract-clear.eml', + content_hash='extract-clear', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + child = FileAsset( + asset_no='FA-EXTRACT-CLEAR-CHILD', + owner_user_id=shipping_user.id, + parent_asset_id=parent.id, + asset_role='derived_attachment', + original_filename='old.pdf', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/extract-clear/old.pdf', + content_hash='extract-clear-child', + file_size=20, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(child) + db.session.flush() + mark_asset_referenced(child) + intake = ShippingNoticeIntake( + intake_no='SNI-EXTRACT-CLEAR', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + structured_result_json={ + 'document_count': 1, + 'candidate_count': 1, + 'attachments': [{'attachment_key': 'att-001', 'document_id': 1, 'asset_no': child.asset_no}], + }, + ) + db.session.add(intake) + db.session.flush() + doc = ShippingNoticeDocument( + intake_id=intake.id, + attachment_key='att-001', + document_type='attachment', + filename='old.pdf', + asset_id=child.id, + classification='order_notice', + parse_status='parsed', + ) + db.session.add(doc) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', + lambda _a: NoticeIntakeResult( + filename='clear.eml', + source_type='email', + source_file_type='message/rfc822', + text='', + warnings=['extract exploded'], + meta={}, + content_hash=parent.content_hash, + file_size=10, + status='extract_failed', + saved_path=None, + ), + ) + result = run_intake_parse(intake, parent) + assert result['status'] == 'parse_failed' + db.session.expire_all() + failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-EXTRACT-CLEAR').one() + assert failed.parse_status == 'parse_failed' + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0 + child2 = db.session.get(FileAsset, child.id) + assert int(child2.reference_count or 0) == 0 + summary = failed.structured_result_json or {} + assert 'document_count' not in summary + + +def test_retry_parse_rejects_cancelled_intake(app, shipping_user): + """已取消 Intake 不得被重试覆盖回 queued。""" + from app.services.shipping_notice.intake_service import retry_intake_parse + + with app.app_context(): + parent = FileAsset( + asset_no='FA-RETRY-CANCELLED', + owner_user_id=shipping_user.id, + original_filename='r.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/retry-cancelled.eml', + content_hash='retry-cancelled', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-RETRY-CANCELLED', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='cancelled', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + with pytest.raises(ConflictError) as excinfo: + retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-RETRY-CANCELLED') + assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS' + db.session.expire_all() + assert ( + db.session.query(ShippingNoticeIntake) + .filter_by(intake_no='SNI-RETRY-CANCELLED') + .one() + .parse_status + == 'cancelled' + ) + + +def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch): + """阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + + msg = EmailMessage() + msg['Subject'] = 'fail after cancel' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('body') + msg.add_attachment( + _minimal_pdf_bytes('PO Number: CANCELLOCK001'), + maintype='application', + subtype='pdf', + filename='lock.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='lock.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-FAIL-CANCELLED', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.flush() + doc = ShippingNoticeDocument( + intake_id=intake.id, + attachment_key='att-001', + document_type='attachment', + filename='lock.pdf', + classification='supporting', + parse_status='parsed', + ) + db.session.add(doc) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + + def _boom_then_cancel(**kwargs): + # 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled + row = db.session.get(ShippingNoticeIntake, intake.id) + row.parse_status = 'cancelled' + db.session.commit() + raise RuntimeError('boom-after-cancel') + + monkeypatch.setattr( + 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', + _boom_then_cancel, + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, parent) + assert result['status'] == 'skipped' + db.session.expire_all() + final = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one() + assert final.parse_status == 'cancelled' + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=final.id).count() == 1 + + +def test_refresh_duplicate_rejects_cancelled_intake(app, shipping_user): + """重复刷新持锁后发现已取消须拒绝,不得改写 Candidate。""" + from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection + + with app.app_context(): + parent = FileAsset( + asset_no='FA-REFRESH-CANCELLED', + owner_user_id=shipping_user.id, + original_filename='x.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{shipping_user.id}/refresh-cancelled.eml', + content_hash='refresh-cancelled', + file_size=10, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + asset_role='upload', + ) + db.session.add(parent) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-REFRESH-CANCELLED', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='cancelled', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + with pytest.raises(ConflictError) as excinfo: + refresh_intake_duplicate_detection( + user_id=shipping_user.id, + intake_no='SNI-REFRESH-CANCELLED', + ) + assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS' + + +def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch): + """阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.intake_service import serialize_intake + + msg = EmailMessage() + msg['Subject'] = 'retry clear' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('body') + msg.add_attachment( + _minimal_pdf_bytes('PO Number: RETRYCLEAR001\nSKU: X qty 1'), + maintype='application', + subtype='pdf', + filename='retry.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='retry-clear.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-RETRY-CLEAR', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + first = run_intake_parse(intake, parent) + assert first['status'] == 'parsed' + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() >= 1 + + intake.parse_status = 'parsing' + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', + lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')), + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + second = run_intake_parse(intake, parent) + assert second['status'] == 'parse_failed' + db.session.expire_all() + failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one() + assert failed.parse_status == 'parse_failed' + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0 + assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=failed.id).count() == 0 + payload = serialize_intake(failed, asset=parent) + assert payload['document_count'] == 0 + assert payload['candidate_count'] == 0 + + +def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch): + """解析完成后取消须删除 Document/Candidate 并归零派生资产引用。""" + from email.message import EmailMessage + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.intake_service import cancel_intake + + msg = EmailMessage() + msg['Subject'] = 'cancel after parse' + msg['From'] = 'a@b.com' + msg['To'] = 'c@d.com' + msg.set_content('body') + msg.add_attachment( + _minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'), + maintype='application', + subtype='pdf', + filename='cancel.pdf', + ) + eml_bytes = msg.as_bytes() + + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), + filename='cancel.eml', + content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-STAGE2-CANCEL', + asset_id=parent.id, + user_id=shipping_user.id, + purpose='shipping_notice', + parse_status='parsing', + parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _a: eml_bytes, + ) + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = run_intake_parse(intake, parent) + assert result['status'] == 'parsed' + derived = ( + db.session.query(FileAsset) + .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None)) + .one() + ) + assert int(derived.reference_count or 0) >= 1 + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() >= 1 + + cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL') + db.session.expire_all() + cancelled = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one() + assert cancelled.parse_status == 'cancelled' + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=cancelled.id).count() == 0 + assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=cancelled.id).count() == 0 + derived2 = db.session.get(FileAsset, derived.id) + assert int(derived2.reference_count or 0) == 0 + assert derived2.lifecycle_status == 'temporary' + + +def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user): + """补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。""" + from app.services.file_assets.service import compensate_uploaded_storage_keys + + with app.app_context(): + with patch( + 'app.services.file_assets.service.file_asset_storage.delete_object', + side_effect=RuntimeError('minio down'), + ): + compensate_uploaded_storage_keys( + ['temporary/orphan-key-for-test.bin'], + owner_user_id=shipping_user.id, + storage_bucket='hxops-file-assets', + ) + orphan = ( + db.session.query(FileAsset) + .filter_by(asset_role='orphan_cleanup', storage_key='temporary/orphan-key-for-test.bin') + .one() + ) + assert orphan.lifecycle_status == 'expired' + assert int(orphan.reference_count or 0) == 0 + assert orphan.deleted_at is None diff --git a/backend/tests/test_shipping_notice_inventory_source_gate.py b/backend/tests/test_shipping_notice_inventory_source_gate.py index 037b8e08..01034add 100644 --- a/backend/tests/test_shipping_notice_inventory_source_gate.py +++ b/backend/tests/test_shipping_notice_inventory_source_gate.py @@ -495,7 +495,7 @@ def test_crane_user_confirm_and_gate_stable(app): @pytest.mark.inventory_source_gate def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch): - """低置信度 + 未命中库存源:先确认库存源,再确认解析,最后才能进入库存准备。""" + """低置信度 + 未命中库存源:先确认解析,再确认库存源,最后才能进入库存准备。""" monkeypatch.setattr( "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", lambda *args, **kwargs: None, @@ -514,6 +514,61 @@ def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch): task_no="SN-GATE-LOW-CONF-SEQ", source_type="pdf", process_status="pending_review", + pending_human_reason=PH_LOW_CONF, + review_status="parse_review", + parse_confidence=0.4, + ship_to="UnknownCity", + lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}], + inventory_source_status="unresolved", + ) + db.session.add(task) + db.session.commit() + + parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) + db.session.refresh(task) + assert parse_result["status"] in {"ok", "needs_human"} + assert parse_result.get("checkpoint") == "inventory_source_review" + assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED + assert not is_inventory_source_stable(task) + option_ids = parse_result.get("human_options") or [ + item.get("id") for item in (parse_result.get("action_buttons") or []) + ] + assert "reparse" not in option_ids + assert "confirm_inventory_source" in option_ids + + source_result = confirm_inventory_source({ + "task_id": task.task_no, + "source_code": "DSV360_AWSDU", + "_trusted_user_id": 11, + }) + db.session.refresh(task) + assert source_result["status"] in {"ok", "running"} + assert is_inventory_source_stable(task) + assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED + assert task.pending_human_reason != PH_LOW_CONF + + +@pytest.mark.inventory_source_gate +def test_legacy_pending_parse_review_after_source_compat(app, monkeypatch): + """存量任务:先库存源后解析的延后标记仍可走完兼容路径。""" + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled", + lambda: False, + ) + monkeypatch.setattr( + "app.services.shipping_notice.decision_workflow.start_task_orchestrator", + lambda task_no: False, + ) + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-LEGACY-PARSE-AFTER-SOURCE", + source_type="pdf", + process_status="pending_review", pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, review_status="parse_review", parse_confidence=0.4, @@ -545,6 +600,90 @@ def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch): assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED +@pytest.mark.inventory_source_gate +def test_parse_notice_high_confidence_unresolved_source_goes_to_source_review(app, client): + """高置信度解析自动通过后,库存源未命中应直接进入 inventory_source_review。""" + from tests.test_shipping_notice_tools import _tool_headers + + headers = _tool_headers(app) + create_res = client.post( + "/api/shipping-notice/tools/create_task", + headers=headers, + json={"source_type": "manual"}, + ) + task_id = create_res.get_json()["task_id"] + + parse_res = client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "ACME", + "ship_to": "Mystery Port", + "lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + parse_data = parse_res.get_json() + assert parse_data["status"] == "needs_human" + assert parse_data.get("checkpoint") == "inventory_source_review" + button_ids = [item.get("id") for item in (parse_data.get("action_buttons") or [])] + assert "confirm_inventory_source" in button_ids + assert "reparse" not in button_ids + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).first() + assert task is not None + assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED + assert not is_inventory_source_stable(task) + + +@pytest.mark.inventory_source_gate +def test_parse_notice_low_confidence_unresolved_source_goes_to_parse_review(app, client): + """低置信度 + 库存源未命中:应先进入 parse_review(含重新解析),而非抢先确认库存源。""" + from app.services.shipping_notice.state_machine import human_options_for_task + from tests.test_shipping_notice_tools import _tool_headers + + headers = _tool_headers(app) + create_res = client.post( + "/api/shipping-notice/tools/create_task", + headers=headers, + json={"source_type": "manual"}, + ) + task_id = create_res.get_json()["task_id"] + + parse_res = client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "ACME", + "ship_to": "Mystery Port", + "lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}], + "confidence": 0.4, + }, + }, + ) + parse_data = parse_res.get_json() + assert parse_data["status"] == "needs_human" + assert parse_data.get("checkpoint") == "parse_review" + assert "重新解析" in (parse_data.get("message") or "") or "置信度" in (parse_data.get("message") or "") + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).first() + assert task is not None + assert task.pending_human_reason == PH_LOW_CONF + assert task.review_status == "parse_review" + options = human_options_for_task(task) or [] + assert "reparse" in options + assert "confirm" in options + assert "confirm_inventory_source" not in options + assert "解析确认通过后" in (parse_data.get("message") or "") + + @pytest.mark.inventory_source_gate def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch): """人工上传身份绑定失败时不应遗留库存文件或数据库记录。""" diff --git a/docs/features/shipping-notice/inventory_source_plan.md b/docs/features/shipping-notice/inventory_source_plan.md index 48c5e303..cd142568 100644 --- a/docs/features/shipping-notice/inventory_source_plan.md +++ b/docs/features/shipping-notice/inventory_source_plan.md @@ -18,10 +18,11 @@ ### 何时判定 -1. **`parse_notice`**:解析结构化订单后,立即调用 `adjudicate_inventory_source()`。 -2. 唯一命中且配置完整 → `inventory_source_status=resolved`,任务可进入 `parsed`。 -3. 未命中 / 多命中 / 配置无效 / 路由指纹变更 → `pending_review`,`current_step=step2_parse_confirm`,`checkpoint=inventory_source_review`,`pending_human_reason=inventory_source_unresolved`。 -4. 用户在聊天区确认 `source_code` → `confirm_inventory_source` → `inventory_source_status=user_confirmed`,再推进至 `parsed` 并允许 RPA。 +1. **`parse_notice`**:解析结构化订单后,立即调用 `adjudicate_inventory_source()` 抽取/写入库存源**线索与候选**(不抢解析人工确认)。 +2. **低置信度**:先进入 `checkpoint=parse_review`(确认 / 重新解析 / 驳回);解析通过后再看库存源是否稳定。 +3. **高置信度且唯一命中且配置完整** → `inventory_source_status=resolved`,任务可进入 `parsed`。 +4. **解析已接受但未命中 / 多命中 / 配置无效 / 路由指纹变更** → `pending_review`,`checkpoint=inventory_source_review`,`pending_human_reason=inventory_source_unresolved`。 +5. 用户在聊天区确认 `source_code` → `confirm_inventory_source` → `inventory_source_status=user_confirmed`,再推进至 `parsed` 并允许 RPA。 ### 稳定状态 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index fe4f04a6..a92795aa 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -8,6 +8,132 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、OpenAPI、多文件批次解析、自动上传与 Agent 指令合集。 +### 第三阶段:业务去重与任务版本(实现摘要) + +- **文件哈希去重**(FileAsset / notice `content_hash`)与 **业务指纹去重**(`shipping-v1`:客户码/PO/Reservation/行 digest)分层独立;建单幂等键、货代上传幂等键语义不变。 +- Intake 预解析完成后写入 `business_summary`、指纹与 `duplicate_status`;与 `parse_status` 正交。 +- 阻断型重复须先 `POST .../intakes/{intake_no}/duplicate-resolution`(`open_existing` / `create_revision` / `force_create`),再确认建单;建单事务内重校检测结果。 +- 修订创建新 `ShippingTask`:`supersedes_task_id` + `document_version+1`;已 `uploaded` 任务禁止原地覆盖;`force_create` 需 `admin` 或 `shipping_notice_force_create` 与原因,审计事件走 `ShippingTaskEvent`。 + +### 附件资产化与订单候选(阶段二) + +> 本阶段在阶段一文本抽取之上,把附件升级为派生 FileAsset + Document,并识别订单 Candidate;**仍不**正式创建多个 Task。 + +| 项 | 说明 | +| --- | --- | +| 派生资产 | EML 根 `FileAsset` → 子资产(`parent_asset_id` / `asset_role=derived_attachment`);SHA-256 幂等;`source_attachment_key` 为首次来源键(复用不覆盖),当前来源以 Document.attachment_key 为准 | +| 引用计数 | Document↔派生资产按关联边原子 `±1`;多 Document 共用同一子资产可正确归零回收;`cancel_intake` 行锁幂等清理并剥离摘要投影 | +| 锁顺序 | 解析成功/失败清理、重复刷新、重试入队均先 `FOR UPDATE` Intake,再碰 Document/资产,与 cancel 同序防死锁;阶段二+parsed+去重同事务 | +| 重试入队 | 仅复用 `queued` Job(不复用 `running`);`enqueue(commit=False)` 与 Intake.queued/`parse_job_id` 同事务提交 | +| 去重降级 | 阶段二先落 Document/Candidate 基础行;Candidate+Intake 重复检测在 SAVEPOINT;异常清空为 `unchecked`,不打挂阶段二 | +| 失败清空 | 阶段二失败清理复用 `clear_duplicate_state_to_unchecked`,去掉 matches/指纹/决策残留 | +| 资产缺失 | 领取后失败统一 `fail_intake_with_stage2_cleanup`;Job `retryable=False` 且不再抛出,外层仅 `running` 才 fail | +| 超时回收 | `FOR UPDATE SKIP LOCKED` + `status/attempts` 条件 UPDATE;同事务清空 `parse_lease` 并 `parsing→queued/parse_failed`;替代者须 `FOR UPDATE`:仅 `queued`,或 running 且 Intake 已持精确 `parse_job_id+parse_lease`,禁止向未接管的 running 伪造 lease | +| 失败收口 | `fail_job` requeue 清空 `started_at`;claim 刷新 `started_at`;终态 failed/cancelled 同步 Intake 离开 `parsing`;唯一冲突窗口消失时保持 running 而非强行 failed | +| 创建终态 | `cancelled`/`expired`(含 `expires_at` 到期)拒绝再次创建,与 `retry_intake_parse` 一致;仅 `created`/`parse_failed` 可重投;重投仅复用 `queued` Job | +| 执行代次 | Intake `parse_lease="{job_id}:{attempts}"`;Job `finish/fail` 条件 UPDATE(禁止 Session 缓存判断拥有权) | +| 原子入队 | 初次创建与重试均 `enqueue(commit=False)`,同事务提交 Intake/`parse_job_id`/Job,禁止半绑定窗口 | +| 创建幂等 | Intake 创建 FOR UPDATE + SAVEPOINT/IntegrityError 回落;`enqueue` 仅在 SAVEPOINT 内 `add+flush`,避免冲突毒化外层事务 | +| queued 唯一 | `shipping_notice_parse` 仅允许一条 queued;旧 running 失败/超时回收撞唯一时→`cancelled` 并重指 Intake,禁止永久卡 `running` | +| 软删除唯一 | `(parent_asset_id, content_hash)` 为 **partial unique**(`deleted_at IS NULL`);清理后同哈希可复活/重建;迁移去重行转 `orphan_cleanup` 供 MinIO 回收 | +| 重复刷新 | `refresh_intake_duplicate_detection` 逐 Candidate 重检再聚合 Intake;避免仅更新概览导致候选状态陈旧 | +| Document | `ShippingNoticeDocument`:`body` + 各附件一行;详情/轮询经 Intake 序列化返回 | +| Candidate | 仅附件/单文件在抽到真实 PO/Reservation/行项目时生成;**正文永不生成 Candidate**(`email_context`) | +| 分类 | 无业务信号的 PDF 等为 `supporting` Document,禁止伪造 PO/SKU | +| 失败与重试 | 阶段二持久化失败 → `parse_failed`(可重试);与文本抽取成功解耦后不再静默 `parsed` | +| 并发 | Job 原子领取 `parsing`;派生资产部分唯一 + IntegrityError 回查;补偿删 MinIO 失败写 `orphan_cleanup` 行供定时回收 | +| 重复隔离 | 候选 A 重复只阻断 A;Intake 概览可为 `partial_duplicate` | +| 重试幂等 | `(parent, content_hash)` / `(intake, attachment_key)` / `(intake, primary_document_id)`;失效 Candidate 按本轮主文档集清理 | +| 解析器版本 | 默认 `SHIPPING_NOTICE_PARSER_VERSION=v6`(相对 v5:落库 Document/Candidate/派生资产) | +| 建单 | `ShippingTask.source_candidate_id` 预留;本阶段结束仍不按 Candidate 建 Task | + +实现入口:`document_candidate_persist.persist_documents_and_candidates` ← `intake_parse_workflow.run_intake_parse`;派生创建:`file_assets.service.create_derived_file_asset_from_bytes`。 + +### EML 附件提取(阶段一) + +> 本阶段只保证「能看到并解析附件」,**不**把多附件拆成多个 Task。 + +#### 能力边界 + +| 项 | 说明 | +| --- | --- | +| 邮件元数据 | `message_id` / `subject` / `from` / `to` / `date`(ISO) | +| 正文 | 优先 `text/plain`,否则清洗后的 `text/html`(去 script/style/标签,**不执行**脚本) | +| 真实附件 | `Content-Disposition: attachment`、带文件名的非正文部件;对 PDF/DOCX/CSV/图片/文本等复用 `extract_notice_text` | +| 内嵌资源 | 仅跳过 **图片** 类 `inline` / `Content-ID` / 文件名像 logo·signature 的图片;`inline` PDF 等仍视为真实附件 | +| 嵌套邮件 | 支持 `message/rfc822`、**.eml 文件附件**与 **disposition=attachment 的 multipart/***(如 `bundle.mime`):共享 attachments/限额/哈希;深度从当前层累加;成功容器须登记独立附件行;`multipart/mixed` 内独立 plain/html 段全部保留,`multipart/alternative` 仍 plain 优先;外层 `body_text` **不穿透** rfc822 / 附件型 multipart;**总大小计费**:顶层容器计入配额,展开子内容不计费;超限/超深登记 `skipped` 行 | +| 文本附件 | 带 `filename`/`name=` 的 `text/plain|html` 视为附件,不当作正文丢弃 | +| 字符集 | 优先 `Content-Type charset`,回退 utf-8/GB/latin-1 | +| HTML 正文 | 保留 `tr/td/th` 行列边界(`\n`+`\t`);`html.unescape` 解码实体 | +| 安全 | 仅 MIME 解码 + 文本抽取;不执行宏、OLE 脚本或嵌入可执行内容 | +| 失败隔离 | 单附件损坏 → `parse_status=failed|empty`,其余附件继续;**前后端** incomplete 门禁阻断建批(含文本预算耗尽、`eml_attachment_text_truncated`、`notice_text_truncated`);不完整时可重试解析 | +| 持久化 | DB 保留附件全文(单附件 + **全部附件合计预算**);预算耗尽写入 `eml_attachment_text_budget_exhausted` 并视为不完整;状态轮询瘦身,详情接口按需返回全文 | +| 计数 | `attachment_count`=发现总数(含超限未登记);`attachment_registered_count`/`attachments[]`=已登记项 | +| 解析器版本 | 默认见阶段二(当前 `v6`);阶段一语义在 v5 已对齐(mixed HTML / 附件型 alternative) | +| 建批门禁 | `create_shipping_batch_from_intakes` 除要求 `parse_status=parsed` 外,须通过 `attachment_integrity`;前端 `shippingNoticeAttachmentIntegrity.ts` 与后端 `BLOCKING_WARNING_PREFIXES` 契约一致(测试双向校验) | +| 重试解析 | 允许 `parse_failed`,或 `parsed` 但附件不完整;UI 对两类均展示重试按钮 | + +#### 配置项(`settings.py`) + +| 环境变量 | 默认 | 含义 | +| --- | --- | --- | +| `SHIPPING_NOTICE_EML_MAX_ATTACHMENTS` | `20` | 单封邮件最多登记的真实附件数 | +| `SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES` | `20971520`(20MB) | 单附件大小上限 | +| `SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` | `52428800`(50MB) | 全部附件合计大小上限 | +| `SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH` | `3` | `message/rfc822` / 嵌套 eml 最大深度 | +| `SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS` | `500000` | 全部附件 `extracted_text` 写入 structured_result_json 的合计字符上限 | + +#### 警告码(`parse_warnings` / meta.warnings) + +| 码 | 含义 | +| --- | --- | +| `eml_inline_resources_skipped:N` | 跳过了 N 个内嵌/签名资源 | +| `eml_attachment_limit_exceeded:N:discovered=M` | 登记上限为 N,实际发现 M 个真实附件 | +| `eml_attachment_too_large:filename:size` | 单附件过大被跳过 | +| `eml_total_attachment_size_exceeded:N` | 附件总大小超限 | +| `eml_nesting_depth_exceeded:N` | 嵌套深度超限 | +| `eml_attachment_duplicate:filename` | 同信内内容哈希重复 | +| `eml_attachment_extract_failed:filename` | 附件文本抽取失败 | +| `eml_attachment_text_truncated:N` / `eml_body_text_truncated:N` | **N=截断上限字符数**;另见 `text_length`/`stored_text_length`。其中 **`eml_attachment_text_truncated` 为建批阻断项**(`eml_body_text_truncated` 暂不阻断) | +| `eml_attachment_text_budget_exhausted:N` | 全部附件落库文本合计超过 `SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS`(建批阻断) | +| `notice_text_truncated:N` | 扁平 `extracted_text` 超 `NOTICE_TEXT_MAX_CHARS`(建批阻断) | +| `eml_nested_message_unreadable` | 嵌套 rfc822 无法解析(建批阻断) | + +#### Intake 结构化结果(节选) + +预解析写入 DB 的 `structured_result_json`(含附件全文,截断后);状态轮询返回瘦身摘要: + +```json +{ + "email": { + "message_id": "", + "subject": "PO 4510039227, 4510039228, 4510039229", + "from": "laszlo.fussy@example.com", + "body_text_length": 1200, + "stored_body_text_length": 1200 + }, + "attachment_count": 3, + "attachment_registered_count": 3, + "attachments": [ + { + "attachment_key": "att-001", + "filename": "4510039227.pdf", + "mime_type": "application/pdf", + "content_hash": "...", + "parse_status": "parsed", + "text_length": 1234, + "stored_text_length": 1234 + } + ] +} +``` + +`GET /shipping-notice/intakes/{intake_no}` 详情另含 `email.body_text` 与 `attachments[].extracted_text`。 + +聊天输入栏在「解析完成」后展示 `附件 ok/total`(悬停 title 含各附件文件名与状态)。 + +实现入口:`eml_parse.parse_eml_bytes` ← `notice_upload.extract_notice_text`;摘要组装:`intake_parse_workflow.intake_result_to_structured_summary`。 + > **实现策略(强制)**:根据行业最佳实践,优先在 Dify 中实现适合由 AI 编排层承接的能力,包括但不限于 Chatflow / Workflow、Agent、LLM 节点、Code 节点、Tool 节点、If-Else 分流,以及人工确认节点所需的解释、建议与交互编排。对于任务/批次持久化、主状态机、后台续跑、失败恢复、审计留痕、二进制文件处理、RPA/上传回执及外部系统集成等生产级业务职责,统一由 hxops 后端承担。本方案的判断标准不是“Dify 是否能实现”,而是“该能力是否适合由 AI 编排层承接,还是应由业务后端作为真相源与主调度层承接”。 **Tool API 基路径**:`/api/shipping-notice`\ @@ -86,6 +212,12 @@ FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx # 建单后延后 parse_notice 到 Dify 画布(默认 true,符合 Dify 编排优先) # SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY=true +# EML 附件提取安全上限(阶段一) +# SHIPPING_NOTICE_EML_MAX_ATTACHMENTS=20 +# SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES=20971520 +# SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES=52428800 +# SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH=3 + # 批次后台调度:每个批次最多同时派发几张票(默认 3) # SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY=3 @@ -3252,7 +3384,9 @@ API 层 | `backend/app/services/shipping_notice/state_machine.py` | checkpoint / action\_buttons / 人工节点规则 | | `backend/app/services/shipping_notice/user_facing_status.py` | Tool 投影字段裁剪、用户可见阶段文案 | | `backend/app/services/shipping_notice/openapi_spec.py` | Dify 使用的 OpenAPI 生成 | -| `backend/app/services/shipping_notice/inventory_upload.py` | 库存文件上传与读取 | +| `backend/app/services/shipping_notice/notice_upload.py` | 通知附件接入、文本抽取、截断;EML 委托 `eml_parse` | +| `backend/app/services/shipping_notice/eml_parse.py` | EML 结构化解析(元数据/正文/真实附件/嵌套 rfc822) | +| `backend/app/services/shipping_notice/intake_parse_workflow.py` | Intake 预解析;EML meta 写入 `structured_result_json` | | `backend/app/services/shipping_notice/export.py` | 发货 Excel 生成 | | `backend/app/services/shipping_notice/rpa.py` | RPA 触发文件写入(低层 I/O) | @@ -3322,8 +3456,9 @@ API 层 > 详细方案见 [`inventory_source_plan.md`](./inventory_source_plan.md)。 -1. **`parse_notice` 内 adjudicate**:读取任务 `destination_*` 与 YAML `match`/`match_aliases`,产出 `InventorySourceAdjudication`。 -2. **稳定才放行**:`inventory_source_status ∈ {resolved, user_confirmed}` 时任务才可 `parsed` 并触发 RPA;否则 `checkpoint=inventory_source_review`,`process_status=pending_review`。 +1. **`parse_notice` 内 adjudicate**:读取任务 `destination_*` 与 YAML `match`/`match_aliases`,产出 `InventorySourceAdjudication`(写入线索/候选)。 +2. **先解析复核,再定库存源**:低置信度先 `checkpoint=parse_review`(含重新解析);解析通过(人工确认或高置信度自动过)后,若源未稳定再进 `inventory_source_review`。RPA 等后续步骤仍要求 `inventory_source_status ∈ {resolved, user_confirmed}`。 + - **问题清单**:`ui_state.summary.issues` 汇总当前检查点原因 + parse warnings;解析复核阶段可提示「确认后再选库存源」;存量 `pending_parse_review_after_source` 仍兼容旧顺序。 3. **独立字段为真相源**:`inventory_source_code`、`inventory_site_id`、`inventory_warehouse_id` 等存于 `shipping_tasks` 列,gate 不读 `step_payload_json`。 4. **用户只确认 source_code**:`confirm_inventory_source` 根据编码回填 site/warehouse;路由指纹变更时要求重确认(`SHIPPING.INVENTORY_SOURCE_CHANGED`)。 5. **硬 Gate**:`inventory_rpa_workflow`、`inventory_workflow`、`fulfillment_workflow`、`progress_workflow` 入口均调用 `assert_inventory_source_gate`。 diff --git a/docs/funclist.md b/docs/funclist.md index 3265af86..adea9bca 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -58,8 +58,12 @@ | --- | --- | --- | | 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) | | 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | +| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | +| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 | +| 附件资产化与订单候选(阶段二) | 已实现 | EML 附件派生 FileAsset;Document 关联边引用计数;partial unique + 软删复活;cancel 释放 Document/Candidate;MinIO 补偿失败记 orphan_cleanup;候选去重在 SAVEPOINT;失败/资产缺失统一阶段二清理;预解析 Job 超时回收同步 Intake + parse_lease 代次隔离;入队原子绑定 parse_job_id;Intake 创建 FOR UPDATE/IntegrityError 幂等,cancelled/expired 禁止复活;enqueue 仅 SAVEPOINT 内插入;替代 Job FOR UPDATE,仅 queued 或已持精确 lease 的 running 可 supersede;parser v6;暂不按候选建 Task;见技术手册「附件资产化与订单候选」 | | 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | -| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate;稳定态 `resolved`/`user_confirmed`;不稳定进入 `inventory_source_review` | +| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | +| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | | 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 | | 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | | 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 68204310..f06833c9 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -515,6 +515,31 @@ export const cancelShippingNoticeIntake = (intakeNo: string) => { method: 'DELETE' }, ); +export const resolveShippingNoticeDuplicate = ( + intakeNo: string, + action: string, + targetTaskNo?: string | null, + reason?: string | null, +) => + requestJson( + `/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/duplicate-resolution`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + action, + target_task_no: targetTaskNo || undefined, + reason: reason || undefined, + }), + }, + ); + +export const refreshShippingNoticeDuplicate = (intakeNo: string) => + requestJson( + `/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/duplicate-refresh`, + { method: 'POST' }, + ); + export const createWorkspaceShippingBatchFromIntakes = ( intakeNos: string[], conversationId?: string | null, diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index b243602f..d5f51b0d 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -20,7 +20,11 @@ import { Square, X, } from 'lucide-vue-next'; -import type { PendingAttachment } from '../types/shipping.types'; +import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types'; +import { + isBlockingWarning, + isShippingNoticeAttachmentParseIncomplete, +} from '../shipping/shippingNoticeAttachmentIntegrity'; export interface ChatInputAttachmentPolicy { anyEnabled: boolean; @@ -60,6 +64,7 @@ const emit = defineEmits<{ 'voice-click': []; 'remove-attachment': [id: string]; 'retry-shipping-notice-attachment': [id: string]; + 'resolve-shipping-notice-duplicate': [id: string]; 'local-files-selected': [event: Event]; 'add-remote-url': [url: string]; 'shipping-inventory-selected': [event: Event]; @@ -79,6 +84,73 @@ const showAttachmentMenu = ref(false); const showAttachmentUrlPanel = ref(false); const showKbDropdown = ref(false); const attachmentUrlInput = ref(''); + +/** + * 汇总 EML 附件解析进度,供输入栏徽标展示。 + * 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。 + */ +function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachment): string { + const summary = attachment.parseSummary; + const total = Number(summary?.attachment_count || 0); + const rows = summary?.attachments || []; + const warnings = summary?.warnings || []; + const hasBlockingWarning = warnings.some((w) => isBlockingWarning(String(w || ''))); + if (!total && !hasBlockingWarning && !rows.length) return ''; + + const effectiveTotal = total || rows.length; + const ok = rows.filter((item) => item.parse_status === 'parsed').length; + const problematic = rows.filter((item) => + ['failed', 'empty', 'skipped'].includes(String(item.parse_status || '')), + ).length; + const duplicates = rows.filter((item) => item.parse_status === 'duplicate').length; + const overflow = Math.max(0, effectiveTotal - rows.length); + const issues = problematic + overflow + (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0); + + if (issues > 0) { + return t('chat.shippingNoticeAttachmentHintPartial', { + ok, + total: effectiveTotal || Math.max(ok + issues, 1), + failed: issues, + }); + } + if (duplicates > 0) { + return t('chat.shippingNoticeAttachmentHintWithDup', { ok, total: effectiveTotal, duplicates }); + } + if (!effectiveTotal) return ''; + return t('chat.shippingNoticeAttachmentHint', { ok, total: effectiveTotal }); +} + +/** + * 是否展示「重试解析」:顶层失败,或已 parsed 但附件不完整。 + */ +function canRetryShippingNoticeParse(attachment: ShippingNoticePendingAttachment): boolean { + if (attachment.kind !== 'shipping_notice') return false; + if (attachment.parseStatus === 'failed') return true; + return ( + attachment.parseStatus === 'parsed' + && isShippingNoticeAttachmentParseIncomplete(attachment.parseSummary) + ); +} + +/** + * 生成附件明细 title(文件名 + 状态 + 关键警告),便于悬停查看完整性。 + */ +function shippingNoticeAttachmentTitle(attachment: ShippingNoticePendingAttachment): string { + const rows = attachment.parseSummary?.attachments || []; + const warnings = attachment.parseSummary?.warnings || []; + const lines: string[] = []; + for (const item of rows) { + const name = item.filename || item.attachment_key || 'attachment'; + const status = item.parse_status || 'unknown'; + lines.push(`${name}: ${status}`); + } + for (const warning of warnings) { + const text = String(warning || '').trim(); + if (text) lines.push(`warning: ${text}`); + } + return lines.join('\n'); +} + const closeAttachmentMenu = () => { showAttachmentMenu.value = false; showAttachmentUrlPanel.value = false; @@ -246,7 +318,36 @@ watch( {{ a.originalFilename }} · {{ t('chat.shippingNoticeUploading') }} · {{ t('chat.shippingNoticeParsing') }} - · {{ t('chat.shippingNoticeParsed') }} + · {{ t('chat.shippingNoticeDuplicatePossibleBadge') }} + · {{ t('chat.shippingNoticeDuplicateBlockingBadge') }} + · {{ t('chat.shippingNoticeDuplicateRevisionChosen') }} + · {{ t('chat.shippingNoticeDuplicateForceChosen') }} + · {{ t('chat.shippingNoticeDuplicateOpenChosen') }} + + · {{ t('chat.shippingNoticeParsed') }} + + · {{ t('chat.shippingNoticeParseFailed') }} +