feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -1,11 +1,13 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/intake_service.py
|
||||
|
||||
用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。
|
||||
用途:发货通知接入记录(ShippingOrderIntake)业务编排(含重复决策投影与权限)。
|
||||
依赖:file_assets.service、intake_parse_workflow、order_extraction、jobs.queue、models、
|
||||
duplicate_detection、attachment_integrity、document_layout 生命周期模型。
|
||||
duplicate_detection、attachment_integrity、document_layout 生命周期模型、
|
||||
order_submission_service(阶段 1 上传 Submission / source_type)。
|
||||
逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行;
|
||||
创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE;
|
||||
业务 purpose 创建时挂接 shipping_order_submissions 并写入 eml|direct_pdf;
|
||||
cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径);
|
||||
状态轮询用瘦身 parse_summary。
|
||||
"""
|
||||
@@ -27,14 +29,20 @@ from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSubmission,
|
||||
ShippingNotice,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
||||
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
|
||||
|
||||
from app.services.shipping_notice.order_submission_service import (
|
||||
attach_intake_to_order_submission,
|
||||
ensure_order_submission_for_upload_batch,
|
||||
resolve_order_intake_source_type,
|
||||
serialize_order_submission,
|
||||
)
|
||||
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
||||
|
||||
ACTIVE_INTAKE_STATUSES = frozenset(
|
||||
@@ -67,7 +75,7 @@ def generate_intake_no() -> str:
|
||||
return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _duplicate_payload_from_intake(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
def _duplicate_payload_from_intake(intake: ShippingOrderIntake) -> dict[str, Any]:
|
||||
"""
|
||||
从 intake 投影 duplicate 载荷(供轮询/卡片展示)。
|
||||
|
||||
@@ -160,7 +168,7 @@ def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def serialize_intake(
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
*,
|
||||
asset: FileAsset | None = None,
|
||||
include_parse_texts: bool = False,
|
||||
@@ -197,6 +205,8 @@ def serialize_intake(
|
||||
'asset_no': asset.asset_no if asset else None,
|
||||
'conversation_id': intake.conversation_id,
|
||||
'upload_batch_id': intake.upload_batch_id,
|
||||
'source_type': intake.source_type,
|
||||
'submission_no': None,
|
||||
'parse_status': intake.parse_status,
|
||||
'parser_version': intake.parser_version,
|
||||
'order_extraction_status': intake.order_extraction_status,
|
||||
@@ -223,6 +233,11 @@ def serialize_intake(
|
||||
'created_at': utc_iso(intake.created_at),
|
||||
'updated_at': utc_iso(intake.updated_at),
|
||||
}
|
||||
if intake.order_submission_id:
|
||||
submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id))
|
||||
if submission is not None:
|
||||
payload['submission_no'] = submission.submission_no
|
||||
payload['order_submission'] = serialize_order_submission(submission)
|
||||
if asset:
|
||||
payload['original_filename'] = asset.original_filename
|
||||
payload['file_size'] = asset.file_size
|
||||
@@ -235,7 +250,7 @@ def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
汇总 Intake 下已调度的文档版面任务,供聊天页判断订单识别是否可启动。
|
||||
|
||||
Args:
|
||||
intake_id: ShippingNoticeIntake 主键;只统计其派生 Document 的布局版本。
|
||||
intake_id: ShippingOrderIntake 主键;只统计其派生 Document 的布局版本。
|
||||
|
||||
Returns:
|
||||
脱敏状态与数量。processing 表示仍有 queued/running;completed 表示所有任务已终结;
|
||||
@@ -244,10 +259,10 @@ def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
rows = (
|
||||
db.session.query(ShippingDocumentLayoutVersion.status)
|
||||
.join(
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocument.id == ShippingDocumentLayoutVersion.document_id,
|
||||
)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake_id))
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake_id))
|
||||
.all()
|
||||
)
|
||||
counts = {
|
||||
@@ -272,12 +287,12 @@ def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
return {'status': status, 'total': total, **counts}
|
||||
|
||||
|
||||
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
||||
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingOrderIntake:
|
||||
"""按编号查询当前用户的接入记录。"""
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == normalized)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == normalized)
|
||||
.first()
|
||||
)
|
||||
if not intake or int(intake.user_id) != int(user_id):
|
||||
@@ -294,7 +309,7 @@ def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
return serialize_intake(intake, asset=asset, include_parse_texts=True)
|
||||
|
||||
|
||||
def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset:
|
||||
def _load_asset_for_intake(intake: ShippingOrderIntake) -> FileAsset:
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if not asset or asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
||||
@@ -306,7 +321,7 @@ def _lock_intake_for_asset_purpose_parser(
|
||||
asset_id: int,
|
||||
purpose: str,
|
||||
parser_version: str,
|
||||
) -> ShippingNoticeIntake | None:
|
||||
) -> ShippingOrderIntake | None:
|
||||
"""
|
||||
FOR UPDATE 锁定同一资产目的+解析器版本下的 Intake(创建/重投入口串行化)。
|
||||
|
||||
@@ -314,11 +329,11 @@ def _lock_intake_for_asset_purpose_parser(
|
||||
锁定的 Intake;不存在则 None。
|
||||
"""
|
||||
return (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == int(asset_id),
|
||||
ShippingNoticeIntake.purpose == purpose,
|
||||
ShippingNoticeIntake.parser_version == parser_version,
|
||||
ShippingOrderIntake.asset_id == int(asset_id),
|
||||
ShippingOrderIntake.purpose == purpose,
|
||||
ShippingOrderIntake.parser_version == parser_version,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -326,6 +341,50 @@ def _lock_intake_for_asset_purpose_parser(
|
||||
)
|
||||
|
||||
|
||||
def _link_intake_to_upload_submission(
|
||||
*,
|
||||
intake: ShippingOrderIntake,
|
||||
asset: FileAsset,
|
||||
user_id: int,
|
||||
upload_batch_id: str,
|
||||
conversation_id: str | None,
|
||||
) -> None:
|
||||
"""
|
||||
将业务 Intake 幂等挂接到同一 upload_batch 的 ShippingOrderSubmission。
|
||||
|
||||
核心逻辑:补齐 source_type;仅当尚未挂接时创建/复用 Submission 并写审计;
|
||||
已挂接则只在 source_type 缺失时回填。Submission 创建失败 fail-closed(抛 ConflictError)。
|
||||
模板样本 purpose 不调用本函数。
|
||||
|
||||
Args:
|
||||
intake: 当前 Intake。
|
||||
asset: 根 FileAsset(用于推断扩展名)。
|
||||
user_id: 上传用户。
|
||||
upload_batch_id: 文件选择批次。
|
||||
conversation_id: 可选会话。
|
||||
"""
|
||||
source_type = intake.source_type or resolve_order_intake_source_type(
|
||||
extension=getattr(asset, 'extension', None),
|
||||
filename=getattr(asset, 'original_filename', None),
|
||||
)
|
||||
if intake.source_type is None and source_type is not None:
|
||||
intake.source_type = source_type
|
||||
if intake.order_submission_id is not None:
|
||||
return
|
||||
submission = ensure_order_submission_for_upload_batch(
|
||||
user_id=user_id,
|
||||
upload_batch_id=upload_batch_id,
|
||||
conversation_id=conversation_id or intake.conversation_id,
|
||||
actor_id=user_id,
|
||||
)
|
||||
attach_intake_to_order_submission(
|
||||
submission=submission,
|
||||
intake=intake,
|
||||
source_type=source_type,
|
||||
actor_id=user_id,
|
||||
)
|
||||
|
||||
|
||||
def create_shipping_notice_intake(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -393,13 +452,18 @@ def _create_intake_for_asset(
|
||||
parser_version=parser_version,
|
||||
)
|
||||
if intake is None:
|
||||
candidate = ShippingNoticeIntake(
|
||||
source_type = resolve_order_intake_source_type(
|
||||
extension=getattr(asset, 'extension', None),
|
||||
filename=getattr(asset, 'original_filename', None),
|
||||
)
|
||||
candidate = ShippingOrderIntake(
|
||||
intake_no=generate_intake_no(),
|
||||
asset_id=int(asset.id),
|
||||
user_id=int(user_id),
|
||||
conversation_id=conv,
|
||||
upload_batch_id=batch_id or str(uuid.uuid4()),
|
||||
purpose=purpose,
|
||||
source_type=source_type,
|
||||
parse_status='created',
|
||||
parser_version=parser_version,
|
||||
expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()),
|
||||
@@ -426,6 +490,16 @@ def _create_intake_for_asset(
|
||||
message='Uploaded asset already belongs to another input batch',
|
||||
)
|
||||
|
||||
# [STEP 1.5] 业务 Intake 挂接上传 Submission,并固化 eml|direct_pdf 来源。
|
||||
if purpose == 'shipping_notice':
|
||||
_link_intake_to_upload_submission(
|
||||
intake=intake,
|
||||
asset=asset,
|
||||
user_id=int(user_id),
|
||||
upload_batch_id=str(intake.upload_batch_id),
|
||||
conversation_id=conv,
|
||||
)
|
||||
|
||||
# [STEP 2] 终态 / 已在飞 / 禁止复活
|
||||
status_now = str(intake.parse_status or '')
|
||||
if status_now in {'parsed', 'consumed', 'queued', 'parsing'}:
|
||||
@@ -487,16 +561,16 @@ def _create_intake_for_asset(
|
||||
def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
|
||||
"""列出会话下未消费的活跃接入记录,供页面恢复。"""
|
||||
conv = str(conversation_id or '').strip()
|
||||
query = db.session.query(ShippingNoticeIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
|
||||
query = db.session.query(ShippingOrderIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingOrderIntake.asset_id
|
||||
).filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
||||
ShippingOrderIntake.consumed_at.is_(None),
|
||||
)
|
||||
if conv:
|
||||
query = query.filter(ShippingNoticeIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all()
|
||||
query = query.filter(ShippingOrderIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all()
|
||||
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
||||
|
||||
|
||||
@@ -506,11 +580,11 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str
|
||||
if not normalized:
|
||||
return []
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
db.session.query(ShippingOrderIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -528,10 +602,10 @@ def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.intake_no == normalized,
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no == normalized,
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -599,10 +673,10 @@ def cancel_intake(*, user_id: int, intake_no: str) -> None:
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.intake_no == normalized,
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no == normalized,
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -646,10 +720,10 @@ def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.intake_no == normalized,
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no == normalized,
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -725,8 +799,8 @@ def resolve_intake_duplicate(
|
||||
target_task = None
|
||||
if target_no:
|
||||
target_task = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter(ShippingTask.task_no == target_no, ShippingTask.user_id == int(user_id))
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(ShippingNotice.task_no == target_no, ShippingNotice.user_id == int(user_id))
|
||||
.first()
|
||||
)
|
||||
if not target_task:
|
||||
@@ -778,21 +852,22 @@ def resolve_intake_duplicate(
|
||||
|
||||
def mark_intakes_consumed(
|
||||
*,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
batch_id: int | None,
|
||||
task_ids_by_intake: dict[int, int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
标记 intake 为 consumed 并增加资产引用计数。
|
||||
|
||||
核心逻辑:可在建批 commit 前预占(batch_id=None),避免 FOR UPDATE 在 create_batch_tasks 提交后释放导致并发双消费。
|
||||
核心逻辑:可在建单 commit 前预占(batch_id 已废弃,仅保留参数兼容);
|
||||
以 consumed_task_id / consumed_at 标记消费,避免 FOR UPDATE 释放后并发双消费。
|
||||
"""
|
||||
del batch_id # co8 起 shipping_batches / consumed_batch_id 已删除
|
||||
now = datetime.utcnow()
|
||||
task_map = task_ids_by_intake or {}
|
||||
for intake in intakes:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.consumed_batch_id = int(batch_id) if batch_id else None
|
||||
intake.consumed_task_id = task_map.get(intake.id)
|
||||
intake.updated_at = now
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
|
||||
Reference in new issue
Block a user