feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载

This commit is contained in:
hugo committed 2026-07-14 09:14:44 +08:00
1 parent 143e054d86
commit 729546a7b7
52 files changed
+3420 -34

No files matched your search

@@ -0,0 +1,261 @@
"""
backend/app/services/shipping_notice/batch_from_intakes.py
用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。
依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency。
逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。
先幂等回放;按 content_hash 去重后 FOR UPDATE 预占 consumed;建批失败须 rollback 预占。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy import select
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import FileAsset, ShippingNoticeIntake, ShippingTask
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.intake_parse_workflow import intake_to_notice_item
from app.services.shipping_notice.intake_service import mark_intakes_consumed
def _batch_intake_nos(batch_id: int) -> set[str]:
"""
读取批次关联的全部 intake_no 集合。
核心逻辑:以 consumed_batch_id 为准(含 content_hash 去重后的附属 intake),
避免仅按 task.source_intake_id 导致幂等集合校验误报冲突。
"""
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 _try_idempotent_replay(
*,
user_id: int,
create_idempotency_key: str | None,
intake_nos: list[str],
) -> dict[str, Any] | None:
"""
按 user_id + create_idempotency_key 查找已有批次,并校验 intake 集合一致。
Returns:
幂等重放响应;无匹配批次时返回 None。
"""
key = normalize_create_idempotency_key(create_idempotency_key)
if not key:
return None
existing = find_batch_by_create_idempotency(user_id, key)
if existing is None:
return None
expected = set(intake_nos)
actual = _batch_intake_nos(int(existing.id))
if expected != actual:
raise ConflictError(
'建单幂等键对应批次的接入集合不一致',
code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT',
details={'batch_no': existing.batch_no, 'expected': sorted(expected), 'actual': sorted(actual)},
)
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 用于建单。
Returns:
(primary_pairs, duplicates_by_hash):duplicates 不含 primary。
"""
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 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 可能已 consumed);
2. FOR UPDATE 锁定 intake,校验 parsed;
3. 按 content_hash 去重后再预标记 consumed(仅 flush),再调用建批;
4. 建批异常必须 rollback,避免 Chat Turn 后续 commit 把预占 consumed 落库;
5. 建批成功后回填 batch/task,并把同 hash 附属 intake 一并关联到同一任务。
"""
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
if not normalized:
raise ValidationError('intake_nos is required')
# [STEP 1] 幂等重放优先:相同 Idempotency-Key 在 intake 已消费后仍可恢复原批次
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',
)
# 锁后再查一次幂等键,覆盖 STEP1 与锁定之间的并发窗口
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()
for intake_no in normalized:
intake, asset = row_by_no[intake_no]
if intake.consumed_at is not None or intake.parse_status == 'consumed':
raise ConflictError(
f'接入记录 {intake.intake_no} 已被消费',
code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED',
)
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'
),
)
if intake.expires_at and intake.expires_at < now:
raise ConflictError(
'接入记录已过期',
code='SHIPPING_NOTICE.INTAKE_EXPIRED',
)
ordered_pairs.append((intake, asset))
# [STEP 3] content_hash 去重:只消费真正用于建单的 primary intake
primary_pairs, duplicates_by_hash = _partition_intakes_by_content_hash(ordered_pairs)
primary_intakes = [intake for intake, _ in primary_pairs]
notice_items = [intake_to_notice_item(intake, asset) for intake, asset in primary_pairs]
# [STEP 4] 预占消费状态(flush 不 commit),与后续 create_batch_tasks 同事务提交
mark_intakes_consumed(intakes=primary_intakes, batch_id=None)
db.session.flush()
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,
)
except Exception:
# [P0] 建批失败时丢弃预占 consumed,避免 Chat Turn 的 touch_chat_session commit 落脏状态
db.session.rollback()
raise
if bool(result.get('idempotent_replay')):
# create 路径返回重放时不会 commit;丢弃本事务内的预占 consumed,避免脏状态落库
db.session.rollback()
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:
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
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)
# [STEP 5] 同 hash 附属 intake 显式关联到同一任务,避免残留 parsed 且保证幂等集合一致
duplicate_intakes: list[ShippingNoticeIntake] = []
for content_hash, dups in duplicates_by_hash.items():
task_id = hash_to_task_id.get(content_hash)
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:
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},
)
db.session.commit()
return result
@@ -149,6 +149,58 @@ class ShippingCreateBatchFromNoticesAction:
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,
)
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")),
}
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 等。"""
@@ -307,6 +359,7 @@ class ShippingMarkManualUploadedAction:
_HANDLERS = (
ShippingCreateBatchFromNoticesAction(),
ShippingCreateBatchFromIntakesAction(),
ShippingSubmitDecisionAction(),
ShippingGenerateExcelAction(),
ShippingRetryUploadAction(),
@@ -0,0 +1,254 @@
"""
backend/app/services/shipping_notice/intake_parse_workflow.py
用途:发货通知接入记录的文本抽取与预解析编排。
依赖:notice_upload、file_assets.service、models.ShippingNoticeIntake。
逻辑:由 shipping_notice_parse Job handler 调用;不写 API 路由。
"""
from __future__ import annotations
import tempfile
from pathlib import Path
from typing import Any
from flask import current_app
from sqlalchemy import update
from app import db
from app.models import FileAsset, ShippingNoticeIntake
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.notice_upload import (
NoticeIntakeResult,
extract_notice_text,
guess_source_type,
truncate_notice_text,
)
def _parser_version() -> str:
return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip()
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:
text, meta = extract_notice_text(tmp_path)
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,
)
def intake_result_to_structured_summary(result: NoticeIntakeResult) -> dict[str, Any]:
"""生成前端可展示的预解析摘要。"""
line_count = 0
for line in str(result.text or '').splitlines():
if line.strip():
line_count += 1
return {
'filename': result.filename,
'source_type': result.source_type,
'text_length': len(result.text or ''),
'line_count': line_count,
'warnings': list(result.warnings),
'parser_version': _parser_version(),
}
_ABORT_WRITE_STATUSES = frozenset({'cancelled', 'expired', 'consumed'})
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 _commit_parse_result_if_writable(
*,
intake_id: int,
values: dict[str, Any],
) -> ShippingNoticeIntake | None:
"""
条件更新解析结果:仅当库中状态仍非 cancelled/expired/consumed 时写回。
Returns:
写成功后的 ORM 对象;被取消/过期/消费则返回 None。
"""
# [STEP 1] 先强制刷新;若已终态则放弃
status = _db_parse_status(intake_id)
if status is None or status in _ABORT_WRITE_STATUSES:
return None
# [STEP 2] 原子 UPDATE,防止 refresh 与 commit 之间的竞态仍覆盖 cancelled
stmt = (
update(ShippingNoticeIntake)
.where(
ShippingNoticeIntake.id == int(intake_id),
ShippingNoticeIntake.parse_status.notin_(tuple(_ABORT_WRITE_STATUSES)),
)
.values(**values)
)
result = db.session.execute(stmt)
if int(result.rowcount or 0) != 1:
db.session.rollback()
return None
db.session.commit()
return db.session.get(ShippingNoticeIntake, int(intake_id))
def run_intake_parse(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]:
"""
执行单条接入记录的预解析并更新 ORM 状态。
核心逻辑:抽取文本后强制刷新并条件 UPDATE;抽取期间被取消则 status=skipped,不覆盖 cancelled。
Returns:
解析结果摘要字典;若期间被取消/过期则 status=skipped。
"""
result = extract_notice_from_asset(asset)
intake_id = int(intake.id)
intake_no = intake.intake_no
parser_version = _parser_version()
summary = intake_result_to_structured_summary(result)
warnings = list(result.warnings)
if result.status == 'extract_failed':
fresh = _commit_parse_result_if_writable(
intake_id=intake_id,
values={
'parser_version': parser_version,
'parse_status': 'parse_failed',
'error_code': 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
'error_message': '; '.join(warnings)[:1000] or '文本抽取失败',
'extracted_text': None,
'structured_result_json': summary,
'parse_warnings_json': warnings,
},
)
if fresh is None:
return {
'status': 'skipped',
'intake_no': intake_no,
'parse_status': _db_parse_status(intake_id),
}
return {'status': 'parse_failed', 'intake_no': intake_no, 'error_message': fresh.error_message}
if result.status == 'empty_text':
fresh = _commit_parse_result_if_writable(
intake_id=intake_id,
values={
'parser_version': parser_version,
'parse_status': 'parse_failed',
'error_code': 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
'error_message': '未提取到有效文本',
'extracted_text': None,
'structured_result_json': summary,
'parse_warnings_json': warnings,
},
)
if fresh is None:
return {
'status': 'skipped',
'intake_no': intake_no,
'parse_status': _db_parse_status(intake_id),
}
return {'status': 'parse_failed', 'intake_no': intake_no, 'error_message': fresh.error_message}
fresh = _commit_parse_result_if_writable(
intake_id=intake_id,
values={
'parser_version': parser_version,
'parse_status': 'parsed',
'error_code': None,
'error_message': None,
'extracted_text': result.text,
'structured_result_json': summary,
'parse_warnings_json': warnings,
},
)
if fresh is None:
return {
'status': 'skipped',
'intake_no': intake_no,
'parse_status': _db_parse_status(intake_id),
}
return {'status': 'parsed', 'intake_no': intake_no}
def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]:
"""将已解析 intake 转为兼容 create_batch 的 notice_item。"""
return {
'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,
}
@@ -0,0 +1,251 @@
"""
backend/app/services/shipping_notice/intake_service.py
用途:发货通知接入记录(ShippingNoticeIntake)业务编排。
依赖:file_assets.service、intake_parse_workflow、jobs.queue、models。
逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行。
"""
from __future__ import annotations
import uuid
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import FileAsset, ShippingNoticeIntake
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
def _parser_version() -> str:
return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').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 serialize_intake(intake: ShippingNoticeIntake, *, asset: FileAsset | None = None) -> dict[str, Any]:
"""对外序列化接入记录。"""
payload: dict[str, Any] = {
'intake_no': intake.intake_no,
'asset_no': asset.asset_no if asset else None,
'conversation_id': intake.conversation_id,
'parse_status': intake.parse_status,
'parser_version': intake.parser_version,
'parse_summary': intake.structured_result_json,
'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)
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 create_shipping_notice_intake(
*,
user_id: int,
asset_no: str,
conversation_id: str | None = None,
) -> dict[str, Any]:
"""
基于已上传 FileAsset 创建接入记录并投递解析 Job。
核心逻辑:校验资产 ready → 复用同 parser 版本 intake → 入队 shipping_notice_parse。
"""
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()
intake = (
db.session.query(ShippingNoticeIntake)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.purpose == 'shipping_notice',
ShippingNoticeIntake.parser_version == parser_version,
)
.first()
)
if intake and intake.parse_status in {'parsed', 'consumed'}:
return serialize_intake(intake, asset=asset)
if not intake:
intake = ShippingNoticeIntake(
intake_no=generate_intake_no(),
asset_id=asset.id,
user_id=int(user_id),
conversation_id=str(conversation_id or '').strip() or None,
purpose='shipping_notice',
parse_status='created',
parser_version=parser_version,
expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()),
)
db.session.add(intake)
db.session.flush()
if intake.parse_status in {'queued', 'parsing'}:
return serialize_intake(intake, asset=asset)
intake.parse_status = 'queued'
intake.conversation_id = str(conversation_id or intake.conversation_id or '').strip() or None
intake.error_code = None
intake.error_message = 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),
)
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 的接入记录。"""
intake = get_intake_for_user(intake_no, user_id)
if intake.parse_status not in {'parse_failed'}:
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
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=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:
"""取消未消费的接入记录。"""
intake = get_intake_for_user(intake_no, user_id)
if intake.consumed_at is not None or intake.parse_status == 'consumed':
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费')
intake.parse_status = 'cancelled'
intake.updated_at = datetime.utcnow()
db.session.commit()
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)
@@ -134,12 +134,13 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
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],
)
@@ -360,6 +360,8 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
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"),
batch_index=idx,
batch_total=total,
raw_content=str(item.get("raw_text") or "").strip() or None,