Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
ffccf19ba2
143 files changed
+27635
-1021
No files matched your search
@@ -2,8 +2,9 @@
|
||||
backend/app/services/chat/turn_runtime.py
|
||||
|
||||
用途:平台统一 Chat Turn 执行器,编排 SSE 生命周期、session、ChatLog 与 action 路由。
|
||||
依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema。
|
||||
依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema、db。
|
||||
逻辑:api/chat/turns/stream 调用 ChatTurnRuntime.stream();业务 handler 只 yield TurnEvent。
|
||||
失败路径先 db.session.rollback(),再 touch_chat_session,避免 handler 脏写被一并提交。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +15,7 @@ from typing import Any, Iterator
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.chat.action_registry import ensure_handlers_loaded, resolve_action_handler
|
||||
from app.services.chat.action_schema import TurnEvent, TurnInput, parse_turn_refs_from_context
|
||||
@@ -183,6 +185,8 @@ class ChatTurnRuntime:
|
||||
getattr(exc, "code", None),
|
||||
exc.message,
|
||||
)
|
||||
# 业务失败后先 rollback,避免 handler 预占/脏写被 touch_chat_session 一并提交
|
||||
db.session.rollback()
|
||||
touch_chat_session(user_id, agent_id, session.session_id, status="error")
|
||||
yield emit_run_failed(
|
||||
run_id=run_id,
|
||||
@@ -193,6 +197,7 @@ class ChatTurnRuntime:
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
||||
db.session.rollback()
|
||||
touch_chat_session(user_id, agent_id, session.session_id, status="error")
|
||||
yield emit_run_failed(
|
||||
run_id=run_id,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
backend/app/services/file_assets/__init__.py
|
||||
|
||||
用途:平台级文件资产服务包入口。
|
||||
依赖:file_assets.service、file_assets.storage、file_assets.cleanup。
|
||||
逻辑:API 与 shipping intake 经 service 层读写 FileAsset 与私有 MinIO 对象。
|
||||
"""
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
backend/app/services/file_assets/cleanup.py
|
||||
|
||||
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
|
||||
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
|
||||
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
|
||||
MinIO 删除失败不伪装成功,保留记录供下次重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingNoticeIntake
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
|
||||
"""
|
||||
清理过期或已标记 expired 但尚未物理删除的临时资产。
|
||||
Returns:
|
||||
统计字典:scanned/expired/deleted/errors。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
assets = (
|
||||
db.session.query(FileAsset)
|
||||
.filter(
|
||||
FileAsset.reference_count == 0,
|
||||
FileAsset.deleted_at.is_(None),
|
||||
or_(
|
||||
(
|
||||
(FileAsset.lifecycle_status == 'temporary')
|
||||
& (FileAsset.expires_at.isnot(None))
|
||||
& (FileAsset.expires_at < now)
|
||||
),
|
||||
FileAsset.lifecycle_status == 'expired',
|
||||
),
|
||||
)
|
||||
.order_by(FileAsset.expires_at.asc().nullsfirst(), FileAsset.id.asc())
|
||||
.limit(max(int(limit or 100), 1))
|
||||
.all()
|
||||
)
|
||||
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
|
||||
for asset in assets:
|
||||
consumed = (
|
||||
db.session.query(ShippingNoticeIntake.id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.parse_status == 'consumed',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if consumed:
|
||||
continue
|
||||
stats['expired'] += 1
|
||||
asset.lifecycle_status = 'expired'
|
||||
(
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
|
||||
)
|
||||
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
try:
|
||||
file_asset_storage.delete_object(asset.storage_key)
|
||||
asset.upload_status = 'deleted'
|
||||
asset.deleted_at = now
|
||||
asset.updated_at = now
|
||||
stats['deleted'] += 1
|
||||
except Exception:
|
||||
stats['errors'] += 1
|
||||
asset.updated_at = now
|
||||
_LOGGER.exception('failed to delete minio object for asset %s', asset.asset_no)
|
||||
db.session.commit()
|
||||
return stats
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
backend/app/services/file_assets/cleanup_schedule.py
|
||||
|
||||
用途:确保 platform Job file-asset-cleanup 存在默认 ScheduleTask(迁移补种 + 启动/建用户补建)。
|
||||
依赖:models.ScheduleTask/User、schedule.timezone_util.compute_next_run_at、SQLAlchemy Session 事件。
|
||||
逻辑:create_app 启动时 ensure 一次;User after_commit 用独立 Session 即时补建(原 session 已 committed 不可再发 SQL)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP"
|
||||
DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH = "file-asset-cleanup"
|
||||
DEFAULT_FILE_ASSET_CLEANUP_CRON = "0 * * * *"
|
||||
DEFAULT_FILE_ASSET_CLEANUP_NAME = "临时文件资产 TTL 清理"
|
||||
|
||||
_HOOKS_REGISTERED = False
|
||||
_SESSION_INFO_KEY = "_seed_file_asset_cleanup"
|
||||
|
||||
|
||||
def ensure_default_file_asset_cleanup_schedule(
|
||||
*,
|
||||
commit: bool = True,
|
||||
session: Any | None = None,
|
||||
) -> ScheduleTask | None:
|
||||
"""
|
||||
幂等确保默认 TTL 清理排程存在。
|
||||
|
||||
核心逻辑:若已有同 schedule_no 或同 platform_api_path 的排程则跳过;
|
||||
否则在存在至少一个用户时创建启用态排程(next_run_at 走 Cron 语义)。
|
||||
|
||||
Args:
|
||||
commit: 是否立即提交。
|
||||
session: 可选独立 Session(User after_commit 钩子须传入,避免 committed 态 Session 发 SQL)。
|
||||
|
||||
Returns:
|
||||
新建或已存在的 ScheduleTask;尚无用户时返回 None。
|
||||
"""
|
||||
sess = session if session is not None else db.session
|
||||
existing = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed file-asset-cleanup schedule: no users yet")
|
||||
return None
|
||||
|
||||
now = datetime.utcnow()
|
||||
next_run = compute_next_run_at(
|
||||
DEFAULT_FILE_ASSET_CLEANUP_CRON,
|
||||
timezone_name="Asia/Shanghai",
|
||||
) or now
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
|
||||
name=DEFAULT_FILE_ASSET_CLEANUP_NAME,
|
||||
schedule_type="platform_job",
|
||||
owner_user_id=int(owner.id),
|
||||
cron_expr=DEFAULT_FILE_ASSET_CLEANUP_CRON,
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
wait_seconds=0,
|
||||
platform_api_path=DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH,
|
||||
job_params=None,
|
||||
kb_sync_enabled=False,
|
||||
notify_user_ids_json=[],
|
||||
notify_enabled=False,
|
||||
enabled=True,
|
||||
next_run_at=next_run,
|
||||
created_by=int(owner.id),
|
||||
updated_by=int(owner.id),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
sess.add(task)
|
||||
if commit:
|
||||
try:
|
||||
sess.commit()
|
||||
except Exception:
|
||||
sess.rollback()
|
||||
existing = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
raise
|
||||
else:
|
||||
sess.flush()
|
||||
_LOGGER.info(
|
||||
"seeded default file-asset-cleanup schedule_no=%s owner_user_id=%s",
|
||||
task.schedule_no,
|
||||
owner.id,
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
def register_file_asset_cleanup_schedule_hooks() -> None:
|
||||
"""
|
||||
注册 Session 钩子:User 插入并 commit 后立即尝试补建默认清理排程。
|
||||
|
||||
核心逻辑:after_flush 标记;after_commit 用独立 Session 调用 ensure
|
||||
(原 session 处于 committed 态不能再发 SQL)。
|
||||
"""
|
||||
global _HOOKS_REGISTERED
|
||||
if _HOOKS_REGISTERED:
|
||||
return
|
||||
|
||||
@event.listens_for(Session, "after_flush")
|
||||
def _mark_user_insert(session: Session, _context) -> None: # type: ignore[no-untyped-def]
|
||||
if any(isinstance(obj, User) for obj in session.new):
|
||||
session.info[_SESSION_INFO_KEY] = True
|
||||
|
||||
@event.listens_for(Session, "after_commit")
|
||||
def _seed_after_user_commit(session: Session) -> None:
|
||||
if not session.info.pop(_SESSION_INFO_KEY, False):
|
||||
return
|
||||
bind = session.get_bind()
|
||||
if bind is None:
|
||||
return
|
||||
try:
|
||||
with Session(bind) as seed_session:
|
||||
ensure_default_file_asset_cleanup_schedule(commit=True, session=seed_session)
|
||||
except Exception as exc: # pragma: no cover - 防御不阻断建用户
|
||||
_LOGGER.warning("ensure file-asset-cleanup after user create failed: %s", exc)
|
||||
|
||||
_HOOKS_REGISTERED = True
|
||||
@@ -0,0 +1,633 @@
|
||||
"""
|
||||
backend/app/services/file_assets/service.py
|
||||
|
||||
用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。
|
||||
依赖:file_assets.storage、models.FileAsset、Flask current_app。
|
||||
逻辑:由 /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
|
||||
import uuid
|
||||
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
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_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',
|
||||
}
|
||||
|
||||
|
||||
def _max_file_size_bytes() -> int:
|
||||
mb = int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30)
|
||||
return max(mb, 1) * 1024 * 1024
|
||||
|
||||
|
||||
def _temp_ttl_hours() -> int:
|
||||
return max(int(current_app.config.get('FILE_ASSET_TEMP_TTL_HOURS', 72) or 72), 1)
|
||||
|
||||
|
||||
def generate_asset_no() -> str:
|
||||
"""生成 FA-YYYYMMDD-XXXXXXXX 格式资产编号。"""
|
||||
return f"FA-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _normalize_extension(filename: str) -> str:
|
||||
ext = os.path.splitext(str(filename or '').strip())[1].lower().lstrip('.')
|
||||
return ext
|
||||
|
||||
|
||||
def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str:
|
||||
now = datetime.utcnow()
|
||||
safe_name = secure_filename(filename) or 'file'
|
||||
safe_name = re.sub(r'[^\w\-.]+', '_', safe_name)[:120] or 'file'
|
||||
return f"temporary/{user_id}/{now:%Y}/{now:%m}/{asset_no}/{safe_name}"
|
||||
|
||||
|
||||
def _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,
|
||||
'original_filename': asset.original_filename,
|
||||
'file_size': asset.file_size,
|
||||
'mime_type': asset.mime_type,
|
||||
'content_hash': asset.content_hash,
|
||||
'upload_status': asset.upload_status,
|
||||
'lifecycle_status': asset.lifecycle_status,
|
||||
'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),
|
||||
}
|
||||
|
||||
|
||||
def get_asset_for_user(asset_no: str, user_id: int) -> FileAsset:
|
||||
"""
|
||||
按编号查询当前用户拥有的资产。
|
||||
Raises:
|
||||
NotFoundError: 不存在或已逻辑删除。
|
||||
ForbiddenError: 非所有者。
|
||||
"""
|
||||
normalized = str(asset_no or '').strip().upper()
|
||||
asset = (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.asset_no == normalized, FileAsset.deleted_at.is_(None))
|
||||
.first()
|
||||
)
|
||||
if not asset:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
|
||||
if int(asset.owner_user_id) != int(user_id):
|
||||
raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问该文件资产')
|
||||
return asset
|
||||
|
||||
|
||||
def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]:
|
||||
"""
|
||||
上传文件并创建 FileAsset 记录。
|
||||
核心逻辑:校验类型与大小 → SHA-256 → 写 MinIO → 落库 ready/temporary。
|
||||
"""
|
||||
filename = str(upload.filename or '').strip() or 'file'
|
||||
ext = _normalize_extension(filename)
|
||||
if ext not in _ALLOWED_EXTENSIONS:
|
||||
raise ValidationError(
|
||||
code='FILE_ASSET.INVALID_TYPE',
|
||||
message=f'不支持的文件类型: .{ext or "unknown"}',
|
||||
)
|
||||
|
||||
data = upload.read()
|
||||
if not data:
|
||||
raise ValidationError(code='FILE_ASSET.UPLOAD_FAILED', message='文件内容为空')
|
||||
if len(data) > _max_file_size_bytes():
|
||||
raise ValidationError(code='FILE_ASSET.SIZE_EXCEEDED', message='文件大小超过限制')
|
||||
|
||||
content_hash = hashlib.sha256(data).hexdigest()
|
||||
asset_no = generate_asset_no()
|
||||
storage_key = _build_storage_key(user_id=user_id, asset_no=asset_no, filename=filename)
|
||||
mime_type = upload.mimetype or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours())
|
||||
|
||||
asset = FileAsset(
|
||||
asset_no=asset_no,
|
||||
owner_user_id=int(user_id),
|
||||
original_filename=filename,
|
||||
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,
|
||||
content_hash=content_hash,
|
||||
file_size=len(data),
|
||||
mime_type=mime_type,
|
||||
extension=ext or None,
|
||||
upload_status='uploading',
|
||||
lifecycle_status='temporary',
|
||||
reference_count=0,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type=mime_type)
|
||||
asset.upload_status = 'ready'
|
||||
except Exception:
|
||||
asset.upload_status = 'failed'
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
db.session.commit()
|
||||
return _serialize_asset(asset)
|
||||
|
||||
|
||||
def _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:
|
||||
"""
|
||||
删除未引用的临时资产:先标记 expired,再删 MinIO;成功后标记 deleted。
|
||||
Raises:
|
||||
ConflictError: 已被业务引用。
|
||||
ServiceUnavailableError: MinIO 删除失败(保留 expired 供清理重试)。
|
||||
"""
|
||||
asset = get_asset_for_user(asset_no, user_id)
|
||||
if str(asset.lifecycle_status or '') == 'referenced' or int(asset.reference_count or 0) > 0:
|
||||
raise ConflictError(code='FILE_ASSET.ALREADY_REFERENCED', message='文件已被业务引用,无法删除')
|
||||
if str(asset.upload_status or '') == 'deleted' and asset.deleted_at is not None:
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
asset.lifecycle_status = 'expired'
|
||||
asset.updated_at = now
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
file_asset_storage.delete_object(asset.storage_key)
|
||||
except Exception:
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
asset.upload_status = 'deleted'
|
||||
asset.deleted_at = now
|
||||
asset.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def read_asset_bytes(asset: FileAsset) -> bytes:
|
||||
"""读取资产对象字节,校验未过期/未删除。"""
|
||||
if asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
|
||||
raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
|
||||
return file_asset_storage.get_bytes(asset.storage_key)
|
||||
|
||||
|
||||
def serialize_asset_public(asset: FileAsset) -> dict[str, Any]:
|
||||
"""对外序列化资产(不含 storage_key)。"""
|
||||
return _serialize_asset(asset)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/services/file_assets/storage.py
|
||||
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import BinaryIO
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
from app.core.config.settings import ACTIVE_ENV_NAME, config
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
class FileAssetStorage:
|
||||
"""私有业务文件 MinIO 存储客户端。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.client = Minio(
|
||||
_cfg.MINIO_ENDPOINT,
|
||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
||||
secure=_cfg.MINIO_SECURE,
|
||||
)
|
||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||
|
||||
def _ensure_bucket_exists(self) -> None:
|
||||
"""确保私有 bucket 存在,不设置 public-read policy。"""
|
||||
try:
|
||||
if not self.client.bucket_exists(self.bucket_name):
|
||||
self.client.make_bucket(self.bucket_name)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO file assets bucket unavailable')
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件存储服务暂不可用,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def upload_bytes(
|
||||
self,
|
||||
*,
|
||||
storage_key: str,
|
||||
data: bytes,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
"""
|
||||
上传字节流到私有 bucket。
|
||||
Raises:
|
||||
ServiceUnavailableError: MinIO 不可用或上传失败。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
stream: BinaryIO = io.BytesIO(data)
|
||||
try:
|
||||
self.client.put_object(
|
||||
bucket_name=self.bucket_name,
|
||||
object_name=storage_key,
|
||||
data=stream,
|
||||
length=len(data),
|
||||
content_type=content_type or 'application/octet-stream',
|
||||
)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO upload failed key=%s', storage_key)
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件上传失败,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def get_bytes(self, storage_key: str) -> bytes:
|
||||
"""
|
||||
读取对象字节内容。
|
||||
Raises:
|
||||
ServiceUnavailableError: 读取失败(含网络异常与 S3Error)。
|
||||
"""
|
||||
try:
|
||||
response = self.client.get_object(self.bucket_name, storage_key)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO read failed key=%s', storage_key)
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件存储服务暂不可用,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def delete_object(self, storage_key: str) -> None:
|
||||
"""
|
||||
删除 MinIO 对象;失败时抛出可重试 503,供清理任务重试。
|
||||
Raises:
|
||||
ServiceUnavailableError: 删除失败。
|
||||
"""
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, storage_key)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('MinIO delete failed key=%s', storage_key)
|
||||
raise ServiceUnavailableError(
|
||||
code='FILE_ASSET.UPLOAD_FAILED',
|
||||
message='文件对象删除失败,请稍后重试',
|
||||
) from exc
|
||||
|
||||
def object_exists(self, storage_key: str) -> bool:
|
||||
"""判断对象是否存在。"""
|
||||
try:
|
||||
self.client.stat_object(self.bucket_name, storage_key)
|
||||
return True
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
|
||||
"""生成短期受控下载 URL。"""
|
||||
self._ensure_bucket_exists()
|
||||
return self.client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
)
|
||||
|
||||
|
||||
file_asset_storage = FileAssetStorage()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
backend/app/services/schedule/file_asset_cleanup_job.py
|
||||
|
||||
用途:排程平台 Job —— 清理过期未引用的临时文件资产。
|
||||
依赖:file_assets.cleanup。
|
||||
逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.file_assets.cleanup import cleanup_expired_temporary_assets
|
||||
|
||||
|
||||
def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]:
|
||||
"""
|
||||
执行临时文件资产 TTL 清理。
|
||||
Args:
|
||||
task: ScheduleTask。
|
||||
run: ScheduleRun。
|
||||
Returns:
|
||||
清理统计。
|
||||
"""
|
||||
_ = task, run
|
||||
return cleanup_expired_temporary_assets(limit=200)
|
||||
@@ -129,6 +129,7 @@ def run_platform_job(
|
||||
def _register_builtin_platform_jobs() -> None:
|
||||
"""模块加载时注册内置平台 Job(含参数契约)。"""
|
||||
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||||
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
|
||||
@@ -191,6 +192,14 @@ def _register_builtin_platform_jobs() -> None:
|
||||
description="同步 PLM 固资快照至本地 manifest。",
|
||||
category="assets",
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="file-asset-cleanup",
|
||||
label="临时文件资产清理",
|
||||
label_key="admin.schedule.form.platformJobFileAssetCleanup",
|
||||
handler=run_file_asset_cleanup_schedule,
|
||||
description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。",
|
||||
category="files",
|
||||
))
|
||||
|
||||
|
||||
_register_builtin_platform_jobs()
|
||||
@@ -80,7 +80,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
|
||||
"""
|
||||
构造排程企微 textcard 跳转 query 参数。
|
||||
|
||||
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 供深链展示下载入口。
|
||||
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图,
|
||||
由前端在登录后自动触发一次下载,失败时保留手动下载入口。
|
||||
"""
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
|
||||
@@ -91,6 +92,7 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
|
||||
}
|
||||
if inventory_raw_zip_available_from_summary(summary):
|
||||
params['raw_zip'] = '1'
|
||||
params['download'] = 'inventory_raw_zip'
|
||||
return params
|
||||
|
||||
|
||||
@@ -99,7 +101,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
组装排程完成企微 textcard 正文。
|
||||
|
||||
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
|
||||
有原始库存归档时提示点击卡片进入 HXOPS(URL 仅放 jump_url,不写进正文)。
|
||||
有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。
|
||||
"""
|
||||
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
|
||||
skipped_count = int(run.skipped_count or 0)
|
||||
@@ -115,7 +117,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
|
||||
if inventory_raw_zip_available_from_summary(summary):
|
||||
description += '\n原始库存包:点击本通知进入 HXOPS 下载'
|
||||
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
|
||||
return description
|
||||
|
||||
|
||||
@@ -160,6 +162,19 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
raw_zip_media_id = None
|
||||
raw_zip_file_name = None
|
||||
try:
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
|
||||
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
|
||||
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
|
||||
except Exception as exc:
|
||||
current_app.logger.info(
|
||||
'[wecom-schedule] raw inventory zip media skipped for run %s: %s',
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
textcard_ok_count = 0
|
||||
errors = []
|
||||
|
||||
@@ -199,6 +214,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: file exception={exc}')
|
||||
|
||||
if raw_zip_media_id:
|
||||
try:
|
||||
raw_zip_audit = _create_audit(
|
||||
f'{_WECOM_EVENT_TYPE}_inventory_raw_zip', u,
|
||||
title, f'[原始库存包] {raw_zip_file_name}', uuid.uuid4().hex,
|
||||
)
|
||||
raw_zip_data = send_wecom_file_message(u.wecom_userid, raw_zip_media_id)
|
||||
if raw_zip_data.get('errcode') == 0:
|
||||
raw_zip_audit.status = 'sent'
|
||||
else:
|
||||
raw_zip_audit.error_code = str(raw_zip_data.get('errcode'))
|
||||
raw_zip_audit.error_message = str(raw_zip_data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: raw zip errcode={raw_zip_data.get("errcode")}')
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
|
||||
|
||||
if textcard_ok_count > 0:
|
||||
run.wecom_notified = True
|
||||
run.wecom_notified_at = datetime.utcnow()
|
||||
@@ -641,6 +672,22 @@ def start_scheduler(app):
|
||||
recovered_awaiting,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
|
||||
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
|
||||
if cleanup_count:
|
||||
current_app.logger.info(
|
||||
"[schedule-worker] processed %d RPA callback cleanup job(s) on startup",
|
||||
cleanup_count,
|
||||
)
|
||||
if cleanup_warnings:
|
||||
current_app.logger.warning(
|
||||
"[schedule-worker] RPA callback cleanup warnings: %s",
|
||||
"; ".join(cleanup_warnings[:5]),
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
||||
maybe_alert_rpa_worker_status(force=True)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,310 @@
|
||||
"""
|
||||
services/shipping_notice/batch_create_idempotency.py
|
||||
|
||||
用途:发货通知建单幂等键标准化、批次回查与跨请求文件内容重复校验。
|
||||
依赖:models.ShippingBatch/ShippingTask、query_service、tool_response 序列化。
|
||||
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingTask.idempotency_key(货代上传幂等)语义分离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import zlib
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_focus_task_for_batch,
|
||||
list_sorted_batch_tasks,
|
||||
serialize_batch_for_tool,
|
||||
serialize_task_summary,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
|
||||
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
|
||||
|
||||
_TERMINAL_TASK_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def normalize_create_idempotency_key(raw: str | None) -> str | None:
|
||||
"""
|
||||
标准化建单幂等键:去首尾空格、校验长度与安全字符集。
|
||||
|
||||
Args:
|
||||
raw: HTTP Header / payload 中的原始幂等键。
|
||||
|
||||
Returns:
|
||||
标准化后的幂等键;空值返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。
|
||||
"""
|
||||
value = str(raw or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN:
|
||||
raise AppError(
|
||||
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
|
||||
message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符",
|
||||
http_status=400,
|
||||
)
|
||||
if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value):
|
||||
raise AppError(
|
||||
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
|
||||
message="幂等键仅允许字母、数字及 . _ : - 字符",
|
||||
http_status=400,
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def warn_missing_create_idempotency_key(*, source: str) -> None:
|
||||
"""兼容期记录缺少建单幂等键的告警,不阻断旧客户端。"""
|
||||
logger.warning(
|
||||
"shipping batch create without create_idempotency_key source=%s",
|
||||
source,
|
||||
)
|
||||
|
||||
|
||||
def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str:
|
||||
"""
|
||||
根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。
|
||||
|
||||
核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。
|
||||
"""
|
||||
hashes = sorted(
|
||||
{
|
||||
str(item.get("source_content_hash") or "").strip().lower()
|
||||
for item in notice_items
|
||||
if isinstance(item, dict) and str(item.get("source_content_hash") or "").strip()
|
||||
}
|
||||
)
|
||||
if not hashes:
|
||||
return ""
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
|
||||
|
||||
def batch_stored_content_fingerprint(batch: ShippingBatch) -> str | None:
|
||||
"""
|
||||
读取批次已持久化的文件集合指纹;历史批次无字段时从任务 source_content_hash 推导。
|
||||
"""
|
||||
summary = batch.process_summary_json if isinstance(batch.process_summary_json, dict) else {}
|
||||
stored = str(summary.get("create_content_fingerprint") or "").strip().lower()
|
||||
if stored:
|
||||
return stored
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
hashes = sorted(
|
||||
{
|
||||
str(task.source_content_hash or "").strip().lower()
|
||||
for task in tasks
|
||||
if str(task.source_content_hash or "").strip()
|
||||
}
|
||||
)
|
||||
if not hashes:
|
||||
return None
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
|
||||
|
||||
def assert_idempotent_batch_content_matches(
|
||||
batch: ShippingBatch,
|
||||
notice_items: list[dict[str, Any]],
|
||||
) -> None:
|
||||
"""
|
||||
校验幂等键命中时,本次文件集合与已有批次一致。
|
||||
|
||||
Raises:
|
||||
ConflictError: 文件集合不一致(SHIPPING.BATCH_IDEMPOTENCY_CONFLICT)。
|
||||
"""
|
||||
stored_fp = batch_stored_content_fingerprint(batch)
|
||||
request_fp = compute_notice_items_content_fingerprint(notice_items)
|
||||
if not stored_fp or not request_fp:
|
||||
return
|
||||
if stored_fp == request_fp:
|
||||
return
|
||||
raise ConflictError(
|
||||
"建单幂等键对应的文件集合与本次上传不一致,请更换幂等键后重试",
|
||||
code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT",
|
||||
details={
|
||||
"batch_no": batch.batch_no,
|
||||
"stored_content_fingerprint": stored_fp,
|
||||
"request_content_fingerprint": request_fp,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _advisory_lock_key(*parts: str) -> int:
|
||||
raw = "|".join(parts)
|
||||
return zlib.crc32(raw.encode("utf-8")) & 0x7FFFFFFF
|
||||
|
||||
|
||||
def acquire_notice_create_locks(user_id: int, content_hashes: Iterable[str]) -> None:
|
||||
"""
|
||||
在建单事务内获取 PostgreSQL 事务级 advisory lock,串行化同用户建单与活跃文件去重。
|
||||
|
||||
核心逻辑:SQLite 等测试库跳过;生产 PostgreSQL 对 user 级与每个 content_hash 加锁。
|
||||
"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_keys = {_advisory_lock_key(str(user_id), "shipping-notice-create")}
|
||||
for content_hash in content_hashes:
|
||||
normalized = str(content_hash or "").strip().lower()
|
||||
if normalized:
|
||||
lock_keys.add(_advisory_lock_key(str(user_id), "shipping-notice-hash", normalized))
|
||||
for lock_key in sorted(lock_keys):
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> ShippingBatch | None:
|
||||
"""
|
||||
按用户与建单幂等键查找已有批次。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户 ID。
|
||||
create_idempotency_key: 已标准化的建单幂等键。
|
||||
|
||||
Returns:
|
||||
匹配的 ShippingBatch 或 None。
|
||||
"""
|
||||
key = str(create_idempotency_key or "").strip()
|
||||
if not key:
|
||||
return None
|
||||
return (
|
||||
ShippingBatch.query.filter_by(user_id=user_id, create_idempotency_key=key).first()
|
||||
)
|
||||
|
||||
|
||||
def build_existing_batch_tool_response(batch: ShippingBatch, *, user_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
将已有批次序列化为 create_batch_tasks 兼容的 Tool 响应结构。
|
||||
|
||||
核心逻辑:不创建新任务、不启动编排器;供幂等重放与唯一约束竞争回查共用。
|
||||
"""
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
|
||||
created_tasks = [
|
||||
{
|
||||
"task_id": task.task_no,
|
||||
"batch_index": task.batch_index,
|
||||
"parse_status": "deferred",
|
||||
}
|
||||
for task in tasks
|
||||
]
|
||||
data: dict[str, Any] = {
|
||||
"batch": serialize_batch_for_tool(batch),
|
||||
"tasks": created_tasks,
|
||||
"orchestrator_started": False,
|
||||
}
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已恢复此前创建的批次 {batch.batch_no}",
|
||||
"data": data,
|
||||
"idempotent_replay": True,
|
||||
}
|
||||
|
||||
|
||||
def assert_no_exact_duplicate_notices(
|
||||
user_id: int,
|
||||
notice_items: list[dict[str, Any]],
|
||||
*,
|
||||
exclude_batch_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
校验跨请求是否存在相同文件内容且仍在进行中的任务。
|
||||
|
||||
核心逻辑:须在 acquire_notice_create_locks 之后调用,避免不同幂等键并发重复建单。
|
||||
合法的 duplicate_resolution_type=revision|force_create 跳过哈希阻断(业务 Gate 已授权)。
|
||||
|
||||
Raises:
|
||||
ConflictError: SHIPPING.NOTICE_EXACT_DUPLICATE,details 含已有 task_no。
|
||||
"""
|
||||
hashes: list[tuple[str, str]] = []
|
||||
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
|
||||
filename = str(item.get("source_file_name") or "").strip() or "notice"
|
||||
hashes.append((content_hash, filename))
|
||||
if not hashes:
|
||||
return
|
||||
|
||||
for content_hash, _filename in hashes:
|
||||
query = ShippingTask.query.filter(
|
||||
ShippingTask.user_id == user_id,
|
||||
ShippingTask.source_content_hash == content_hash,
|
||||
ShippingTask.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
|
||||
)
|
||||
if exclude_batch_id is not None:
|
||||
query = query.filter(
|
||||
(ShippingTask.batch_id.is_(None)) | (ShippingTask.batch_id != exclude_batch_id)
|
||||
)
|
||||
existing = query.order_by(ShippingTask.id.desc()).first()
|
||||
if existing:
|
||||
raise ConflictError(
|
||||
f"该文件已存在于进行中的任务 {existing.task_no}",
|
||||
code="SHIPPING.NOTICE_EXACT_DUPLICATE",
|
||||
details={
|
||||
"task_no": existing.task_no,
|
||||
"source_content_hash": content_hash,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""请求内按 source_content_hash 二次去重,防止绕过 intake 时重复建任务。"""
|
||||
seen: set[str] = set()
|
||||
unique: list[dict[str, Any]] = []
|
||||
for item in notice_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
content_hash = str(item.get("source_content_hash") or "").strip().lower()
|
||||
if content_hash:
|
||||
if content_hash in seen:
|
||||
continue
|
||||
seen.add(content_hash)
|
||||
unique.append(item)
|
||||
return unique
|
||||
|
||||
|
||||
def handle_batch_create_integrity_error(
|
||||
*,
|
||||
user_id: int,
|
||||
create_idempotency_key: str | None,
|
||||
exc: IntegrityError,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
捕获批次建单唯一约束竞争,回滚后回查已有批次。
|
||||
|
||||
Returns:
|
||||
幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。
|
||||
"""
|
||||
db.session.rollback()
|
||||
key = str(create_idempotency_key or "").strip()
|
||||
if not key:
|
||||
return None
|
||||
batch = find_batch_by_create_idempotency(user_id, key)
|
||||
if not batch:
|
||||
return None
|
||||
logger.info(
|
||||
"shipping batch create idempotency race resolved batch_no=%s user_id=%s",
|
||||
batch.batch_no,
|
||||
user_id,
|
||||
)
|
||||
return build_existing_batch_tool_response(batch, user_id=user_id)
|
||||
@@ -0,0 +1,740 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/batch_from_intakes.py
|
||||
|
||||
用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。
|
||||
依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency、
|
||||
attachment_integrity。
|
||||
逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。
|
||||
幂等以 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
|
||||
|
||||
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, 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)。
|
||||
注意:open_existing 会挂到旧任务批次,不可单独用于混合请求的全量比对。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake.intake_no)
|
||||
.filter(ShippingNoticeIntake.consumed_batch_id == int(batch_id))
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]).strip().upper() for row in rows if row and row[0]}
|
||||
|
||||
|
||||
def _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,
|
||||
create_idempotency_key: str | None,
|
||||
intake_nos: list[str],
|
||||
) -> dict[str, Any] | 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
|
||||
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),
|
||||
'source': 'batch_fallback',
|
||||
},
|
||||
)
|
||||
result = build_existing_batch_tool_response(existing, user_id=user_id)
|
||||
result['idempotent_replay'] = True
|
||||
return result
|
||||
|
||||
|
||||
def _partition_intakes_by_content_hash(
|
||||
ordered: list[tuple[ShippingNoticeIntake, FileAsset]],
|
||||
) -> tuple[list[tuple[ShippingNoticeIntake, FileAsset]], dict[str, list[ShippingNoticeIntake]]]:
|
||||
"""按 FileAsset.content_hash 去重,保留首次出现的 intake 用于建单。"""
|
||||
seen: set[str] = set()
|
||||
primary: list[tuple[ShippingNoticeIntake, FileAsset]] = []
|
||||
duplicates_by_hash: dict[str, list[ShippingNoticeIntake]] = {}
|
||||
for intake, asset in ordered:
|
||||
content_hash = str(asset.content_hash or '').strip()
|
||||
if not content_hash:
|
||||
primary.append((intake, asset))
|
||||
continue
|
||||
if content_hash in seen:
|
||||
duplicates_by_hash.setdefault(content_hash, []).append(intake)
|
||||
continue
|
||||
seen.add(content_hash)
|
||||
primary.append((intake, asset))
|
||||
return primary, duplicates_by_hash
|
||||
|
||||
|
||||
def _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,
|
||||
conversation_id: str | None,
|
||||
intake_nos: list[str],
|
||||
create_idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
根据已解析且未消费的 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] 幂等重放优先
|
||||
replay = _try_idempotent_replay(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
intake_nos=normalized,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
|
||||
# [STEP 2] 锁定并校验
|
||||
stmt = (
|
||||
select(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
.where(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.with_for_update()
|
||||
)
|
||||
rows = list(db.session.execute(stmt).all())
|
||||
row_by_no = {intake.intake_no: (intake, asset) for intake, asset in rows}
|
||||
if len(row_by_no) != len(set(normalized)):
|
||||
raise ValidationError(
|
||||
'部分接入记录不存在或无权访问',
|
||||
code='SHIPPING_NOTICE.INTAKE_NOT_FOUND',
|
||||
)
|
||||
|
||||
replay = _try_idempotent_replay(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
intake_nos=normalized,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
|
||||
ordered_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = []
|
||||
now = datetime.utcnow()
|
||||
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':
|
||||
consumed_pairs.append(intake)
|
||||
continue
|
||||
if intake.parse_status != 'parsed':
|
||||
raise ConflictError(
|
||||
f'接入记录 {intake.intake_no} 尚未解析完成',
|
||||
code=(
|
||||
'SHIPPING_NOTICE.INTAKE_PARSE_PENDING'
|
||||
if intake.parse_status in {'created', 'queued', 'parsing'}
|
||||
else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
),
|
||||
)
|
||||
# [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(
|
||||
'接入记录已过期',
|
||||
code='SHIPPING_NOTICE.INTAKE_EXPIRED',
|
||||
)
|
||||
ordered_pairs.append((intake, asset))
|
||||
|
||||
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]
|
||||
|
||||
mark_intakes_consumed(intakes=primary_intakes, batch_id=None)
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
result = create_shipping_batch_from_notice_items(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
notice_items=notice_items,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
defer_commit=True,
|
||||
start_orchestrator=False,
|
||||
)
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
if bool(result.get('idempotent_replay')):
|
||||
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
|
||||
|
||||
batch_obj = get_batch_for_user(batch_no, user_id)
|
||||
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)
|
||||
.order_by(ShippingTask.batch_index.asc(), ShippingTask.id.asc())
|
||||
.all()
|
||||
)
|
||||
task_by_intake_id = {
|
||||
int(task.source_intake_id): task
|
||||
for task in tasks
|
||||
if task.source_intake_id is not None
|
||||
}
|
||||
hash_to_task_id: dict[str, int] = {}
|
||||
for intake, asset in primary_pairs:
|
||||
task = task_by_intake_id.get(int(intake.id))
|
||||
if task is None:
|
||||
continue
|
||||
intake.consumed_batch_id = int(batch_obj.id)
|
||||
intake.consumed_task_id = int(task.id)
|
||||
intake.updated_at = datetime.utcnow()
|
||||
content_hash = str(asset.content_hash or '').strip()
|
||||
if content_hash:
|
||||
hash_to_task_id[content_hash] = int(task.id)
|
||||
# 审计:修订 / 强制新建
|
||||
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),
|
||||
},
|
||||
)
|
||||
|
||||
duplicate_intakes: list[ShippingNoticeIntake] = []
|
||||
for content_hash, dups in duplicates_by_hash.items():
|
||||
task_id = hash_to_task_id.get(content_hash)
|
||||
if task_id is None:
|
||||
continue
|
||||
for dup in dups:
|
||||
duplicate_intakes.append(dup)
|
||||
dup.consumed_batch_id = int(batch_obj.id)
|
||||
dup.consumed_task_id = int(task_id)
|
||||
if duplicate_intakes:
|
||||
_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
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/batch_from_notices.py
|
||||
|
||||
用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。
|
||||
依赖:shipping_tools、notice_upload、batch_orchestrator、query_service。
|
||||
依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。
|
||||
逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,18 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
assert_idempotent_batch_content_matches,
|
||||
build_existing_batch_tool_response,
|
||||
dedupe_notice_items_by_content_hash,
|
||||
find_batch_by_create_idempotency,
|
||||
handle_batch_create_integrity_error,
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import build_notice_file_summary
|
||||
from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary
|
||||
|
||||
@@ -21,22 +32,36 @@ def create_shipping_batch_from_notice_items(
|
||||
conversation_id: str | None,
|
||||
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。
|
||||
conversation_id: 可选 Agent 会话 ID。
|
||||
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 一致的结果字典。
|
||||
与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。
|
||||
|
||||
Raises:
|
||||
ValidationError: notice_items 为空。
|
||||
"""
|
||||
normalized_key = normalize_create_idempotency_key(create_idempotency_key)
|
||||
if not normalized_key:
|
||||
warn_missing_create_idempotency_key(source="create_shipping_batch_from_notice_items")
|
||||
|
||||
notice_items = dedupe_notice_items_by_content_hash(notice_items)
|
||||
if not notice_items:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
@@ -45,22 +70,46 @@ def create_shipping_batch_from_notice_items(
|
||||
details={"file_summary": file_summary or {}},
|
||||
)
|
||||
|
||||
if normalized_key:
|
||||
existing_batch = find_batch_by_create_idempotency(user_id, normalized_key)
|
||||
if existing_batch:
|
||||
assert_idempotent_batch_content_matches(existing_batch, notice_items)
|
||||
created = build_existing_batch_tool_response(existing_batch, user_id=user_id)
|
||||
if file_summary:
|
||||
created["file_summary"] = file_summary
|
||||
return created
|
||||
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
"defer_parse": True,
|
||||
"create_idempotency_key": normalized_key,
|
||||
"defer_commit": bool(defer_commit),
|
||||
}
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
try:
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
except IntegrityError as exc:
|
||||
replay = handle_batch_create_integrity_error(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=normalized_key,
|
||||
exc=exc,
|
||||
)
|
||||
if replay is None:
|
||||
raise
|
||||
created = replay
|
||||
|
||||
if not isinstance(created, dict):
|
||||
return {"status": "failed", "message": "create batch failed"}
|
||||
|
||||
idempotent_replay = bool(created.get("idempotent_replay"))
|
||||
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:
|
||||
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)
|
||||
@@ -72,6 +121,8 @@ def create_shipping_batch_from_notice_items(
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = f"{base_message},后台已开始逐票处理。" if base_message else "后台已开始逐票处理。"
|
||||
if idempotent_replay:
|
||||
created["idempotent_replay"] = True
|
||||
if file_summary:
|
||||
created["file_summary"] = file_summary
|
||||
return created
|
||||
@@ -85,8 +136,12 @@ def format_batch_created_assistant_message(
|
||||
"""
|
||||
格式化建批成功后写入 Chat Turn assistant 气泡的文案。
|
||||
|
||||
核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构。
|
||||
核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。
|
||||
"""
|
||||
if bool(result.get("idempotent_replay")):
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。"
|
||||
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
batch = data.get("batch") if isinstance(data.get("batch"), dict) else {}
|
||||
tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else []
|
||||
@@ -132,11 +187,12 @@ def intake_notice_uploads_for_batch(
|
||||
"""
|
||||
from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads
|
||||
|
||||
accepted, rejected = intake_temp_notice_uploads(request_id, uploads)
|
||||
accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads)
|
||||
file_summary = build_notice_file_summary(
|
||||
total_files=len(uploads),
|
||||
accepted=accepted,
|
||||
rejected=rejected,
|
||||
duplicate_files=duplicate_files,
|
||||
)
|
||||
notice_items = [item.to_notice_item() for item in accepted]
|
||||
return notice_items, file_summary
|
||||
@@ -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,
|
||||
}
|
||||
@@ -113,6 +113,7 @@ class ShippingCreateBatchFromNoticesAction:
|
||||
raise ValidationError("notice_items is required")
|
||||
file_summary = payload.get("file_summary") if isinstance(payload.get("file_summary"), dict) else None
|
||||
conversation_id = _payload_str(payload, "conversation_id", "conversationId") or None
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_notices", "label": "处理发货通知..."})
|
||||
|
||||
@@ -126,6 +127,7 @@ class ShippingCreateBatchFromNoticesAction:
|
||||
conversation_id=conversation_id,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
@@ -141,11 +143,89 @@ class ShippingCreateBatchFromNoticesAction:
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
}
|
||||
yield from _stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"})
|
||||
|
||||
|
||||
class ShippingCreateBatchFromIntakesAction:
|
||||
"""基于已解析接入记录确认建批(第二阶段主路径)。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_intakes"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
intake_nos = payload.get("intake_nos")
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError("intake_nos is required")
|
||||
# 空白新会话 payload 常无 conversation_id;回退到 Chat Turn 刚创建的本地 session_id
|
||||
conversation_id = (
|
||||
_payload_str(payload, "conversation_id", "conversationId")
|
||||
or str(getattr(ctx, "session_id", "") or "").strip()
|
||||
or None
|
||||
)
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."})
|
||||
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.batch_from_notices import format_batch_created_assistant_message
|
||||
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
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)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(intake_nos)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
message_payload = {
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
"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"})
|
||||
|
||||
|
||||
class ShippingSubmitDecisionAction:
|
||||
"""提交人工决策:confirm / reject / rematch / retry_rpa 等。"""
|
||||
|
||||
@@ -264,6 +344,7 @@ class ShippingConfirmInventorySourceAction:
|
||||
"task_id": task.task_no,
|
||||
"source_code": source_code,
|
||||
"event_source": "chat_turn",
|
||||
"_trusted_user_id": ctx.user_id,
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed")
|
||||
@@ -303,6 +384,7 @@ class ShippingMarkManualUploadedAction:
|
||||
|
||||
_HANDLERS = (
|
||||
ShippingCreateBatchFromNoticesAction(),
|
||||
ShippingCreateBatchFromIntakesAction(),
|
||||
ShippingSubmitDecisionAction(),
|
||||
ShippingGenerateExcelAction(),
|
||||
ShippingRetryUploadAction(),
|
||||
|
||||
@@ -12,8 +12,10 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_OK,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_RPA_PENDING,
|
||||
PH_SHORTAGE,
|
||||
@@ -36,9 +38,17 @@ from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
has_uploaded_task_inventory,
|
||||
read_task_inventory_schema_preview,
|
||||
resolve_task_inventory_upload_path,
|
||||
task_inventory_upload_path,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
adjudicate_and_apply_inventory_source,
|
||||
ensure_inventory_source_review_state,
|
||||
task_needs_parse_review,
|
||||
transition_task_to_inventory_source_review,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
|
||||
@@ -160,6 +170,25 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
and not match_completed(task)
|
||||
)
|
||||
):
|
||||
is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
|
||||
# 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。
|
||||
if (
|
||||
not is_low_confidence_parse_confirm
|
||||
and (
|
||||
task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
or not is_inventory_source_stable(task)
|
||||
)
|
||||
):
|
||||
ui = resolve_task_ui_state(task)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
@@ -172,6 +201,24 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
if not is_inventory_source_stable(task):
|
||||
adjudication = ensure_inventory_source_review_state(task)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="解析内容已确认,请继续选择正式库存源。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_source_candidates": adjudication.candidates,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=resolve_task_ui_state(task).human_options,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
@@ -408,8 +455,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
|
||||
log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment})
|
||||
db.session.commit()
|
||||
upload_path = task_inventory_upload_path(task.task_no)
|
||||
if upload_path.is_file():
|
||||
upload_path = resolve_task_inventory_upload_path(task.task_no)
|
||||
if upload_path is not None:
|
||||
try:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
except OSError as exc:
|
||||
@@ -444,12 +491,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
|
||||
else:
|
||||
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
|
||||
upload_path = task_inventory_upload_path(task.task_no)
|
||||
if upload_path.is_file():
|
||||
try:
|
||||
upload_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
for suffix in (".xlsx", ".csv"):
|
||||
upload_path = task_inventory_upload_path(task.task_no, suffix=suffix)
|
||||
if upload_path.is_file():
|
||||
try:
|
||||
upload_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
log_task_event(task, "inventory_reparse_requested", {"comment": comment})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -39,6 +39,7 @@ from app.services.shipping_notice.rpa_attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
upload_rpa_attempts,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
@@ -270,6 +271,16 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源尚未确定,无法执行库存匹配。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint="inventory_source_review",
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 3] 执行匹配并按结果分流。
|
||||
# fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。
|
||||
def _on_match_progress(processed: int, total: int) -> None:
|
||||
@@ -363,6 +374,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="库存源尚未确定,无法生成发货 Excel。",
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
|
||||
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
|
||||
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
|
||||
if task.export_file_path and not task_export_error_message(task):
|
||||
@@ -440,6 +460,14 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="库存源尚未确定,无法上传货代系统。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 1] 先确保上传所需的 Excel 已经存在。
|
||||
# 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。
|
||||
if not task.export_file_path:
|
||||
|
||||
@@ -105,7 +105,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。",
|
||||
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
|
||||
"workflow.inventory.file_missing": "未收到 file 字段",
|
||||
"workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .xls / .csv 库存文件",
|
||||
"workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .csv 库存文件",
|
||||
"workflow.inventory.uploading": "正在上传并解析库存文件",
|
||||
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
|
||||
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
|
||||
@@ -240,7 +240,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.",
|
||||
"workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}",
|
||||
"workflow.inventory.file_missing": "The file field was not received.",
|
||||
"workflow.inventory.file_type_unsupported": "Only .xlsx / .xls / .csv inventory files are supported.",
|
||||
"workflow.inventory.file_type_unsupported": "Only .xlsx / .csv inventory files are supported.",
|
||||
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
|
||||
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
|
||||
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
|
||||
@@ -375,7 +375,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers",
|
||||
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
|
||||
"workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file",
|
||||
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .xls / .csv",
|
||||
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .csv",
|
||||
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
|
||||
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
|
||||
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -0,0 +1,823 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/intake_parse_workflow.py
|
||||
|
||||
用途:发货通知接入记录的文本抽取与预解析编排;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 app import db
|
||||
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', '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:
|
||||
"""
|
||||
从 FileAsset 下载并抽取发货通知文本。
|
||||
核心逻辑:写入临时文件后复用 extract_notice_text,避免长期落盘到 notice_uploads。
|
||||
"""
|
||||
raw = read_asset_bytes(asset)
|
||||
filename = str(asset.original_filename or 'notice')
|
||||
source_type = guess_source_type(filename)
|
||||
suffix = Path(filename).suffix or '.bin'
|
||||
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
||||
tmp.write(raw)
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
# 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(
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
source_file_type=asset.mime_type,
|
||||
text='',
|
||||
warnings=[f'notice_extract_failed:{exc}'],
|
||||
meta={},
|
||||
content_hash=str(asset.content_hash or ''),
|
||||
file_size=int(asset.file_size or 0),
|
||||
status='extract_failed',
|
||||
saved_path=None,
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
if not str(text or '').strip():
|
||||
return NoticeIntakeResult(
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
source_file_type=asset.mime_type,
|
||||
text='',
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=str(asset.content_hash or ''),
|
||||
file_size=int(asset.file_size or 0),
|
||||
status='empty_text',
|
||||
saved_path=None,
|
||||
)
|
||||
|
||||
text, warnings = truncate_notice_text(text, warnings)
|
||||
return NoticeIntakeResult(
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
source_file_type=asset.mime_type,
|
||||
text=text,
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=str(asset.content_hash or ''),
|
||||
file_size=int(asset.file_size or 0),
|
||||
status='accepted',
|
||||
saved_path=None,
|
||||
)
|
||||
|
||||
|
||||
_ABORT_WRITE_STATUSES = frozenset({'cancelled', 'expired', 'consumed'})
|
||||
# 与 cancel 同序写路径:解析写回 / 失败清理允许的状态
|
||||
_WRITABLE_PARSE_STATUSES = frozenset({'parsing', 'queued', 'created'})
|
||||
|
||||
|
||||
def _db_parse_status(intake_id: int) -> str | None:
|
||||
"""
|
||||
绕过 Session 身份映射强制读库中的 parse_status。
|
||||
|
||||
核心逻辑:expire 本地缓存后 refresh,避免抽取耗时窗口内他事务 cancel 后仍读到 parsing。
|
||||
"""
|
||||
obj = db.session.get(ShippingNoticeIntake, int(intake_id))
|
||||
if obj is None:
|
||||
return None
|
||||
db.session.expire(obj)
|
||||
db.session.refresh(obj)
|
||||
return str(obj.parse_status or '')
|
||||
|
||||
|
||||
def _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,
|
||||
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]:
|
||||
"""
|
||||
持 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:
|
||||
duplicate 检测结果字典。
|
||||
"""
|
||||
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,
|
||||
)
|
||||
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,
|
||||
*,
|
||||
parse_lease: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
执行单条接入记录的预解析并更新 ORM 状态。
|
||||
|
||||
核心逻辑:抽取文本(无锁)→ FOR UPDATE Intake → 校验 parse_lease →
|
||||
同事务落阶段二基础行 + parsed;重复检测在 SAVEPOINT;失败出口持锁清理。
|
||||
parse_lease 不匹配(超时后被新 Worker 接替)则 skipped,防止旧结果覆盖。
|
||||
|
||||
Returns:
|
||||
解析结果摘要字典;若期间被取消/过期/租约失效则 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()
|
||||
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 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 '未提取到有效文本'
|
||||
)
|
||||
return _fail_intake_with_stage2_cleanup(
|
||||
intake_id=intake_id,
|
||||
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,
|
||||
)
|
||||
|
||||
# [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': status_now,
|
||||
}
|
||||
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(含业务指纹与重复决策元数据)。
|
||||
|
||||
核心逻辑: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,
|
||||
'source_content_hash': asset.content_hash,
|
||||
'file_size': asset.file_size,
|
||||
'raw_text': intake.extracted_text or '',
|
||||
'warnings': list(intake.parse_warnings_json or []),
|
||||
'source_asset_id': asset.id,
|
||||
'source_intake_id': intake.id,
|
||||
'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
|
||||
@@ -0,0 +1,695 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/intake_service.py
|
||||
|
||||
用途:发货通知接入记录(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
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.jobs.queue import QUEUED_ONLY_STATUSES, enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, 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', 'v6') or 'v6').strip()
|
||||
|
||||
|
||||
def _intake_ttl_hours() -> int:
|
||||
return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1)
|
||||
|
||||
|
||||
def generate_intake_no() -> str:
|
||||
"""生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。"""
|
||||
return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _duplicate_payload_from_intake(intake: 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': 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,
|
||||
'expires_at': utc_iso(intake.expires_at),
|
||||
'consumed_at': utc_iso(intake.consumed_at),
|
||||
'created_at': utc_iso(intake.created_at),
|
||||
'updated_at': utc_iso(intake.updated_at),
|
||||
}
|
||||
if asset:
|
||||
payload['original_filename'] = asset.original_filename
|
||||
payload['file_size'] = asset.file_size
|
||||
payload['content_hash'] = asset.content_hash
|
||||
return payload
|
||||
|
||||
|
||||
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
||||
"""按编号查询当前用户的接入记录。"""
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == normalized)
|
||||
.first()
|
||||
)
|
||||
if not intake or int(intake.user_id) != int(user_id):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在')
|
||||
return intake
|
||||
|
||||
|
||||
def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
"""查询单个接入记录详情(含资产摘要与附件全文)。"""
|
||||
intake = get_intake_for_user(intake_no, user_id)
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if not asset:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
||||
return serialize_intake(intake, asset=asset, include_parse_texts=True)
|
||||
|
||||
|
||||
def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset:
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if not asset or asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
||||
return asset
|
||||
|
||||
|
||||
def _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,
|
||||
asset_no: str,
|
||||
conversation_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
基于已上传 FileAsset 创建接入记录并投递解析 Job。
|
||||
|
||||
核心逻辑:
|
||||
1. 校验资产 ready;
|
||||
2. FOR UPDATE 查同 (asset, purpose, parser_version);无则 SAVEPOINT 插入,
|
||||
IntegrityError 后回落再锁已有行(并发首次创建幂等);
|
||||
3. parsed/consumed/queued/parsing 直接返回;cancelled/expired(含过期时间到期)冲突拒绝;
|
||||
4. 仅 created/parse_failed 持锁重投:enqueue(commit=False) 并绑定 parse_job_id。
|
||||
"""
|
||||
asset = get_asset_for_user(asset_no, user_id)
|
||||
if str(asset.upload_status or '') != 'ready':
|
||||
raise ValidationError(code='FILE_ASSET.INVALID_STATUS', message='文件尚未上传完成')
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
|
||||
raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
|
||||
|
||||
parser_version = _parser_version()
|
||||
purpose = 'shipping_notice'
|
||||
conv = str(conversation_id or '').strip() or None
|
||||
|
||||
# [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=int(asset.id),
|
||||
user_id=int(user_id),
|
||||
conversation_id=conv,
|
||||
purpose=purpose,
|
||||
parse_status='created',
|
||||
parser_version=parser_version,
|
||||
expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()),
|
||||
)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
intake = candidate
|
||||
except IntegrityError:
|
||||
# 并发他事务已插入:回落锁定已有行并幂等继续
|
||||
intake = _lock_intake_for_asset_purpose_parser(
|
||||
asset_id=int(asset.id),
|
||||
purpose=purpose,
|
||||
parser_version=parser_version,
|
||||
)
|
||||
if intake is None:
|
||||
raise
|
||||
|
||||
# [STEP 2] 终态 / 已在飞 / 禁止复活
|
||||
status_now = str(intake.parse_status or '')
|
||||
if status_now in {'parsed', 'consumed', 'queued', 'parsing'}:
|
||||
db.session.commit()
|
||||
return serialize_intake(intake, asset=asset)
|
||||
if status_now == 'cancelled':
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
|
||||
message='接入已取消,无法再次创建',
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if status_now == 'expired' or (
|
||||
intake.expires_at is not None and intake.expires_at < now
|
||||
):
|
||||
if status_now != 'expired':
|
||||
intake.parse_status = 'expired'
|
||||
intake.updated_at = now
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.INTAKE_EXPIRED',
|
||||
message='接入已过期,请重新上传文件',
|
||||
)
|
||||
if status_now not in {'created', 'parse_failed'}:
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
|
||||
message='当前接入状态不允许再次创建',
|
||||
)
|
||||
|
||||
# [STEP 3] 持锁重投解析(仅 created / parse_failed)
|
||||
intake.parse_status = 'queued'
|
||||
intake.conversation_id = conv or intake.conversation_id
|
||||
intake.error_code = None
|
||||
intake.error_message = None
|
||||
intake.parse_lease = None
|
||||
intake.updated_at = now
|
||||
|
||||
# 与 retry 一致:仅复用 queued,不复用残留 running,避免挂到僵尸 Job
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_NOTICE_PARSE,
|
||||
{'intake_no': intake.intake_no},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=intake.intake_no,
|
||||
created_by_id=user_id,
|
||||
message='等待预解析发货通知',
|
||||
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
|
||||
dedupe_active=True,
|
||||
dedupe_statuses=QUEUED_ONLY_STATUSES,
|
||||
commit=False,
|
||||
)
|
||||
intake.parse_job_id = job_id
|
||||
db.session.commit()
|
||||
return serialize_intake(intake, asset=asset)
|
||||
|
||||
|
||||
def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
|
||||
"""列出会话下未消费的活跃接入记录,供页面恢复。"""
|
||||
query = db.session.query(ShippingNoticeIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
|
||||
).filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
)
|
||||
conv = str(conversation_id or '').strip()
|
||||
if conv:
|
||||
query = query.filter(ShippingNoticeIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all()
|
||||
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
||||
|
||||
|
||||
def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]:
|
||||
"""批量查询接入状态。"""
|
||||
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
|
||||
if not normalized:
|
||||
return []
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
||||
|
||||
|
||||
def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
"""
|
||||
重试解析:parse_failed,或顶层已 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='当前状态不允许重试解析',
|
||||
)
|
||||
asset = _load_asset_for_intake(intake)
|
||||
intake.parse_status = 'queued'
|
||||
intake.error_code = None
|
||||
intake.error_message = None
|
||||
intake.parse_lease = None
|
||||
intake.updated_at = datetime.utcnow()
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_NOTICE_PARSE,
|
||||
{'intake_no': intake.intake_no},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=intake.intake_no,
|
||||
created_by_id=user_id,
|
||||
message='等待重试预解析发货通知',
|
||||
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
|
||||
dedupe_active=True,
|
||||
dedupe_statuses=QUEUED_ONLY_STATUSES,
|
||||
commit=False,
|
||||
)
|
||||
intake.parse_job_id = job_id
|
||||
db.session.commit()
|
||||
return serialize_intake(intake, asset=asset)
|
||||
|
||||
|
||||
def cancel_intake(*, user_id: int, intake_no: str) -> None:
|
||||
"""
|
||||
取消未消费的接入记录。
|
||||
|
||||
核心逻辑:FOR UPDATE 锁定后幂等取消;删除阶段二 Document/Candidate、释放派生引用,
|
||||
并清理 structured_result 中的阶段二投影字段,避免并发双释放与摘要自相矛盾。
|
||||
"""
|
||||
from app.services.shipping_notice.document_candidate_persist import (
|
||||
clear_intake_stage2_structured_projection,
|
||||
release_unconsumed_intake_stage2,
|
||||
)
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(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],
|
||||
batch_id: int | None,
|
||||
task_ids_by_intake: dict[int, int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
标记 intake 为 consumed 并增加资产引用计数。
|
||||
|
||||
核心逻辑:可在建批 commit 前预占(batch_id=None),避免 FOR UPDATE 在 create_batch_tasks 提交后释放导致并发双消费。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
task_map = task_ids_by_intake or {}
|
||||
for intake in intakes:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.consumed_batch_id = int(batch_id) if batch_id else None
|
||||
intake.consumed_task_id = task_map.get(intake.id)
|
||||
intake.updated_at = now
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if asset:
|
||||
mark_asset_referenced(asset)
|
||||
@@ -0,0 +1,296 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_file_identity.py
|
||||
|
||||
用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
|
||||
依赖:openpyxl、csv、app.core.errors.AppError。
|
||||
逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
_WAREHOUSE_ID_HEADER_ALIASES = {
|
||||
"warehouseid",
|
||||
"warehouse",
|
||||
"warehousecode",
|
||||
"warehousecodeid",
|
||||
"whid",
|
||||
}
|
||||
_HEADER_SCAN_ROWS = 20
|
||||
|
||||
|
||||
def _normalize_header_key(value: Any) -> str:
|
||||
"""将 Excel 表头标准化为可比较 key。"""
|
||||
return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum())
|
||||
|
||||
|
||||
def _row_non_empty_count(row: tuple[Any, ...] | list[Any]) -> int:
|
||||
"""统计行内非空单元格数量,用于跳过标题行。"""
|
||||
return sum(1 for cell in row if str(cell or "").strip())
|
||||
|
||||
|
||||
def _score_warehouse_header_row(row: tuple[Any, ...] | list[Any]) -> tuple[int, int] | None:
|
||||
"""
|
||||
为候选表头行打分并定位 Warehouse 列。
|
||||
核心逻辑:要求行内至少 2 个非空单元格,避免报表标题行单独出现 Warehouse 被误判为表头。
|
||||
"""
|
||||
if _row_non_empty_count(row) < 2:
|
||||
return None
|
||||
best_col: int | None = None
|
||||
for col_idx, cell in enumerate(row):
|
||||
if _normalize_header_key(cell) in _WAREHOUSE_ID_HEADER_ALIASES:
|
||||
best_col = col_idx
|
||||
break
|
||||
if best_col is None:
|
||||
return None
|
||||
score = _row_non_empty_count(row) * 10 + (5 if best_col == 0 else 0)
|
||||
return score, best_col
|
||||
|
||||
|
||||
def _find_warehouse_column(rows: list[tuple[Any, ...]]) -> tuple[int | None, int | None]:
|
||||
"""在表头候选区定位得分最高的 Warehouse 列。"""
|
||||
scan_limit = min(len(rows), _HEADER_SCAN_ROWS)
|
||||
best_score = 0
|
||||
best_row: int | None = None
|
||||
best_col: int | None = None
|
||||
for row_idx in range(scan_limit):
|
||||
scored = _score_warehouse_header_row(rows[row_idx])
|
||||
if scored is None:
|
||||
continue
|
||||
score, col_idx = scored
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_row = row_idx
|
||||
best_col = col_idx
|
||||
return best_row, best_col
|
||||
|
||||
|
||||
def _load_xlsx_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
|
||||
"""仅读取 xlsx 前若干行供表头定位(小内存)。"""
|
||||
try:
|
||||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||||
except Exception:
|
||||
return []
|
||||
try:
|
||||
ws = wb.active
|
||||
rows: list[tuple[Any, ...]] = []
|
||||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||||
if i >= max_rows:
|
||||
break
|
||||
rows.append(tuple(row))
|
||||
return rows
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
|
||||
"""流式遍历 xlsx Warehouse 列非空值。"""
|
||||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||||
if i <= header_row_idx:
|
||||
continue
|
||||
if col_idx >= len(row):
|
||||
continue
|
||||
value = str(row[col_idx] or "").strip().upper()
|
||||
if value:
|
||||
yield value
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _detect_csv_dialect(sample: str) -> csv.Dialect:
|
||||
"""探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。"""
|
||||
try:
|
||||
return csv.Sniffer().sniff(sample, delimiters=",;\t|")
|
||||
except csv.Error:
|
||||
return csv.excel
|
||||
|
||||
|
||||
def _load_csv_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
|
||||
"""仅读取 CSV 前若干行供表头定位。"""
|
||||
for encoding in ("utf-8-sig", "utf-8", "gbk"):
|
||||
try:
|
||||
with path.open("r", encoding=encoding, newline="") as handle:
|
||||
sample = handle.read(4096)
|
||||
handle.seek(0)
|
||||
dialect = _detect_csv_dialect(sample)
|
||||
rows: list[tuple[Any, ...]] = []
|
||||
for row in csv.reader(handle, dialect=dialect):
|
||||
rows.append(tuple(row))
|
||||
if len(rows) >= max_rows:
|
||||
break
|
||||
return rows
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
except OSError:
|
||||
return []
|
||||
return []
|
||||
|
||||
|
||||
def _iter_csv_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
|
||||
"""流式遍历 CSV Warehouse 列非空值。"""
|
||||
for encoding in ("utf-8-sig", "utf-8", "gbk"):
|
||||
try:
|
||||
with path.open("r", encoding=encoding, newline="") as handle:
|
||||
sample = handle.read(4096)
|
||||
handle.seek(0)
|
||||
dialect = _detect_csv_dialect(sample)
|
||||
for row_idx, row in enumerate(csv.reader(handle, dialect=dialect)):
|
||||
if row_idx <= header_row_idx:
|
||||
continue
|
||||
if col_idx >= len(row):
|
||||
continue
|
||||
value = str(row[col_idx] or "").strip().upper()
|
||||
if value:
|
||||
yield value
|
||||
return
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
|
||||
|
||||
def load_inventory_csv_rows(path: Path, *, max_rows: int | None = None) -> list[list[Any]]:
|
||||
"""
|
||||
读取库存 CSV 行。
|
||||
核心逻辑:max_rows 为 None 时读取全文件;预览场景请显式传入较小上限。
|
||||
身份校验请使用流式 extract_warehouse_ids_from_inventory_excel。
|
||||
"""
|
||||
limit = None if max_rows is None else max(1, int(max_rows))
|
||||
for encoding in ("utf-8-sig", "utf-8", "gbk"):
|
||||
try:
|
||||
with path.open("r", encoding=encoding, newline="") as handle:
|
||||
sample = handle.read(4096)
|
||||
handle.seek(0)
|
||||
dialect = _detect_csv_dialect(sample)
|
||||
rows: list[list[Any]] = []
|
||||
for row in csv.reader(handle, dialect=dialect):
|
||||
rows.append(list(row))
|
||||
if limit is not None and len(rows) >= limit:
|
||||
break
|
||||
return rows
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
except OSError:
|
||||
return []
|
||||
return []
|
||||
|
||||
|
||||
def _collect_unique_warehouse_values(values: Iterator[str]) -> set[str]:
|
||||
"""从 Warehouse 列迭代器收集去重集合。"""
|
||||
warehouses: set[str] = set()
|
||||
for value in values:
|
||||
warehouses.add(value)
|
||||
return warehouses
|
||||
|
||||
|
||||
def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]:
|
||||
"""
|
||||
从库存文件提取所有非空 Warehouse ID 值(去重)。
|
||||
核心逻辑:前 20 行定位表头;数据区流式扫描目标列,避免全表加载。
|
||||
"""
|
||||
if not path or not path.is_file():
|
||||
return set()
|
||||
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".csv":
|
||||
header_rows = _load_csv_header_rows(path)
|
||||
header_row_idx, col_idx = _find_warehouse_column(header_rows)
|
||||
if header_row_idx is None or col_idx is None:
|
||||
return set()
|
||||
return _collect_unique_warehouse_values(
|
||||
_iter_csv_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
|
||||
)
|
||||
if suffix == ".xlsx":
|
||||
header_rows = _load_xlsx_header_rows(path)
|
||||
header_row_idx, col_idx = _find_warehouse_column(header_rows)
|
||||
if header_row_idx is None or col_idx is None:
|
||||
return set()
|
||||
return _collect_unique_warehouse_values(
|
||||
_iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
|
||||
)
|
||||
if suffix == ".xls":
|
||||
return set()
|
||||
return set()
|
||||
|
||||
|
||||
def assert_inventory_excel_warehouse_identity(
|
||||
path: Path,
|
||||
*,
|
||||
expected_warehouse_id: str,
|
||||
operation: str = "inventory_import",
|
||||
) -> str:
|
||||
"""
|
||||
强制校验 Excel 内 Warehouse ID 与预期库位一致且唯一。
|
||||
核心逻辑:混合多库位或内容与预期不符时抛出 AppError,拒绝入库/绑定。
|
||||
|
||||
Args:
|
||||
path: 库存 Excel 路径。
|
||||
expected_warehouse_id: 任务或运行时 source 要求的库位。
|
||||
operation: 审计用途的操作名。
|
||||
|
||||
Returns:
|
||||
str: Excel 中唯一的 Warehouse ID(大写)。
|
||||
|
||||
Raises:
|
||||
AppError: 缺列、多库位或与预期不一致。
|
||||
"""
|
||||
expected = str(expected_warehouse_id or "").strip().upper()
|
||||
if not expected:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
message="预期库位为空,无法校验库存文件内容",
|
||||
http_status=409,
|
||||
details={"operation": operation},
|
||||
)
|
||||
|
||||
suffix = path.suffix.lower()
|
||||
if suffix not in {".xlsx", ".csv"}:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传",
|
||||
http_status=409,
|
||||
details={"operation": operation, "file_suffix": suffix},
|
||||
)
|
||||
|
||||
found = extract_warehouse_ids_from_inventory_excel(path)
|
||||
if not found:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING",
|
||||
message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库",
|
||||
http_status=409,
|
||||
details={"operation": operation, "expected_warehouse_id": expected},
|
||||
)
|
||||
if len(found) > 1:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED",
|
||||
message="库存文件包含多个 Warehouse ID,已拒绝入库",
|
||||
http_status=409,
|
||||
details={
|
||||
"operation": operation,
|
||||
"expected_warehouse_id": expected,
|
||||
"excel_warehouse_ids": sorted(found),
|
||||
},
|
||||
)
|
||||
actual = next(iter(found))
|
||||
if actual != expected:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库",
|
||||
http_status=409,
|
||||
details={
|
||||
"operation": operation,
|
||||
"expected_warehouse_id": expected,
|
||||
"excel_warehouse_id": actual,
|
||||
},
|
||||
)
|
||||
return actual
|
||||
@@ -17,12 +17,18 @@ from typing import Any
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
|
||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
@@ -44,9 +50,79 @@ def generate_inventory_file_no() -> str:
|
||||
return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def inventory_file_upload_path(inventory_file_no: str) -> Path:
|
||||
"""库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory.xlsx)。"""
|
||||
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / "inventory.xlsx"
|
||||
_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"})
|
||||
|
||||
|
||||
def resolve_inventory_upload_suffix(filename: str) -> str:
|
||||
"""
|
||||
解析人工上传库存文件的合法落盘后缀。
|
||||
核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。
|
||||
|
||||
Raises:
|
||||
AppError: 后缀缺失、不支持或为 .xls。
|
||||
"""
|
||||
name = str(filename or "").strip().lower()
|
||||
if not name or "." not in name:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传缺少可识别的文件后缀",
|
||||
http_status=409,
|
||||
)
|
||||
if name.endswith(".xlsx"):
|
||||
return ".xlsx"
|
||||
if name.endswith(".csv"):
|
||||
return ".csv"
|
||||
if name.endswith(".xls"):
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传不支持 .xls,请转换为 .xlsx 或 .csv 后重新上传",
|
||||
http_status=409,
|
||||
)
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传仅支持 .xlsx / .csv",
|
||||
http_status=409,
|
||||
)
|
||||
|
||||
|
||||
def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx") -> Path:
|
||||
"""库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory{suffix})。"""
|
||||
normalized = str(suffix or ".xlsx").lower()
|
||||
if normalized not in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES:
|
||||
normalized = ".xlsx"
|
||||
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}"
|
||||
|
||||
|
||||
def inventory_storage_suffix_for_path(path: str | Path) -> str:
|
||||
"""根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。"""
|
||||
suffix = Path(path).suffix.lower()
|
||||
return suffix if suffix in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES else ".xlsx"
|
||||
|
||||
|
||||
def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
|
||||
"""
|
||||
删除库存快照托管文件及空目录。
|
||||
核心逻辑:数据库回滚或唯一约束冲突时清理已复制文件,避免孤儿目录。
|
||||
"""
|
||||
import logging
|
||||
|
||||
if not storage_path or str(storage_path).startswith("failed://"):
|
||||
return
|
||||
path = Path(storage_path)
|
||||
if path.is_file():
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError as exc:
|
||||
logging.getLogger(__name__).warning("failed to delete inventory file %s: %s", path, exc)
|
||||
parent = path.parent
|
||||
if parent.is_dir():
|
||||
try:
|
||||
next(parent.iterdir())
|
||||
except StopIteration:
|
||||
try:
|
||||
parent.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None:
|
||||
@@ -77,18 +153,74 @@ def has_uploaded_inventory_file(task: ShippingTask) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> bool:
|
||||
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
|
||||
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
|
||||
return False
|
||||
left = task_inventory_identity(lhs)
|
||||
right = task_inventory_identity(rhs)
|
||||
return (
|
||||
left["inventory_source_code"] == right["inventory_source_code"]
|
||||
and left["inventory_site_id"] == right["inventory_site_id"]
|
||||
and left["inventory_warehouse_id"] == right["inventory_warehouse_id"]
|
||||
)
|
||||
|
||||
|
||||
def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile:
|
||||
"""
|
||||
保存库存 Excel 并创建批次级库存快照。
|
||||
|
||||
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
|
||||
核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。
|
||||
"""
|
||||
if not is_inventory_source_stable(task):
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
|
||||
message="库存源尚未稳定,拒绝保存库存上传文件",
|
||||
http_status=409,
|
||||
)
|
||||
|
||||
identity = task_inventory_identity(task)
|
||||
source_code = identity["inventory_source_code"] or ""
|
||||
site_id = identity["inventory_site_id"]
|
||||
warehouse_id = identity["inventory_warehouse_id"]
|
||||
from datetime import datetime
|
||||
|
||||
inventory_file_no = generate_inventory_file_no()
|
||||
path = inventory_file_upload_path(inventory_file_no)
|
||||
upload_suffix = resolve_inventory_upload_suffix(str(upload.filename or ""))
|
||||
path = inventory_file_upload_path(inventory_file_no, suffix=upload_suffix)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
upload.save(str(path))
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(upload.filename or path.name)
|
||||
try:
|
||||
upload.save(str(path))
|
||||
from app.services.shipping_notice.inventory_file_identity import (
|
||||
assert_inventory_excel_warehouse_identity,
|
||||
)
|
||||
|
||||
assert_inventory_excel_warehouse_identity(
|
||||
path,
|
||||
expected_warehouse_id=str(warehouse_id or ""),
|
||||
operation="manual_upload",
|
||||
)
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(upload.filename or path.name)
|
||||
except AppError:
|
||||
if path.is_file():
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).warning(
|
||||
"failed to delete rejected inventory upload file %s", path
|
||||
)
|
||||
raise
|
||||
except Exception:
|
||||
if path.is_file():
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
@@ -97,16 +229,59 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
source_file_name=str(upload.filename or "").strip() or path.name,
|
||||
storage_path=str(path),
|
||||
schema_preview_json=preview,
|
||||
share_mode="batch_all" if task.batch_id else "task_only",
|
||||
share_mode="task_only",
|
||||
line_count=0,
|
||||
source_code=source_code,
|
||||
source_type=str(task.inventory_source_type or "").strip() or None,
|
||||
site_id=site_id,
|
||||
warehouse_id=warehouse_id,
|
||||
source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(),
|
||||
identity_status="pending",
|
||||
snapshot_status="ready",
|
||||
exported_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
|
||||
candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
|
||||
linked_tasks = [item for item in candidates if _can_relink_inventory(item)]
|
||||
linked_tasks = [
|
||||
item
|
||||
for item in candidates
|
||||
if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item)
|
||||
]
|
||||
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
||||
|
||||
created_links: list[ShippingTaskInventoryLink] = []
|
||||
for item in linked_tasks:
|
||||
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
|
||||
link = link_snapshot_to_task(
|
||||
item,
|
||||
inv_file,
|
||||
reason="manual_upload",
|
||||
role="owner" if item.id == task.id else "member",
|
||||
audit_payload={"upload_filename": preview.get("upload_filename")},
|
||||
)
|
||||
if link is None:
|
||||
for prior in created_links:
|
||||
db.session.delete(prior)
|
||||
db.session.delete(inv_file)
|
||||
db.session.flush()
|
||||
if path.is_file():
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).warning(
|
||||
"failed to delete inventory upload after link failure %s", path
|
||||
)
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定",
|
||||
http_status=409,
|
||||
)
|
||||
created_links.append(link)
|
||||
if len(linked_tasks) > 1:
|
||||
inv_file.share_mode = "batch_same_identity"
|
||||
return inv_file
|
||||
|
||||
|
||||
@@ -139,7 +314,8 @@ def save_task_inventory_file_from_local_path(
|
||||
raise FileNotFoundError(f"未找到库存源文件: {source}")
|
||||
|
||||
inventory_file_no = generate_inventory_file_no()
|
||||
path = inventory_file_upload_path(inventory_file_no)
|
||||
storage_suffix = inventory_storage_suffix_for_path(source)
|
||||
path = inventory_file_upload_path(inventory_file_no, suffix=storage_suffix)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, path)
|
||||
preview = read_inventory_schema_preview(path)
|
||||
|
||||
@@ -282,6 +282,7 @@ def inventory_loaded_response(
|
||||
chain_payload: dict[str, Any] | None = None,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str | None = None,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。
|
||||
@@ -289,7 +290,14 @@ def inventory_loaded_response(
|
||||
Args:
|
||||
require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。
|
||||
chain_payload: 传递给 auto-chain 的原始请求体。
|
||||
commit: False 时仅 flush,供 batch 外层统一提交,避免中途 commit 破坏事务边界。
|
||||
"""
|
||||
def _persist_inventory_loaded() -> None:
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
|
||||
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
@@ -351,8 +359,11 @@ def inventory_loaded_response(
|
||||
"column_meta": column_meta,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
|
||||
_persist_inventory_loaded()
|
||||
if commit:
|
||||
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
|
||||
else:
|
||||
chained = None
|
||||
if chained is not None:
|
||||
return chained
|
||||
lang = None
|
||||
@@ -391,8 +402,8 @@ def inventory_loaded_response(
|
||||
"linked_task_nos": [item.task_no for item in linked_tasks],
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
if inv_file:
|
||||
_persist_inventory_loaded()
|
||||
if commit and inv_file:
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_callback_cleanup.py
|
||||
|
||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
|
||||
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
|
||||
逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir
|
||||
|
||||
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
|
||||
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
|
||||
_CLEANUP_FAILED_DIRNAME = ".cleanup_failed"
|
||||
_QUARANTINE_DIRNAME = ".hxops_quarantine"
|
||||
_DEFAULT_MAX_CLEANUP_ATTEMPTS = 16
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def callback_cleanup_queue_dir() -> Path | None:
|
||||
"""drop 目录下 callback 归档重试队列路径。"""
|
||||
drop = inventory_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_QUEUE_DIRNAME
|
||||
|
||||
|
||||
def callback_cleanup_failed_dir() -> Path | None:
|
||||
"""超过最大重试次数的 cleanup job 隔离目录。"""
|
||||
drop = inventory_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_FAILED_DIRNAME
|
||||
|
||||
|
||||
def callback_quarantine_dir() -> Path | None:
|
||||
"""
|
||||
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
|
||||
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
|
||||
"""
|
||||
drop = inventory_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _QUARANTINE_DIRNAME
|
||||
|
||||
|
||||
def callback_cleanup_max_attempts() -> int:
|
||||
"""cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
|
||||
try:
|
||||
return max(
|
||||
1,
|
||||
int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
|
||||
|
||||
|
||||
def is_callback_drop_file_consumed(callback_path: Path) -> bool:
|
||||
"""判断 drop 文件是否已被 HXOPS 消费(sidecar 或已位于 quarantine)。"""
|
||||
path = Path(callback_path)
|
||||
if not path.name:
|
||||
return False
|
||||
quarantine = callback_quarantine_dir()
|
||||
if quarantine and quarantine in path.parents:
|
||||
return True
|
||||
sidecar = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
|
||||
return sidecar.is_file()
|
||||
|
||||
|
||||
def mark_callback_drop_file_consumed(
|
||||
callback_path: Path,
|
||||
*,
|
||||
run_no: str | None = None,
|
||||
task_no: str | None = None,
|
||||
schedule_run_id: int | None = None,
|
||||
inventory_file_no: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
标记 drop 区 callback 文件已被系统消费。
|
||||
核心逻辑:写 sidecar JSON;配合 quarantine 供 Worker 跳过重复扫描(Worker 须忽略 .hxops_* 子目录)。
|
||||
"""
|
||||
if not callback_path.is_file():
|
||||
return
|
||||
sidecar = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
|
||||
payload = {
|
||||
"callback_path": str(callback_path),
|
||||
"consumed_at": datetime.utcnow().isoformat(),
|
||||
"run_no": str(run_no or "").strip() or None,
|
||||
"task_no": str(task_no or "").strip() or None,
|
||||
"schedule_run_id": schedule_run_id,
|
||||
"inventory_file_no": str(inventory_file_no or "").strip() or None,
|
||||
}
|
||||
try:
|
||||
sidecar.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as exc:
|
||||
_LOGGER.warning("failed to write callback consumed marker %s: %s", sidecar, exc)
|
||||
|
||||
|
||||
def quarantine_callback_drop_file(callback_path: Path) -> Path | None:
|
||||
"""
|
||||
将归档失败的 callback 原子移入隔离目录,避免 Worker 扫描 drop 根目录时重复上报。
|
||||
Returns:
|
||||
隔离后的路径;不可用时返回 None。
|
||||
"""
|
||||
path = Path(callback_path)
|
||||
if not path.is_file():
|
||||
return None
|
||||
quarantine = callback_quarantine_dir()
|
||||
if quarantine is None:
|
||||
return None
|
||||
quarantine.mkdir(parents=True, exist_ok=True)
|
||||
target = quarantine / path.name
|
||||
if target.exists():
|
||||
target = quarantine / (
|
||||
f"{path.stem}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{path.suffix}"
|
||||
)
|
||||
shutil.move(str(path), str(target))
|
||||
consumed = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
|
||||
if consumed.is_file():
|
||||
try:
|
||||
consumed.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return target
|
||||
|
||||
|
||||
def enqueue_callback_file_move(
|
||||
callback_path: Path,
|
||||
*,
|
||||
processed_dir: Path,
|
||||
run_no: str | None = None,
|
||||
task_no: str | None = None,
|
||||
schedule_run_id: int | None = None,
|
||||
error: str | None = None,
|
||||
) -> Path | None:
|
||||
"""
|
||||
将失败的 callback 归档操作写入持久化队列,供后续重试。
|
||||
Returns:
|
||||
队列 job 文件路径;队列不可用时返回 None。
|
||||
"""
|
||||
queue = callback_cleanup_queue_dir()
|
||||
if queue is None:
|
||||
return None
|
||||
queue.mkdir(parents=True, exist_ok=True)
|
||||
job_id = uuid.uuid4().hex
|
||||
job_path = queue / f"move_{job_id}.json"
|
||||
payload: dict[str, Any] = {
|
||||
"job_id": job_id,
|
||||
"callback_path": str(callback_path),
|
||||
"processed_dir": str(processed_dir),
|
||||
"run_no": str(run_no or "").strip() or None,
|
||||
"task_no": str(task_no or "").strip() or None,
|
||||
"schedule_run_id": schedule_run_id,
|
||||
"last_error": str(error or "").strip() or None,
|
||||
"enqueued_at": datetime.utcnow().isoformat(),
|
||||
"attempts": 0,
|
||||
}
|
||||
tmp = job_path.with_suffix(".json.tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
tmp.replace(job_path)
|
||||
except OSError as exc:
|
||||
_LOGGER.warning("failed to enqueue callback move job for %s: %s", callback_path, exc)
|
||||
return None
|
||||
return job_path
|
||||
|
||||
|
||||
def move_callback_drop_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
|
||||
"""将 callback 文件移入 processed 目录(公开给 workflow 直接调用)。"""
|
||||
_move_callback_file_to_processed(callback_path, processed_dir)
|
||||
|
||||
|
||||
def _move_callback_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
|
||||
"""将 callback 文件移入 processed 目录。"""
|
||||
if not callback_path.is_file():
|
||||
return
|
||||
processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = processed_dir / callback_path.name
|
||||
if target.exists():
|
||||
target = processed_dir / (
|
||||
f"{callback_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{callback_path.suffix}"
|
||||
)
|
||||
shutil.move(str(callback_path), str(target))
|
||||
consumed = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
|
||||
if consumed.is_file():
|
||||
try:
|
||||
consumed.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _archive_failed_cleanup_job(job_path: Path, payload: dict[str, Any]) -> None:
|
||||
"""超过最大重试次数后将 job 移入 failed 目录。"""
|
||||
failed_dir = callback_cleanup_failed_dir()
|
||||
if failed_dir is None:
|
||||
try:
|
||||
job_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
failed_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = failed_dir / job_path.name
|
||||
payload["archived_at"] = datetime.utcnow().isoformat()
|
||||
try:
|
||||
target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
job_path.unlink()
|
||||
except OSError as exc:
|
||||
_LOGGER.warning("failed to archive cleanup job %s: %s", job_path, exc)
|
||||
|
||||
|
||||
def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
|
||||
"""
|
||||
重试持久化 callback 归档队列。
|
||||
核心逻辑:源文件已不存在视为完成;超限 job 移入 failed;仍失败则累加 attempts。
|
||||
"""
|
||||
queue = callback_cleanup_queue_dir()
|
||||
if queue is None or not queue.is_dir():
|
||||
return []
|
||||
warnings: list[str] = []
|
||||
max_attempts = callback_cleanup_max_attempts()
|
||||
jobs = sorted(queue.glob("move_*.json"))[: max(max_jobs, 1)]
|
||||
for job_path in jobs:
|
||||
try:
|
||||
payload = json.loads(job_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
|
||||
warnings.append(f"{job_path.name}:invalid_job:{str(exc)[:80]}")
|
||||
try:
|
||||
job_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
callback_raw = str(payload.get("callback_path") or "").strip()
|
||||
processed_raw = str(payload.get("processed_dir") or "").strip()
|
||||
callback_path = Path(callback_raw) if callback_raw else None
|
||||
processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir()
|
||||
if callback_path is None or processed_dir is None:
|
||||
try:
|
||||
job_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
if not callback_path.is_file():
|
||||
try:
|
||||
job_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
if int(payload.get("attempts") or 0) >= max_attempts:
|
||||
warnings.append(f"{callback_path}:max_attempts_exceeded")
|
||||
_archive_failed_cleanup_job(job_path, payload)
|
||||
continue
|
||||
try:
|
||||
_move_callback_file_to_processed(callback_path, processed_dir)
|
||||
try:
|
||||
job_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
payload["attempts"] = int(payload.get("attempts") or 0) + 1
|
||||
payload["last_error"] = str(exc)[:240]
|
||||
payload["last_attempt_at"] = datetime.utcnow().isoformat()
|
||||
warnings.append(f"{callback_path}:{str(exc)[:120]}")
|
||||
if int(payload["attempts"]) >= max_attempts:
|
||||
_archive_failed_cleanup_job(job_path, payload)
|
||||
else:
|
||||
try:
|
||||
job_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
_LOGGER.warning(
|
||||
"callback cleanup retry failed for %s (attempt=%s)",
|
||||
callback_path,
|
||||
payload["attempts"],
|
||||
exc_info=exc,
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
def recover_pending_rpa_callback_cleanup_jobs(*, max_jobs: int = 64) -> tuple[int, list[str]]:
|
||||
"""
|
||||
启动或调度恢复时消费 callback cleanup 队列。
|
||||
Returns:
|
||||
tuple: (成功消化或移除的 job 数, 告警列表)。
|
||||
"""
|
||||
queue = callback_cleanup_queue_dir()
|
||||
before = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
|
||||
warnings = flush_callback_cleanup_queue(max_jobs=max_jobs)
|
||||
after = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
|
||||
return max(0, before - after), warnings
|
||||
File diff suppressed because it is too large.
Load diff
@@ -248,7 +248,18 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40
|
||||
|
||||
|
||||
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
|
||||
"""Load worksheet rows; returns (rows, total_row_count_hint)."""
|
||||
"""Load worksheet or CSV rows; returns (rows, total_row_count_hint)."""
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".csv":
|
||||
from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
|
||||
|
||||
rows = load_inventory_csv_rows(path, max_rows=max_rows)
|
||||
try:
|
||||
total = sum(1 for _ in path.open("r", encoding="utf-8", errors="ignore"))
|
||||
except OSError:
|
||||
total = len(rows)
|
||||
return rows, int(total)
|
||||
|
||||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
|
||||
@@ -14,7 +14,6 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
@@ -22,6 +21,7 @@ from app.services.shipping_notice.inventory_file_store import (
|
||||
_can_relink_inventory,
|
||||
generate_inventory_file_no,
|
||||
inventory_file_upload_path,
|
||||
inventory_storage_suffix_for_path,
|
||||
replace_task_inventory_link,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
|
||||
@@ -71,33 +71,156 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
|
||||
|
||||
def find_latest_ready_snapshot(
|
||||
source_code: str | None,
|
||||
warehouse_id: str | None,
|
||||
site_id: str | None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> ShippingInventoryFile | None:
|
||||
"""
|
||||
查找指定 source/warehouse 最新 ready 且未过期的库存快照。
|
||||
核心逻辑:按 exported_at 倒序取第一条;过期快照不在此返回。
|
||||
查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。
|
||||
核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。
|
||||
"""
|
||||
code = str(source_code or "").strip().upper()
|
||||
site = str(site_id or "").strip().upper()
|
||||
warehouse = str(warehouse_id or "").strip().upper()
|
||||
if not code or not warehouse:
|
||||
if not code:
|
||||
return None
|
||||
if not site and not warehouse:
|
||||
return None
|
||||
|
||||
rows = (
|
||||
ShippingInventoryFile.query.filter_by(
|
||||
source_code=code,
|
||||
warehouse_id=warehouse,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc())
|
||||
.limit(5)
|
||||
.all()
|
||||
query = ShippingInventoryFile.query.filter_by(
|
||||
source_code=code,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
if site:
|
||||
query = query.filter_by(site_id=site)
|
||||
if warehouse:
|
||||
query = query.filter_by(warehouse_id=warehouse)
|
||||
elif site:
|
||||
query = query.filter(
|
||||
(ShippingInventoryFile.warehouse_id.is_(None)) | (ShippingInventoryFile.warehouse_id == "")
|
||||
)
|
||||
|
||||
rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
|
||||
for row in rows:
|
||||
if is_snapshot_fresh(row):
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
def find_ready_rpa_inventory_snapshot(
|
||||
*,
|
||||
rpa_run_no: str,
|
||||
source_code: str,
|
||||
site_id: str,
|
||||
warehouse_id: str,
|
||||
) -> ShippingInventoryFile | None:
|
||||
"""
|
||||
按 RPA 轮次 + 四字段身份查找已入库 ready 快照。
|
||||
核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。
|
||||
"""
|
||||
run_no = str(rpa_run_no or "").strip()
|
||||
code = str(source_code or "").strip().upper()
|
||||
site = str(site_id or "").strip().upper()
|
||||
warehouse = str(warehouse_id or "").strip().upper()
|
||||
if not run_no or not code or not site or not warehouse:
|
||||
return None
|
||||
return (
|
||||
ShippingInventoryFile.query.filter_by(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
site_id=site,
|
||||
warehouse_id=warehouse,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
.order_by(ShippingInventoryFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def get_or_create_rpa_inventory_snapshot(
|
||||
*,
|
||||
source: dict[str, Any],
|
||||
local_path: str | Path,
|
||||
source_file_name: str | None = None,
|
||||
rpa_run_no: str | None = None,
|
||||
schedule_run_id: int | None = None,
|
||||
trigger_type: str = "on_demand",
|
||||
success: bool = True,
|
||||
error_message: str | None = None,
|
||||
user_id: int | None = None,
|
||||
batch_id: int | None = None,
|
||||
share_mode: str | None = None,
|
||||
verify_warehouse_id: str | None = None,
|
||||
) -> tuple[ShippingInventoryFile, bool]:
|
||||
"""
|
||||
幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。
|
||||
核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。
|
||||
|
||||
Returns:
|
||||
tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。
|
||||
"""
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
run_no = str(rpa_run_no or "").strip()
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
site = str(source.get("site_id") or "").strip().upper()
|
||||
warehouse = str(verify_warehouse_id or source.get("warehouse_id") or "").strip().upper()
|
||||
if run_no and code and site and warehouse:
|
||||
existing = find_ready_rpa_inventory_snapshot(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
site_id=site,
|
||||
warehouse_id=warehouse,
|
||||
)
|
||||
if existing:
|
||||
return existing, False
|
||||
|
||||
savepoint = db.session.begin_nested()
|
||||
orphan_storage_path: str | None = None
|
||||
try:
|
||||
inv_file = create_inventory_snapshot_from_rpa(
|
||||
source=source,
|
||||
local_path=local_path,
|
||||
source_file_name=source_file_name,
|
||||
rpa_run_no=rpa_run_no,
|
||||
schedule_run_id=schedule_run_id,
|
||||
trigger_type=trigger_type,
|
||||
success=success,
|
||||
error_message=error_message,
|
||||
user_id=user_id,
|
||||
batch_id=batch_id,
|
||||
share_mode=share_mode,
|
||||
verify_warehouse_id=verify_warehouse_id,
|
||||
)
|
||||
if inv_file.storage_path and not str(inv_file.storage_path).startswith("failed://"):
|
||||
orphan_storage_path = str(inv_file.storage_path)
|
||||
db.session.flush()
|
||||
savepoint.commit()
|
||||
return inv_file, True
|
||||
except IntegrityError:
|
||||
savepoint.rollback()
|
||||
if orphan_storage_path:
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(orphan_storage_path)
|
||||
if run_no and code and site and warehouse:
|
||||
existing = find_ready_rpa_inventory_snapshot(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
site_id=site,
|
||||
warehouse_id=warehouse,
|
||||
)
|
||||
if existing:
|
||||
return existing, False
|
||||
raise
|
||||
except Exception:
|
||||
savepoint.rollback()
|
||||
if orphan_storage_path:
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(orphan_storage_path)
|
||||
raise
|
||||
|
||||
|
||||
def list_available_snapshots(
|
||||
*,
|
||||
source_code: str | None = None,
|
||||
@@ -126,33 +249,15 @@ def _normalize_header_key(value: Any) -> str:
|
||||
|
||||
|
||||
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
|
||||
"""
|
||||
从库存 Excel 内容中提取 Warehouse ID。
|
||||
核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。
|
||||
"""
|
||||
if not path or not path.is_file():
|
||||
return ""
|
||||
try:
|
||||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||||
except Exception:
|
||||
return ""
|
||||
try:
|
||||
ws = wb.active
|
||||
rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True))
|
||||
finally:
|
||||
wb.close()
|
||||
"""从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。"""
|
||||
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
|
||||
|
||||
for row_idx, row in enumerate(rows):
|
||||
for col_idx, cell in enumerate(row):
|
||||
if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES:
|
||||
continue
|
||||
for data_row in rows[row_idx + 1:]:
|
||||
if col_idx >= len(data_row):
|
||||
continue
|
||||
value = str(data_row[col_idx] or "").strip().upper()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
values = extract_warehouse_ids_from_inventory_excel(path)
|
||||
if not values:
|
||||
return ""
|
||||
if len(values) > 1:
|
||||
return ""
|
||||
return next(iter(values))
|
||||
|
||||
|
||||
def create_inventory_snapshot_from_rpa(
|
||||
@@ -168,6 +273,7 @@ def create_inventory_snapshot_from_rpa(
|
||||
user_id: int | None = None,
|
||||
batch_id: int | None = None,
|
||||
share_mode: str | None = None,
|
||||
verify_warehouse_id: str | None = None,
|
||||
) -> ShippingInventoryFile:
|
||||
"""
|
||||
从 RPA 导出文件创建库存快照记录。
|
||||
@@ -187,19 +293,39 @@ def create_inventory_snapshot_from_rpa(
|
||||
source_code = str(source.get("source_code") or "").strip().upper()
|
||||
configured_site_id = str(source.get("site_id") or "").strip().upper()
|
||||
export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
|
||||
runtime_identity_applied = bool(source.get("_runtime_identity_applied"))
|
||||
excel_warehouse_id = ""
|
||||
warehouse_id = configured_site_id
|
||||
warehouse_code = warehouse_id
|
||||
warehouse_id = export_warehouse_id
|
||||
warehouse_code = warehouse_id or configured_site_id
|
||||
excel_verified = False
|
||||
|
||||
if success:
|
||||
path = inventory_file_upload_path(inventory_file_no)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(local_path, path)
|
||||
excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path)
|
||||
warehouse_id = configured_site_id or excel_warehouse_id
|
||||
warehouse_code = warehouse_id
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name
|
||||
local = Path(local_path)
|
||||
expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper()
|
||||
if expected_wh:
|
||||
from app.services.shipping_notice.inventory_file_identity import (
|
||||
assert_inventory_excel_warehouse_identity,
|
||||
)
|
||||
|
||||
excel_warehouse_id = assert_inventory_excel_warehouse_identity(
|
||||
local,
|
||||
expected_warehouse_id=expected_wh,
|
||||
operation="rpa_snapshot",
|
||||
)
|
||||
warehouse_id = expected_wh
|
||||
warehouse_code = warehouse_id
|
||||
excel_verified = True
|
||||
path = inventory_file_upload_path(
|
||||
inventory_file_no,
|
||||
suffix=inventory_storage_suffix_for_path(local),
|
||||
)
|
||||
if not excel_verified and not warehouse_id:
|
||||
excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(local)
|
||||
if excel_warehouse_id:
|
||||
warehouse_id = excel_warehouse_id
|
||||
warehouse_code = warehouse_id
|
||||
preview = read_inventory_schema_preview(local)
|
||||
preview["upload_filename"] = str(source_file_name or local.name).strip() or path.name
|
||||
snapshot_status = _SNAPSHOT_STATUS_READY
|
||||
storage_path = str(path)
|
||||
else:
|
||||
@@ -208,6 +334,8 @@ def create_inventory_snapshot_from_rpa(
|
||||
snapshot_status = _SNAPSHOT_STATUS_FAILED
|
||||
storage_path = str(path) if path and path.is_file() else ""
|
||||
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
batch_id=batch_id,
|
||||
@@ -219,6 +347,9 @@ def create_inventory_snapshot_from_rpa(
|
||||
line_count=0,
|
||||
warehouse_id=warehouse_id or None,
|
||||
warehouse_code=warehouse_code or None,
|
||||
site_id=configured_site_id or None,
|
||||
source_config_version=get_inventory_sources_config_version(),
|
||||
identity_status="pending" if success else "unknown",
|
||||
source_code=source_code or None,
|
||||
source_type=str(source.get("source_type") or "").strip() or None,
|
||||
snapshot_status=snapshot_status,
|
||||
@@ -233,12 +364,38 @@ def create_inventory_snapshot_from_rpa(
|
||||
"site_id": configured_site_id or None,
|
||||
"export_warehouse_id": export_warehouse_id,
|
||||
"excel_warehouse_id": excel_warehouse_id or None,
|
||||
"warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None),
|
||||
"warehouse_id_source": (
|
||||
"task_identity_excel_verified"
|
||||
if excel_verified
|
||||
else (
|
||||
"runtime_identity"
|
||||
if runtime_identity_applied
|
||||
else (
|
||||
"export_config"
|
||||
if export_warehouse_id
|
||||
else ("inventory_excel" if excel_warehouse_id else None)
|
||||
)
|
||||
)
|
||||
),
|
||||
"excel_warehouse_verified": excel_verified,
|
||||
"trigger_type": trigger_type,
|
||||
},
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
# [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。
|
||||
if success and storage_path and not str(storage_path).startswith("failed://"):
|
||||
path = Path(storage_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
shutil.copy2(local_path, path)
|
||||
except Exception:
|
||||
if path.exists():
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
return inv_file
|
||||
|
||||
|
||||
@@ -247,6 +404,7 @@ def link_snapshot_to_task(
|
||||
inv_file: ShippingInventoryFile,
|
||||
*,
|
||||
reason: str,
|
||||
role: str = "member",
|
||||
audit_payload: dict[str, Any] | None = None,
|
||||
) -> ShippingTaskInventoryLink | None:
|
||||
"""
|
||||
@@ -265,9 +423,25 @@ def link_snapshot_to_task(
|
||||
if inv_file.exported_at:
|
||||
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file, role="member")
|
||||
from app.services.shipping_notice.inventory_source_gate import inventory_identities_match
|
||||
|
||||
identity_ok = inventory_identities_match(
|
||||
task,
|
||||
source_code=inv_file.source_code,
|
||||
site_id=inv_file.site_id,
|
||||
warehouse_id=inv_file.warehouse_id,
|
||||
)
|
||||
inv_file.identity_status = "verified" if identity_ok else "mismatch"
|
||||
if not identity_ok:
|
||||
return None
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file, role=role)
|
||||
link.link_reason = reason
|
||||
link.matched_warehouse_id = inv_file.warehouse_id
|
||||
link.matched_source_code = inv_file.source_code
|
||||
link.matched_site_id = inv_file.site_id
|
||||
link.identity_check_status = "verified" if identity_ok else "mismatch"
|
||||
link.identity_checked_at = datetime.utcnow()
|
||||
link.snapshot_age_seconds = age_seconds
|
||||
link.audit_payload_json = {
|
||||
**(audit_payload or {}),
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
|
||||
依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。
|
||||
逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
|
||||
RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_source_identity import identity_matches_config
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
confirm_inventory_source_by_code,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version
|
||||
|
||||
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"})
|
||||
|
||||
INVENTORY_SOURCE_ERROR_CODES = {
|
||||
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
|
||||
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
|
||||
"invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
|
||||
"conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
|
||||
"confirmation_required": "SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED",
|
||||
"changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
|
||||
"identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
"gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
|
||||
}
|
||||
|
||||
|
||||
def _inventory_source_config_current(task: ShippingTask) -> bool:
|
||||
"""任务上记录的库存源配置版本须与当前 YAML 版本一致。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
current = get_inventory_sources_config_version()
|
||||
if not stored:
|
||||
return False
|
||||
return stored == current
|
||||
|
||||
|
||||
def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
|
||||
核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。
|
||||
"""
|
||||
status = str(task.inventory_source_status or "").strip()
|
||||
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
return False
|
||||
if not _inventory_source_config_current(task):
|
||||
return False
|
||||
code = str(task.inventory_source_code or "").strip().upper()
|
||||
if not code:
|
||||
return False
|
||||
source_type = str(task.inventory_source_type or "").strip()
|
||||
if not source_type:
|
||||
return False
|
||||
source = get_inventory_source(code)
|
||||
if not source:
|
||||
return False
|
||||
if source_type != str(source.get("source_type") or "").strip():
|
||||
return False
|
||||
|
||||
site_id = str(task.inventory_site_id or "").strip().upper()
|
||||
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
|
||||
if not site_id or not task_wh:
|
||||
return False
|
||||
if not identity_matches_config(
|
||||
source,
|
||||
site_id=site_id,
|
||||
warehouse_id=task_wh,
|
||||
context=extract_routing_context(task),
|
||||
):
|
||||
return False
|
||||
|
||||
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not fingerprint:
|
||||
return False
|
||||
context = extract_routing_context(task)
|
||||
if fingerprint != compute_routing_fingerprint(context):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def routing_fingerprint_changed(task: ShippingTask, context: dict[str, Any]) -> bool:
|
||||
"""比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。"""
|
||||
previous = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not previous:
|
||||
return False
|
||||
return previous != compute_routing_fingerprint(context)
|
||||
|
||||
|
||||
def inventory_source_config_changed(task: ShippingTask) -> bool:
|
||||
"""配置版本变化会使已确认库存源失效。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
if not stored:
|
||||
return bool(str(task.inventory_source_status or "").strip())
|
||||
return stored != get_inventory_sources_config_version()
|
||||
|
||||
|
||||
def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None:
|
||||
"""将标准化目的地线索写入任务独立字段。"""
|
||||
task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
|
||||
task.destination_city = str(context.get("destination_city") or "").strip() or None
|
||||
task.destination_country = str(context.get("destination_country") or "").strip().upper() or None
|
||||
task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
|
||||
|
||||
|
||||
def clear_inventory_source_confirmation(task: ShippingTask) -> None:
|
||||
"""路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。"""
|
||||
task.inventory_source_confirmed_by = None
|
||||
task.inventory_source_confirmed_at = None
|
||||
if str(task.inventory_source_status or "").strip() == "user_confirmed":
|
||||
task.inventory_source_status = "unresolved"
|
||||
task.inventory_source_method = None
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。"""
|
||||
context = extract_routing_context(task)
|
||||
return InventorySourceAdjudication(
|
||||
status=str(task.inventory_source_status or "").strip(),
|
||||
method=str(task.inventory_source_method or "").strip() or None,
|
||||
source_code=str(task.inventory_source_code or "").strip().upper() or None,
|
||||
source_type=str(task.inventory_source_type or "").strip() or None,
|
||||
site_id=str(task.inventory_site_id or "").strip().upper() or None,
|
||||
warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
config_version=str(task.inventory_source_config_version or "").strip() or None,
|
||||
routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip()
|
||||
or compute_routing_fingerprint(context),
|
||||
destination_candidates=context.get("destination_candidates") or [],
|
||||
)
|
||||
|
||||
|
||||
def apply_inventory_source_adjudication(
|
||||
task: ShippingTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
confirmed_by_user_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
|
||||
核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
|
||||
task.inventory_routing_fingerprint = fingerprint
|
||||
apply_destination_fields(task, context)
|
||||
|
||||
task.inventory_source_status = adjudication.status
|
||||
task.inventory_source_method = adjudication.method or None
|
||||
task.inventory_source_config_version = adjudication.config_version or get_inventory_sources_config_version()
|
||||
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
task.inventory_source_code = adjudication.source_code
|
||||
task.inventory_source_type = adjudication.source_type
|
||||
task.inventory_site_id = adjudication.site_id
|
||||
task.inventory_warehouse_id = adjudication.warehouse_id or None
|
||||
if adjudication.status == "user_confirmed" and confirmed_by_user_id:
|
||||
task.inventory_source_confirmed_by = confirmed_by_user_id
|
||||
task.inventory_source_confirmed_at = datetime.utcnow()
|
||||
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
task.inventory_source_code = None
|
||||
task.inventory_source_type = None
|
||||
task.inventory_site_id = None
|
||||
task.inventory_warehouse_id = None
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
task.step_payload_json = payload
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": adjudication.status,
|
||||
"method": adjudication.method,
|
||||
"reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
"candidates": adjudication.candidates,
|
||||
"evidence": adjudication.evidence,
|
||||
"conflicts": adjudication.conflicts,
|
||||
"config_version": adjudication.config_version,
|
||||
"routing_fingerprint": fingerprint,
|
||||
}
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
|
||||
|
||||
rpa_source = build_task_rpa_inventory_source(task)
|
||||
if rpa_source:
|
||||
payload["rpa_inventory_source"] = rpa_source
|
||||
else:
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对任务执行库存源裁决并写入独立字段。
|
||||
【AI 触发时机】:订单解析完成后由 parse_notice 调用;重解析时同样调用以刷新裁决。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
|
||||
clear_inventory_source_confirmation(task)
|
||||
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and is_inventory_source_stable(task)
|
||||
and not routing_fingerprint_changed(task, context)
|
||||
and not inventory_source_config_changed(task)
|
||||
):
|
||||
return _adjudication_from_stable_task(task)
|
||||
|
||||
adjudication = adjudicate_inventory_source(task)
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and adjudication.status == "resolved"
|
||||
and adjudication.source_code
|
||||
and str(adjudication.source_code).strip().upper() == str(task.inventory_source_code or "").strip().upper()
|
||||
and is_inventory_source_stable(task)
|
||||
):
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=adjudication.source_code,
|
||||
source_type=adjudication.source_type,
|
||||
site_id=adjudication.site_id,
|
||||
warehouse_id=adjudication.warehouse_id,
|
||||
config_version=adjudication.config_version,
|
||||
routing_fingerprint=adjudication.routing_fingerprint,
|
||||
candidates=adjudication.candidates,
|
||||
destination_candidates=adjudication.destination_candidates,
|
||||
evidence=adjudication.evidence,
|
||||
reason=adjudication.reason,
|
||||
)
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
return adjudication
|
||||
|
||||
|
||||
def task_needs_parse_review(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断任务是否仍需完成低置信度解析人工确认。
|
||||
|
||||
核心逻辑:仅认显式标记——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 {}
|
||||
return bool(payload.get("pending_parse_review_after_source"))
|
||||
|
||||
|
||||
def transition_task_to_inventory_source_review(
|
||||
task: ShippingTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
error_message: str | None = None,
|
||||
mark_pending_parse_review: bool = False,
|
||||
) -> 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
|
||||
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
task.current_step = "step2_parse_confirm"
|
||||
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": adjudication.status,
|
||||
"method": adjudication.method,
|
||||
"reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
"candidates": adjudication.candidates,
|
||||
"evidence": adjudication.evidence,
|
||||
"conflicts": adjudication.conflicts,
|
||||
"config_version": adjudication.config_version,
|
||||
"routing_fingerprint": adjudication.routing_fingerprint,
|
||||
}
|
||||
if mark_pending_parse_review:
|
||||
payload["pending_parse_review_after_source"] = True
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 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):
|
||||
transition_task_to_inventory_source_review(
|
||||
task,
|
||||
adjudication,
|
||||
mark_pending_parse_review=task_needs_parse_review(task),
|
||||
)
|
||||
return adjudication
|
||||
|
||||
|
||||
def confirm_task_inventory_source(
|
||||
task: ShippingTask,
|
||||
source_code: str,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
用户选择 source_code 后由后端重新校验并写入正式库存源。
|
||||
核心逻辑:前端只提交 source_code;站点与库位始终从配置生成。
|
||||
"""
|
||||
adjudication = confirm_inventory_source_by_code(task, source_code)
|
||||
apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=user_id)
|
||||
return adjudication
|
||||
|
||||
|
||||
def assert_inventory_source_gate(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
operation: str = "continue",
|
||||
) -> None:
|
||||
"""
|
||||
库存源硬门禁:未稳定时抛出统一业务异常,防止后续流程绕过。
|
||||
Args:
|
||||
task: 当前发货任务。
|
||||
operation: 触发门禁的操作名,写入错误 details。
|
||||
Raises:
|
||||
AppError: 库存源未稳定或身份不一致。
|
||||
"""
|
||||
if inventory_source_config_changed(task):
|
||||
raise AppError(
|
||||
code=INVENTORY_SOURCE_ERROR_CODES["changed"],
|
||||
message="库存源配置已更新,请重新确认库存查询来源",
|
||||
http_status=409,
|
||||
details={"operation": operation, "task_no": task.task_no},
|
||||
)
|
||||
if is_inventory_source_stable(task):
|
||||
return
|
||||
status = str(task.inventory_source_status or "unresolved").strip()
|
||||
code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
|
||||
raise AppError(
|
||||
code=code,
|
||||
message="库存源尚未确定,无法继续后续流程",
|
||||
http_status=409,
|
||||
details={
|
||||
"operation": operation,
|
||||
"inventory_source_status": status,
|
||||
"task_no": task.task_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
|
||||
"""返回任务当前正式库存身份,供库存文件绑定与匹配校验。"""
|
||||
return {
|
||||
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
|
||||
"inventory_site_id": str(task.inventory_site_id or "").strip().upper() or None,
|
||||
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
}
|
||||
|
||||
|
||||
def inventory_identities_match(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
source_code: str | None,
|
||||
site_id: str | None,
|
||||
warehouse_id: str | None,
|
||||
) -> bool:
|
||||
"""校验库存文件/链接身份与任务正式库存源是否完全一致。"""
|
||||
identity = task_inventory_identity(task)
|
||||
if not is_inventory_source_stable(task):
|
||||
return False
|
||||
expected_code = str(source_code or "").strip().upper()
|
||||
if expected_code != identity["inventory_source_code"]:
|
||||
return False
|
||||
|
||||
file_site = str(site_id or "").strip().upper()
|
||||
file_wh = str(warehouse_id or "").strip().upper()
|
||||
if not file_site or file_site != (identity["inventory_site_id"] or ""):
|
||||
return False
|
||||
if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""):
|
||||
return False
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_identity.py
|
||||
|
||||
用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。
|
||||
依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。
|
||||
逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
def normalize_destination(value: Any) -> str:
|
||||
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
"""别名按词元匹配,避免短 token 误命中更长编码。"""
|
||||
return _alias_token_match(normalize_destination(candidate), alias)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedInventoryIdentity:
|
||||
"""稳定库存源四元组中的站点/库位解析结果。"""
|
||||
|
||||
source_code: str
|
||||
source_type: str
|
||||
site_id: str
|
||||
warehouse_id: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryIdentityResolution:
|
||||
"""身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。"""
|
||||
|
||||
ok: bool
|
||||
identity: ResolvedInventoryIdentity | None = None
|
||||
reason: str = ""
|
||||
warehouse_candidates: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _alias_token_match(candidate: str, alias: str) -> bool:
|
||||
"""库位别名按词元精确匹配,禁止短别名误命中长编码。"""
|
||||
alias_norm = normalize_destination(alias)
|
||||
if not alias_norm:
|
||||
return False
|
||||
if candidate == alias_norm:
|
||||
return True
|
||||
return alias_norm in candidate.split()
|
||||
|
||||
|
||||
def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) -> InventoryIdentityResolution:
|
||||
"""Crane 库位由订单线索与 match_aliases 唯一命中决定。"""
|
||||
aliases = [str(alias).strip() for alias in (source.get("match_aliases") or []) if str(alias).strip()]
|
||||
if not aliases:
|
||||
return InventoryIdentityResolution(ok=False, reason="crane_aliases_missing")
|
||||
|
||||
destination_candidates = list(context.get("destination_candidates") or [])
|
||||
hint = normalize_destination(context.get("warehouse_hint"))
|
||||
if hint:
|
||||
destination_candidates.append(hint)
|
||||
|
||||
matched: list[str] = []
|
||||
for candidate in destination_candidates:
|
||||
candidate_norm = normalize_destination(candidate)
|
||||
if not candidate_norm:
|
||||
continue
|
||||
for alias in aliases:
|
||||
if _alias_token_match(candidate_norm, alias):
|
||||
token = str(alias).strip().upper()
|
||||
if token and token not in matched:
|
||||
matched.append(token)
|
||||
|
||||
if len(matched) == 1:
|
||||
site_id = str(source.get("site_id") or "CRANE").strip().upper()
|
||||
return InventoryIdentityResolution(
|
||||
ok=True,
|
||||
identity=ResolvedInventoryIdentity(
|
||||
source_code=str(source.get("source_code") or "").strip().upper(),
|
||||
source_type=str(source.get("source_type") or "").strip(),
|
||||
site_id=site_id,
|
||||
warehouse_id=matched[0],
|
||||
),
|
||||
)
|
||||
if len(matched) > 1:
|
||||
return InventoryIdentityResolution(
|
||||
ok=False,
|
||||
reason="crane_warehouse_ambiguous",
|
||||
warehouse_candidates=tuple(matched),
|
||||
)
|
||||
return InventoryIdentityResolution(ok=False, reason="crane_warehouse_unresolved")
|
||||
|
||||
|
||||
def resolve_inventory_source_identity(
|
||||
source: dict[str, Any],
|
||||
context: dict[str, Any],
|
||||
) -> InventoryIdentityResolution:
|
||||
"""
|
||||
解析库存源在订单上下文下的正式 site_id / warehouse_id。
|
||||
核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。
|
||||
"""
|
||||
source_code = str(source.get("source_code") or "").strip().upper()
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
if not source_code or not source_type:
|
||||
return InventoryIdentityResolution(ok=False, reason="source_incomplete")
|
||||
|
||||
if source_type == "crane_footprint":
|
||||
return _resolve_crane_warehouse_id(source, context)
|
||||
|
||||
site_id = str(source.get("site_id") or "").strip().upper()
|
||||
warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
|
||||
if not site_id or not warehouse_id:
|
||||
return InventoryIdentityResolution(ok=False, reason="identity_incomplete")
|
||||
return InventoryIdentityResolution(
|
||||
ok=True,
|
||||
identity=ResolvedInventoryIdentity(
|
||||
source_code=source_code,
|
||||
source_type=source_type,
|
||||
site_id=site_id,
|
||||
warehouse_id=warehouse_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def identity_matches_config(
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
site_id: str | None,
|
||||
warehouse_id: str | None,
|
||||
context: dict[str, Any] | None = None,
|
||||
) -> bool:
|
||||
"""校验任务身份与配置一致;Crane 额外要求库位与当前路由上下文唯一解析结果一致。"""
|
||||
cfg_site = str(source.get("site_id") or "").strip().upper()
|
||||
cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
|
||||
task_site = str(site_id or "").strip().upper()
|
||||
task_wh = str(warehouse_id or "").strip().upper()
|
||||
if not task_site or not task_wh:
|
||||
return False
|
||||
if cfg_site and task_site != cfg_site:
|
||||
return False
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
if source_type == "crane_footprint":
|
||||
if context is None:
|
||||
return False
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return False
|
||||
return resolution.identity.warehouse_id == task_wh
|
||||
return bool(cfg_wh) and task_wh == cfg_wh
|
||||
@@ -1,38 +1,89 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。
|
||||
依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。
|
||||
逻辑:从 JSON 配置的 match_aliases 命中库存源;Dify 只提供候选字段,本模块负责标准化与唯一性判断。
|
||||
用途:根据发货通知路由线索对库存源做确定性裁决。
|
||||
依赖:inventory_sources、ShippingTask 独立字段与 step_payload_json。
|
||||
逻辑:Dify/LLM 只提供路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
|
||||
from app.services.shipping_notice.inventory_source_identity import (
|
||||
normalize_destination,
|
||||
resolve_inventory_source_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import (
|
||||
build_rpa_inventory_source,
|
||||
get_inventory_source,
|
||||
get_inventory_sources_config_version,
|
||||
list_inventory_sources,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventorySourceResolution:
|
||||
"""库存源解析结果。"""
|
||||
class InventorySourceAdjudication:
|
||||
"""库存源裁决结构化结果。"""
|
||||
|
||||
status: str
|
||||
source: dict[str, Any] | None
|
||||
candidates: list[dict[str, Any]]
|
||||
destination_candidates: list[str]
|
||||
method: str | None = None
|
||||
source_code: str | None = None
|
||||
source_type: str | None = None
|
||||
site_id: str | None = None
|
||||
warehouse_id: str | None = None
|
||||
config_version: str | None = None
|
||||
routing_fingerprint: str | None = None
|
||||
candidates: list[dict[str, Any]] = field(default_factory=list)
|
||||
destination_candidates: list[str] = field(default_factory=list)
|
||||
evidence: list[dict[str, Any]] = field(default_factory=list)
|
||||
conflicts: list[str] = field(default_factory=list)
|
||||
reason: str = ""
|
||||
|
||||
|
||||
# Backward-compatible alias
|
||||
InventorySourceResolution = InventorySourceAdjudication
|
||||
|
||||
|
||||
def compute_routing_fingerprint(context: dict[str, Any]) -> str:
|
||||
"""
|
||||
根据标准化路由上下文与配置版本生成可比较指纹。
|
||||
核心逻辑:相同输入与相同配置版本下指纹必须稳定,用于判断人工确认是否失效。
|
||||
"""
|
||||
normalized = {
|
||||
"destination_code": str(context.get("destination_code") or "").strip().upper(),
|
||||
"destination_city": str(context.get("destination_city") or "").strip().upper(),
|
||||
"destination_country": str(context.get("destination_country") or "").strip().upper(),
|
||||
"warehouse_hint": str(context.get("warehouse_hint") or "").strip().upper(),
|
||||
"customer_code": str(context.get("customer_code") or "").strip().upper(),
|
||||
"customer_name": str(context.get("customer_name") or "").strip().upper(),
|
||||
"order_type": str(context.get("order_type") or "").strip().upper(),
|
||||
"config_version": get_inventory_sources_config_version(),
|
||||
"destination_candidates": sorted(
|
||||
str(item).strip().upper()
|
||||
for item in (context.get("destination_candidates") or [])
|
||||
if str(item).strip()
|
||||
),
|
||||
}
|
||||
digest = hashlib.sha256(json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode("utf-8"))
|
||||
return digest.hexdigest()[:32]
|
||||
|
||||
|
||||
def normalize_destination(value: Any) -> str:
|
||||
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
|
||||
from app.services.shipping_notice.inventory_source_identity import normalize_destination as _normalize
|
||||
|
||||
return _normalize(value)
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
from app.services.shipping_notice.inventory_source_identity import _matches_alias as _match
|
||||
|
||||
return _match(candidate, alias)
|
||||
|
||||
|
||||
def _append_candidate(candidates: list[str], value: Any) -> None:
|
||||
@@ -45,14 +96,14 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None:
|
||||
if not isinstance(value, dict):
|
||||
_append_candidate(candidates, value)
|
||||
return
|
||||
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text"):
|
||||
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text", "destination_code"):
|
||||
_append_candidate(candidates, value.get(key))
|
||||
|
||||
|
||||
def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
从任务解析结果提取目的地/港口/仓库候选。
|
||||
【AI 触发时机】:需要根据发货通知判断库存 RPA 源时调用,Dify 输出与后端字段都作为候选证据。
|
||||
【AI 触发时机】:订单解析后由裁决服务调用,Dify 输出与后端字段都作为候选证据。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
@@ -60,6 +111,10 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
_append_candidate(candidates, item)
|
||||
_extract_destination_object(candidates, payload.get("destination"))
|
||||
_append_candidate(candidates, task.ship_to)
|
||||
_append_candidate(candidates, task.destination_code)
|
||||
_append_candidate(candidates, task.destination_city)
|
||||
_append_candidate(candidates, task.destination_country)
|
||||
_append_candidate(candidates, task.warehouse_hint)
|
||||
for line in task.lines_json or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
@@ -69,104 +124,413 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
return candidates
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
normalized_alias = normalize_destination(alias)
|
||||
if not normalized_alias:
|
||||
return False
|
||||
return (
|
||||
candidate == normalized_alias
|
||||
or normalized_alias in candidate.split()
|
||||
or normalized_alias in candidate
|
||||
)
|
||||
|
||||
|
||||
def _candidate_summary(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""人工确认候选项展示字段。"""
|
||||
def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
|
||||
"""将任务解析结果标准化为库存路由上下文。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
destination = payload.get("destination") if isinstance(payload.get("destination"), dict) else {}
|
||||
return {
|
||||
"source_code": source.get("source_code"),
|
||||
"display_name": source.get("display_name"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"site": source.get("site"),
|
||||
"source_type": source.get("source_type"),
|
||||
"destination_code": task.destination_code or destination.get("port_code") or destination.get("destination_code"),
|
||||
"destination_city": task.destination_city or destination.get("city"),
|
||||
"destination_country": task.destination_country or destination.get("country"),
|
||||
"warehouse_hint": task.warehouse_hint or destination.get("warehouse_hint"),
|
||||
"customer_code": task.customer_code,
|
||||
"customer_name": task.customer_name,
|
||||
"order_type": payload.get("order_type"),
|
||||
"destination_candidates": extract_destination_candidates(task),
|
||||
}
|
||||
|
||||
|
||||
def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
|
||||
"""根据任务目的地候选与 JSON match_aliases 解析唯一库存源。"""
|
||||
candidates = extract_destination_candidates(task)
|
||||
matched_codes: list[str] = []
|
||||
for candidate in candidates:
|
||||
for source in list_inventory_sources():
|
||||
aliases = source.get("match_aliases") or []
|
||||
if any(_matches_alias(candidate, alias) for alias in aliases):
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
if code and code not in matched_codes:
|
||||
matched_codes.append(code)
|
||||
def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]:
|
||||
"""人工确认候选项展示字段;前端必须提交 source_code。"""
|
||||
return {
|
||||
"source_code": source.get("source_code"),
|
||||
"display_name": source.get("display_name"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"source_type": source.get("source_type"),
|
||||
"match_score": score,
|
||||
"matched_by": matched_by,
|
||||
}
|
||||
|
||||
if len(matched_codes) == 1:
|
||||
source = build_rpa_inventory_source(matched_codes[0])
|
||||
if source:
|
||||
return InventorySourceResolution(
|
||||
status="resolved",
|
||||
source=source,
|
||||
candidates=[_candidate_summary(source)],
|
||||
destination_candidates=candidates,
|
||||
|
||||
def _normalize_token_list(values: Any) -> list[str]:
|
||||
if not isinstance(values, list):
|
||||
return []
|
||||
return [normalize_destination(item) for item in values if normalize_destination(item)]
|
||||
|
||||
|
||||
def _all_enabled_source_candidates() -> list[dict[str, Any]]:
|
||||
"""返回全部启用库存源候选项,供未命中时人工选择。"""
|
||||
return [
|
||||
_candidate_summary(source)
|
||||
for source in list_inventory_sources()
|
||||
if source.get("enabled", True) is not False
|
||||
]
|
||||
|
||||
|
||||
def _source_matches_destination(source: dict[str, Any], destination_candidates: list[str]) -> bool:
|
||||
"""判断库存源别名是否与订单目的地线索有交集。"""
|
||||
aliases = list(source.get("match_aliases") or [])
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
aliases.extend(_normalize_token_list(match_cfg.get("aliases")))
|
||||
if not aliases:
|
||||
return False
|
||||
return any(_matches_alias(candidate, alias) for candidate in destination_candidates for alias in aliases)
|
||||
|
||||
|
||||
def _source_field_excluded(source: dict[str, Any], context: dict[str, Any]) -> bool:
|
||||
"""显式 match 规则已声明但订单字段未命中时,排除该库存源。"""
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
for field_name, cfg_key in (
|
||||
("destination_code", "destination_codes"),
|
||||
("customer_code", "customers"),
|
||||
("order_type", "order_types"),
|
||||
("warehouse_hint", "warehouse_hints"),
|
||||
):
|
||||
field_value = normalize_destination(context.get(field_name))
|
||||
allowed = _normalize_token_list(match_cfg.get(cfg_key))
|
||||
if allowed and field_value:
|
||||
if not (
|
||||
field_value in allowed
|
||||
or any(field_value in item or item in field_value for item in allowed)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _detect_rule_conflicts(
|
||||
matches: list[tuple[int, dict[str, Any], list[dict[str, Any]]]],
|
||||
context: dict[str, Any],
|
||||
) -> list[str]:
|
||||
"""多候选同分时,检测不同来源对同一订单字段给出互斥规则命中。"""
|
||||
conflicts: list[str] = []
|
||||
field_hits: dict[str, set[str]] = {}
|
||||
for _, source, _ in matches:
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
for field_name, cfg_key in (
|
||||
("destination_code", "destination_codes"),
|
||||
("customer_code", "customers"),
|
||||
("order_type", "order_types"),
|
||||
("warehouse_hint", "warehouse_hints"),
|
||||
):
|
||||
field_value = normalize_destination(context.get(field_name))
|
||||
allowed = _normalize_token_list(match_cfg.get(cfg_key))
|
||||
if not allowed or not field_value:
|
||||
continue
|
||||
hits = {
|
||||
item
|
||||
for item in allowed
|
||||
if field_value in item or item in field_value or field_value == item
|
||||
}
|
||||
if hits:
|
||||
field_hits.setdefault(field_name, set()).update(hits)
|
||||
for field_name, hits in field_hits.items():
|
||||
if len(hits) > 1:
|
||||
conflicts.append(f"{field_name}_rule_conflict")
|
||||
return conflicts
|
||||
|
||||
|
||||
def _source_match_score(source: dict[str, Any], context: dict[str, Any], destination_candidates: list[str]) -> tuple[int, list[dict[str, Any]]]:
|
||||
"""按配置 match 规则与 match_aliases 计算命中分数与证据。"""
|
||||
score = 0
|
||||
evidence: list[dict[str, Any]] = []
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
|
||||
for field_name, cfg_key in (
|
||||
("destination_code", "destination_codes"),
|
||||
("customer_code", "customers"),
|
||||
("order_type", "order_types"),
|
||||
("warehouse_hint", "warehouse_hints"),
|
||||
):
|
||||
field_value = normalize_destination(context.get(field_name))
|
||||
allowed = _normalize_token_list(match_cfg.get(cfg_key))
|
||||
if allowed and field_value:
|
||||
if field_value in allowed or any(field_value in item or item in field_value for item in allowed):
|
||||
score += 10
|
||||
evidence.append({"field": field_name, "value": field_value, "rule": cfg_key})
|
||||
|
||||
aliases = list(source.get("match_aliases") or []) + _normalize_token_list(match_cfg.get("aliases"))
|
||||
for candidate in destination_candidates:
|
||||
for alias in aliases:
|
||||
if _matches_alias(candidate, alias):
|
||||
score += 5
|
||||
evidence.append({"field": "destination_candidate", "value": candidate, "alias": alias})
|
||||
break
|
||||
|
||||
priority = int(source.get("priority") or 0)
|
||||
if score > 0 and priority:
|
||||
score += min(priority // 10, 5)
|
||||
return score, evidence
|
||||
|
||||
|
||||
def _stable_from_source(
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
method: str,
|
||||
evidence: list[dict[str, Any]],
|
||||
context: dict[str, Any],
|
||||
) -> InventorySourceAdjudication:
|
||||
"""仅在四元组身份可完整解析时返回 resolved。"""
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
config_version = get_inventory_sources_config_version()
|
||||
fingerprint = compute_routing_fingerprint(context)
|
||||
destination_candidates = context.get("destination_candidates") or []
|
||||
if not resolution.ok or not resolution.identity:
|
||||
if resolution.reason == "crane_warehouse_ambiguous":
|
||||
return InventorySourceAdjudication(
|
||||
status="ambiguous",
|
||||
method=method,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[_candidate_summary(source, matched_by=method)],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=evidence,
|
||||
reason=resolution.reason,
|
||||
)
|
||||
if len(matched_codes) > 1:
|
||||
matched_sources = [
|
||||
_candidate_summary(source)
|
||||
for code in matched_codes
|
||||
for source in [build_rpa_inventory_source(code)]
|
||||
if source
|
||||
]
|
||||
return InventorySourceResolution(
|
||||
status="ambiguous",
|
||||
source=None,
|
||||
candidates=matched_sources,
|
||||
destination_candidates=candidates,
|
||||
reason="matched_multiple_sources",
|
||||
status = "invalid" if resolution.reason in {"source_incomplete", "crane_aliases_missing"} else "unresolved"
|
||||
return InventorySourceAdjudication(
|
||||
status=status,
|
||||
method=method,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[_candidate_summary(source, matched_by=method)],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=evidence,
|
||||
conflicts=[resolution.reason] if resolution.reason else [],
|
||||
reason=resolution.reason or "identity_incomplete",
|
||||
)
|
||||
return InventorySourceResolution(
|
||||
status="unresolved",
|
||||
source=None,
|
||||
candidates=[_candidate_summary(item) for item in list_inventory_sources()],
|
||||
destination_candidates=candidates,
|
||||
reason="no_route_rule_matched",
|
||||
identity = resolution.identity
|
||||
return InventorySourceAdjudication(
|
||||
status="resolved",
|
||||
method=method,
|
||||
source_code=identity.source_code,
|
||||
source_type=identity.source_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[_candidate_summary(source, score=100, matched_by=method)],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=evidence,
|
||||
)
|
||||
|
||||
|
||||
def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""
|
||||
根据任务路由上下文与配置规则做确定性库存源裁决。
|
||||
核心逻辑:相同输入与相同配置必须产生相同结果;区分未命中、多命中、冲突与配置无效。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
destination_candidates = context.get("destination_candidates") or []
|
||||
config_version = get_inventory_sources_config_version()
|
||||
|
||||
scored: list[tuple[int, dict[str, Any], list[dict[str, Any]]]] = []
|
||||
for source in list_inventory_sources():
|
||||
if _source_field_excluded(source, context):
|
||||
continue
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
if source_type == "dsv360" and (
|
||||
not str(source.get("site_id") or "").strip()
|
||||
or not str(source.get("warehouse_id") or "").strip()
|
||||
):
|
||||
continue
|
||||
score, evidence = _source_match_score(source, context, destination_candidates)
|
||||
if score > 0:
|
||||
scored.append((score, source, evidence))
|
||||
|
||||
if not scored:
|
||||
# Fallback: legacy match_aliases only
|
||||
matched_codes: list[str] = []
|
||||
alias_evidence: dict[str, list[dict[str, Any]]] = {}
|
||||
for candidate in destination_candidates:
|
||||
for source in list_inventory_sources():
|
||||
aliases = source.get("match_aliases") or []
|
||||
if any(_matches_alias(candidate, alias) for alias in aliases):
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
if code and code not in matched_codes:
|
||||
matched_codes.append(code)
|
||||
alias_evidence.setdefault(code, []).append(
|
||||
{"field": "destination_candidate", "value": candidate, "alias_only": True}
|
||||
)
|
||||
if len(matched_codes) == 1:
|
||||
source = get_inventory_source(matched_codes[0])
|
||||
if source:
|
||||
return _stable_from_source(
|
||||
source,
|
||||
method="rule_exact",
|
||||
evidence=alias_evidence.get(matched_codes[0], []),
|
||||
context=context,
|
||||
)
|
||||
if len(matched_codes) > 1:
|
||||
candidates = [
|
||||
_candidate_summary(src, matched_by="rule_exact")
|
||||
for code in matched_codes
|
||||
for src in [get_inventory_source(code)]
|
||||
if src
|
||||
]
|
||||
return InventorySourceAdjudication(
|
||||
status="ambiguous",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=candidates,
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[item for ev in alias_evidence.values() for item in ev],
|
||||
reason="matched_multiple_sources",
|
||||
)
|
||||
return InventorySourceAdjudication(
|
||||
status="unresolved",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=_all_enabled_source_candidates(),
|
||||
destination_candidates=destination_candidates,
|
||||
reason="no_route_rule_matched",
|
||||
)
|
||||
|
||||
scored.sort(key=lambda item: (-item[0], str(item[1].get("source_code") or "")))
|
||||
top_score = scored[0][0]
|
||||
top_matches = [item for item in scored if item[0] == top_score]
|
||||
|
||||
if len(top_matches) == 1:
|
||||
_, source, evidence = top_matches[0]
|
||||
method = "rule_combined" if len(evidence) > 1 else "rule_exact"
|
||||
return _stable_from_source(source, method=method, evidence=evidence, context=context)
|
||||
|
||||
conflicts = _detect_rule_conflicts(top_matches, context)
|
||||
if conflicts:
|
||||
candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
|
||||
return InventorySourceAdjudication(
|
||||
status="conflicted",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=candidates,
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[ev for _, _, ev in top_matches for ev in ev],
|
||||
conflicts=conflicts,
|
||||
reason="matched_conflicting_rules",
|
||||
)
|
||||
|
||||
candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
|
||||
return InventorySourceAdjudication(
|
||||
status="ambiguous",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=candidates,
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[ev for _, _, ev in top_matches for ev in ev],
|
||||
reason="matched_multiple_sources",
|
||||
)
|
||||
|
||||
|
||||
def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication:
|
||||
"""
|
||||
用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。
|
||||
【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
destination_candidates = context.get("destination_candidates") or []
|
||||
code = str(source_code or "").strip().upper()
|
||||
source = get_inventory_source(code)
|
||||
if not source or source.get("enabled", True) is False:
|
||||
return InventorySourceAdjudication(
|
||||
status="invalid",
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=_all_enabled_source_candidates(),
|
||||
destination_candidates=destination_candidates,
|
||||
conflicts=["source_code_not_found"],
|
||||
reason="source_code_not_found",
|
||||
)
|
||||
if str(source.get("source_type") or "").strip() == "dsv360" and (
|
||||
not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip()
|
||||
):
|
||||
return InventorySourceAdjudication(
|
||||
status="invalid",
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate_summary(source)],
|
||||
destination_candidates=destination_candidates,
|
||||
conflicts=["identity_incomplete_in_config"],
|
||||
reason="identity_incomplete_in_config",
|
||||
)
|
||||
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
status = "ambiguous" if resolution.reason == "crane_warehouse_ambiguous" else "invalid"
|
||||
return InventorySourceAdjudication(
|
||||
status=status,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate_summary(source)],
|
||||
destination_candidates=destination_candidates,
|
||||
conflicts=[resolution.reason] if resolution.reason else [],
|
||||
reason=resolution.reason or "identity_incomplete",
|
||||
)
|
||||
|
||||
identity = resolution.identity
|
||||
return InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=identity.source_code,
|
||||
source_type=identity.source_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate_summary(source, matched_by="user_confirmed")],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[{"field": "user_selection", "value": code}],
|
||||
)
|
||||
|
||||
|
||||
# Backward-compatible wrappers
|
||||
def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""兼容旧调用点:委托 adjudicate_inventory_source。"""
|
||||
return adjudicate_inventory_source(task)
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""读取任务当前已确认的 rpa_inventory_source。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
source = payload.get("rpa_inventory_source")
|
||||
return source if isinstance(source, dict) and source.get("source_code") else None
|
||||
"""读取任务当前运行时 RPA source(静态配置 + 任务动态库位)。"""
|
||||
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
|
||||
|
||||
return build_task_rpa_inventory_source(task)
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(
|
||||
task: ShippingTask,
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
resolution: InventorySourceResolution | None = None,
|
||||
resolution: InventorySourceAdjudication | None = None,
|
||||
) -> None:
|
||||
"""把已确认库存源写入 task.step_payload_json,供后续 RPA trigger 使用。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["rpa_inventory_source"] = source
|
||||
"""把已确认库存源写入独立字段与 step_payload_json。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
if resolution:
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": resolution.status,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"reason": resolution.reason,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
return
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
cfg = get_inventory_source(code)
|
||||
if not cfg:
|
||||
return
|
||||
context = extract_routing_context(task)
|
||||
resolution = resolve_inventory_source_identity(cfg, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return
|
||||
identity = resolution.identity
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=identity.source_code,
|
||||
source_type=identity.source_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
)
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceResolution) -> None:
|
||||
"""库存源无法唯一命中时,把候选项写入 task.step_payload_json 供前端/Agent 展示。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": resolution.status,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"reason": resolution.reason,
|
||||
"candidates": resolution.candidates,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None:
|
||||
"""库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
@@ -22,6 +22,49 @@ _VALID_SOURCE_TYPES = {
|
||||
}
|
||||
_VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"})
|
||||
_CONFIG_CACHE: dict[str, Any] | None = None
|
||||
_CONFIG_PATH: str | None = None
|
||||
_CONFIG_RAW_DIGEST: str | None = None
|
||||
|
||||
|
||||
def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""提取参与版本哈希的语义字段,忽略注释/空白等文件层噪声。"""
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
return {
|
||||
"source_code": source.get("source_code"),
|
||||
"source_type": source.get("source_type"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"warehouse_resolution": source.get("warehouse_resolution"),
|
||||
"enabled": source.get("enabled", True),
|
||||
"priority": source.get("priority", 0),
|
||||
"entry_url": source.get("entry_url"),
|
||||
"display_name": source.get("display_name"),
|
||||
"match_aliases": sorted(source.get("match_aliases") or []),
|
||||
"allowed_warehouse_ids": sorted(source.get("allowed_warehouse_ids") or []),
|
||||
"match": {
|
||||
key: sorted(value) if isinstance(value, list) else value
|
||||
for key, value in sorted(match_cfg.items())
|
||||
},
|
||||
"navigation": source.get("navigation"),
|
||||
"parameters": source.get("parameters"),
|
||||
"export": source.get("export"),
|
||||
}
|
||||
|
||||
|
||||
def _normalized_config_digest(sources: dict[str, dict[str, Any]]) -> str:
|
||||
"""基于规范化结构计算配置内容哈希。"""
|
||||
import hashlib
|
||||
|
||||
canonical = [_canonical_source_for_digest(sources[code]) for code in sorted(sources)]
|
||||
payload = json.dumps(canonical, sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _config_content_version(payload: dict[str, Any], sources: dict[str, dict[str, Any]]) -> str:
|
||||
"""配置版本 = 声明版本 + 规范化结构哈希。"""
|
||||
digest = _normalized_config_digest(sources)
|
||||
declared = str(payload.get("version") or "1").strip()
|
||||
return f"{declared}-{digest}"
|
||||
|
||||
|
||||
class InventorySourceConfigError(ValueError):
|
||||
@@ -131,6 +174,11 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
|
||||
return query
|
||||
|
||||
|
||||
def effective_warehouse_id(source: dict[str, Any]) -> str:
|
||||
"""返回配置中显式声明的 warehouse_id;禁止用 site_id 回填。"""
|
||||
return str(source.get("warehouse_id") or "").strip().upper()
|
||||
|
||||
|
||||
def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]:
|
||||
"""校验并规范化单条库存源配置。"""
|
||||
source_code = str(raw.get("source_code") or "").strip().upper()
|
||||
@@ -146,8 +194,31 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
|
||||
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
|
||||
site_id = str(raw.get("site_id") or "").strip().upper()
|
||||
if source_type == "dsv360" and not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
|
||||
if source_type == "dsv360":
|
||||
if not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
|
||||
if not warehouse_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360")
|
||||
elif source_type == "crane_footprint":
|
||||
if not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint")
|
||||
aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()]
|
||||
if not aliases:
|
||||
raise InventorySourceConfigError(f"{source_code}: match_aliases is required for crane_footprint")
|
||||
allowed_warehouse_ids = [
|
||||
str(item).strip()
|
||||
for item in (raw.get("allowed_warehouse_ids") or [])
|
||||
if str(item).strip()
|
||||
]
|
||||
if not allowed_warehouse_ids:
|
||||
raise InventorySourceConfigError(
|
||||
f"{source_code}: allowed_warehouse_ids is required for crane_footprint"
|
||||
)
|
||||
warehouse_resolution = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
|
||||
if warehouse_resolution != "alias_match":
|
||||
raise InventorySourceConfigError(
|
||||
f"{source_code}: warehouse_resolution must be alias_match for crane_footprint"
|
||||
)
|
||||
parameters: list[dict[str, Any]] = []
|
||||
for item in raw.get("parameters") or []:
|
||||
if not isinstance(item, dict):
|
||||
@@ -167,6 +238,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
"site_id": site_id,
|
||||
"display_name": str(raw.get("display_name") or source_code).strip(),
|
||||
"enabled": bool(raw.get("enabled", True)),
|
||||
"priority": int(raw.get("priority") or 0),
|
||||
"entry_url": str(raw.get("entry_url") or "").strip(),
|
||||
"warehouse_id": warehouse_id,
|
||||
"navigation": dict(raw.get("navigation") or {}),
|
||||
@@ -177,6 +249,18 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
if str(alias).strip()
|
||||
],
|
||||
}
|
||||
if source_type == "crane_footprint":
|
||||
normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
|
||||
normalized["allowed_warehouse_ids"] = allowed_warehouse_ids
|
||||
match_cfg = raw.get("match")
|
||||
if isinstance(match_cfg, dict) and match_cfg:
|
||||
normalized["match"] = {
|
||||
"destination_codes": [str(v).strip() for v in (match_cfg.get("destination_codes") or []) if str(v).strip()],
|
||||
"customers": [str(v).strip() for v in (match_cfg.get("customers") or []) if str(v).strip()],
|
||||
"order_types": [str(v).strip() for v in (match_cfg.get("order_types") or []) if str(v).strip()],
|
||||
"warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()],
|
||||
"aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()],
|
||||
}
|
||||
if source_type == "crane_footprint" and raw.get("export"):
|
||||
normalized["export"] = dict(raw.get("export") or {})
|
||||
normalized["query"] = _build_legacy_query(normalized)
|
||||
@@ -184,15 +268,24 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
|
||||
|
||||
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
|
||||
"""加载并缓存 YAML/JSON 配置;force_reload 用于测试。"""
|
||||
global _CONFIG_CACHE
|
||||
if _CONFIG_CACHE is not None and not force_reload:
|
||||
return _CONFIG_CACHE
|
||||
"""加载并缓存 YAML/JSON 配置;路径或文件内容变化时刷新(不依赖 mtime 单独命中)。"""
|
||||
import hashlib
|
||||
|
||||
global _CONFIG_CACHE, _CONFIG_PATH, _CONFIG_RAW_DIGEST
|
||||
path = _config_path()
|
||||
if not path.is_file():
|
||||
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
|
||||
|
||||
path_str = str(path.resolve())
|
||||
raw_digest = hashlib.sha256(path.read_bytes()).hexdigest()[:16]
|
||||
if (
|
||||
_CONFIG_CACHE is not None
|
||||
and not force_reload
|
||||
and _CONFIG_PATH == path_str
|
||||
and _CONFIG_RAW_DIGEST == raw_digest
|
||||
):
|
||||
return _CONFIG_CACHE
|
||||
|
||||
payload = _parse_config_payload(path)
|
||||
sources_raw = payload.get("sources")
|
||||
if not isinstance(sources_raw, list):
|
||||
@@ -207,13 +300,21 @@ def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
|
||||
sources[normalized["source_code"]] = normalized
|
||||
|
||||
_CONFIG_CACHE = {
|
||||
"version": int(payload.get("version") or 1),
|
||||
"version": _config_content_version(payload, sources),
|
||||
"sources": sources,
|
||||
"path": str(path),
|
||||
"path": path_str,
|
||||
"raw_digest": raw_digest,
|
||||
}
|
||||
_CONFIG_PATH = path_str
|
||||
_CONFIG_RAW_DIGEST = raw_digest
|
||||
return _CONFIG_CACHE
|
||||
|
||||
|
||||
def get_inventory_sources_config_version() -> str:
|
||||
"""返回当前加载的库存源配置版本字符串。"""
|
||||
return str(_load_config().get("version") or "1")
|
||||
|
||||
|
||||
def reload_inventory_sources_config() -> dict[str, Any]:
|
||||
"""强制重新加载库存源配置(管理/测试用)。"""
|
||||
return _load_config(force_reload=True)
|
||||
@@ -230,6 +331,44 @@ def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
|
||||
return deepcopy(source)
|
||||
|
||||
|
||||
def source_uses_dynamic_warehouse_id(source: dict[str, Any] | None) -> bool:
|
||||
"""判断库存源是否采用运行时动态库位(如 CRANE alias_match)。"""
|
||||
if not source:
|
||||
return False
|
||||
if str(source.get("warehouse_id") or "").strip():
|
||||
return False
|
||||
resolution = str(source.get("warehouse_resolution") or "").strip().lower()
|
||||
return resolution in {"alias_match", "dynamic", "runtime"}
|
||||
|
||||
|
||||
def configured_warehouse_aliases(source: dict[str, Any] | None) -> set[str]:
|
||||
"""返回配置中的路由匹配别名集合(大写),供订单目的地裁决使用。"""
|
||||
if not source:
|
||||
return set()
|
||||
return {
|
||||
str(alias).strip().upper()
|
||||
for alias in (source.get("match_aliases") or [])
|
||||
if str(alias).strip()
|
||||
}
|
||||
|
||||
|
||||
def configured_allowed_warehouse_ids(source: dict[str, Any] | None) -> set[str]:
|
||||
"""
|
||||
返回 Worker 回调允许落库的库位 ID 集合(大写)。
|
||||
核心逻辑:优先读 allowed_warehouse_ids;静态源回退 warehouse_id;与 match_aliases 解耦。
|
||||
"""
|
||||
if not source:
|
||||
return set()
|
||||
allowed = source.get("allowed_warehouse_ids")
|
||||
if allowed:
|
||||
return {str(item).strip().upper() for item in allowed if str(item).strip()}
|
||||
# fallback for static DSV 等源
|
||||
warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
|
||||
if warehouse_id:
|
||||
return {warehouse_id}
|
||||
return set()
|
||||
|
||||
|
||||
def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]:
|
||||
"""返回库存源配置副本,供人工检查点展示候选项。"""
|
||||
sources = _load_config()["sources"].values()
|
||||
@@ -242,6 +381,8 @@ def build_rpa_inventory_source(
|
||||
source_code: str | None,
|
||||
*,
|
||||
query_override: dict[str, Any] | None = None,
|
||||
site_id: str | None = None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 RPA trigger 使用的 rpa_inventory_source。
|
||||
@@ -256,4 +397,59 @@ def build_rpa_inventory_source(
|
||||
if value is not None and str(value).strip():
|
||||
query[key] = value
|
||||
source["query"] = query
|
||||
return source
|
||||
return merge_runtime_inventory_identity(source, site_id=site_id, warehouse_id=warehouse_id)
|
||||
|
||||
|
||||
def merge_runtime_inventory_identity(
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
site_id: str | None = None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将任务已解析的 site/warehouse 合并进 RPA source,并同步 query.warehouse_code。
|
||||
核心逻辑:Crane 动态库位、DSV 子仓均通过本函数进入 trigger/回调/快照复用。
|
||||
"""
|
||||
merged = deepcopy(source)
|
||||
site = str(site_id or merged.get("site_id") or "").strip().upper()
|
||||
warehouse = str(warehouse_id or merged.get("warehouse_id") or "").strip().upper()
|
||||
if site:
|
||||
merged["site_id"] = site
|
||||
if warehouse:
|
||||
merged["warehouse_id"] = warehouse
|
||||
merged["_runtime_identity_applied"] = True
|
||||
query = dict(merged.get("query") or {})
|
||||
query["warehouse_code"] = warehouse
|
||||
merged["query"] = query
|
||||
source_type = str(merged.get("source_type") or "").strip()
|
||||
if source_type == "crane_footprint":
|
||||
navigation = dict(merged.get("navigation") or {})
|
||||
navigation["project_code"] = warehouse
|
||||
merged["navigation"] = navigation
|
||||
query["project_code"] = warehouse
|
||||
merged["query"] = query
|
||||
return merged
|
||||
|
||||
|
||||
def build_task_rpa_inventory_source(task: "ShippingTask") -> dict[str, Any] | None:
|
||||
"""
|
||||
基于任务正式库存身份构造运行时 RPA source(配置 + 动态库位)。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa、RPA 回调、快照复用统一调用。
|
||||
"""
|
||||
from app.models import ShippingTask
|
||||
|
||||
if not isinstance(task, ShippingTask):
|
||||
return None
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
code = str(task.inventory_source_code or "").strip().upper()
|
||||
site_id = str(task.inventory_site_id or "").strip().upper() or None
|
||||
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() or None
|
||||
if not code:
|
||||
legacy = payload.get("rpa_inventory_source")
|
||||
if isinstance(legacy, dict) and legacy.get("source_code"):
|
||||
return merge_runtime_inventory_identity(legacy, site_id=site_id, warehouse_id=warehouse_id)
|
||||
return None
|
||||
base = get_inventory_source(code)
|
||||
if not base:
|
||||
return None
|
||||
return merge_runtime_inventory_identity(base, site_id=site_id, warehouse_id=warehouse_id)
|
||||
@@ -3,25 +3,199 @@ services/shipping_notice/inventory_upload.py
|
||||
|
||||
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
|
||||
依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
|
||||
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息。
|
||||
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
|
||||
正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingTask
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
|
||||
_TASK_INVENTORY_SUFFIXES = (".xlsx", ".csv")
|
||||
_TASK_INVENTORY_MARKER = ".current_inventory"
|
||||
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
|
||||
|
||||
|
||||
def _inventory_file_sha256(path: Path) -> str:
|
||||
"""计算库存附件 SHA256,用于幂等安装判断。"""
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _task_inventory_attachment_marker_path(task_no: str) -> Path:
|
||||
"""任务当前正式库存附件指针文件路径。"""
|
||||
return _task_inventory_upload_dir(task_no) / _TASK_INVENTORY_MARKER
|
||||
|
||||
|
||||
def _atomic_write_task_inventory_marker(task_no: str, attachment_filename: str) -> None:
|
||||
"""通过临时文件 + os.replace 原子切换 .current_inventory 指针。"""
|
||||
import os
|
||||
|
||||
marker = _task_inventory_attachment_marker_path(task_no)
|
||||
tmp = marker.with_name(f"{marker.name}.tmp")
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp.write_text(attachment_filename, encoding="utf-8")
|
||||
os.replace(tmp, marker)
|
||||
|
||||
|
||||
def _read_task_inventory_attachment_marker(task_no: str) -> Path | None:
|
||||
"""读取指针文件并校验对应附件仍存在。"""
|
||||
marker = _task_inventory_attachment_marker_path(task_no)
|
||||
if not marker.is_file():
|
||||
return None
|
||||
name = marker.read_text(encoding="utf-8").strip()
|
||||
if not name:
|
||||
return None
|
||||
path = _task_inventory_upload_dir(task_no) / name
|
||||
if path.is_file() and _is_task_inventory_attachment_name(path.name):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _is_task_inventory_attachment_name(name: str) -> bool:
|
||||
"""判断文件名是否为合法任务库存附件。"""
|
||||
lowered = str(name or "").lower()
|
||||
if not lowered.startswith("inventory"):
|
||||
return False
|
||||
return any(lowered.endswith(suffix) for suffix in _TASK_INVENTORY_SUFFIXES)
|
||||
|
||||
|
||||
def _versioned_task_inventory_path(task_no: str, suffix: str) -> Path:
|
||||
"""生成不可变版本化任务库存附件路径。"""
|
||||
token = datetime.utcnow().strftime("%Y%m%d%H%M%S%f")
|
||||
normalized = suffix if suffix in _TASK_INVENTORY_SUFFIXES else ".xlsx"
|
||||
return _task_inventory_upload_dir(task_no) / f"{_TASK_INVENTORY_VERSION_PREFIX}{token}{normalized}"
|
||||
|
||||
|
||||
def _list_task_inventory_attachment_candidates(task_no: str) -> list[Path]:
|
||||
"""列出任务目录下全部库存附件候选文件。"""
|
||||
base = _task_inventory_upload_dir(task_no)
|
||||
if not base.is_dir():
|
||||
return []
|
||||
return [
|
||||
path
|
||||
for path in base.iterdir()
|
||||
if path.is_file() and _is_task_inventory_attachment_name(path.name)
|
||||
]
|
||||
|
||||
|
||||
def _cleanup_superseded_task_inventory_files(task_no: str, *, keep_name: str) -> list[str]:
|
||||
"""
|
||||
指针切换后清理旧版附件(best effort)。
|
||||
Returns:
|
||||
未能删除的文件名列表。
|
||||
"""
|
||||
warnings: list[str] = []
|
||||
for path in _list_task_inventory_attachment_candidates(task_no):
|
||||
if path.name == keep_name:
|
||||
continue
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError as exc:
|
||||
warnings.append(f"{path.name}:{str(exc)[:80]}")
|
||||
return warnings
|
||||
|
||||
|
||||
def install_task_inventory_attachment_from_file(
|
||||
task_no: str,
|
||||
source_path: str | Path,
|
||||
*,
|
||||
source_file_name: str | None = None,
|
||||
) -> Path:
|
||||
"""
|
||||
将源库存文件安装为任务正式附件(版本化文件名 + 原子 marker 切换)。
|
||||
【AI 触发时机】:RPA 回调晋升失败补偿、人工修复任务附件时调用;不依赖重新消费 callback。
|
||||
|
||||
核心逻辑:复制到 inventory_{timestamp}{suffix} → 原子切换 .current_inventory → 清理旧附件。
|
||||
若当前正式附件与源文件内容一致则幂等返回现有路径。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
source_path: 源库存文件(通常为 inv_file.storage_path 或 staging)。
|
||||
source_file_name: 可选展示名,仅用于日志语义。
|
||||
|
||||
Returns:
|
||||
安装后的正式附件路径。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源文件不存在。
|
||||
OSError: 复制或 marker 切换失败。
|
||||
"""
|
||||
source = Path(source_path)
|
||||
if not source.is_file():
|
||||
raise FileNotFoundError(f"未找到库存源文件: {source}")
|
||||
|
||||
current = resolve_task_inventory_upload_path(task_no)
|
||||
if current is not None and _inventory_file_sha256(current) == _inventory_file_sha256(source):
|
||||
return current
|
||||
|
||||
suffix = inventory_storage_suffix_for_path(source)
|
||||
versioned = _versioned_task_inventory_path(task_no, suffix)
|
||||
versioned.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, versioned)
|
||||
try:
|
||||
_atomic_write_task_inventory_marker(task_no, versioned.name)
|
||||
_cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
|
||||
except Exception:
|
||||
if versioned.is_file():
|
||||
try:
|
||||
versioned.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
if source_file_name:
|
||||
_ = source_file_name
|
||||
return versioned
|
||||
|
||||
|
||||
def rebuild_task_inventory_attachment_from_snapshot(
|
||||
task: ShippingTask | str,
|
||||
inv_file: ShippingInventoryFile,
|
||||
) -> Path:
|
||||
"""
|
||||
从已提交库存快照 storage_path 幂等重建任务正式附件。
|
||||
【AI 触发时机】:RPA 回调 DB 已提交但任务附件晋升失败,或运维人工补偿时调用。
|
||||
|
||||
Args:
|
||||
task: 任务对象或 task_no。
|
||||
inv_file: 已链接的库存快照。
|
||||
|
||||
Returns:
|
||||
重建后的任务正式附件路径。
|
||||
"""
|
||||
task_no = task.task_no if isinstance(task, ShippingTask) else str(task or "").strip()
|
||||
if not task_no:
|
||||
raise ValueError("task_no is required")
|
||||
storage_path = Path(str(inv_file.storage_path or ""))
|
||||
if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
|
||||
raise FileNotFoundError(
|
||||
f"库存快照托管文件不存在: {inv_file.inventory_file_no}",
|
||||
)
|
||||
return install_task_inventory_attachment_from_file(
|
||||
task_no,
|
||||
storage_path,
|
||||
source_file_name=str(inv_file.source_file_name or storage_path.name),
|
||||
)
|
||||
|
||||
|
||||
def inventory_text_max_chars() -> int:
|
||||
"""库存粘贴文本最大字符数(SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS,默认 80000)。"""
|
||||
@@ -31,18 +205,72 @@ def inventory_text_max_chars() -> int:
|
||||
return 80000
|
||||
|
||||
|
||||
def task_inventory_upload_path(task_no: str) -> Path:
|
||||
"""任务级库存 Excel 标准落盘路径(inventory_uploads/{task_no}/inventory.xlsx)。"""
|
||||
safe = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
|
||||
return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx"
|
||||
def _task_inventory_upload_dir(task_no: str) -> Path:
|
||||
"""任务级库存附件目录(inventory_uploads/{task_no})。"""
|
||||
safe = _sanitize_task_no(task_no)
|
||||
return _storage_root() / "inventory_uploads" / safe
|
||||
|
||||
|
||||
def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path:
|
||||
"""
|
||||
任务级库存附件标准落盘路径(默认 inventory.xlsx)。
|
||||
suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。
|
||||
"""
|
||||
normalized = (suffix or ".xlsx").lower()
|
||||
if normalized not in _TASK_INVENTORY_SUFFIXES:
|
||||
normalized = ".xlsx"
|
||||
return _task_inventory_upload_dir(task_no) / f"inventory{normalized}"
|
||||
|
||||
|
||||
def _recover_and_repair_task_inventory_marker(task_no: str) -> Path | None:
|
||||
"""
|
||||
marker 缺失或损坏时扫描附件目录并修复 .current_inventory。
|
||||
核心逻辑:仅在此路径下根据 mtime 选择候选;修复后返回已提交附件。
|
||||
"""
|
||||
candidates = _list_task_inventory_attachment_candidates(task_no)
|
||||
if not candidates:
|
||||
return None
|
||||
versioned = [
|
||||
path
|
||||
for path in candidates
|
||||
if path.name.startswith(_TASK_INVENTORY_VERSION_PREFIX)
|
||||
]
|
||||
if versioned:
|
||||
chosen = max(versioned, key=lambda item: item.stat().st_mtime)
|
||||
elif len(candidates) == 1:
|
||||
chosen = candidates[0]
|
||||
else:
|
||||
chosen = max(candidates, key=lambda item: item.stat().st_mtime)
|
||||
_atomic_write_task_inventory_marker(task_no, chosen.name)
|
||||
return chosen
|
||||
|
||||
|
||||
def resolve_task_inventory_upload_path(task_no: str) -> Path | None:
|
||||
"""
|
||||
返回任务当前已提交的正式库存附件路径。
|
||||
核心逻辑:marker 有效且目标文件存在时必须无条件相信 marker;
|
||||
仅 marker 缺失或损坏时才执行恢复扫描并同步修复 marker。
|
||||
"""
|
||||
marked = _read_task_inventory_attachment_marker(task_no)
|
||||
if marked is not None:
|
||||
return marked
|
||||
return _recover_and_repair_task_inventory_marker(task_no)
|
||||
|
||||
|
||||
def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
|
||||
"""保存 werkzeug FileStorage 库存上传并返回落盘路径。"""
|
||||
path = task_inventory_upload_path(task_no)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
upload.save(str(path))
|
||||
return path
|
||||
suffix = ".xlsx"
|
||||
filename = str(getattr(upload, "filename", "") or "").lower()
|
||||
if filename.endswith(".csv"):
|
||||
suffix = ".csv"
|
||||
staging_dir = _task_inventory_upload_dir(task_no) / ".staging"
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}"
|
||||
upload.save(str(staging))
|
||||
try:
|
||||
return install_task_inventory_attachment_from_file(task_no, staging)
|
||||
finally:
|
||||
delete_staged_task_inventory_file(staging)
|
||||
|
||||
|
||||
def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path:
|
||||
@@ -66,16 +294,111 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat
|
||||
source = Path(source_path)
|
||||
if not source.is_file():
|
||||
raise FileNotFoundError(f"未找到库存源文件: {source}")
|
||||
path = task_inventory_upload_path(task_no)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, path)
|
||||
return path
|
||||
return install_task_inventory_attachment_from_file(
|
||||
task_no,
|
||||
source,
|
||||
source_file_name=source.name,
|
||||
)
|
||||
|
||||
|
||||
def _sanitize_task_no(task_no: str) -> str:
|
||||
"""将任务号规范为库存上传目录名。"""
|
||||
return re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
|
||||
|
||||
|
||||
def stage_task_inventory_callback_file(
|
||||
task_no: str,
|
||||
source_path: str | Path,
|
||||
*,
|
||||
run_no: str | None = None,
|
||||
) -> Path:
|
||||
"""
|
||||
将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。
|
||||
核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
source_path: Worker 回调提供的本地库存文件。
|
||||
run_no: 可选轮次号,用于生成稳定且唯一的 staging 文件名。
|
||||
|
||||
Returns:
|
||||
Path: staging 文件路径。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源文件不存在。
|
||||
"""
|
||||
source = Path(source_path)
|
||||
if not source.is_file():
|
||||
raise FileNotFoundError(f"未找到库存源文件: {source}")
|
||||
token = re.sub(
|
||||
r"[^\w\-]+",
|
||||
"_",
|
||||
str(run_no or "").strip() or datetime.utcnow().strftime("%Y%m%d%H%M%S%f"),
|
||||
)
|
||||
suffix = source.suffix.lower() if source.suffix else ".xlsx"
|
||||
staging_dir = _storage_root() / "inventory_uploads" / _sanitize_task_no(task_no) / ".staging"
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
staging_path = staging_dir / f"rpa_callback_{token}{suffix}"
|
||||
shutil.copy2(source, staging_path)
|
||||
return staging_path
|
||||
|
||||
|
||||
def promote_staged_task_inventory_file(task_no: str, staging_path: str | Path) -> Path:
|
||||
"""
|
||||
校验与数据库提交成功后,将 staging 安装为任务正式库存附件。
|
||||
核心逻辑:版本化落盘 + 原子 marker 切换 + 异步清理旧附件;旧附件删除失败返回 warning 列表。
|
||||
"""
|
||||
import os
|
||||
|
||||
staging = Path(staging_path)
|
||||
if not staging.is_file():
|
||||
raise FileNotFoundError(f"未找到 staging 库存文件: {staging}")
|
||||
suffix = staging.suffix.lower() if staging.suffix else ".xlsx"
|
||||
if suffix not in _TASK_INVENTORY_SUFFIXES:
|
||||
suffix = ".xlsx"
|
||||
versioned = _versioned_task_inventory_path(task_no, suffix)
|
||||
versioned.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(staging, versioned)
|
||||
try:
|
||||
_atomic_write_task_inventory_marker(task_no, versioned.name)
|
||||
cleanup_warnings = _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
|
||||
if cleanup_warnings:
|
||||
raise OSError(f"legacy_attachment_cleanup_failed:{';'.join(cleanup_warnings)[:200]}")
|
||||
except Exception:
|
||||
if versioned.is_file():
|
||||
try:
|
||||
versioned.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
try:
|
||||
staging.parent.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
return versioned
|
||||
|
||||
|
||||
def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None:
|
||||
"""删除本轮 staging 库存文件(失败回滚用,不触碰任务正式附件)。"""
|
||||
if not staging_path:
|
||||
return
|
||||
path = Path(staging_path)
|
||||
if not path.is_file():
|
||||
return
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
path.parent.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
|
||||
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
|
||||
path = task_inventory_upload_path(task_no)
|
||||
if not path.is_file():
|
||||
path = resolve_task_inventory_upload_path(task_no)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = path.name
|
||||
@@ -97,8 +420,8 @@ def parse_uploaded_task_inventory(
|
||||
Returns:
|
||||
tuple: (inventory_lines, column_meta, 文件路径)。
|
||||
"""
|
||||
path = task_inventory_upload_path(task_no)
|
||||
if not path.is_file():
|
||||
path = resolve_task_inventory_upload_path(task_no)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
path,
|
||||
@@ -112,5 +435,5 @@ def parse_uploaded_task_inventory(
|
||||
|
||||
|
||||
def has_uploaded_task_inventory(task_no: str) -> bool:
|
||||
"""任务是否已有落盘的库存 Excel 文件。"""
|
||||
return task_inventory_upload_path(task_no).is_file()
|
||||
"""任务是否已有落盘的库存附件(.xlsx 或 .csv)。"""
|
||||
return resolve_task_inventory_upload_path(task_no) is not None
|
||||
@@ -12,9 +12,11 @@ import json
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_MAP,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_UPLOAD_REQ,
|
||||
SUGGEST_OK,
|
||||
@@ -57,6 +59,8 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
@@ -117,6 +121,29 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
|
||||
return result
|
||||
|
||||
|
||||
def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
|
||||
核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。
|
||||
"""
|
||||
if is_inventory_source_stable(task):
|
||||
return None
|
||||
try:
|
||||
assert_inventory_source_gate(task, operation=operation)
|
||||
except AppError:
|
||||
ui = resolve_task_ui_state(task)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Parse inventory from uploaded file, chat text, or structured JSON."""
|
||||
lang = resolve_lang(payload)
|
||||
@@ -124,6 +151,10 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
gate_resp = _inventory_source_gate_response(task, operation="parse_inventory", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
# [STEP 1] 先归一化库存输入来源与映射提示。
|
||||
# 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。
|
||||
use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in {
|
||||
@@ -237,6 +268,10 @@ def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
gate_resp = _inventory_source_gate_response(task, operation="get_inventory_schema_preview", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -279,6 +314,10 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
gate_resp = _inventory_source_gate_response(task, operation="apply_inventory_mapping", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
# [STEP 1] 先校验上传文件与 schema preview 是否存在。
|
||||
# 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。
|
||||
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
|
||||
@@ -415,6 +454,9 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
||||
lang = resolve_lang({"lang": None})
|
||||
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
@@ -432,7 +474,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
filename = str(upload.filename or "").strip()
|
||||
if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
|
||||
if not filename.lower().endswith((".xlsx", ".csv")):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
@@ -452,7 +494,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
db.session.flush()
|
||||
inv_file = save_batch_inventory_upload(task, upload)
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=str(exc.message or "库存上传被拒绝"),
|
||||
data=serialize_task_for_tool(task),
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
except OSError as exc:
|
||||
db.session.rollback()
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
@@ -537,6 +590,20 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
try:
|
||||
assert_inventory_source_gate(task, operation="ensure_inventory")
|
||||
except AppError:
|
||||
pass
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint="inventory_source_review",
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 1] 优先接受当前请求直接携带的库存明细。
|
||||
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
|
||||
mode = str(payload.get("mode") or "auto").strip().lower()
|
||||
|
||||
@@ -2,19 +2,18 @@
|
||||
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
|
||||
|
||||
import base64
|
||||
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
|
||||
|
||||
@@ -23,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:
|
||||
@@ -111,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 []
|
||||
@@ -171,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(".")
|
||||
@@ -188,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"}:
|
||||
@@ -249,6 +239,8 @@ class NoticeIntakeResult:
|
||||
text: str
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
meta: dict[str, Any] = field(default_factory=dict)
|
||||
content_hash: str = ""
|
||||
file_size: int = 0
|
||||
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
|
||||
saved_path: Path | None = None
|
||||
|
||||
@@ -263,6 +255,8 @@ class NoticeIntakeResult:
|
||||
"source_type": self.source_type,
|
||||
"source_file_name": self.filename,
|
||||
"source_file_type": self.source_file_type,
|
||||
"source_content_hash": self.content_hash,
|
||||
"file_size": self.file_size,
|
||||
"raw_text": self.text,
|
||||
"warnings": list(self.warnings),
|
||||
}
|
||||
@@ -274,6 +268,8 @@ class NoticeIntakeResult:
|
||||
"source_type": self.source_type,
|
||||
"source_file_type": self.source_file_type,
|
||||
"text_length": len(self.text),
|
||||
"content_hash": self.content_hash,
|
||||
"file_size": self.file_size,
|
||||
"warnings": list(self.warnings),
|
||||
}
|
||||
|
||||
@@ -349,6 +345,9 @@ def intake_notice_attachment(
|
||||
"""
|
||||
name = str(filename or "").strip() or "notice"
|
||||
source_type = guess_source_type(name)
|
||||
raw_bytes = raw or b""
|
||||
content_hash = hashlib.sha256(raw_bytes).hexdigest().lower()
|
||||
file_size = len(raw_bytes)
|
||||
saved_path: Path | None = None
|
||||
text = ""
|
||||
meta: dict[str, Any] = {}
|
||||
@@ -359,11 +358,11 @@ def intake_notice_attachment(
|
||||
if storage == "task":
|
||||
if not task_no:
|
||||
raise ValueError("task_no is required for task storage")
|
||||
saved_path = save_task_notice_upload(task_no, name, raw or b"")
|
||||
saved_path = save_task_notice_upload(task_no, name, raw_bytes)
|
||||
else:
|
||||
if not temp_request_id:
|
||||
raise ValueError("temp_request_id is required for temp storage")
|
||||
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"")
|
||||
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw_bytes)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
@@ -376,6 +375,8 @@ def intake_notice_attachment(
|
||||
text="",
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=content_hash,
|
||||
file_size=file_size,
|
||||
status=status,
|
||||
saved_path=saved_path,
|
||||
)
|
||||
@@ -388,6 +389,8 @@ def intake_notice_attachment(
|
||||
text="",
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=content_hash,
|
||||
file_size=file_size,
|
||||
status="empty_text",
|
||||
saved_path=saved_path,
|
||||
)
|
||||
@@ -400,6 +403,8 @@ def intake_notice_attachment(
|
||||
text=text,
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
content_hash=content_hash,
|
||||
file_size=file_size,
|
||||
status="accepted",
|
||||
saved_path=saved_path,
|
||||
)
|
||||
@@ -408,23 +413,37 @@ def intake_notice_attachment(
|
||||
def intake_temp_notice_uploads(
|
||||
temp_request_id: str,
|
||||
uploads: Sequence[Any],
|
||||
) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]:
|
||||
) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult], list[dict[str, Any]]]:
|
||||
"""
|
||||
批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。
|
||||
批量建单入口:逐份附件接入、同请求内按内容哈希去重,并在 finally 外由调用方清理临时目录。
|
||||
|
||||
Args:
|
||||
temp_request_id: 请求级临时目录 ID。
|
||||
uploads: Flask request.files 中的上传对象序列。
|
||||
|
||||
Returns:
|
||||
tuple[list, list]: (accepted 结果列表, rejected 结果列表)。
|
||||
tuple: (accepted 结果列表, rejected 结果列表, duplicate_files 摘要列表)。
|
||||
"""
|
||||
accepted: list[NoticeIntakeResult] = []
|
||||
rejected: list[NoticeIntakeResult] = []
|
||||
duplicate_files: list[dict[str, Any]] = []
|
||||
seen_hashes: dict[str, str] = {}
|
||||
for index, upload in enumerate(uploads, start=1):
|
||||
raw = upload.read() or b""
|
||||
content_hash = hashlib.sha256(raw).hexdigest().lower()
|
||||
filename = str(upload.filename or "notice").strip() or "notice"
|
||||
if content_hash in seen_hashes:
|
||||
duplicate_files.append(
|
||||
{
|
||||
"filename": filename,
|
||||
"duplicate_of": seen_hashes[content_hash],
|
||||
"content_hash": content_hash,
|
||||
}
|
||||
)
|
||||
continue
|
||||
seen_hashes[content_hash] = filename
|
||||
result = intake_notice_attachment(
|
||||
filename=upload.filename or "notice",
|
||||
filename=filename,
|
||||
raw=raw,
|
||||
source_file_type=notice_source_file_type(upload),
|
||||
storage="temp",
|
||||
@@ -435,7 +454,7 @@ def intake_temp_notice_uploads(
|
||||
accepted.append(result)
|
||||
else:
|
||||
rejected.append(result)
|
||||
return accepted, rejected
|
||||
return accepted, rejected, duplicate_files
|
||||
|
||||
|
||||
def build_notice_file_summary(
|
||||
@@ -443,6 +462,7 @@ def build_notice_file_summary(
|
||||
total_files: int,
|
||||
accepted: Sequence[NoticeIntakeResult],
|
||||
rejected: Sequence[NoticeIntakeResult],
|
||||
duplicate_files: Sequence[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建批量上传预检摘要,供前端回显与测试断言。
|
||||
@@ -451,16 +471,20 @@ def build_notice_file_summary(
|
||||
total_files: 请求内附件总数。
|
||||
accepted: 接入成功的结果列表。
|
||||
rejected: 接入失败的结果列表。
|
||||
duplicate_files: 同请求内内容重复、已跳过的文件摘要。
|
||||
|
||||
Returns:
|
||||
dict: total/accepted/rejected 计数与文件明细。
|
||||
dict: total/accepted/rejected/duplicate 计数与文件明细。
|
||||
"""
|
||||
accepted_files = [item.to_accepted_file_summary() for item in accepted]
|
||||
rejected_files = [item.to_rejected_file_summary() for item in rejected]
|
||||
duplicates = [dict(item) for item in (duplicate_files or [])]
|
||||
return {
|
||||
"total_files": total_files,
|
||||
"accepted_count": len(accepted_files),
|
||||
"rejected_count": len(rejected_files),
|
||||
"duplicate_count": len(duplicates),
|
||||
"accepted_files": accepted_files,
|
||||
"rejected_files": rejected_files,
|
||||
"duplicate_files": duplicates,
|
||||
}
|
||||
@@ -183,6 +183,24 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["task_id", MAP_JSON],
|
||||
),
|
||||
"/tools/confirm_inventory_source": _post_op(
|
||||
"confirm_inventory_source",
|
||||
"在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"source_code": _str_prop(
|
||||
"启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;"
|
||||
"站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传"
|
||||
),
|
||||
},
|
||||
required=["task_id", "source_code"],
|
||||
description=(
|
||||
"库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,"
|
||||
"且 routing_fingerprint 与当前配置版本一致。"
|
||||
"Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
|
||||
"若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_decision": _post_op(
|
||||
"submit_decision",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||
@@ -218,11 +236,19 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
),
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
|
||||
"查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
},
|
||||
description=(
|
||||
"返回 inventory_source_code、inventory_source_type、inventory_site_id、"
|
||||
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
|
||||
"user_confirmed|invalid|conflicted)、inventory_source_method、"
|
||||
"inventory_source_config_version、inventory_routing_fingerprint、"
|
||||
"inventory_source_confirmed_by、inventory_source_confirmed_at,"
|
||||
"以及 step_payload.inventory_source_resolution.candidates。"
|
||||
),
|
||||
),
|
||||
"/tools/get_batch_status": _post_op(
|
||||
"get_batch_status",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -14,7 +14,17 @@ from flask import current_app
|
||||
|
||||
from app.services.shipping_notice import fulfillment_workflow
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_UPLOAD_REQ,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
ensure_inventory_source_review_state,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_mapping_checkpoint_response,
|
||||
@@ -84,6 +94,27 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task):
|
||||
adjudication = ensure_inventory_source_review_state(task)
|
||||
db.session.commit()
|
||||
if not is_inventory_source_stable(task):
|
||||
ui = resolve_task_ui_state(task)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_source_candidates": adjudication.candidates,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
},
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 2] 保证库存已经就绪。
|
||||
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
|
||||
if not task.inventory_lines_json:
|
||||
|
||||
@@ -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),
|
||||
@@ -331,12 +366,28 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
|
||||
"rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None,
|
||||
"inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None,
|
||||
"destination_code": task.destination_code,
|
||||
"destination_city": task.destination_city,
|
||||
"destination_country": task.destination_country,
|
||||
"warehouse_hint": task.warehouse_hint,
|
||||
"inventory_source_code": task.inventory_source_code,
|
||||
"inventory_source_type": task.inventory_source_type,
|
||||
"inventory_site_id": task.inventory_site_id,
|
||||
"inventory_warehouse_id": task.inventory_warehouse_id,
|
||||
"inventory_source_status": task.inventory_source_status,
|
||||
"inventory_source_method": task.inventory_source_method,
|
||||
"inventory_source_config_version": task.inventory_source_config_version,
|
||||
"inventory_routing_fingerprint": task.inventory_routing_fingerprint,
|
||||
"inventory_source_confirmed_at": task.inventory_source_confirmed_at.isoformat() if task.inventory_source_confirmed_at else None,
|
||||
"inventory_source_confirmed_by": task.inventory_source_confirmed_by,
|
||||
"inventory_snapshot": _serialize_inventory_snapshot(task),
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"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({
|
||||
|
||||
@@ -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,23 +111,66 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
|
||||
|
||||
|
||||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
|
||||
from app.jobs.queue import recover_stale_jobs
|
||||
"""
|
||||
回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。
|
||||
|
||||
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)
|
||||
核心逻辑:单票编排与预解析分超时配置回收;预解析 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,
|
||||
)
|
||||
|
||||
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)
|
||||
return count, f'recovered_{count}' if count else 'no_stale_jobs'
|
||||
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 = []
|
||||
if count:
|
||||
parts.append(f'recovered_{count}')
|
||||
if cleanup_count:
|
||||
parts.append(f'callback_cleanup_{cleanup_count}')
|
||||
return count, '_'.join(parts) if parts else 'no_stale_jobs'
|
||||
|
||||
|
||||
def claim_next_shipping_notice_job() -> Job | None:
|
||||
"""兼容旧调用:领取下一条发货通知通用任务。"""
|
||||
"""领取下一条发货通知通用任务(单票编排或预解析)。"""
|
||||
from app.jobs.queue import claim_next_job
|
||||
from app.jobs.types import JobType
|
||||
|
||||
return claim_next_job(
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN],
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN, JobType.SHIPPING_NOTICE_PARSE],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
|
||||
body = {
|
||||
"action": "inventory_export",
|
||||
"task_no": task_no,
|
||||
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
@@ -177,7 +178,7 @@ def write_inventory_export_trigger_for_task(
|
||||
"""
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
|
||||
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
|
||||
return write_inventory_export_batch_trigger(
|
||||
run_no,
|
||||
[rpa_source],
|
||||
|
||||
@@ -512,7 +512,7 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
pending_human_reason=PH_INV_UNAVAIL,
|
||||
),
|
||||
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
process_status="pending_review",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
),
|
||||
|
||||
@@ -14,15 +14,24 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_OK,
|
||||
CP_RSV_REQ,
|
||||
CP_TASK_EXISTS,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
adjudicate_and_apply_inventory_source,
|
||||
is_inventory_source_stable,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.extract import extract_notice_fields
|
||||
@@ -46,6 +55,17 @@ from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||||
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
acquire_notice_create_locks,
|
||||
assert_idempotent_batch_content_matches,
|
||||
assert_no_exact_duplicate_notices,
|
||||
build_existing_batch_tool_response,
|
||||
compute_notice_items_content_fingerprint,
|
||||
dedupe_notice_items_by_content_hash,
|
||||
find_batch_by_create_idempotency,
|
||||
handle_batch_create_integrity_error,
|
||||
normalize_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
auto_progress_enabled,
|
||||
defer_parse_to_dify_enabled,
|
||||
@@ -66,11 +86,23 @@ def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lin
|
||||
if isinstance(destination, dict):
|
||||
payload["destination"] = destination
|
||||
candidates.append(destination)
|
||||
task.destination_code = str(destination.get("port_code") or destination.get("destination_code") or "").strip().upper() or None
|
||||
task.destination_city = str(destination.get("city") or "").strip() or None
|
||||
task.destination_country = str(destination.get("country") or "").strip().upper() or None
|
||||
task.warehouse_hint = str(destination.get("warehouse_hint") or "").strip() or None
|
||||
elif destination:
|
||||
candidates.append(destination)
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"):
|
||||
if parsed.get(key):
|
||||
candidates.append(parsed.get(key))
|
||||
if parsed.get("destination_port") and not task.destination_code:
|
||||
task.destination_code = str(parsed.get("destination_port") or "").strip().upper() or None
|
||||
if parsed.get("destination_city") and not task.destination_city:
|
||||
task.destination_city = str(parsed.get("destination_city") or "").strip() or None
|
||||
if parsed.get("destination_country") and not task.destination_country:
|
||||
task.destination_country = str(parsed.get("destination_country") or "").strip().upper() or None
|
||||
if parsed.get("warehouse_hint") and not task.warehouse_hint:
|
||||
task.warehouse_hint = str(parsed.get("warehouse_hint") or "").strip() or None
|
||||
if task.ship_to:
|
||||
candidates.append(task.ship_to)
|
||||
for line in lines:
|
||||
@@ -175,42 +207,56 @@ def sync_batch_after_task_change(task: ShippingTask | None) -> None:
|
||||
recompute_batch_summary(task.batch)
|
||||
|
||||
|
||||
def create_batch(payload: dict[str, Any]) -> ShippingBatch:
|
||||
def create_batch(payload: dict[str, Any]) -> tuple[ShippingBatch, bool]:
|
||||
"""
|
||||
创建或复用发货批次壳(不含 notice 解析)。
|
||||
【AI 触发时机】:当用户一次上传多份发货通知、需要归并到同一批次时调用。
|
||||
|
||||
核心逻辑:优先复用已有 `batch_no`,否则生成新的批次号并初始化批次汇总字段。
|
||||
核心逻辑:优先复用已有 `batch_no` 或 `(user_id, create_idempotency_key)`,否则生成新批次号。
|
||||
Args:
|
||||
payload: 可包含 batch_no、user_id、conversation_id、file_count 等批次创建参数。
|
||||
payload: 可包含 batch_no、user_id、conversation_id、file_count、create_idempotency_key 等。
|
||||
|
||||
Returns:
|
||||
ShippingBatch: 已存在或新建但尚未提交事务的批次对象。
|
||||
tuple[ShippingBatch, bool]: (批次对象, 是否本次新建)。复用已有批次时第二项为 False。
|
||||
"""
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
existing = ShippingBatch.query.filter_by(batch_no=batch_no).first()
|
||||
if existing:
|
||||
return existing
|
||||
return existing, False
|
||||
|
||||
user_id = payload.get("user_id")
|
||||
idem_key = normalize_create_idempotency_key(payload.get("create_idempotency_key"))
|
||||
if idem_key and user_id is not None:
|
||||
existing_by_idem = find_batch_by_create_idempotency(int(user_id), idem_key)
|
||||
if existing_by_idem:
|
||||
return existing_by_idem, False
|
||||
|
||||
try:
|
||||
file_count = max(1, int(payload.get("file_count") or 1))
|
||||
except (TypeError, ValueError):
|
||||
file_count = 1
|
||||
content_fingerprint = str(payload.get("create_content_fingerprint") or "").strip().lower() or None
|
||||
summary: dict[str, Any] = {"total": 0, "completed": 0, "failed": 0, "running": 0}
|
||||
if content_fingerprint:
|
||||
summary["create_content_fingerprint"] = content_fingerprint
|
||||
batch = ShippingBatch(
|
||||
batch_no=f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}",
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
|
||||
file_count=file_count,
|
||||
process_summary_json={"total": 0, "completed": 0, "failed": 0, "running": 0},
|
||||
create_idempotency_key=idem_key,
|
||||
process_summary_json=summary,
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
return batch
|
||||
return batch, True
|
||||
|
||||
|
||||
def _create_single_task_batch(payload: dict[str, Any]) -> ShippingBatch:
|
||||
"""为单票任务创建 file_count=1 的标准批次容器。"""
|
||||
return create_batch({**payload, "file_count": 1})
|
||||
batch, _created = create_batch({**payload, "file_count": 1})
|
||||
return batch
|
||||
|
||||
|
||||
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
|
||||
@@ -231,15 +277,33 @@ 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 标准响应,包含批次摘要和每个任务的解析状态。
|
||||
"""
|
||||
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 = create_batch(payload)
|
||||
db.session.commit()
|
||||
batch, _created = create_batch(payload)
|
||||
try:
|
||||
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),
|
||||
create_idempotency_key=idem_key,
|
||||
exc=exc,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
raise
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
@@ -250,13 +314,49 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
},
|
||||
}
|
||||
|
||||
batch = create_batch({**payload, "file_count": len(notice_items)})
|
||||
notice_items = dedupe_notice_items_by_content_hash(notice_items)
|
||||
content_hashes = [
|
||||
str(item.get("source_content_hash") or "").strip().lower()
|
||||
for item in notice_items
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if user_id is not None:
|
||||
acquire_notice_create_locks(int(user_id), content_hashes)
|
||||
|
||||
request_fingerprint = compute_notice_items_content_fingerprint(notice_items)
|
||||
if idem_key and user_id is not None:
|
||||
existing_batch = find_batch_by_create_idempotency(int(user_id), idem_key)
|
||||
if existing_batch:
|
||||
assert_idempotent_batch_content_matches(existing_batch, notice_items)
|
||||
return build_existing_batch_tool_response(existing_batch, user_id=int(user_id))
|
||||
|
||||
if user_id is not None:
|
||||
assert_no_exact_duplicate_notices(int(user_id), notice_items)
|
||||
|
||||
batch, created_new = create_batch(
|
||||
{
|
||||
**payload,
|
||||
"file_count": len(notice_items),
|
||||
"create_content_fingerprint": request_fingerprint,
|
||||
}
|
||||
)
|
||||
if not created_new:
|
||||
if idem_key and user_id is not None:
|
||||
assert_idempotent_batch_content_matches(batch, notice_items)
|
||||
return build_existing_batch_tool_response(batch, user_id=int(user_id))
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
"批次已存在,禁止向已有批次重复追加任务",
|
||||
code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT",
|
||||
details={"batch_no": batch.batch_no},
|
||||
)
|
||||
db.session.flush()
|
||||
created_tasks: list[dict[str, Any]] = []
|
||||
total = len(notice_items)
|
||||
for idx, item in enumerate(notice_items, start=1):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
content_hash = str(item.get("source_content_hash") or "").strip().lower() or None
|
||||
task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
batch_id=batch.id,
|
||||
@@ -265,6 +365,16 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
source_type=str(item.get("source_type") or "manual"),
|
||||
source_file_name=str(item.get("source_file_name") or "").strip() or None,
|
||||
source_file_type=item.get("source_file_type"),
|
||||
source_content_hash=content_hash,
|
||||
source_asset_id=item.get("source_asset_id"),
|
||||
source_intake_id=item.get("source_intake_id"),
|
||||
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,
|
||||
@@ -272,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"),
|
||||
@@ -307,7 +436,20 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
try:
|
||||
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),
|
||||
create_idempotency_key=idem_key,
|
||||
exc=exc,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
raise
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
@@ -565,32 +707,126 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 4] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。
|
||||
if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
|
||||
if not _has_parse_review_content(task, lines):
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
|
||||
db.session.commit()
|
||||
message = (
|
||||
"未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
|
||||
"或复制粘贴通知正文后重新解析。"
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=message,
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
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)
|
||||
# [STEP 4] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。
|
||||
if not _has_parse_review_content(task, lines):
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
|
||||
db.session.commit()
|
||||
message = (
|
||||
"未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
|
||||
"或复制粘贴通知正文后重新解析。"
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload),
|
||||
message=message,
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
|
||||
# [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)
|
||||
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="无法根据发货通知唯一确定库存查询来源",
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="库存源待确认",
|
||||
progress_percent=100,
|
||||
detail="解析已通过,请确认本票应使用哪个库存源后继续。",
|
||||
extra={"warnings": warnings, "inventory_source_status": adjudication.status},
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_review_required",
|
||||
{
|
||||
"status": adjudication.status,
|
||||
"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="\n".join(message_parts),
|
||||
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,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
@@ -605,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 = (
|
||||
|
||||
@@ -32,6 +32,7 @@ apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
|
||||
upload_inventory_file = inventory_workflow.upload_inventory_file
|
||||
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
|
||||
rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch
|
||||
repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment
|
||||
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
|
||||
|
||||
# 履约阶段
|
||||
|
||||
@@ -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
|
||||
@@ -29,6 +30,7 @@ from app.services.shipping_notice.constants import (
|
||||
CP_UPLOAD_REQ,
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_MAP_INFER,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
@@ -39,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,
|
||||
@@ -82,6 +85,7 @@ _TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
|
||||
_BLOCKED_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_ALIGN_REVIEW,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
@@ -129,7 +133,7 @@ def _derive_current_step_index(task: ShippingTask) -> int:
|
||||
if process_status in {"parsed", "pending_review"} or review_status in {
|
||||
RS_PARSE_REVIEW,
|
||||
PH_RSV_REQ,
|
||||
} or pending_reason in {"low_confidence", PH_RSV_REQ}:
|
||||
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
@@ -159,7 +163,11 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) ->
|
||||
index == 2
|
||||
and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
|
||||
)
|
||||
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked):
|
||||
parse_blocked = index == 1 and (
|
||||
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED}
|
||||
or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}
|
||||
)
|
||||
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked):
|
||||
status = "blocked"
|
||||
steps.append({**step, "status": status})
|
||||
return steps
|
||||
@@ -173,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] = {
|
||||
@@ -181,7 +270,7 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
|
||||
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
|
||||
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
|
||||
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
|
||||
CP_INVENTORY_SOURCE_REVIEW: "库存查询来源不明确,需要先确认。",
|
||||
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
|
||||
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
|
||||
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
|
||||
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
|
||||
@@ -194,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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user