feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测
This commit is contained in:
1 parent
729546a7b7
commit
ceb49461e8
72 files changed
+14270
-460
No files matched your search
@@ -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],
|
||||
|
||||
Reference in new issue
Block a user