docs(tec): 更新货代发货通知批次库存能力文档

- 添加单票与多票发货需求的处理方式
- 说明库存 Excel 上传后的保存与关联机制
- 解释库存匹配与 Excel 生成的独立执行方式
- 明确批次库存的真相来源

feat(chat): 优化发货库存上传提示语
- 根据上传结果生成更详细的提示信息
- 增加批次号的提示逻辑
- 使用国际化支持替换硬编码字符串

refactor(chat): 重构发货库存上传处理逻辑
- 移除多余的任务选择逻辑
- 简化上传处理流程
- 增强代码可读性与维护性

feat(locales): 更新多语言支持的提示信息
- 添加库存上传与任务处理的多语言提示
- 更新库存缺口与任务状态的描述
This commit is contained in:
hugo committed 2026-06-26 16:27:49 +08:00
1 parent 1bd9f278fe
commit 1cf8ff40bd
34 files changed
+4367 -3553

No files matched your search

+3 -4
View File
@@ -1189,7 +1189,7 @@ def chat_completions():
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
dify_inputs: dict[str, str] | None = None
dify_inputs: dict[str, object] | None = None
hxops_turn_id: str | None = None
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
@@ -1220,12 +1220,11 @@ def chat_completions():
elif is_shipping_agent:
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
dify_inputs = build_shipping_notice_dify_inputs(
external_conversation_id or session.session_id,
session.session_id,
task_id=shipping_task_id,
batch_no=shipping_batch_no,
entry_mode="user_chat",
user_message=query,
trigger_source="frontend_chat",
request_id=request_id,
)
generator = DifyService.stream_chat(
query,
+8 -8
View File
@@ -137,7 +137,7 @@ def openapi_dify_yaml():
def tool_create_task():
"""
创建单个发货任务。
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.create_task(_payload()))
@@ -146,7 +146,7 @@ def tool_create_task():
def tool_create_batch():
"""
创建或复用发货批次。
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
@@ -262,7 +262,7 @@ def tool_apply_inventory_mapping():
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.ensure_inventory(_payload()))
@@ -271,7 +271,7 @@ def tool_ensure_inventory():
def tool_auto_progress():
"""
自动推进任务。
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.auto_progress(_payload()))
@@ -280,7 +280,7 @@ def tool_auto_progress():
def tool_match_inventory():
"""
执行库存匹配。
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.match_inventory(_payload()))
@@ -298,7 +298,7 @@ def tool_submit_decision():
def tool_generate_shipment_excel():
"""
生成出货 Excel。
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.generate_excel(_payload()))
@@ -307,7 +307,7 @@ def tool_generate_shipment_excel():
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@@ -353,7 +353,7 @@ def tool_get_batch_status():
def tool_switch_focus_task():
"""
切换批次当前焦点任务。
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
+239 -13
View File
@@ -1,34 +1,260 @@
"""
backend/app/jobs/queue.py
用途:任务入队 API。
逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。
用途:通用后台任务入队、领取与完成状态管理。
依赖:models.Job、jobs.types、Flask app.config。
逻辑:业务服务调用 enqueue 写入 jobs;worker 调用 claim/finish/fail 完成执行闭环。
"""
from __future__ import annotations
import socket
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.jobs.types import JobType
from app.models import Job
ACTIVE_STATUSES = ("queued", "running")
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
def _normalize_job_type(job_type: JobType | str) -> str:
"""把 JobType 或字符串统一成数据库保存值。"""
return str(getattr(job_type, "value", job_type) or "").strip()
def _worker_id() -> str:
"""生成当前 worker 标识,用于锁记录和排障。"""
try:
host = socket.gethostname()
except Exception:
host = "unknown-host"
return f"{host}:{id(db.session)}"
def enqueue(
job_type: JobType,
job_type: JobType | str,
payload: dict[str, Any],
*,
domain: str = "default",
business_ref: str | None = None,
created_by_id: int | None = None,
priority: int = 0,
max_attempts: int = 3,
message: str | None = None,
dedupe_active: bool = True,
correlation_id: str | None = None,
scheduled_at: Any = None,
) -> int:
"""
将任务写入队列并返回 job id。
核心逻辑:Wave 2 实现 store.create + KbJob adapter。
将任务写入通用 jobs 队列并返回 job id。
Args:
job_type: 任务类型。
payload: 任务参数 JSON。
correlation_id: 关联业务 id(如 kb_document_id)。
scheduled_at: 延迟执行时间(可选)。
Returns:
Job 主键。
Raises:
NotImplementedError: Wave 0 占位。
payload: JSON payload。
domain: 业务域,如 shipping_notice。
business_ref: 业务幂等锚点,如发货任务号。
created_by_id: 创建人。
priority: 优先级,数值越大越先执行。
max_attempts: 最大尝试次数。
message: 初始状态说明。
dedupe_active: 是否复用 active 状态的同业务任务。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 预留参数,当前阶段不启用延迟调度。
"""
raise NotImplementedError('jobs.enqueue is not wired until Wave 2')
normalized_type = _normalize_job_type(job_type)
normalized_domain = str(domain or "").strip() or "default"
normalized_ref = str(business_ref or correlation_id or "").strip() or None
if not normalized_type:
raise ValueError("job_type is required")
if not isinstance(payload, dict):
raise ValueError("payload must be a dict")
if dedupe_active and normalized_ref:
existing = (
db.session.query(Job)
.filter(
Job.domain == normalized_domain,
Job.job_type == normalized_type,
Job.business_ref == normalized_ref,
Job.status.in_(ACTIVE_STATUSES),
)
.order_by(Job.created_at.desc(), Job.id.desc())
.first()
)
if existing:
return int(existing.id)
now = datetime.utcnow()
job = Job(
domain=normalized_domain,
job_type=normalized_type,
status="queued",
priority=int(priority or 0),
business_ref=normalized_ref,
payload_json=payload,
progress=0,
message=message or "等待后台处理",
attempts=0,
max_attempts=max(1, int(max_attempts or 1)),
created_by_id=created_by_id,
created_at=now,
updated_at=now,
)
db.session.add(job)
db.session.commit()
return int(job.id)
def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
"""回收指定业务域内超时 running 的通用任务。"""
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
query = (
db.session.query(Job)
.filter(
Job.domain == domain,
Job.status == "running",
Job.started_at.isnot(None),
Job.started_at < cutoff,
)
)
normalized_type = _normalize_job_type(job_type) if job_type else ""
if normalized_type:
query = query.filter(Job.job_type == normalized_type)
stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
if not stale_jobs:
return 0
now = datetime.utcnow()
for job in stale_jobs:
if int(job.attempts or 0) < int(job.max_attempts or 1):
job.status = "queued"
job.message = "任务执行超时,已回收等待重试"
job.locked_by = None
job.locked_at = None
job.started_at = None
job.updated_at = now
continue
job.status = "failed"
job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
job.message = job.error_message
job.progress = 100
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
db.session.commit()
return len(stale_jobs)
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
"""原子领取指定业务域下一条 queued 任务。"""
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
now = datetime.utcnow()
try:
query = db.session.query(Job).filter(Job.domain == domain, Job.status == "queued")
if normalized_types:
query = query.filter(Job.job_type.in_(normalized_types))
job = (
query.order_by(Job.priority.desc(), Job.created_at.asc(), Job.id.asc())
.with_for_update(skip_locked=True)
.first()
)
except OperationalError:
db.session.rollback()
raise
if not job:
db.session.rollback()
return None
job.status = "running"
job.started_at = job.started_at or now
job.locked_at = now
job.locked_by = worker_id or _worker_id()
job.attempts = int(job.attempts or 0) + 1
job.progress = max(int(job.progress or 0), 1)
job.message = "worker 已领取任务"
job.updated_at = now
db.session.commit()
return job
def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
"""标记任务成功完成。"""
now = datetime.utcnow()
job.status = "success"
job.progress = 100
job.result_json = result or {}
job.message = message or "任务处理完成"
job.error_message = None
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
db.session.commit()
def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
"""标记任务失败;retryable 且未达上限时重新排队。"""
now = datetime.utcnow()
can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
job.status = "queued" if can_retry else "failed"
job.progress = 0 if can_retry else 100
job.result_json = result or {}
job.error_message = str(error or "job failed")[:1000]
job.message = "任务失败,等待重试" if can_retry else job.error_message
job.locked_by = None
job.locked_at = None
job.finished_at = None if can_retry else now
job.updated_at = now
db.session.commit()
def process_next_job(
*,
ctx: Any,
domain: str,
job_types: list[str | JobType] | None = None,
timeout_config_key: str | None = None,
default_timeout_seconds: float = 300,
) -> tuple[bool, str]:
"""领取并分发一条通用任务。"""
import app.jobs.handlers # noqa: F401
from app.jobs.registry import get_handler
timeout_seconds = float(
current_app.config.get(timeout_config_key, default_timeout_seconds)
if timeout_config_key
else default_timeout_seconds
)
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
job = claim_next_job(domain=domain, job_types=job_types)
if not job:
return False, "no_job"
job_id = int(job.id)
job_type_value = str(job.job_type or "").strip()
payload = dict(job.payload_json or {})
payload.setdefault("job_id", job_id)
handler = get_handler(JobType(job_type_value))
if handler is None:
fail_job(job, error=f"no handler registered for {job.job_type}")
return True, "missing_handler"
try:
handler(ctx, payload)
refreshed = db.session.get(Job, job_id)
if refreshed and refreshed.status == "running":
finish_job(refreshed, message="任务处理完成")
return True, job_type_value
except Exception as exc:
db.session.rollback()
refreshed = db.session.get(Job, job_id)
if refreshed:
fail_job(refreshed, error=str(exc), retryable=True)
raise
+96
View File
@@ -556,6 +556,45 @@ class KbJob(Base):
)
class Job(Base):
"""
通用后台任务
用途:承载非知识库专属的后台任务队列与执行记录。
依赖关系:由 app.jobs.queue 写入和领取,由 worker.py 分发到 app.jobs.handlers。
逻辑关系:业务表保存业务状态,本表只保存后台执行状态、锁、重试与结果。
"""
__tablename__ = 'jobs'
__table_args__ = (
Index('ix_jobs_domain_status_created', 'domain', 'status', 'created_at'),
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
Index('ix_jobs_locked_at', 'locked_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
domain: Mapped[str] = mapped_column(String(64), index=True)
job_type: Mapped[str] = mapped_column(String(64), index=True)
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
priority: Mapped[int] = mapped_column(Integer, default=0, index=True)
business_ref: Mapped[Optional[str]] = mapped_column(String(128))
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
progress: Mapped[int] = mapped_column(Integer, default=0)
message: Mapped[Optional[str]] = mapped_column(Text)
error_message: Mapped[Optional[str]] = mapped_column(Text)
attempts: Mapped[int] = mapped_column(Integer, default=0)
max_attempts: Mapped[int] = mapped_column(Integer, default=3)
locked_by: Mapped[Optional[str]] = mapped_column(String(128))
locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
class KbDifySyncRecord(Base):
"""
知识库 Dify 同步记录
@@ -858,6 +897,63 @@ class ShippingTaskEvent(Base):
task: Mapped["ShippingTask"] = relationship("ShippingTask", back_populates="events")
class ShippingInventoryFile(Base):
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
__tablename__ = 'shipping_inventory_files'
__table_args__ = (
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
line_count: Mapped[int] = mapped_column(Integer, default=0)
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped[Optional["ShippingBatch"]] = relationship("ShippingBatch", foreign_keys=[batch_id])
links: Mapped[List["ShippingTaskInventoryLink"]] = relationship(
"ShippingTaskInventoryLink",
back_populates="inventory_file",
cascade="all, delete-orphan",
)
class ShippingTaskInventoryLink(Base):
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
__tablename__ = 'shipping_task_inventory_links'
__table_args__ = (
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped["ShippingTask"] = relationship("ShippingTask", foreign_keys=[task_id])
inventory_file: Mapped["ShippingInventoryFile"] = relationship(
"ShippingInventoryFile",
back_populates="links",
foreign_keys=[inventory_file_id],
)
class ShippingInventoryMapping(Base):
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
__tablename__ = 'shipping_inventory_mappings'
@@ -0,0 +1,76 @@
"""
backend/app/services/chat/hxops_context.py
用途:构建 HXOPS -> Dify 的平台统一上下文注入协议。
依赖:无业务域依赖,仅提供平台级上下文结构与 refs 规范化工具。
逻辑:由聊天入口、后台编排器或各 Agent 适配层调用本模块,统一生成 hxops_context,
避免各业务目录重复定义 Dify Start 输入协议。
"""
from __future__ import annotations
from typing import Any
HXOPS_CONTEXT_INPUT = "hxops_context"
HXOPS_CONTEXT_SCHEMA_VERSION = "1"
def build_ref(field: str, value: str | None) -> dict[str, str] | None:
"""构建单个业务对象引用;缺值时返回 None。"""
normalized_field = str(field or "").strip()
normalized_value = str(value or "").strip()
if not normalized_field or not normalized_value:
return None
return {"field": normalized_field, "value": normalized_value}
def build_hxops_context(
*,
session_id: str,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
refs: list[dict[str, str] | None] | None = None,
) -> dict[str, Any]:
"""
构建平台统一的 hxops_context。
设计约束:
- 只注入平台基础信息与当前已知对象锚点
- 不注入 query/files 等 Dify 原生输入
- 不注入 checkpoint/stage 等运行态状态
"""
normalized_session_id = str(session_id or "").strip()
if not normalized_session_id:
return {}
request_payload: dict[str, str] = {}
normalized_request_id = str(request_id or "").strip()
normalized_trigger_source = str(trigger_source or "").strip()
normalized_locale = str(locale or "").strip()
if normalized_request_id:
request_payload["id"] = normalized_request_id
if normalized_trigger_source:
request_payload["trigger_source"] = normalized_trigger_source
if normalized_locale:
request_payload["locale"] = normalized_locale
normalized_refs: list[dict[str, str]] = []
seen_fields: set[str] = set()
for item in refs or []:
if not item:
continue
field = str(item.get("field") or "").strip()
value = str(item.get("value") or "").strip()
if not field or not value or field in seen_fields:
continue
normalized_refs.append({"field": field, "value": value})
seen_fields.add(field)
return {
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
"session": {"id": normalized_session_id},
"request": request_payload,
"refs": normalized_refs,
}
+3
View File
@@ -512,6 +512,7 @@ class DifyService:
hxops_turn_id: str | None = None,
files: list[dict[str, Any]] | None = None,
inputs: dict[str, Any] | None = None,
persist_chat_log: bool = True,
):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
@@ -592,6 +593,8 @@ class DifyService:
return None
def persist_stream_chat(data: dict, event_name: str) -> None:
if not persist_chat_log:
return
result = persist_stream_chat_async(data, event_name)
if isinstance(result, dict):
if result.get("chat_log_id") is not None:
@@ -3,7 +3,7 @@ services/shipping_notice/batch_orchestrator.py
用途:发货通知批次/单票后台编排器。
依赖:query_service、task_workflow、dify_executor、shipping_notice.tools、tool_common。
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成 AI 解析,其余确定性步骤由后端 auto_progress 推进。
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成单票 AI 解析,其余确定性步骤由后端 auto_progress 推进。
"""
from __future__ import annotations
@@ -95,7 +95,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
"""
后台执行单票任务的一轮推进。
`created` 先由 Dify 做单票解析,其余状态尝试走 auto_progress;进入人工检查点时自然返回。
`created` 先由 Dify 做单票解析;解析完成后和其他可续跑状态统一交给后端 auto_progress。
一旦进入人工检查点或等待外部回执状态,本轮自动停止,等待用户或外部系统回写。
"""
normalized_task_no = _normalize_ref(task_no)
if not normalized_task_no:
@@ -14,7 +14,7 @@ from typing import Any
MAP_JSON = "map_json"
SUGGEST_OK = "suggest_ok"
AUTO_MAP = "auto_map"
# Workspace / Hxops chat fallback only — Dify Agent 主路径应调 auto_progress,勿在画布 HTTP 传此字段
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Legacy request field names (read-only compat)
@@ -3,7 +3,7 @@ services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow。
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调 auto_progress 或 parse_notice。
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator 或 parse_notice。
"""
from __future__ import annotations
@@ -28,12 +28,18 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
inventory_mapping_checkpoint_response,
latest_inventory_column_meta,
)
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
linked_task_nos_for_inventory_file,
start_inventory_file_linked_tasks,
)
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
read_task_inventory_schema_preview,
task_inventory_upload_path,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
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
from app.services.shipping_notice.tool_common import (
@@ -44,6 +50,13 @@ from app.services.shipping_notice.tool_common import (
from app.services.shipping_notice.tool_response import tool_response
def start_task_orchestrator(task_no: str | None) -> bool:
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
return _start(task_no)
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
@@ -60,14 +73,12 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(
status="failed",
message=(
"未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。"
"请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。"
),
message=t("workflow.decision.task_not_found", lang="zh"),
)
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
lang = resolve_lang(payload)
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
@@ -78,7 +89,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message="已驳回该发货任务。",
message=t("workflow.decision.rejected", lang=lang),
data=serialize_task_for_tool(task),
)
@@ -89,7 +100,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message="已关闭该发货任务(可在同一会话重新开新单)。",
message=t("workflow.decision.closed", lang=lang),
data=serialize_task_for_tool(task),
)
@@ -100,7 +111,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="failed",
task_id=task.task_no,
message="库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
message=t("workflow.decision.shortage_confirm_blocked", lang=lang),
data=serialize_task_for_tool(task),
)
@@ -120,23 +131,23 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
log_task_event(task, "parse_confirmed", {"comment": comment})
db.session.commit()
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
next_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
if payload_wants_auto_chain_fallback(payload):
from app.services.shipping_notice.task_workflow import auto_progress
return auto_progress(next_payload)
return ensure_inventory(next_payload)
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.parse_confirmed_running", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="ok",
task=task,
message=(
"发货通知已确认。"
"请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。"
"禁止跳过匹配直接 generate_shipment_excel。"
),
message=t("workflow.decision.parse_confirmed_next", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action="ensure_inventory 或 parse_inventory",
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
@@ -147,59 +158,67 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message="已确认,可继续生成 Excel 并上传货代系统。",
message=t("workflow.decision.matched_confirmed", lang=lang),
data=serialize_task_for_tool(task),
)
if task.process_status == "waiting_inventory" or (
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
):
follow_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
if payload_wants_auto_chain_fallback(payload):
from app.services.shipping_notice.task_workflow import auto_progress
return auto_progress(follow_payload)
return ensure_inventory(follow_payload)
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.inventory_preparing", lang=lang),
data=serialize_task_for_tool(task),
)
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
if task.inventory_lines_json or task.process_status == "inventory_ready":
follow_payload = merge_tool_payload(task, payload)
if payload_wants_auto_chain_fallback(payload):
from app.services.shipping_notice.task_workflow import auto_progress
return auto_progress(follow_payload)
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="ok",
status="running" if orchestrator_started else "ok",
task=task,
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
message=t("workflow.decision.fulfillment_running", lang=lang),
data=serialize_task_for_tool(task),
)
return tool_response(
status="failed",
task_id=task.task_no,
message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
message=t("workflow.decision.confirm_invalid_state", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 3] 处理重算型决策。
# rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
# retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "retry_rpa":
log_task_event(task, "decision_retry_rpa", {"comment": comment})
db.session.flush()
retry_payload = merge_tool_payload(task, payload, extra={"mode": "retry_rpa"})
return ensure_inventory(retry_payload)
if decision == "rematch":
log_task_event(task, "decision_rematch", {"comment": comment})
db.session.commit()
rematch_payload = merge_tool_payload(task, payload)
return match_inventory(rematch_payload)
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.rematch_running", lang=lang),
data=serialize_task_for_tool(task),
)
if decision == "confirm_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
return tool_response(
status="failed",
task_id=task.task_no,
message="当前无需确认库存字段对齐。",
message=t("workflow.decision.mapping_not_needed", lang=lang),
data=serialize_task_for_tool(task),
)
meta = latest_inventory_column_meta(task) or {}
@@ -216,8 +235,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
column_meta=meta,
extra_data={
"warnings": [
"库存表必须包含 Reservation ID 列标题(该列允许为空值)。"
"请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。"
t("workflow.decision.mapping_missing_reservation_warning", lang=lang),
],
},
lang=lang or None,
@@ -234,17 +252,58 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
)
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
inv_file = active_inventory_file_for_task(task)
linked_task_nos = [task.task_no]
if inv_file:
inv_file.mapping_confirmed = True
log_task_event(
task,
"inventory_mapping_confirmed",
{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
)
for link in inv_file.links or []:
linked_task = link.task
if not link.is_active or not linked_task:
continue
linked_task_nos.append(linked_task.task_no)
if awaiting_inventory_mapping_confirm(linked_task):
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(
linked_task,
"inventory_mapping_confirmed",
{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
)
else:
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
db.session.commit()
next_payload = merge_tool_payload(task, payload)
return match_inventory(next_payload)
orchestrator_started = (
start_inventory_file_linked_tasks(inv_file)
if inv_file
else start_task_orchestrator(task.task_no)
)
if inv_file:
linked_task_nos = linked_task_nos_for_inventory_file(inv_file)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.mapping_confirmed_running", lang=lang),
data={**serialize_task_for_tool(task), "linked_task_nos": linked_task_nos},
)
if decision == "correct_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
return tool_response(
status="failed",
task_id=task.task_no,
message="当前不在库存字段对齐确认步骤,无法更正映射。",
message=t("workflow.decision.mapping_correction_invalid_state", lang=lang),
data=serialize_task_for_tool(task),
)
task.inventory_lines_json = None
@@ -259,7 +318,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="failed",
task_id=task.task_no,
message=f"读取库存表头失败: {exc}",
message=t("workflow.decision.read_inventory_preview_failed", lang=lang).format(error=exc),
data=serialize_task_for_tool(task),
)
else:
@@ -268,18 +327,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"headers": meta.get("headers") or [],
"sample_rows": [],
"suggested_mapping": meta.get("field_mapping") or {},
"note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
"note": t("workflow.decision.mapping_preview_note", lang=lang),
}
return tool_response(
status="needs_human",
task=task,
message=(
"已回到列映射步骤。请根据 schema_preview 提供新的 map_json,"
"再调用 apply_inventory_mapping。"
),
message=t("workflow.decision.mapping_correction_needed", lang=lang),
data={**serialize_task_for_tool(task), "schema_preview": preview},
checkpoint=CP_MAP_INFER,
next_required_action="apply_inventory_mapping(map_json=...)",
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
@@ -301,8 +357,10 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message="已清除库存快照,请重新上传或粘贴库存后调用 parse_inventory。",
message=t("workflow.decision.inventory_cleared", lang=lang),
data=serialize_task_for_tool(task),
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
# [STEP 4] 最后处理整单重新解析。
@@ -312,4 +370,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
return parse_notice({"task_id": task.task_no, "raw_text": task.raw_content or ""})
return tool_response(status="failed", task_id=task.task_no, message=f"未知 decision: {decision}")
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.unknown", lang=lang).format(decision=decision),
)
@@ -25,24 +25,12 @@ from app.services.shipping_notice.tool_common import cfg_int
def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None) -> str:
"""构造后台排程器发给 Dify 的单票解析指令。"""
pieces = [
"你正在处理货代发货通知任务。",
f"当前任务编号:{task_no}。",
]
if batch_no:
pieces.append(f"所属批次:{batch_no}。")
pieces.extend(
[
"只允许处理当前这一票,禁止切换任务、禁止整批循环、禁止调用 switch_focus_task。",
"先调用 get_task_status 获取当前任务状态和 raw_text。",
"如果当前任务已经不是待解析状态,或已经进入人工确认/下游阶段,请直接总结当前状态并结束。",
"如果当前任务仍待解析,请基于 raw_text 用 LLM 抽取结构化字段,并调用 parse_notice(structured=...) 落库。",
"禁止再次询问用户“是否开始解析”。",
"完成后只返回当前票的简短解析结果摘要。",
]
)
return "".join(pieces)
"""
构造后台排程器发给 Dify 的用户意图短句。
后台任务号与批次号通过 hxops_context.refs 注入,不能拼入 query,避免 Dify 预处理把 SB-/流程指令误判为切换任务。
"""
return "解析当前发货通知任务"
def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatSession | None:
@@ -86,29 +74,6 @@ def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatS
return session
def _update_chat_session_after_stream(
session: ChatSession | None,
*,
provider_conversation_id: str | None,
status: str,
) -> None:
if not session:
return
provider_id = str(provider_conversation_id or "").strip() or None
changed = False
if provider_id and session.external_conversation_id != provider_id:
session.external_conversation_id = provider_id
changed = True
if status and session.status != status:
session.status = status
changed = True
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
changed = True
if changed:
db.session.commit()
def _log_executor_context(
*,
task: Any,
@@ -160,18 +125,16 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
or str(getattr(task, "conversation_id", "") or "").strip()
or task.task_no
)
provider_conversation_id = (
str(getattr(session, "external_conversation_id", "") or "").strip() or None
)
# 后台编排每票都从新的 Dify provider conversation 开始,避免多票复用前端会话导致上下文串单。
provider_conversation_id = None
request_id = f"shipping-orch-{task.task_no}"
inputs = build_dify_chat_inputs(
local_conversation_id,
task_id=task.task_no,
batch_no=batch_no,
entry_mode="orchestrator_parse",
user_message="",
trigger_source="backend_orchestrator",
request_id=request_id,
)
request_id = f"shipping-orch-{task.task_no}"
started_at = time.perf_counter()
total_timeout_seconds = _parse_total_timeout_seconds()
@@ -210,6 +173,7 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
request_id=request_id,
session_id=local_conversation_id,
inputs=inputs,
persist_chat_log=False,
)
for chunk in stream:
if time.perf_counter() - started_at > total_timeout_seconds:
@@ -260,11 +224,6 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
break
except Exception as exc:
db.session.rollback()
_update_chat_session_after_stream(
session,
provider_conversation_id=provider_conversation_id,
status="error",
)
if current_app:
current_app.logger.exception(
"[shipping-dify-executor] exception request_id=%s task_no=%s provider_conversation_id=%s",
@@ -274,11 +233,6 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
)
return {"status": "failed", "message": str(exc)[:500] or "dify execution failed"}
_update_chat_session_after_stream(
session,
provider_conversation_id=provider_conversation_id,
status=terminal_status,
)
refreshed = get_task_by_ref(task.task_no)
process_status = str(getattr(refreshed, "process_status", "") or "").strip() if refreshed else ""
review_status = str(getattr(refreshed, "review_status", "") or "").strip() if refreshed else ""
@@ -2,27 +2,27 @@
services/shipping_notice/dify_inputs.py
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
依赖:agent_resolver、models.ShippingBatch/ShippingTask。
依赖:agent_resolver、models.ShippingBatch/ShippingTask、chat.hxops_context。
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
把 Dify 画布需要的 conversation_id、current_batch_no、current_task_no 注入 Start 节点变量。
仅补充货代发货场景可识别的 refs,再委托平台级上下文构造器生成 hxops_context。
"""
from __future__ import annotations
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
from typing import Any
SHIPPING_CONVERSATION_ID_INPUT = "conversation_id"
SHIPPING_CURRENT_BATCH_NO_INPUT = "current_batch_no"
SHIPPING_CURRENT_TASK_NO_INPUT = "current_task_no"
SHIPPING_ENTRY_MODE_INPUT = "entry_mode"
SHIPPING_USER_MESSAGE_INPUT = "user_message"
SHIPPING_TRIGGER_SOURCE_INPUT = "trigger_source"
from app.models import ShippingBatch, ShippingTask
from app.services.chat.hxops_context import HXOPS_CONTEXT_INPUT, build_hxops_context, build_ref
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
def is_shipping_notice_chat_agent(agent) -> bool:
"""判断 Agent 记录是否为发货通知聊天 Agent。"""
return getattr(agent, "name", None) == CHAT_AGENT_NAME
agent_name = str(getattr(agent, "name", None) or "").strip()
if agent_name == CHAT_AGENT_NAME:
return True
normalized_name = agent_name.replace(" ", "")
return "发货通知" in normalized_name and "Agent" in normalized_name
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
@@ -50,53 +50,63 @@ def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
)
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
"""构建货代发货 Agent 当前已知业务对象锚点。"""
return [
build_ref("task", task),
build_ref("batch", batch),
]
def build_dify_chat_inputs(
conversation_id: str | None = None,
*,
task_id: str | None = None,
batch_no: str | None = None,
entry_mode: str | None = None,
user_message: str | None = None,
trigger_source: str | None = None,
) -> dict[str, str]:
request_id: str | None = None,
locale: str | None = None,
) -> dict[str, Any]:
"""
构建发货通知 Dify Chatflow inputs。
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布稳定读取当前 task/batch。
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布通过 refs 稳定定位当前 task/batch。
"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return {}
explicit_task_no = str(task_id or "").strip().upper()
explicit_batch_no = str(batch_no or "").strip().upper()
explicit_task = str(task_id or "").strip().upper()
explicit_batch = str(batch_no or "").strip().upper()
batch = _latest_batch_for_conversation(conv_id)
task = _latest_task_for_conversation(conv_id)
current_task_no = explicit_task_no
if not current_task_no and batch and batch.current_focus_task_no:
current_task_no = str(batch.current_focus_task_no or "").strip().upper()
elif not current_task_no and task and task.task_no:
current_task_no = str(task.task_no or "").strip().upper()
focus_task = explicit_task
if not focus_task and batch and batch.current_focus_task_no:
focus_task = str(batch.current_focus_task_no or "").strip().upper()
elif not focus_task and task and task.task_no:
focus_task = str(task.task_no or "").strip().upper()
current_batch_no = explicit_batch_no
if not current_batch_no and batch and batch.batch_no:
current_batch_no = str(batch.batch_no or "").strip().upper()
focus_batch = explicit_batch
if not focus_batch and batch and batch.batch_no:
focus_batch = str(batch.batch_no or "").strip().upper()
elif (
not current_batch_no
not focus_batch
and task
and getattr(task, "batch", None) is not None
and getattr(task.batch, "batch_no", None)
):
current_batch_no = str(task.batch.batch_no or "").strip().upper()
focus_batch = str(task.batch.batch_no or "").strip().upper()
return {
SHIPPING_ENTRY_MODE_INPUT: str(entry_mode or "").strip(),
SHIPPING_CONVERSATION_ID_INPUT: conv_id,
SHIPPING_CURRENT_BATCH_NO_INPUT: current_batch_no,
SHIPPING_CURRENT_TASK_NO_INPUT: current_task_no,
SHIPPING_USER_MESSAGE_INPUT: str(user_message or "").strip(),
SHIPPING_TRIGGER_SOURCE_INPUT: str(trigger_source or "").strip(),
}
hxops_context = build_hxops_context(
session_id=conv_id,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
refs=_build_hxops_refs(task=focus_task, batch=focus_batch),
)
if not hxops_context:
return {}
return {HXOPS_CONTEXT_INPUT: hxops_context}
@@ -21,6 +21,7 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory,
parse_inventory_lines,
@@ -31,6 +32,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_for_tool,
task_export_error_message,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import extract_reservation_id
from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.rpa_attempts import (
@@ -109,7 +111,7 @@ def excel_gate_error(task: ShippingTask) -> str | None:
if task.process_status == "uploaded" and task.export_file_path:
return None
if not match_completed(task):
return "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。"
return "workflow.fulfillment.excel_gate_unmatched"
return None
@@ -195,9 +197,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: Tool 标准响应;status 可为 ok / needs_human / failed。
"""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
# [STEP 1] 先确认字段对齐与库存快照是否已经就绪。
# 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。
@@ -208,7 +211,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
task.inventory_lines_json = inventory_lines
elif not task.inventory_lines_json:
else:
inventory_lines = active_inventory_lines_for_task(task)
if not inventory_lines:
inv_payload: dict[str, Any] = {"task_id": task.task_no}
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
if lang:
@@ -221,11 +226,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="正在执行库存匹配",
message=t("workflow.fulfillment.match_running", lang=lang),
progress_percent=10,
current=0,
total=total_notice_lines or None,
detail="按 SKU + Reservation ID 逐行比对需求与库存",
detail=t("workflow.fulfillment.match_running_detail", lang=lang),
)
db.session.flush()
@@ -238,7 +243,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
]
inv_missing_count = sum(
1
for row in (task.inventory_lines_json or [])
for row in (inventory_lines or [])
if not extract_reservation_id((row or {}).get("reservation_id"))
)
if order_missing:
@@ -255,11 +260,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="needs_human",
task=task,
message=(
"当前匹配规则要求发货需求(订单)必须提供 Reservation ID。"
f"订单缺少 Reservation ID:{len(order_missing)} 行。"
"请重新解析发货通知后再匹配。"
),
message=t("workflow.fulfillment.reservation_required", lang=lang).format(count=len(order_missing)),
data={**serialize_task_for_tool(task), "reservation_id_required": detail},
stop_agent_turn=True,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
@@ -274,18 +275,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="正在执行库存匹配",
message=t("workflow.fulfillment.match_running", lang=lang),
progress_percent=percent,
current=processed,
total=total,
detail=f"已匹配 {processed}/{total} 行",
detail=t("workflow.fulfillment.match_progress_detail", lang=lang).format(processed=processed, total=total),
)
if processed == total or processed % 50 == 0:
db.session.flush()
match_status, line_results, shortage = match_notice_lines(
notice_lines,
task.inventory_lines_json or [],
inventory_lines or [],
progress_callback=_on_match_progress,
)
if inv_missing_count and isinstance(shortage, dict):
@@ -298,18 +299,16 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step5_match_inventory",
step_title="匹配库存",
status="needs_human" if match_status != "fulfillable" else "completed",
message="库存匹配已完成",
message=t("workflow.fulfillment.match_completed", lang=lang),
progress_percent=100,
current=len(line_results),
total=len(line_results),
detail=(
f"已匹配 {len(line_results)}/{len(line_results)} 行,全部订单行库存满足"
t("workflow.fulfillment.match_completed_ok_detail", lang=lang).format(count=len(line_results))
if match_status == "fulfillable"
else f"已匹配 {len(line_results)}/{len(line_results)} 行,存在缺口,需人工处理"
else t("workflow.fulfillment.match_completed_shortage_detail", lang=lang).format(count=len(line_results))
),
)
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() or None
match_summary = format_match_summary(
match_status,
line_results,
@@ -353,9 +352,10 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。
"""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
@@ -363,7 +363,9 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message=f"发货 Excel 已生成:{task.export_file_name or task.export_file_path}",
message=t("workflow.fulfillment.excel_exists", lang=lang).format(
file=task.export_file_name or task.export_file_path
),
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
)
@@ -374,19 +376,19 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="failed",
task_id=task.task_no,
message=gate_error,
message=t(gate_error, lang=lang) if gate_error.startswith("workflow.") else gate_error,
data=serialize_task_for_tool(task),
forbidden_next_tools=["upload_to_freight"],
next_required_action="match_inventory(须先完成库存上传与字段对齐确认)",
next_required_action=t("workflow.fulfillment.match_first", lang=lang),
)
set_task_step_progress(
task,
step_key="step6_generate_file",
step_title="生成发货文件",
status="running",
message="正在生成发货 Excel",
message=t("workflow.fulfillment.generate_running", lang=lang),
progress_percent=60,
detail="正在按货代模板填充全部应发行",
detail=t("workflow.fulfillment.generate_running_detail", lang=lang),
)
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
@@ -400,7 +402,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step6_generate_file",
step_title="生成发货文件",
status="completed",
message="发货 Excel 已生成",
message=t("workflow.fulfillment.generate_completed", lang=lang),
progress_percent=100,
detail=filename,
)
@@ -409,7 +411,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message=f"已生成发货 Excel:{filename}",
message=t("workflow.fulfillment.generate_done", lang=lang).format(file=filename),
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
)
@@ -427,9 +429,10 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: status 可为 ok / running / needs_human / failed。
"""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
# [STEP 1] 先确保上传所需的 Excel 已经存在。
# 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。
@@ -447,7 +450,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
status="ok",
task=task,
task_id=task.task_no,
message=f"任务 {task.task_no} 已标记为完成,无需重复操作。",
message=t("workflow.fulfillment.manual_already_done", lang=lang).format(task_no=task.task_no),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
@@ -459,9 +462,9 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message="已确认手工上传货代完成",
message=t("workflow.fulfillment.manual_confirmed", lang=lang),
progress_percent=100,
detail="任务已完成",
detail=t("workflow.fulfillment.task_completed", lang=lang),
)
# [STEP 2.1] 手工上传确认属于任务终态写路径,需要同步刷新批次汇总,
# 否则聊天顶部批次卡片仍会读取旧的 process_summary_json,显示成未完成。
@@ -477,10 +480,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
status="ok",
task=task,
task_id=task.task_no,
message=(
f"已标记为手工上传货代系统完成。任务 {task.task_no} 已全部处理完毕,"
"无需再进行任何操作。"
),
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
@@ -506,10 +506,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"RPA 上传进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
f"请稍后再试(建议 {remaining}s 后)。"
message=t("workflow.fulfillment.upload_running", lang=lang).format(
attempt=max(attempts, 1),
max_attempts=max_attempts,
elapsed=elapsed,
timeout=timeout_seconds,
remaining=remaining,
),
data={
**serialize_task_for_tool(task),
@@ -524,7 +526,9 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
)
last_failed = latest_event(task, "upload_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
task.error_message = f"RPA 上传超时(>{timeout_seconds}s)"
task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format(
timeout=timeout_seconds
)
log_task_event(
task,
"upload_rpa_failed",
@@ -535,7 +539,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
attempts = upload_rpa_attempts(task)
if attempts >= max_attempts:
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
task.error_message = t("workflow.fulfillment.upload_exhausted", lang=lang).format(attempts=attempts)
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
db.session.commit()
return tool_response(
@@ -555,10 +559,13 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step7_upload_freight",
step_title="上传货代",
status="running",
message="已触发 RPA 上传货代,等待回执",
message=t("workflow.fulfillment.upload_triggered_wait", lang=lang),
current=attempt_no,
total=max_attempts,
detail=f"第 {attempt_no}/{max_attempts} 次上传尝试",
detail=t("workflow.fulfillment.upload_triggered_detail", lang=lang).format(
attempt=attempt_no,
max_attempts=max_attempts,
),
)
log_task_event(
task,
@@ -575,9 +582,10 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"已触发 RPA 上传货代(第 {attempt_no}/{max_attempts} 次)。"
f"若 {timeout_seconds}s 内无回调,可重试;超过最大次数将转手工上传。"
message=t("workflow.fulfillment.upload_triggered_message", lang=lang).format(
attempt=attempt_no,
max_attempts=max_attempts,
timeout=timeout_seconds,
),
data={
**serialize_task_for_tool(task),
@@ -592,17 +600,17 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message="RPA 自动上传失败,请人工接管",
message=t("workflow.fulfillment.upload_takeover", lang=lang),
progress_percent=100,
detail="请下载 Excel 手工上传后确认完成",
detail=t("workflow.fulfillment.upload_takeover_detail", lang=lang),
)
task.error_message = "RPA 上传目录未配置或触发失败"
task.error_message = t("workflow.fulfillment.upload_trigger_failed", lang=lang)
log_task_event(task, "upload_rpa_pending", {})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。",
message=t("workflow.fulfillment.upload_takeover_message", lang=lang),
data=serialize_task_for_tool(task),
)
@@ -620,9 +628,10 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。
"""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
success = bool(payload.get("success", True))
if success:
@@ -633,9 +642,9 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message="RPA 已成功上传货代系统",
message=t("workflow.fulfillment.rpa_uploaded", lang=lang),
progress_percent=100,
detail="任务已完成",
detail=t("workflow.fulfillment.task_completed", lang=lang),
)
task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None
log_task_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no})
@@ -644,7 +653,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
status="ok",
task=task,
task_id=task.task_no,
message="RPA 已成功上传货代系统,任务已全部处理完毕。",
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
@@ -657,9 +666,9 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message="货代上传失败,等待人工处理",
message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang),
progress_percent=100,
detail="可重试上传或改为手工上传",
detail=t("workflow.fulfillment.upload_failed_detail", lang=lang),
)
task.error_message = str(payload.get("error_message") or "RPA upload failed")[:500]
log_task_event(task, "upload_rpa_failed", {"error": task.error_message})
@@ -667,7 +676,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
attempts = upload_rpa_attempts(task)
max_attempts = max_rpa_upload_attempts()
if attempts >= max_attempts:
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
task.error_message = t("workflow.fulfillment.upload_exhausted", lang=lang).format(attempts=attempts)
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
db.session.commit()
return tool_response(
@@ -67,6 +67,87 @@ _MESSAGES: dict[str, dict[str, str]] = {
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法发货。请补库存或返回修订后重新匹配。",
"match.conclusion.other": "**结论**:match_status={status}",
"match.no_lines": "无订单明细,无法比对数量。",
"workflow.parse.auto_continued": "解析完成,后台已开始继续处理后续步骤。",
"workflow.parse.check_later": "解析完成,请稍后继续查看任务状态。",
"workflow.decision.parse_confirmed_running": "发货通知已确认,后台已开始继续处理库存与后续步骤。",
"workflow.decision.inventory_preparing": "已确认,后台继续处理库存准备步骤。",
"workflow.decision.fulfillment_running": "发货通知已确认,后台继续处理库存与后续步骤。",
"workflow.decision.rematch_running": "已提交重新匹配请求,后台继续处理。",
"workflow.decision.mapping_confirmed_running": "库存字段对齐已确认,后台继续处理匹配与后续步骤。",
"workflow.decision.task_not_found": "未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。",
"workflow.decision.rejected": "已驳回该发货任务。",
"workflow.decision.closed": "已关闭该发货任务(可在同一会话重新开新单)。",
"workflow.decision.shortage_confirm_blocked": "库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
"workflow.decision.parse_confirmed_next": "发货通知已确认。请继续在当前任务中补充库存或等待后端继续处理,并稍后刷新任务状态。",
"workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory",
"workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。",
"workflow.decision.confirm_invalid_state": "当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
"workflow.decision.mapping_not_needed": "当前无需确认库存字段对齐。",
"workflow.decision.mapping_missing_reservation_warning": "库存表必须包含 Reservation ID 列标题(该列允许为空值)。请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。",
"workflow.decision.mapping_correction_invalid_state": "当前不在库存字段对齐确认步骤,无法更正映射。",
"workflow.decision.read_inventory_preview_failed": "读取库存表头失败: {error}",
"workflow.decision.mapping_preview_note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
"workflow.decision.mapping_correction_needed": "已回到列映射步骤。请根据 schema_preview 提供新的 map_json,再调用 apply_inventory_mapping。",
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
"workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。",
"workflow.decision.unknown": "未知 decision: {decision}",
"workflow.inventory.task_not_found": "未找到任务编号",
"workflow.inventory.uploaded_file_missing": "未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
"workflow.inventory.text_too_large": "库存文本过大({chars} 字符,上限 {max_chars})。请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 POST /tools/upload_inventory_file 上传,再 parse_inventory(use_uploaded_file=true)。",
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
"workflow.inventory.parse_failed": "未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
"workflow.inventory.preview_read_failed": "读取库存表头失败: {error}",
"workflow.inventory.preview_ready": "已读取库存表头与样例行。请根据 schema_preview 推断列映射,调用 apply_inventory_mapping(map_json=...)。",
"workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"sku\":\"<列名>\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "未找到已上传的库存文件。请先 upload_inventory_file。",
"workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"sku\":\"列名\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"}。(库存的 Reservation ID 列允许为空值,但必须有该列标题)",
"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.uploading": "正在上传并解析库存文件",
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
"workflow.inventory.uploaded": "库存文件已上传。",
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "已有库存快照且字段对齐已确认,可调用 match_inventory。",
"workflow.inventory.unavailable": "暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
"workflow.fulfillment.task_not_found": "未找到任务编号",
"workflow.fulfillment.match_running": "正在执行库存匹配",
"workflow.fulfillment.match_running_detail": "按 SKU + Reservation ID 逐行比对需求与库存",
"workflow.fulfillment.match_progress_detail": "已匹配 {processed}/{total} 行",
"workflow.fulfillment.match_completed": "库存匹配已完成",
"workflow.fulfillment.match_completed_ok_detail": "已匹配 {count}/{count} 行,全部订单行库存满足",
"workflow.fulfillment.match_completed_shortage_detail": "已匹配 {count}/{count} 行,存在缺口,需人工处理",
"workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。",
"workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。",
"workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}",
"workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)",
"workflow.fulfillment.generate_running": "正在生成发货 Excel",
"workflow.fulfillment.generate_running_detail": "正在按货代模板填充全部应发行",
"workflow.fulfillment.generate_completed": "发货 Excel 已生成",
"workflow.fulfillment.generate_done": "已生成发货 Excel:{file}",
"workflow.fulfillment.manual_already_done": "任务 {task_no} 已标记为完成,无需重复操作。",
"workflow.fulfillment.manual_confirmed": "已确认手工上传货代完成",
"workflow.fulfillment.task_completed": "任务已完成",
"workflow.fulfillment.manual_done_message": "已标记为手工上传货代系统完成。任务 {task_no} 已全部处理完毕,无需再进行任何操作。",
"workflow.fulfillment.upload_running": "RPA 上传进行中(第 {attempt}/{max_attempts} 次)。已等待 {elapsed}s / 超时 {timeout}s。请稍后再试(建议 {remaining}s 后)。",
"workflow.fulfillment.upload_timeout_error": "RPA 上传超时(>{timeout}s)",
"workflow.fulfillment.upload_exhausted": "已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。",
"workflow.fulfillment.upload_triggered_wait": "已触发 RPA 上传货代,等待回执",
"workflow.fulfillment.upload_triggered_detail": "第 {attempt}/{max_attempts} 次上传尝试",
"workflow.fulfillment.upload_triggered_message": "已触发 RPA 上传货代(第 {attempt}/{max_attempts} 次)。若 {timeout}s 内无回调,可重试;超过最大次数将转手工上传。",
"workflow.fulfillment.upload_takeover": "RPA 自动上传失败,请人工接管",
"workflow.fulfillment.upload_takeover_detail": "请下载 Excel 手工上传后确认完成",
"workflow.fulfillment.upload_trigger_failed": "RPA 上传目录未配置或触发失败",
"workflow.fulfillment.upload_takeover_message": "RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。",
"workflow.fulfillment.rpa_uploaded": "RPA 已成功上传货代系统",
"workflow.fulfillment.rpa_uploaded_done": "RPA 已成功上传货代系统,任务已全部处理完毕。",
"workflow.fulfillment.upload_failed_wait_manual": "货代上传失败,等待人工处理",
"workflow.fulfillment.upload_failed_detail": "可重试上传或改为手工上传",
},
"en": {
"parse.title": "[Shipping notice parsed] Task: {task_no}",
@@ -120,6 +201,87 @@ _MESSAGES: dict[str, dict[str, str]] = {
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines. Shipment blocked until inventory is replenished.",
"match.conclusion.other": "**Result**: match_status={status}",
"match.no_lines": "No order lines to compare.",
"workflow.parse.auto_continued": "Parsing is complete. The backend has started the remaining steps.",
"workflow.parse.check_later": "Parsing is complete. Please check the task status again later.",
"workflow.decision.parse_confirmed_running": "The shipping notice is confirmed. The backend has started inventory handling and the remaining steps.",
"workflow.decision.inventory_preparing": "Confirmed. The backend is continuing the inventory preparation steps.",
"workflow.decision.fulfillment_running": "The shipping notice is confirmed. The backend is continuing inventory handling and the remaining steps.",
"workflow.decision.rematch_running": "The rematch request has been submitted. The backend is continuing processing.",
"workflow.decision.mapping_confirmed_running": "The inventory mapping is confirmed. The backend is continuing matching and the remaining steps.",
"workflow.decision.task_not_found": "Task not found. When the user says confirm / re-parse / reject, do not call create_task. Please call get_task_status(conversation_id=...) first or pass the task ID to submit_decision.",
"workflow.decision.rejected": "The shipping task has been rejected.",
"workflow.decision.closed": "The shipping task has been closed. You may start a new one in the same conversation.",
"workflow.decision.shortage_confirm_blocked": "Inventory is insufficient. You cannot use confirm for the whole task. Please use reparse_inventory, rematch, or reject.",
"workflow.decision.parse_confirmed_next": "The shipping notice is confirmed. Please continue with inventory for the current task or wait for the backend to continue, then refresh the task status later.",
"workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory",
"workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.",
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Please complete inventory matching first, or use confirm_inventory_mapping / reparse.",
"workflow.decision.mapping_not_needed": "Inventory field alignment confirmation is not needed right now.",
"workflow.decision.mapping_missing_reservation_warning": "The inventory sheet must contain a Reservation ID column header (the values in that column may be empty). Please use Fix Mapping to choose the Reservation ID column again, or re-upload an inventory Excel that contains that column.",
"workflow.decision.mapping_correction_invalid_state": "The task is not currently in the inventory field alignment confirmation step, so the mapping cannot be corrected.",
"workflow.decision.read_inventory_preview_failed": "Failed to read inventory headers: {error}",
"workflow.decision.mapping_preview_note": "No uploaded Excel was found. Please paste a small inventory table or re-upload, then call apply_inventory_mapping / parse_inventory.",
"workflow.decision.mapping_correction_needed": "The task has returned to the mapping step. Please provide a new map_json based on schema_preview, then call apply_inventory_mapping.",
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
"workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.",
"workflow.decision.unknown": "Unknown decision: {decision}",
"workflow.inventory.task_not_found": "Task ID not found.",
"workflow.inventory.uploaded_file_missing": "No uploaded inventory file was found. Please POST /tools/upload_inventory_file to upload the Excel file first.",
"workflow.inventory.text_too_large": "The inventory text is too large ({chars} characters, limit {max_chars}). Do not send the full Excel content to the LLM. Please call POST /tools/upload_inventory_file first, then parse_inventory(use_uploaded_file=true).",
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
"workflow.inventory.parse_failed": "Inventory lines could not be parsed. For large Excel files, use upload_inventory_file; for small tables, paste the content; if inventory is unavailable, use RPA.",
"workflow.inventory.preview_read_failed": "Failed to read inventory headers: {error}",
"workflow.inventory.preview_ready": "Inventory headers and sample rows have been loaded. Please infer the column mapping from schema_preview and call apply_inventory_mapping(map_json=...).",
"workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"sku\":\"<column>\",\"reservation_id\":\"<column>\",\"available_qty\":\"<column>\"}, then call apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "No uploaded inventory file was found. Please call upload_inventory_file first.",
"workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. You must provide {\"sku\":\"column\",\"reservation_id\":\"column\",\"available_qty\":\"column\"}. The Reservation ID column may contain empty values, but the column header itself must exist.",
"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.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}",
"workflow.inventory.uploaded": "The inventory file has been uploaded.",
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping is complete, so the canvas can call apply_inventory_mapping directly without using the LLM.",
"workflow.inventory.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "An inventory snapshot already exists and the field alignment has been confirmed. You may call match_inventory.",
"workflow.inventory.unavailable": "No usable inventory data is available yet. Please retry the RPA export or upload the freight inventory Excel manually.",
"workflow.fulfillment.task_not_found": "Task ID not found.",
"workflow.fulfillment.match_running": "Running inventory matching.",
"workflow.fulfillment.match_running_detail": "Comparing demand and inventory line by line using SKU + Reservation ID",
"workflow.fulfillment.match_progress_detail": "Matched {processed}/{total} lines",
"workflow.fulfillment.match_completed": "Inventory matching is complete.",
"workflow.fulfillment.match_completed_ok_detail": "Matched {count}/{count} lines. All order lines are fulfillable.",
"workflow.fulfillment.match_completed_shortage_detail": "Matched {count}/{count} lines. Shortage exists and manual handling is required.",
"workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.",
"workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.",
"workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}",
"workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)",
"workflow.fulfillment.generate_running": "Generating shipment Excel.",
"workflow.fulfillment.generate_running_detail": "Filling all shippable lines into the freight template",
"workflow.fulfillment.generate_completed": "Shipment Excel has been generated.",
"workflow.fulfillment.generate_done": "Shipment Excel generated: {file}",
"workflow.fulfillment.manual_already_done": "Task {task_no} is already marked complete. No further action is needed.",
"workflow.fulfillment.manual_confirmed": "Manual freight upload has been confirmed.",
"workflow.fulfillment.task_completed": "Task completed.",
"workflow.fulfillment.manual_done_message": "The task has been marked as manually uploaded to the freight system. Task {task_no} is fully completed and no further action is needed.",
"workflow.fulfillment.upload_running": "RPA upload is in progress (attempt {attempt}/{max_attempts}). Waited {elapsed}s / timeout {timeout}s. Please try again later (recommended after {remaining}s).",
"workflow.fulfillment.upload_timeout_error": "RPA upload timed out (>{timeout}s)",
"workflow.fulfillment.upload_exhausted": "RPA upload failed after {attempts} attempts. Please download the Excel and upload it manually.",
"workflow.fulfillment.upload_triggered_wait": "RPA upload to freight has been triggered. Waiting for callback.",
"workflow.fulfillment.upload_triggered_detail": "Upload attempt {attempt}/{max_attempts}",
"workflow.fulfillment.upload_triggered_message": "RPA upload to freight has been triggered (attempt {attempt}/{max_attempts}). If no callback arrives within {timeout}s, you may retry. After the max attempts, the flow will fall back to manual upload.",
"workflow.fulfillment.upload_takeover": "RPA auto-upload failed. Manual takeover is required.",
"workflow.fulfillment.upload_takeover_detail": "Please download the Excel, upload it manually, then confirm completion.",
"workflow.fulfillment.upload_trigger_failed": "The RPA upload directory is not configured or triggering failed.",
"workflow.fulfillment.upload_takeover_message": "RPA auto-upload failed or is not configured. Please download the Excel and upload it manually in the freight system, then let me know when it is done.",
"workflow.fulfillment.rpa_uploaded": "RPA has uploaded to the freight system successfully.",
"workflow.fulfillment.rpa_uploaded_done": "RPA uploaded to the freight system successfully. The task is fully completed.",
"workflow.fulfillment.upload_failed_wait_manual": "Freight upload failed. Waiting for manual handling.",
"workflow.fulfillment.upload_failed_detail": "You may retry the upload or switch to manual upload.",
},
"th": {
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
@@ -173,6 +335,87 @@ _MESSAGES: dict[str, dict[str, str]] = {
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด ไม่สามารถจัดส่งได้ กรุณาเติมสต็อกหรือแก้ไขแล้วจับคู่ใหม่",
"match.conclusion.other": "**สรุป**: match_status={status}",
"match.no_lines": "ไม่มีรายการสั่งซื้อสำหรับเปรียบเทียบ",
"workflow.parse.auto_continued": "แยกข้อมูลเสร็จแล้ว ระบบหลังบ้านได้เริ่มดำเนินขั้นตอนถัดไปต่อแล้ว",
"workflow.parse.check_later": "แยกข้อมูลเสร็จแล้ว กรุณากลับมาตรวจสอบสถานะงานอีกครั้งภายหลัง",
"workflow.decision.parse_confirmed_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านได้เริ่มจัดการสต็อกและขั้นตอนถัดไปต่อแล้ว",
"workflow.decision.inventory_preparing": "ยืนยันแล้ว ระบบหลังบ้านกำลังดำเนินขั้นตอนเตรียมสต็อกต่อ",
"workflow.decision.fulfillment_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านกำลังดำเนินการสต็อกและขั้นตอนถัดไปต่อ",
"workflow.decision.rematch_running": "ส่งคำขอจับคู่ใหม่แล้ว ระบบหลังบ้านกำลังดำเนินการต่อ",
"workflow.decision.mapping_confirmed_running": "ยืนยันการจับคู่คอลัมน์สต็อกแล้ว ระบบหลังบ้านกำลังดำเนินการจับคู่และขั้นตอนถัดไปต่อ",
"workflow.decision.task_not_found": "ไม่พบงาน เมื่อผู้ใช้พูดว่ายืนยัน / แยกใหม่ / ปฏิเสธ ห้ามเรียก create_task โปรดเรียก get_task_status(conversation_id=...) ก่อน หรือส่ง task ID ให้ submit_decision",
"workflow.decision.rejected": "ปฏิเสธงานจัดส่งนี้แล้ว",
"workflow.decision.closed": "ปิดงานจัดส่งนี้แล้ว และสามารถเริ่มงานใหม่ในบทสนทนาเดิมได้",
"workflow.decision.shortage_confirm_blocked": "สต็อกไม่เพียงพอ จึงไม่สามารถใช้ confirm เพื่อยืนยันทั้งงานได้ โปรดใช้ reparse_inventory, rematch หรือ reject",
"workflow.decision.parse_confirmed_next": "ยืนยันใบแจ้งส่งสินค้าแล้ว โปรดดำเนินการเรื่องสต็อกในงานปัจจุบันต่อ หรือรอให้ระบบหลังบ้านทำต่อ แล้วค่อยรีเฟรชสถานะงาน",
"workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory",
"workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้",
"workflow.decision.confirm_invalid_state": "ไม่สามารถใช้ confirm ในสถานะปัจจุบันได้ โปรดทำ inventory matching ให้เสร็จก่อน หรือใช้ confirm_inventory_mapping / reparse",
"workflow.decision.mapping_not_needed": "ขณะนี้ยังไม่ต้องยืนยันการจับคู่คอลัมน์สต็อก",
"workflow.decision.mapping_missing_reservation_warning": "ไฟล์สต็อกต้องมีหัวคอลัมน์ Reservation ID (ค่าภายในคอลัมน์นี้สามารถเว้นว่างได้) โปรดใช้ Fix Mapping เพื่อเลือกคอลัมน์ Reservation ID ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกที่มีคอลัมน์นี้อีกครั้ง",
"workflow.decision.mapping_correction_invalid_state": "ขณะนี้งานไม่ได้อยู่ในขั้นตอนยืนยันการจับคู่คอลัมน์สต็อก จึงไม่สามารถแก้ไข mapping ได้",
"workflow.decision.read_inventory_preview_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
"workflow.decision.mapping_preview_note": "ไม่พบไฟล์ Excel ที่อัปโหลดไว้ โปรดวางตารางสต็อกขนาดเล็กหรืออัปโหลดใหม่ แล้วจึงเรียก apply_inventory_mapping / parse_inventory",
"workflow.decision.mapping_correction_needed": "งานได้ย้อนกลับมาที่ขั้นตอนจับคู่คอลัมน์แล้ว โปรดส่ง map_json ใหม่ตาม schema_preview แล้วเรียก apply_inventory_mapping",
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
"workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน",
"workflow.decision.unknown": "ไม่รู้จัก decision: {decision}",
"workflow.inventory.task_not_found": "ไม่พบรหัสงาน",
"workflow.inventory.uploaded_file_missing": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดอัปโหลดไฟล์ Excel ผ่าน POST /tools/upload_inventory_file ก่อน",
"workflow.inventory.text_too_large": "ข้อความสต็อกมีขนาดใหญ่เกินไป ({chars} ตัวอักษร, จำกัด {max_chars}) โปรดอย่าส่งเนื้อหา Excel ทั้งหมดเข้า LLM ให้เรียก POST /tools/upload_inventory_file ก่อน แล้วจึงใช้ parse_inventory(use_uploaded_file=true)",
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
"workflow.inventory.parse_failed": "ไม่สามารถแยกรายการสต็อกได้ สำหรับไฟล์ Excel ขนาดใหญ่ให้ใช้ upload_inventory_file; สำหรับตารางเล็กสามารถวางข้อความได้; หากไม่มีสต็อกให้ใช้ RPA",
"workflow.inventory.preview_read_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
"workflow.inventory.preview_ready": "อ่านหัวตารางและแถวตัวอย่างของสต็อกแล้ว โปรดอนุมานการจับคู่คอลัมน์จาก schema_preview แล้วเรียก apply_inventory_mapping(map_json=...)",
"workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows: {\"sku\":\"<คอลัมน์>\",\"reservation_id\":\"<คอลัมน์>\",\"available_qty\":\"<คอลัมน์>\"} แล้วจึงเรียก apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดเรียก upload_inventory_file ก่อน",
"workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ {\"sku\":\"ชื่อคอลัมน์\",\"reservation_id\":\"ชื่อคอลัมน์\",\"available_qty\":\"ชื่อคอลัมน์\"} โดยคอลัมน์ Reservation ID สามารถมีค่าว่างได้ แต่ต้องมีหัวคอลัมน์นี้",
"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.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "มี inventory snapshot อยู่แล้วและยืนยันการจับคู่คอลัมน์แล้ว สามารถเรียก match_inventory ได้",
"workflow.inventory.unavailable": "ยังไม่มีข้อมูลสต็อกที่ใช้งานได้ โปรดลองส่งออกผ่าน RPA ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกของผู้ให้บริการขนส่งด้วยตนเอง",
"workflow.fulfillment.task_not_found": "ไม่พบรหัสงาน",
"workflow.fulfillment.match_running": "กำลังจับคู่สต็อก",
"workflow.fulfillment.match_running_detail": "กำลังเทียบความต้องการกับสต็อกทีละบรรทัดด้วย SKU + Reservation ID",
"workflow.fulfillment.match_progress_detail": "จับคู่แล้ว {processed}/{total} รายการ",
"workflow.fulfillment.match_completed": "จับคู่สต็อกเสร็จแล้ว",
"workflow.fulfillment.match_completed_ok_detail": "จับคู่แล้ว {count}/{count} รายการ และทุกรายการมีสต็อกเพียงพอ",
"workflow.fulfillment.match_completed_shortage_detail": "จับคู่แล้ว {count}/{count} รายการ แต่ยังมีของขาดและต้องให้คนจัดการต่อ",
"workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่",
"workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน",
"workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}",
"workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)",
"workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel",
"workflow.fulfillment.generate_running_detail": "กำลังเติมรายการที่สามารถจัดส่งได้ลงในเทมเพลตของผู้ให้บริการขนส่ง",
"workflow.fulfillment.generate_completed": "สร้าง Shipment Excel แล้ว",
"workflow.fulfillment.generate_done": "สร้าง Shipment Excel แล้ว: {file}",
"workflow.fulfillment.manual_already_done": "งาน {task_no} ถูกทำเครื่องหมายว่าเสร็จแล้ว จึงไม่ต้องดำเนินการซ้ำ",
"workflow.fulfillment.manual_confirmed": "ยืนยันการอัปโหลดเข้าระบบขนส่งด้วยตนเองแล้ว",
"workflow.fulfillment.task_completed": "งานเสร็จสิ้นแล้ว",
"workflow.fulfillment.manual_done_message": "ทำเครื่องหมายว่าอัปโหลดเข้าระบบขนส่งด้วยตนเองเสร็จแล้ว งาน {task_no} เสร็จสมบูรณ์และไม่ต้องดำเนินการต่อ",
"workflow.fulfillment.upload_running": "RPA กำลังอัปโหลดอยู่ (ครั้งที่ {attempt}/{max_attempts}) รอแล้ว {elapsed}s / หมดเวลา {timeout}s โปรดลองอีกครั้งภายหลัง (แนะนำหลัง {remaining}s)",
"workflow.fulfillment.upload_timeout_error": "RPA อัปโหลดหมดเวลา (>{timeout}s)",
"workflow.fulfillment.upload_exhausted": "พยายามอัปโหลดผ่าน RPA มาแล้ว {attempts} ครั้งแต่ยังไม่สำเร็จ โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง",
"workflow.fulfillment.upload_triggered_wait": "ทริกเกอร์ RPA ให้อัปโหลดเข้าระบบขนส่งแล้ว กำลังรอผลตอบกลับ",
"workflow.fulfillment.upload_triggered_detail": "พยายามอัปโหลดครั้งที่ {attempt}/{max_attempts}",
"workflow.fulfillment.upload_triggered_message": "ทริกเกอร์ RPA ให้อัปโหลดเข้าระบบขนส่งแล้ว (ครั้งที่ {attempt}/{max_attempts}) หากไม่มี callback ภายใน {timeout}s สามารถลองใหม่ได้ และถ้าเกินจำนวนครั้งสูงสุดจะเปลี่ยนเป็นอัปโหลดด้วยตนเอง",
"workflow.fulfillment.upload_takeover": "RPA อัปโหลดอัตโนมัติไม่สำเร็จ ต้องให้คนรับช่วงต่อ",
"workflow.fulfillment.upload_takeover_detail": "โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง จากนั้นค่อยยืนยันว่าเสร็จแล้ว",
"workflow.fulfillment.upload_trigger_failed": "ไม่ได้ตั้งค่าไดเรกทอรีอัปโหลดของ RPA หรือการทริกเกอร์ล้มเหลว",
"workflow.fulfillment.upload_takeover_message": "RPA อัปโหลดอัตโนมัติล้มเหลวหรือยังไม่ได้ตั้งค่า โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเองในระบบขนส่ง จากนั้นแจ้งฉันเมื่อเสร็จแล้ว",
"workflow.fulfillment.rpa_uploaded": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว",
"workflow.fulfillment.rpa_uploaded_done": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว และงานเสร็จสมบูรณ์",
"workflow.fulfillment.upload_failed_wait_manual": "อัปโหลดเข้าระบบขนส่งล้มเหลว กำลังรอให้คนจัดการต่อ",
"workflow.fulfillment.upload_failed_detail": "สามารถลองอัปโหลดใหม่หรือเปลี่ยนเป็นอัปโหลดด้วยตนเองได้",
},
}
@@ -0,0 +1,249 @@
"""
services/shipping_notice/inventory_file_store.py
用途:管理货代发货批次级库存快照文件、任务 link 与解析结果投影。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
"""
from __future__ import annotations
import re
import uuid
from pathlib import Path
from typing import Any
from werkzeug.datastructures import FileStorage
from app import db
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.query_service import list_sorted_batch_tasks
def _safe_ref(value: str) -> str:
return re.sub(r"[^\w\-]+", "_", str(value or "").strip()) or "unknown"
def generate_inventory_file_no() -> str:
"""生成库存快照外部编号。"""
from datetime import datetime
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"
def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None:
"""读取任务当前 active link 指向的库存快照。"""
if task.id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
)
return link.inventory_file if link else None
def active_inventory_lines_for_task(task: ShippingTask) -> list[dict[str, Any]]:
"""解析任务可用于匹配的库存行;批次库存快照优先,单票任务回退到任务投影字段。"""
inv_file = active_inventory_file_for_task(task)
if inv_file and isinstance(inv_file.inventory_lines_json, list):
return [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
def has_uploaded_inventory_file(task: ShippingTask) -> bool:
"""任务是否已有可读取的库存上传文件。"""
inv_file = active_inventory_file_for_task(task)
if inv_file:
return Path(inv_file.storage_path).is_file()
return False
def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile:
"""
保存库存 Excel 并创建批次级库存快照。
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
"""
inventory_file_no = generate_inventory_file_no()
path = inventory_file_upload_path(inventory_file_no)
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)
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
batch_id=task.batch_id,
user_id=task.user_id,
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",
line_count=0,
)
db.session.add(inv_file)
db.session.flush()
linked_tasks = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
for item in linked_tasks:
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
return inv_file
def replace_task_inventory_link(
task: ShippingTask,
inv_file: ShippingInventoryFile,
*,
role: str = "member",
) -> ShippingTaskInventoryLink:
"""替换任务 active 库存 link,保留历史 link 审计。"""
if task.id is None:
db.session.flush()
existing = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all()
for link in existing:
link.is_active = False
new_link = ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inv_file.id,
link_role=role,
access_mode="readonly",
linked_by_user_id=inv_file.user_id,
)
db.session.add(new_link)
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_file_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
"role": role,
"share_mode": inv_file.share_mode,
},
)
)
return new_link
def read_linked_inventory_schema_preview(task: ShippingTask) -> dict[str, Any]:
"""读取任务 active 库存快照的 schema preview。"""
inv_file = active_inventory_file_for_task(task)
if not inv_file:
raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照")
if inv_file.schema_preview_json:
return dict(inv_file.schema_preview_json)
path = Path(inv_file.storage_path)
if not path.is_file():
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = inv_file.source_file_name or path.name
inv_file.schema_preview_json = preview
return preview
def parse_linked_inventory_file(
task: ShippingTask,
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any], Path, ShippingInventoryFile]:
"""解析任务 active 库存快照 Excel,并返回解析行、列元数据、文件路径和快照对象。"""
inv_file = active_inventory_file_for_task(task)
if not inv_file:
raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照")
path = Path(inv_file.storage_path)
if not path.is_file():
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
lines, column_meta = parse_inventory_excel_with_meta(
path,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=header_row_index,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
return lines, column_meta, path, inv_file
def apply_inventory_parse_result_to_linked_tasks(
inv_file: ShippingInventoryFile,
inventory_lines: list[dict[str, Any]],
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
mapping_confirmed: bool = False,
) -> list[ShippingTask]:
"""把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。"""
inv_file.inventory_lines_json = inventory_lines
inv_file.line_count = len(inventory_lines)
if field_mapping:
inv_file.field_mapping_json = field_mapping
if mapping_source:
inv_file.mapping_source = mapping_source
inv_file.mapping_confirmed = bool(mapping_confirmed)
linked_tasks: list[ShippingTask] = []
for link in inv_file.links or []:
if not link.is_active or not link.task:
continue
link.task.inventory_snapshot_id = inv_file.id
link.task.inventory_lines_json = inventory_lines
linked_tasks.append(link.task)
return linked_tasks
def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -> list[str]:
"""返回库存快照当前 active link 关联的任务编号列表。"""
if not inv_file:
return []
task_nos: list[str] = []
for link in inv_file.links or []:
if link.is_active and link.task and link.task.task_no:
task_nos.append(link.task.task_no)
return sorted(set(task_nos))
def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> bool:
"""
按库存快照关联任务批量入队续跑。
【AI 触发时机】:库存快照完成解析或字段映射确认后由内部调用;不暴露给 Agent。
"""
task_nos = linked_task_nos_for_inventory_file(inv_file)
if not task_nos:
return False
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
from app.services.shipping_notice.tool_common import set_task_step_progress
started = False
for link in inv_file.links or []:
task = link.task
if not link.is_active or not task:
continue
if task.task_no in task_nos and task.process_status in {"inventory_ready", "parsed", "waiting_inventory"}:
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="本批库存快照已确认,等待匹配库存",
progress_percent=5,
detail="后端已按批次将任务加入库存匹配队列",
)
db.session.commit()
for task_no in task_nos:
started = start_task_orchestrator(task_no) or started
return started
@@ -16,6 +16,11 @@ from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
apply_inventory_parse_result_to_linked_tasks,
start_inventory_file_linked_tasks,
)
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
@@ -213,7 +218,27 @@ def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool:
field_alignment = field_alignment_for_task(task)
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment})
inv_file = active_inventory_file_for_task(task)
if inv_file:
inv_file.mapping_confirmed = True
for link in inv_file.links or []:
linked_task = link.task
if not link.is_active or not linked_task or linked_task.id == task.id:
continue
if awaiting_inventory_mapping_confirm(linked_task):
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(
linked_task,
"inventory_mapping_auto_confirmed",
{
"field_alignment": field_alignment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
)
db.session.commit()
if inv_file:
start_inventory_file_linked_tasks(inv_file)
return True
@@ -255,6 +280,8 @@ def inventory_loaded_response(
require_mapping_review: bool,
event_type: str,
chain_payload: dict[str, Any] | None = None,
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
) -> dict[str, Any]:
"""
库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。
@@ -265,7 +292,18 @@ def inventory_loaded_response(
"""
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
task.inventory_lines_json = inventory_lines
inv_file = active_inventory_file_for_task(task)
linked_tasks: list[ShippingTask] = []
if inv_file:
linked_tasks = apply_inventory_parse_result_to_linked_tasks(
inv_file,
inventory_lines,
field_mapping=field_mapping,
mapping_source=mapping_source,
mapping_confirmed=False,
)
else:
task.inventory_lines_json = inventory_lines
field_alignment = field_alignment_for_task(task, column_meta)
set_task_step_progress(
task,
@@ -292,8 +330,27 @@ def inventory_loaded_response(
"source": source,
"mapping_review": True,
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
},
)
for linked_task in linked_tasks:
if linked_task.id == task.id:
continue
apply_task_transition(linked_task, TaskTransition.INVENTORY_ALIGN_REVIEW)
log_task_event(
linked_task,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"mapping_review": True,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"owner_task_no": task.task_no,
"column_meta": column_meta,
},
)
db.session.commit()
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
if chained is not None:
@@ -319,6 +376,9 @@ def inventory_loaded_response(
# [STEP 3] 无需映射复核时,直接推进到 inventory_ready。
# 这条路径主要服务于明确结构化库存输入,尽快把任务交给后续匹配阶段。
apply_task_transition(task, TaskTransition.INVENTORY_READY)
for linked_task in linked_tasks:
if linked_task.id != task.id:
apply_task_transition(linked_task, TaskTransition.INVENTORY_READY)
log_task_event(
task,
event_type,
@@ -327,9 +387,13 @@ def inventory_loaded_response(
"warnings": warnings or [],
"source": source,
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
},
)
db.session.commit()
if inv_file:
start_inventory_file_linked_tasks(inv_file)
return tool_response(
status="ok",
task=task,
@@ -34,6 +34,13 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
inventory_loaded_response,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
has_uploaded_inventory_file,
parse_linked_inventory_file,
read_linked_inventory_schema_preview,
save_batch_inventory_upload,
)
from app.services.shipping_notice.inventory_snapshot import parse_inventory_text
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
@@ -46,8 +53,10 @@ from app.services.shipping_notice.match_rule_desc import extract_mapping_payload
from app.services.shipping_notice.query_service import (
get_task_by_ref,
resolve_task_from_payload,
serialize_batch_for_tool,
serialize_task_for_tool,
)
from app.services.shipping_notice.i18n import resolve_lang, t
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
@@ -108,9 +117,10 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""Parse inventory from uploaded file, chat text, or structured JSON."""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
# [STEP 1] 先归一化库存输入来源与映射提示。
# 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。
@@ -131,23 +141,34 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 2] 按来源解析库存内容。
# 优先复用已上传文件;否则再回退到 structured 或 raw_text,避免大 Excel 直接走 LLM 文本链路。
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_task_inventory(task.task_no)):
if not has_uploaded_task_inventory(task.task_no):
has_uploaded_file = has_uploaded_inventory_file(task) or has_uploaded_task_inventory(task.task_no)
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_file):
if not has_uploaded_file:
return tool_response(
status="needs_human",
task=task,
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
inv_file = active_inventory_file_for_task(task)
if inv_file:
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
task,
field_mapping=field_mapping,
mapping_source=mapping_source,
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
else:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
source = "uploaded_file"
warnings.append(f"parsed from uploaded file: {path.name}")
elif not inventory_lines:
@@ -167,15 +188,13 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="needs_human",
task=task,
message=(
f"库存文本过大({len(raw_text)} 字符,上限 {max_chars})。"
"请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 "
"POST /tools/upload_inventory_file 上传,再 "
"parse_inventory(use_uploaded_file=true)。"
message=t("workflow.inventory.text_too_large", lang=lang).format(
chars=len(raw_text),
max_chars=max_chars,
),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
next_required_action="upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
next_required_action=t("workflow.inventory.upload_then_parse", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
@@ -192,7 +211,7 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="needs_human",
task=task,
message="未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
message=t("workflow.inventory.parse_failed", lang=lang),
data={**serialize_task_for_tool(task), "warnings": warnings},
checkpoint=CP_MAP_INFER,
)
@@ -211,67 +230,76 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
"""Return headers + sample rows for LLM column mapping (small payload)."""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
if not has_uploaded_task_inventory(task.task_no):
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
task=task,
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
try:
preview = read_task_inventory_schema_preview(task.task_no)
if has_uploaded_inventory_file(task):
preview = read_linked_inventory_schema_preview(task)
else:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}")
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
)
log_task_event(task, "inventory_schema_preview", {"headers": preview.get("headers")})
db.session.commit()
return tool_response(
status="ok",
task=task,
message=(
"已读取库存表头与样例行。请根据 schema_preview 推断列映射,"
"调用 apply_inventory_mapping(map_json=...)。"
),
message=t("workflow.inventory.preview_ready", lang=lang),
data={**serialize_task_for_tool(task), "schema_preview": preview},
checkpoint=CP_MAP_INFER,
next_required_action=(
"根据 data.schema_preview.headers 与 sample_rows 推断 JSON:"
'{"sku":"<列名>","reservation_id":"<列名>","available_qty":"<列名>"},'
"再调用 apply_inventory_mapping"
),
next_required_action=t("workflow.inventory.preview_next", lang=lang),
forbidden_next_tools=["match_inventory"],
)
def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
"""Apply LLM/manual column mapping and parse full uploaded inventory file."""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
# [STEP 1] 先校验上传文件与 schema preview 是否存在。
# 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。
if not has_uploaded_task_inventory(task.task_no):
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
task=task,
message="未找到已上传的库存文件。请先 upload_inventory_file。",
message=t("workflow.inventory.uploaded_file_missing_short", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
try:
preview = read_task_inventory_schema_preview(task.task_no)
if has_uploaded_inventory_file(task):
preview = read_linked_inventory_schema_preview(task)
else:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}")
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
)
raw = payload_map_json(payload)
@@ -306,11 +334,7 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="failed",
task_id=task.task_no,
message=(
"map_json 无效或不完整。"
'需要提供 {"sku":"列名","reservation_id":"列名","available_qty":"列名"}。'
"(库存的 Reservation ID 列允许为空值,但必须有该列标题)"
),
message=t("workflow.inventory.mapping_invalid", lang=lang),
data={
**serialize_task_for_tool(task),
"schema_preview": preview,
@@ -331,28 +355,41 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="failed",
task_id=task.task_no,
message=(
"列映射与 Excel 表头不匹配。"
f"(表头在第 {header_row} 行)"
+ " ".join(mapping_errors)
+ " 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。"
message=t("workflow.inventory.mapping_header_mismatch", lang=lang).format(
row=header_row,
errors=" ".join(mapping_errors),
),
data={**serialize_task_for_tool(task), "schema_preview": preview},
)
try:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=preview.get("header_row_index"),
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
inv_file = active_inventory_file_for_task(task)
if inv_file:
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
task,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=preview.get("header_row_index"),
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
else:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=preview.get("header_row_index"),
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
except FileNotFoundError as exc:
return tool_response(status="failed", task_id=task.task_no, message=str(exc))
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"解析库存失败: {exc}")
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.parse_failed_detail", lang=lang).format(error=exc),
)
warnings = [f"parsed with mapping from uploaded file: {path.name}"]
upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping)
@@ -365,6 +402,8 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
require_mapping_review=True,
event_type="inventory_mapping_applied",
chain_payload=payload,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
@@ -372,16 +411,21 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
"""Save multipart Excel; return schema preview for LLM mapping (no full parse)."""
task = get_task_by_ref(str(task_id or ""))
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
lang = resolve_lang({"lang": None})
if upload is None or not getattr(upload, "filename", None):
return tool_response(status="failed", task_id=task.task_no, message="未收到 file 字段")
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.file_missing", lang=lang),
)
filename = str(upload.filename or "").strip()
if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
return tool_response(
status="failed",
task_id=task.task_no,
message="仅支持 .xlsx / .xls / .csv 库存文件",
message=t("workflow.inventory.file_type_unsupported", lang=lang),
)
try:
@@ -390,21 +434,25 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="正在上传并解析库存文件",
message=t("workflow.inventory.uploading", lang=lang),
progress_percent=35,
detail=f"正在处理库存文件 {filename}",
detail=t("workflow.inventory.uploading_detail", lang=lang).format(filename=filename),
)
db.session.flush()
save_task_inventory_upload(task.task_no, upload)
preview = read_task_inventory_schema_preview(task.task_no)
inv_file = save_batch_inventory_upload(task, upload)
preview = read_linked_inventory_schema_preview(task)
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"保存库存文件失败: {exc}")
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.save_failed", lang=lang).format(error=exc),
)
template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview)
if template_mapping and mapping_is_complete(template_mapping):
try:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
task,
field_mapping=template_mapping,
mapping_source="template",
)
@@ -418,6 +466,8 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
source="uploaded_file_template",
require_mapping_review=True,
event_type="inventory_template_mapping_used",
field_mapping=template_mapping,
mapping_source="template",
)
except Exception:
pass
@@ -431,31 +481,50 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.MAP_INFER)
log_task_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")})
log_task_event(
task,
"inventory_snapshot_created",
{
"inventory_file_no": inv_file.inventory_file_no,
"share_mode": inv_file.share_mode,
"batch_no": task.batch.batch_no if task.batch else None,
},
)
db.session.commit()
upload_message = "库存文件已上传。"
upload_message = t("workflow.inventory.uploaded", lang=lang)
if suggested_complete:
upload_message += " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。"
upload_message += t("workflow.inventory.uploaded_suggested_complete", lang=lang)
else:
upload_message += " 请由画布 LLM 推断列映射后 apply_inventory_mapping。"
upload_message += t("workflow.inventory.uploaded_need_llm", lang=lang)
return tool_response(
status="ok",
task=task,
message=upload_message,
data={
**serialize_task_for_tool(task),
"batch_no": task.batch.batch_no if task.batch else None,
"batch": serialize_batch_for_tool(task.batch) if task.batch else None,
"schema_preview": preview,
"inventory_file_no": inv_file.inventory_file_no,
"share_mode": inv_file.share_mode,
"linked_task_nos": [
link.task.task_no
for link in (inv_file.links or [])
if link.is_active and link.task
],
SUGGEST_OK: suggested_complete,
AUTO_MAP: auto_map,
},
next_required_action="apply_inventory_mapping(map_json=...)",
next_required_action=t("workflow.inventory.apply_mapping_next", lang=lang),
forbidden_next_tools=["match_inventory"],
)
def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
# [STEP 1] 优先接受当前请求直接携带的库存明细。
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
@@ -488,7 +557,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="ok",
task_id=task.task_no,
message="已有库存快照且字段对齐已确认,可调用 match_inventory。",
message=t("workflow.inventory.ready_for_match", lang=lang),
data=serialize_task_for_tool(task),
)
@@ -498,6 +567,6 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="needs_human",
task=task,
message="暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
message=t("workflow.inventory.unavailable", lang=lang),
data=serialize_task_for_tool(task),
)
@@ -79,36 +79,15 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。",
"description": (
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
"不包含由 hxops worker 统一续跑的主推进工具,也不包含 RPA 回调。"
"鉴权:Authorization Bearer 或 X-Integration-Key。"
),
},
"servers": [{"url": server}],
"paths": {
"/tools/create_batch": _post_op(
"create_batch",
"创建发货批次 batch(一次多文件上传的聚合容器)",
{
"batch_no": _str_prop("已存在的批次编号(可选)。传入时将直接复用该批次。"),
"user_id": _int_prop("Hxops 用户 ID(可选)"),
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
"file_count": _int_prop("本批通知文件数量"),
},
),
"/tools/create_task": _post_op(
"create_task",
"创建发货任务 task(可挂到某个 batch)",
{
"batch_no": batch_id,
"task_id": _str_prop("已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"),
"user_id": _int_prop("Hxops 用户 ID(可选)"),
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
"source_type": _str_prop("来源:manual|email|wecom|pdf", enum=["manual", "email", "wecom", "pdf"]),
"source_file_name": _str_prop("原始通知文件名(多文件场景建议传)"),
"source_file_type": _str_prop("原始通知文件类型(多文件场景建议传)"),
"batch_index": _int_prop("当前任务在批次中的顺序,从 1 开始"),
"batch_total": _int_prop("当前批次总任务数"),
"raw_content": _str_prop("原始发货通知文本(可选,后续 parse 也可传入)"),
},
),
"/tools/parse_notice": _post_op(
"parse_notice",
"解析发货通知文本",
@@ -177,30 +156,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", "line_index"],
),
"/tools/parse_inventory": _post_op(
"parse_inventory",
"解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);"
"先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → "
"apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。"
"成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
{
"task_id": task_id,
"use_uploaded_file": _str_prop(
"true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
enum=["true", "false"],
),
MAP_JSON: _str_prop(
'可选,列映射 JSON 字符串,如 {"sku":"AWS Sku","available_qty":"Qty Available"}'
),
"raw_inventory_text": _str_prop(
"仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
),
"inventory_lines_json": _str_prop(
'可选,已整理好的 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
),
},
required=["task_id"],
),
"/tools/get_inventory_schema_preview": _post_op(
"get_inventory_schema_preview",
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
@@ -209,7 +164,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/apply_inventory_mapping": _post_op(
"apply_inventory_mapping",
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由 hxops worker 续跑",
{
"task_id": task_id,
MAP_JSON: _str_prop(
@@ -218,49 +173,20 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", MAP_JSON],
),
"/tools/ensure_inventory": _post_op(
"ensure_inventory",
"确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
{
"task_id": task_id,
"mode": _str_prop("auto=自动/RPA;retry_rpa=重试 RPA", enum=["auto", "retry_rpa"]),
"inventory_lines_json": _str_prop(
'手工库存 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
),
},
required=["task_id"],
),
"/tools/auto_progress": _post_op(
"auto_progress",
"按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID(可选,用于仅知道会话时定位任务)"),
},
),
"/tools/match_inventory": _post_op(
"match_inventory",
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
"未确认时调用会被拒绝并返回 forbidden_next_tools",
{
"task_id": task_id,
"inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"),
},
required=["task_id"],
),
"/tools/submit_decision": _post_op(
"submit_decision",
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
"decision": _str_prop(
"confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;"
"confirm=确认继续;reject=驳回;retry_rpa=重试 RPA 库存导出;rematch=重新匹配;reparse=重新解析;"
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
enum=[
"confirm",
"confirm_parse",
"reject",
"retry_rpa",
"rematch",
"reparse",
"confirm_inventory_mapping",
@@ -272,25 +198,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["decision"],
),
"/tools/generate_shipment_excel": _post_op(
"generate_shipment_excel",
"生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
{"task_id": task_id},
required=["task_id"],
),
"/tools/upload_to_freight": _post_op(
"upload_to_freight",
"上传 Excel 到货代系统(RPA 或手工确认)",
{
"task_id": task_id,
"mode": _str_prop(
"auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
enum=["auto", "retry_upload", "manual_confirm"],
),
"freight_ref_no": _str_prop("货代系统单号(可选;manual_confirm 通常无需填写)"),
},
required=["task_id"],
),
"/tools/get_task_status": _post_op(
"get_task_status",
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
@@ -307,15 +214,5 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["batch_no"],
),
"/tools/switch_focus_task": _post_op(
"switch_focus_task",
"切换当前批次的聚焦任务",
{
"batch_no": batch_id,
"task_no": task_id,
"target_task_no": task_id,
},
required=["batch_no"],
),
},
}
@@ -1,65 +1,53 @@
"""
services/shipping_notice/queue_service.py
用途:货代发货后台任务最小队列实现(基于 KbJob 持久化表)。
依赖:models.KbJob、jobs.types、shipping_notice.batch_orchestrator。
逻辑:Web 侧负责 enqueue;worker 侧通过 claim/process 消费单票任务,避免使用进程内 threading。
用途:货代发货后台任务队列适配层。
依赖:app.jobs.queue、jobs.types、shipping_notice.batch_orchestrator。
逻辑:发货通知只写入通用 jobs 表,worker 通过 Job Runner 消费后执行单票编排。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
import logging
from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, process_next_job
from app.jobs.types import JobType
from app.models import KbJob
from app.models import Job
logger = logging.getLogger('shipping-worker')
SHIPPING_NOTICE_JOB_DOMAIN = "shipping_notice"
def shipping_task_execution_mode() -> str:
"""读取发货任务执行模式;默认 worker,sync 仅用于开发排查。"""
return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower()
def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = None, batch_no: str | None = None) -> tuple[bool, str]:
"""持久化一条单票发货后台任务;sync 模式下直接执行。"""
"""持久化一条单票发货后台任务;不再复用 kb_jobs。"""
normalized_task_no = str(task_no or '').strip().upper()
if not normalized_task_no:
return False, 'task_no is required'
existing = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status.in_(('queued', 'running')),
)
.all()
)
for job in existing:
payload = job.payload_json or {}
if str(payload.get('task_no') or '').strip().upper() == normalized_task_no:
return True, 'already_queued'
job = KbJob(
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status='queued',
progress=0,
message='等待后台处理发货任务',
payload_json={
job_id = enqueue(
JobType.SHIPPING_NOTICE_RUN,
{
'task_no': normalized_task_no,
'batch_no': str(batch_no or '').strip().upper() or None,
},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref=normalized_task_no,
created_by_id=created_by_id,
message='等待后台处理发货任务',
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3),
)
db.session.add(job)
db.session.commit()
if shipping_task_execution_mode() == 'sync':
ok, result = run_shipping_notice_job({'job_id': job.id})
ok, result = run_shipping_notice_job({'job_id': job_id})
return ok, result
if shipping_task_execution_mode() in ('worker', 'rq'):
return True, 'queued_for_worker'
@@ -67,73 +55,33 @@ def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = Non
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
"""回收长时间 running 的发货后台任务,避免 worker 被卡死任务阻塞。"""
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
from app.jobs.queue import recover_stale_jobs
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
stale_jobs = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status == 'running',
KbJob.started_at.isnot(None),
KbJob.started_at < cutoff,
)
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
.all()
count = recover_stale_jobs(domain=SHIPPING_NOTICE_JOB_DOMAIN, timeout_seconds=timeout_sec)
if count:
logger.warning('recovered %s stale shipping_notice job(s)', count)
return count, f'recovered_{count}' if count else 'no_stale_jobs'
def claim_next_shipping_notice_job() -> Job | None:
"""兼容旧调用:领取下一条发货通知通用任务。"""
from app.jobs.queue import claim_next_job
return claim_next_job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_types=[JobType.SHIPPING_NOTICE_RUN],
)
if not stale_jobs:
return 0, 'no_stale_jobs'
now = datetime.utcnow()
message = f'发货任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
for job in stale_jobs:
job.status = 'failed'
job.error_message = message
job.message = message
job.finished_at = now
job.progress = 100
db.session.commit()
logger.warning('recovered %s stale shipping_notice job(s)', len(stale_jobs))
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
def claim_next_shipping_notice_job() -> KbJob | None:
"""原子领取下一条 queued 的发货后台任务。"""
now = datetime.utcnow()
try:
job = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status == 'queued',
)
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.with_for_update(skip_locked=True)
.first()
)
except OperationalError:
db.session.rollback()
logger.exception('failed to claim next shipping notice job')
return None
if not job:
db.session.rollback()
return None
job.status = 'running'
job.started_at = job.started_at or now
job.progress = max(int(job.progress or 0), 1)
job.message = 'worker 已领取发货任务'
db.session.commit()
return job
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
"""执行单票发货任务;既可被 worker 调用,也可被 sync enqueue 直调。"""
"""执行单票发货任务;既可被通用 Job handler 调用,也可被 sync enqueue 直调。"""
from app.services.shipping_notice.batch_orchestrator import _run_single_task
job_id = payload.get('job_id')
job = db.session.get(KbJob, int(job_id)) if job_id else None
raw_job_id = payload.get('job_id')
job_id = int(raw_job_id) if raw_job_id else None
job = db.session.get(Job, job_id) if job_id else None
if job is None:
task_no = str(payload.get('task_no') or '').strip().upper()
else:
@@ -146,28 +94,38 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
status = str(result.get('status') or '').strip().lower()
success = status in {'ok', 'running', 'needs_human', 'skipped'}
if job_id is not None:
job = db.session.get(Job, job_id)
if job is not None:
job.progress = 100
job.finished_at = datetime.utcnow()
job.result_json = dict(result)
job.message = str(result.get('message') or '')[:500] or '发货任务处理完成'
if success:
job.status = 'success'
job.error_message = None
finish_job(
job,
result=dict(result),
message=str(result.get('message') or '')[:500] or '发货任务处理完成',
)
else:
job.status = 'failed'
job.error_message = str(result.get('message') or 'shipping notice job failed')[:1000]
db.session.commit()
fail_job(
job,
error=str(result.get('message') or 'shipping notice job failed')[:1000],
result=dict(result),
retryable=True,
)
if logger:
logger.info('shipping_notice job task_no=%s status=%s', task_no, status or 'unknown')
return success, status or 'done'
def process_next_shipping_notice_job() -> tuple[bool, str]:
def process_next_shipping_notice_job(ctx: Any | None = None) -> tuple[bool, str]:
"""worker 消费发货后台队列的单步入口。"""
recover_stale_shipping_notice_jobs()
job = claim_next_shipping_notice_job()
if not job:
return False, 'no_job'
return run_shipping_notice_job({'job_id': job.id})
if ctx is None:
from app.jobs.context import JobContext
ctx = JobContext(config=dict(current_app.config), logger=logger, extras={'queues': ['shipping']})
return process_next_job(
ctx=ctx,
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_types=[JobType.SHIPPING_NOTICE_RUN],
timeout_config_key='SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS',
default_timeout_seconds=300,
)
@@ -22,6 +22,7 @@ from app.services.shipping_notice.constants import (
CP_TASK_EXISTS,
RS_PARSE_REVIEW,
)
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
from app.services.shipping_notice.notice_lines import normalize_notice_lines
@@ -55,6 +56,13 @@ EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to",
EDITABLE_NOTICE_LINE_FIELDS = frozenset({"sku", "reservation_id", "qty", "quantity", "required_date", "uom"})
def start_task_orchestrator(task_no: str | None) -> bool:
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
return _start(task_no)
def _build_parse_review_chat_payload(task: ShippingTask) -> dict[str, Any]:
return {
"taskId": task.task_no,
@@ -193,6 +201,11 @@ def create_batch(payload: dict[str, Any]) -> ShippingBatch:
return batch
def _create_single_task_batch(payload: dict[str, Any]) -> ShippingBatch:
"""为单票任务创建 file_count=1 的标准批次容器。"""
return create_batch({**payload, "file_count": 1})
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
"""判断是否将 parse_notice 延后到 Dify 画布(有 structured 或显式 auto_parse 时不延后)。"""
if isinstance(item.get("structured"), dict) and item.get("structured"):
@@ -356,22 +369,31 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
checkpoint=CP_TASK_EXISTS,
)
batch = _create_single_task_batch(payload)
db.session.flush()
task = ShippingTask(
task_no=generate_task_no(),
batch_id=batch.id,
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
source_type=str(payload.get("source_type") or "manual"),
batch_index=1,
batch_total=1,
raw_content=str(payload.get("raw_content") or "").strip() or None,
process_status="created",
)
db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type})
log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no})
db.session.flush()
batch.current_focus_task_no = task.task_no
recompute_batch_summary(batch)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=f"已创建发货任务 {task.task_no}",
data=serialize_task_for_tool(task),
batch_no=batch.batch_no,
message=f"已创建发货批次 {batch.batch_no},任务 {task.task_no}",
data={**serialize_task_for_tool(task), "batch": serialize_batch_for_tool(batch)},
)
@@ -405,11 +427,16 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
and new_notice_payload
and str(task.process_status or "").strip().lower() in {"uploaded", "rejected", "closed"}
):
batch = _create_single_task_batch(payload)
db.session.flush()
new_task = ShippingTask(
task_no=generate_task_no(),
batch_id=batch.id,
user_id=payload.get("user_id"),
conversation_id=conv_id or None,
source_type=str(payload.get("source_type") or task.source_type or "manual"),
batch_index=1,
batch_total=1,
raw_content=None,
process_status="created",
)
@@ -417,8 +444,11 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
log_task_event(
new_task,
"task_created",
{"source_type": new_task.source_type, "created_from": task.task_no},
{"source_type": new_task.source_type, "created_from": task.task_no, "batch_no": batch.batch_no},
)
db.session.flush()
batch.current_focus_task_no = new_task.task_no
recompute_batch_summary(batch)
db.session.commit()
task = new_task
@@ -507,33 +537,27 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit()
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
lang = resolve_lang(payload)
summary_text = format_parse_summary(
**summary_kwargs,
payload=payload,
include_confirmation_hint=not should_auto_continue,
)
# [STEP 4] 高置信度且尚无库存时,自动串联 auto_progress 或 ensure_inventory。
# [STEP 4] 高置信度解析后不在当前请求线程里继续串行推进。
# 统一把后续库存/匹配/导出链路交给后台 worker,避免请求线程兼任主调度器。
if should_auto_continue:
lang = payload.get("lang") if isinstance(payload, dict) else None
auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
if lang:
auto_payload["lang"] = lang
auto_result = auto_progress(auto_payload) if auto_progress_enabled() else ensure_inventory(auto_payload)
msg = str(auto_result.get("message") or "").strip()
merged_message = summary_text if not msg else f"{summary_text}\n\n{msg}"
merged_data = {}
if isinstance(auto_result.get("data"), dict):
merged_data.update(auto_result["data"])
merged_data["warnings"] = warnings
db.session.refresh(task)
orchestrator_started = start_task_orchestrator(task.task_no)
merged_message = (
f"{summary_text}\n\n{t('workflow.parse.auto_continued', lang=lang)}"
if orchestrator_started
else f"{summary_text}\n\n{t('workflow.parse.check_later', lang=lang)}"
)
return tool_response(
status=str(auto_result.get("status") or "ok"),
status="running" if orchestrator_started else "ok",
task=task,
message=merged_message,
data=merged_data,
next_required_action=auto_result.get("next_required_action"),
forbidden_next_tools=auto_result.get("forbidden_next_tools"),
data={**serialize_task_for_tool(task), "warnings": warnings},
)
return tool_response(
@@ -0,0 +1,74 @@
"""Add generic jobs table for non-KB background tasks.
Purpose:
Introduce a domain-aware background job table so shipping_notice no longer
reuses kb_jobs for orchestration.
Dependencies:
Alembic revision f9a0b1c2d3e4.
Flow:
Shipping notice workers enqueue and consume rows from jobs while existing
knowledge-base jobs remain on kb_jobs during phase one.
Revision ID: fa1b2c3d4e5f
Revises: f9a0b1c2d3e4
Create Date: 2026-06-26 08:45:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "fa1b2c3d4e5f"
down_revision = "f9a0b1c2d3e4"
branch_labels = None
depends_on = None
def upgrade():
"""Create the generic jobs table used by phase-one shipping jobs."""
op.create_table(
"jobs",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("domain", sa.String(length=64), nullable=False),
sa.Column("job_type", sa.String(length=64), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False),
sa.Column("priority", sa.Integer(), nullable=False),
sa.Column("business_ref", sa.String(length=128), nullable=True),
sa.Column("payload_json", sa.JSON(), nullable=True),
sa.Column("result_json", sa.JSON(), nullable=True),
sa.Column("progress", sa.Integer(), nullable=False),
sa.Column("message", sa.Text(), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("attempts", sa.Integer(), nullable=False),
sa.Column("max_attempts", sa.Integer(), nullable=False),
sa.Column("locked_by", sa.String(length=128), nullable=True),
sa.Column("locked_at", sa.DateTime(), nullable=True),
sa.Column("created_by_id", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.Column("started_at", sa.DateTime(), nullable=True),
sa.Column("finished_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["created_by_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_jobs_business_ref", "jobs", ["domain", "job_type", "business_ref"], unique=False)
op.create_index("ix_jobs_domain", "jobs", ["domain"], unique=False)
op.create_index("ix_jobs_domain_status_created", "jobs", ["domain", "status", "created_at"], unique=False)
op.create_index("ix_jobs_job_type", "jobs", ["job_type"], unique=False)
op.create_index("ix_jobs_locked_at", "jobs", ["locked_at"], unique=False)
op.create_index("ix_jobs_priority", "jobs", ["priority"], unique=False)
op.create_index("ix_jobs_status", "jobs", ["status"], unique=False)
op.create_index("ix_jobs_type_status_created", "jobs", ["job_type", "status", "created_at"], unique=False)
def downgrade():
"""Drop the generic jobs table."""
op.drop_index("ix_jobs_type_status_created", table_name="jobs")
op.drop_index("ix_jobs_status", table_name="jobs")
op.drop_index("ix_jobs_priority", table_name="jobs")
op.drop_index("ix_jobs_locked_at", table_name="jobs")
op.drop_index("ix_jobs_job_type", table_name="jobs")
op.drop_index("ix_jobs_domain_status_created", table_name="jobs")
op.drop_index("ix_jobs_domain", table_name="jobs")
op.drop_index("ix_jobs_business_ref", table_name="jobs")
op.drop_table("jobs")
@@ -0,0 +1,95 @@
"""Add shipping inventory file sharing tables.
Purpose:
Store freight shipping inventory as a batch-level snapshot that can be
linked to all tasks in the batch.
Dependencies:
Alembic revision fa1b2c3d4e5f.
Flow:
Upload creates one shipping_inventory_files row and active links in
shipping_task_inventory_links; each task still matches independently.
Revision ID: fb2c3d4e5f6a
Revises: fa1b2c3d4e5f
Create Date: 2026-06-26 10:30:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "fb2c3d4e5f6a"
down_revision = "fa1b2c3d4e5f"
branch_labels = None
depends_on = None
def upgrade():
"""Create shipping inventory snapshot and task link tables."""
op.create_table(
"shipping_inventory_files",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("inventory_file_no", sa.String(length=64), nullable=False),
sa.Column("batch_id", sa.Integer(), nullable=True),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("source_file_name", sa.String(length=255), nullable=True),
sa.Column("storage_path", sa.String(length=500), nullable=False),
sa.Column("schema_preview_json", sa.JSON(), nullable=True),
sa.Column("field_mapping_json", sa.JSON(), nullable=True),
sa.Column("mapping_source", sa.String(length=32), nullable=True),
sa.Column("mapping_confirmed", sa.Boolean(), server_default=sa.text("false"), nullable=False),
sa.Column("inventory_lines_json", sa.JSON(), nullable=True),
sa.Column("line_count", sa.Integer(), nullable=False),
sa.Column("share_mode", sa.String(length=32), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["batch_id"], ["shipping_batches.id"]),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_inventory_files_batch_created", "shipping_inventory_files", ["batch_id", "created_at"], unique=False)
op.create_index("ix_shipping_inventory_files_batch_id", "shipping_inventory_files", ["batch_id"], unique=False)
op.create_index("ix_shipping_inventory_files_created_at", "shipping_inventory_files", ["created_at"], unique=False)
op.create_index("ix_shipping_inventory_files_inventory_file_no", "shipping_inventory_files", ["inventory_file_no"], unique=True)
op.create_index("ix_shipping_inventory_files_user_created", "shipping_inventory_files", ["user_id", "created_at"], unique=False)
op.create_index("ix_shipping_inventory_files_user_id", "shipping_inventory_files", ["user_id"], unique=False)
op.create_table(
"shipping_task_inventory_links",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("task_id", sa.Integer(), nullable=False),
sa.Column("inventory_file_id", sa.Integer(), nullable=False),
sa.Column("link_role", sa.String(length=32), nullable=False),
sa.Column("access_mode", sa.String(length=32), nullable=False),
sa.Column("is_active", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("linked_by_user_id", sa.Integer(), nullable=True),
sa.Column("linked_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["inventory_file_id"], ["shipping_inventory_files.id"]),
sa.ForeignKeyConstraint(["linked_by_user_id"], ["users.id"]),
sa.ForeignKeyConstraint(["task_id"], ["shipping_tasks.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_task_inventory_links_file_active", "shipping_task_inventory_links", ["inventory_file_id", "is_active"], unique=False)
op.create_index("ix_shipping_task_inventory_links_inventory_file_id", "shipping_task_inventory_links", ["inventory_file_id"], unique=False)
op.create_index("ix_shipping_task_inventory_links_is_active", "shipping_task_inventory_links", ["is_active"], unique=False)
op.create_index("ix_shipping_task_inventory_links_linked_at", "shipping_task_inventory_links", ["linked_at"], unique=False)
op.create_index("ix_shipping_task_inventory_links_task_active", "shipping_task_inventory_links", ["task_id", "is_active"], unique=False)
op.create_index("ix_shipping_task_inventory_links_task_id", "shipping_task_inventory_links", ["task_id"], unique=False)
def downgrade():
"""Drop shipping inventory snapshot tables."""
op.drop_index("ix_shipping_task_inventory_links_task_id", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_task_active", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_linked_at", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_is_active", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_inventory_file_id", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_file_active", table_name="shipping_task_inventory_links")
op.drop_table("shipping_task_inventory_links")
op.drop_index("ix_shipping_inventory_files_user_id", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_user_created", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_inventory_file_no", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_created_at", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_batch_id", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_batch_created", table_name="shipping_inventory_files")
op.drop_table("shipping_inventory_files")
+141 -19
View File
@@ -10,8 +10,11 @@
from io import BytesIO
from app import db
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, User
from app.auth_jwt import issue_local_access_token
from app.jobs.context import JobContext
from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
@@ -202,6 +205,75 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
assert started == [data["batch_no"]]
def test_shipping_orchestrator_enqueues_generic_job_not_kb_job(app):
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
batch = ShippingBatch(batch_no="SB-JOBS-QUEUE", file_count=1, user_id=123)
task = ShippingTask(
task_no="SN-20260626-JOBS0001",
batch=batch,
user_id=123,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
started = batch_orchestrator.start_task_orchestrator(task.task_no)
assert started is True
job = Job.query.filter_by(
domain="shipping_notice",
job_type="shipping_notice_run",
business_ref=task.task_no,
).first()
assert job is not None
assert job.status == "queued"
assert job.payload_json["task_no"] == task.task_no
assert KbJob.query.filter_by(job_type="shipping_notice_run").count() == 0
def test_process_shipping_job_survives_session_remove(app, monkeypatch):
"""Job Runner 应能处理业务编排内部 db.session.remove 后的状态回写。"""
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
job = Job(
domain="shipping_notice",
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status="queued",
business_ref="SN-20260626-DETACHED1",
payload_json={"task_no": "SN-20260626-DETACHED1"},
message="等待后台处理发货任务",
)
db.session.add(job)
db.session.commit()
job_id = job.id
def fake_run_single_task(task_no: str):
db.session.remove()
return {"status": "ok", "message": f"done {task_no}"}
monkeypatch.setattr(batch_orchestrator, "_run_single_task", fake_run_single_task)
ctx = JobContext(config=dict(app.config), logger=app.logger, extras={"queues": ["shipping"]})
processed, message = process_next_job(
ctx=ctx,
domain="shipping_notice",
job_types=[JobType.SHIPPING_NOTICE_RUN],
timeout_config_key="SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS",
)
assert processed is True
assert message == JobType.SHIPPING_NOTICE_RUN.value
refreshed = db.session.get(Job, job_id)
assert refreshed is not None
assert refreshed.status == "success"
assert refreshed.result_json["status"] == "ok"
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
with app.app_context():
@@ -266,8 +338,8 @@ def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypat
assert called["auto_progress"]["task_id"] == task_no
def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app, monkeypatch):
"""后台 Dify 执行器应带上当前任务上下文,并回写 provider conversation id。"""
def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat(app, monkeypatch):
"""后台 Dify 执行器应带当前任务上下文,但不复用/污染前端聊天记录。"""
with app.app_context():
user = User(
username="shipping_dify_user",
@@ -293,6 +365,7 @@ def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app
agent_id=agent.id,
title="shipping parse",
status="running",
external_conversation_id="22222222-2222-2222-2222-222222222222",
)
batch = ShippingBatch(
batch_no="SB-DIFY-EXEC",
@@ -321,28 +394,35 @@ def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app
captured["conversation_id"] = conversation_id
captured["session_id"] = kwargs.get("session_id")
captured["inputs"] = kwargs.get("inputs")
captured["persist_chat_log"] = kwargs.get("persist_chat_log")
yield 'data: {"event":"message_end","conversation_id":"11111111-1111-1111-1111-111111111111","answer":"parsed"}\n\n'
monkeypatch.setattr(dify_executor.DifyService, "stream_chat", staticmethod(fake_stream_chat))
result = dify_executor.run_shipping_parse_via_dify(task.task_no)
assert result["status"] == "ok"
assert captured["query"] == "解析当前发货通知任务"
assert captured["user_id"] == user.id
assert captured["agent_id"] == agent.id
assert captured["conversation_id"] is None
assert captured["session_id"] == session.session_id
assert captured["persist_chat_log"] is False
assert isinstance(captured["inputs"], dict)
assert captured["inputs"]["entry_mode"] == "orchestrator_parse"
assert captured["inputs"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["user_message"] == ""
assert captured["inputs"]["current_task_no"] == task.task_no
assert captured["inputs"]["current_batch_no"] == batch.batch_no
assert captured["inputs"]["hxops_context"]["schema_version"] == "1"
assert captured["inputs"]["hxops_context"]["session"]["id"] == session.session_id
assert captured["inputs"]["hxops_context"]["request"]["id"] == f"shipping-orch-{task.task_no}"
assert captured["inputs"]["hxops_context"]["request"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["hxops_context"]["refs"] == [
{"field": "task", "value": task.task_no},
{"field": "batch", "value": batch.batch_no},
]
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "11111111-1111-1111-1111-111111111111"
assert refreshed_session.external_conversation_id == "22222222-2222-2222-2222-222222222222"
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
def test_build_dify_chat_inputs_returns_hxops_context_only(app):
"""货代发货 Agent 应只注入平台统一的 hxops_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
@@ -362,17 +442,59 @@ def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
inputs = dify_inputs.build_dify_chat_inputs(
"conv-shipping-inputs-001",
entry_mode="user_chat",
user_message="这票现在什么状态?",
trigger_source="frontend_chat",
request_id="req-frontend-001",
)
assert inputs["entry_mode"] == "user_chat"
assert inputs["conversation_id"] == "conv-shipping-inputs-001"
assert inputs["current_batch_no"] == "SB-DIFY-INPUTS"
assert inputs["current_task_no"] == "SN-20260622-DDDD0004"
assert inputs["user_message"] == "这票现在什么状态?"
assert inputs["trigger_source"] == "frontend_chat"
assert set(inputs.keys()) == {"hxops_context"}
assert inputs["hxops_context"]["schema_version"] == "1"
assert inputs["hxops_context"]["session"]["id"] == "conv-shipping-inputs-001"
assert inputs["hxops_context"]["request"]["id"] == "req-frontend-001"
assert inputs["hxops_context"]["request"]["trigger_source"] == "frontend_chat"
assert inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260622-DDDD0004"},
{"field": "batch", "value": "SB-DIFY-INPUTS"},
]
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
"""已有 Dify provider 会话号时,HXOPS 上下文仍应按本地 session 解析。"""
with app.app_context():
local_session_id = "conv-shipping-local-session-001"
provider_conversation_id = "f3b371e7-4d8b-40b6-80be-76fd98459c65"
batch = ShippingBatch(
batch_no="SB-DIFY-LOCAL",
conversation_id=local_session_id,
current_focus_task_no="SN-20260626-LOCAL001",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260626-LOCAL001",
batch=batch,
conversation_id=local_session_id,
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
provider_inputs = dify_inputs.build_dify_chat_inputs(provider_conversation_id)
local_inputs = dify_inputs.build_dify_chat_inputs(local_session_id)
assert provider_inputs["hxops_context"]["refs"] == []
assert local_inputs["hxops_context"]["session"]["id"] == local_session_id
assert local_inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260626-LOCAL001"},
{"field": "batch", "value": "SB-DIFY-LOCAL"},
]
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
class AgentLike:
name = "智能发货通知Agent"
assert dify_inputs.is_shipping_notice_chat_agent(AgentLike()) is True
def test_create_empty_batch_returns_batch_shell(app, client):
+154 -8
View File
@@ -1,7 +1,7 @@
import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
from app.models import ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.match import match_notice_lines
@@ -165,14 +165,21 @@ def test_openapi_spec_public(app, client):
res = client.get("/api/shipping-notice/tools/openapi.json")
assert res.status_code == 200
spec = res.get_json()
assert "create_task" in str(spec)
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
props = spec["paths"]["/tools/create_task"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
assert "raw_content" in props
assert "/rpa/" not in str(spec["paths"])
assert "/tools/parse_inventory" in spec["paths"]
assert "/tools/create_task" not in spec["paths"]
assert "/tools/create_batch" not in spec["paths"]
assert "/tools/parse_inventory" not in spec["paths"]
assert "/tools/ensure_inventory" not in spec["paths"]
assert "/tools/auto_progress" not in spec["paths"]
assert "/tools/match_inventory" not in spec["paths"]
assert "/tools/generate_shipment_excel" not in spec["paths"]
assert "/tools/upload_to_freight" not in spec["paths"]
assert "/tools/switch_focus_task" not in spec["paths"]
assert "/tools/get_inventory_schema_preview" in spec["paths"]
assert "/tools/apply_inventory_mapping" in spec["paths"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
def test_parse_inventory_from_chat_text(app, client):
@@ -841,8 +848,17 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -864,17 +880,30 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "running"
assert "【发货通知解析确认】" in parse_data["message"]
assert "回复「确认」进入库存检查" not in parse_data["message"]
assert parse_data.get("checkpoint") != "parse_review"
assert called.get("task_no") == task_id
@pytest.mark.auto_rpa
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path):
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
import app.services.shipping_notice.decision_workflow as decision_workflow
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -904,7 +933,87 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "running"
assert "RPA 库存导出" in confirm_data["message"]
assert "后台" in confirm_data["message"]
assert "ensure_inventory" not in confirm_data["message"]
assert "match_inventory" not in confirm_data["message"]
assert called.get("task_no") == task_id
def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, monkeypatch):
import app.services.shipping_notice.decision_workflow as decision_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task_db_id = task.id
task.inventory_lines_json = [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
db.session.commit()
with app.app_context():
db.session.add(
ShippingTaskEvent(
task_id=task_db_id,
event_type="inventory_mapping_inferred",
detail_json={
"column_meta": {
"headers": ["Reservation ID", "SKU", "Qty Available"],
"field_mapping": {
"reservation_id": "Reservation ID",
"sku": "SKU",
"available_qty": "Qty Available",
},
"mapping": {
"reservation_id": {"source_column": "Reservation ID"},
"sku": {"source_column": "SKU"},
"available_qty": {"source_column": "Qty Available"},
},
}
},
)
)
db.session.commit()
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "running"
assert "后台继续处理匹配与后续步骤" in confirm_data["message"]
assert called.get("task_no") == task_id
def test_submit_decision_by_conversation_id(app, client):
@@ -950,6 +1059,43 @@ def test_submit_decision_by_conversation_id(app, client):
assert dup_data.get("checkpoint") == "task_exists"
def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
import app.services.shipping_notice.decision_workflow as decision_workflow
captured: dict[str, object] = {}
def fake_ensure_inventory(payload):
captured.update(payload)
return {
"status": "running",
"task_id": payload["task_id"],
"message": "已触发 RPA 库存导出(测试桩)",
}
monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory)
res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"},
)
data = res.get_json()
assert data["status"] == "running"
assert data["task_id"] == task_id
assert data["message"] == "已触发 RPA 库存导出(测试桩)"
assert captured["task_id"] == task_id
assert captured["mode"] == "retry_rpa"
def test_parse_inventory_rejects_oversized_text(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
@@ -0,0 +1,417 @@
# HXOPS 统一上下文注入原型设计
| 项目 | 说明 |
|------|------|
| 文档版本 | v1.0 |
| 读者 | 产品负责人、平台研发、Agent 研发、Dify 画布维护者、测试验收 |
| 产品名称 | HXOPS 统一上下文注入 |
| 适用范围 | 所有接入 HXOPS 的 Dify Agent / Chatflow / Workflow |
---
## 目录
- [一、需求缘起和要解决的问题](#一需求缘起和要解决的问题)
- [二、需求输出设计](#二需求输出设计)
- [三、规格需求](#三规格需求)
- [四、测试场景案例](#四测试场景案例)
- [五、补充说明](#五补充说明)
---
## 一、需求缘起和要解决的问题
### 1.1 需求缘起
HXOPS 当前已接入多个 Agent 场景,包括但不限于:
- 货代发货通知
- 文件检核
- OA / 请假类流程
- 知识库与其他平台型能力
这些 Agent 在接入 Dify 时,普遍存在一类平台共性问题:
**HXOPS 需要向 Dify 注入上下文,但各 Agent 当前使用的输入变量并不统一。**
例如:
- 有的 Agent 依赖 `task_id`
- 有的 Agent 依赖 `current_task_no`
- 有的 Agent 依赖 `conversation_id`
- 有的 Agent 依赖 `current_batch_no`
- 有的 Agent 还会定义业务专属输入变量
结果是:
- 平台侧要理解“每个应用需要什么字段”
- Dify 画布 Start 输入越来越分散
- 新增 Agent 时常常复制旧模式再改名
- 输入协议逐渐与业务实现强耦合
因此,需要抽象出一套**平台统一上下文注入协议**,由 HXOPS 统一注入,供所有 Dify 应用按统一方式消费。
### 1.2 现存核心痛点
#### 1.2.1 平台侧痛点
- 平台需要为不同 Agent 写不同的 Dify 输入拼装逻辑,难以维护。
- 输入字段名没有统一规范,平台很难形成稳定抽象层。
- 当业务对象命名变化时,平台与画布都要同步调整,改动成本高。
- 平台无法只做“上下文锚点注入”,而被迫承担部分业务流程输入设计。
#### 1.2.2 Dify 画布侧痛点
- 画布 Start 输入变量过多,且字段含义不稳定。
- 画布分支依赖输入变量本身,而不是依赖后端 Tool 的实时状态。
- 不同 Agent 画布重复定义同类变量,难以复用通用节点与通用分支。
- 当没有 `task_id/current_task_no` 等上下文时,很多画布缺少统一兜底流程。
#### 1.2.3 架构一致性痛点
- 用户输入、业务对象锚点、运行态状态混在一起,职责边界不清晰。
- Dify 原生 `query/files` 与 HXOPS 自定义输入重复表达,易形成双写。
- 平台无法明确区分“当前已知上下文”与“实时运行状态”。
- 运行态判断散落在输入变量、LLM 提示词和 Tool message 文案里,不利于平台化收敛。
### 1.3 原型开发目标与边界
#### 目标
提供一套 **HXOPS 统一上下文注入协议**,用于 HXOPS 调用 Dify 时统一传递上下文。
核心目标如下:
1. HXOPS 平台统一只传一个上下文对象:`hxops_context`
2. 用户输入与附件继续使用 Dify 原生 `query` / `files`
3. 业务对象统一通过 `refs` 表达
4. Dify 画布统一通过 `hxops_context` 定位当前业务对象
5. 运行态分支统一依赖后端 Tool 返回,不再依赖 Start 私有变量
#### 原型范围内
- 定义 `hxops_context` 的平台级结构
- 定义 `refs` 的统一表达方式
- 定义 HXOPS 如何发现并注入“当前已知业务对象”
- 定义 Dify 画布如何消费统一上下文
- 定义运行态分支与 Tool 返回的职责边界
#### 原型范围外
- 各业务 Tool 的具体实现细节
- 各 Agent OpenAPI 文档全面重写
- 前端工作台 UI 改版
- 某一类 Agent 的专属输入协议扩展
---
## 二、需求输出设计
### 2.1 整体设计思路
本原型将 HXOPS -> Dify 的输入模型拆成三层:
1. **Dify 原生输入层**
- `query`
- `files`
2. **HXOPS 平台上下文层**
- `inputs.hxops_context`
3. **Tool 运行态层**
- `status`
- `checkpoint`
- `stage`
- `next_required_action`
- `stop_agent_turn`
- 其他状态字段
三层职责如下:
```mermaid
flowchart TB
subgraph inputLayer [输入层]
Query["query"]
Files["files"]
end
subgraph contextLayer [平台上下文层]
HxopsContext["hxops_context"]
Refs["refs"]
end
subgraph runtimeLayer [运行态层]
ToolStatus["Tool 返回状态"]
end
Query --> HxopsContext
Files --> HxopsContext
HxopsContext --> Refs
Refs --> ToolStatus
```
**设计原则**
1. **输入与上下文分层**:用户输入继续走 `query/files`,平台补充上下文统一走 `hxops_context`。
2. **上下文只表达已知锚点**:`hxops_context` 只承载平台基础信息和当前已知对象引用。
3. **业务对象统一表达**:所有 Agent 统一通过 `refs` 传递业务对象锚点。
4. **运行态不提前注入**:`checkpoint/stage` 等实时状态不进入 `hxops_context`。
5. **画布先查状态再分支**:Dify 画布通过 `refs` 找对象,再通过 Tool 获取运行态。
### 2.2 核心功能清单
| 编号 | 功能名称 | 用户价值 | 主要输入 | 主要输出 |
|------|----------|----------|----------|----------|
| F1 | 统一上下文注入 | 平台不再为每个 Agent 单独定制变量 | HXOPS 会话、请求、绑定对象 | `hxops_context` |
| F2 | 基础上下文表达 | 稳定传递平台级会话与请求信息 | session/request 元数据 | `schema_version`、`session`、`request` |
| F3 | 业务对象锚点表达 | 统一表达 task/run/document 等对象 | 当前已知业务对象 | `refs[]` |
| F4 | Dify 统一消费 | 画布不再依赖私有 Start 输入协议 | `hxops_context` | 标准化内部变量 |
| F5 | 运行态状态驱动 | 流程分支统一依赖 Tool 返回 | 状态查询 Tool 响应 | 结构化流程状态 |
| F6 | 缺失上下文兜底 | 没有 refs 时仍可工作 | 空 `refs` | 用户提示 / 补充动作 |
### 2.3 核心业务流程
本原型的目标流程不是业务流程,而是**上下文注入与消费流程**。
```mermaid
flowchart TD
S1["步骤1 HXOPS 接收 query/files"] --> S2["步骤2 构造 hxops_context"]
S2 --> S3["步骤3 发现当前已知 refs"]
S3 --> S4["步骤4 调用 Dify 并传入 hxops_context"]
S4 --> S5["步骤5 Dify 读取 refs"]
S5 --> S6["步骤6 调状态查询 Tool"]
S6 --> S7["步骤7 按 Tool 返回状态分支"]
```
#### 流程说明
| 步骤 | 平台/画布做什么 | 输出 |
|------|------------------|------|
| 1 | HXOPS 收到用户请求或系统触发 | `query` / `files` |
| 2 | HXOPS 构造统一上下文对象 | `hxops_context` |
| 3 | HXOPS 发现当前已知业务对象 | `refs[]` |
| 4 | HXOPS 调用 Dify | `query` + `files` + `hxops_context` |
| 5 | Dify 画布读取 `hxops_context` | 内部标准化变量 |
| 6 | Dify 通过对象锚点调用状态 Tool | 结构化状态 |
| 7 | Dify 按 Tool 返回分支 | 动作 / 等待用户 / 完成 |
### 2.4 输出结果规范
#### 2.4.1 `hxops_context` 标准结构
```json
{
"hxops_context": {
"schema_version": "1",
"session": {
"id": "hxops-session-id"
},
"request": {
"id": "req_xxx",
"trigger_source": "user_chat",
"locale": "zh-CN"
},
"refs": [
{
"field": "task",
"value": "SN-20260623-AB12CD34"
}
]
}
}
```
#### 2.4.2 字段定义
| 字段 | 必填 | 说明 |
|------|------|------|
| `schema_version` | 是 | 协议版本,当前固定为 `"1"` |
| `session.id` | 是 | HXOPS 本地会话 ID |
| `request.id` | 否 | 请求追踪 ID |
| `request.trigger_source` | 否 | 平台触发来源 |
| `request.locale` | 否 | 当前语言环境 |
| `refs` | 是 | 当前已知业务对象锚点列表 |
#### 2.4.3 `refs` 标准结构
```json
"refs": [
{
"field": "task",
"value": "SN-20260623-AB12CD34"
},
{
"field": "batch",
"value": "BATCH-20260623-001"
}
]
```
#### 2.4.4 `refs.field` 推荐枚举
- `task`
- `batch`
- `run`
- `document`
- `group`
- `approval`
- `request`
#### 2.4.5 注入规则
| 规则 | 说明 |
|------|------|
| 基础字段始终注入 | `schema_version`、`session.id`、`request.*`、`refs` |
| `refs` 只注入当前已知对象 | 不根据“某应用需要什么”反向定制 |
| `refs` 可为空 | 无对象锚点时允许 `[]` |
| 同一 `field` 默认最多一条 | v1 不支持同类对象多值并列 |
| 运行态字段禁止进入 `hxops_context` | `checkpoint/stage/...` 一律从 Tool 返回 |
---
## 三、规格需求
### 3.1 平台注入规格
HXOPS 调用 Dify 时:
- 用户消息继续传 `query`
- 用户附件继续传 `files`
- 平台上下文统一传 `inputs.hxops_context`
不再要求平台按 Agent 注入以下字段:
- `current_task_no`
- `current_batch_no`
- `task_id`
- `conversation_id`
- `entry_mode`
### 3.2 `trigger_source` 规格
推荐枚举:
- `user_chat`
- `system`
- `scheduler`
- `callback`
- `retry`
要求:
- 仅表达平台来源
- 不表达业务模式
- 不夹带 Agent 私有流程语义
### 3.3 `refs` 发现规格
HXOPS 发现 `refs` 的优先级:
1. 当前显式上下文
2. 当前会话已绑定对象
3. 当前入口页面/路由带入对象
4. 最近一次已确认有效对象
5. 没有则不注入
### 3.4 Dify 消费规格
画布统一流程要求:
1. 读取 `hxops_context`
2. 解析 `refs`
3. 调用状态查询 Tool
4. 按 Tool 返回分支
禁止:
- 把 `hxops_context` 当实时状态来源
- 依赖私有 Start 变量做主流程分支
- 在缺少 `refs` 时直接报错终止
### 3.5 Tool 返回规格
为支持统一上下文注入,状态查询 Tool 与动作 Tool 应逐步统一返回:
- `status`
- `checkpoint`
- `stage`
- `next_required_action`
- `allowed_tools`
- `forbidden_next_tools`
- `stop_agent_turn`
- `human_options`
- `display_message`
- `display_payload`
优先级最高字段:
1. `checkpoint`
2. `next_required_action`
3. `stop_agent_turn`
### 3.6 禁止项
以下内容不得进入 `hxops_context`:
#### 与 Dify 原生输入重复
- `query`
- `files`
- `user_message`
- `attachments`
#### 运行态状态字段
- `checkpoint`
- `stage`
- `current_step`
- `next_required_action`
- `allowed_tools`
- `forbidden_next_tools`
- `stop_agent_turn`
#### Agent 私有流程开关
- `entry_mode`
- `shipping_mode`
- `parse_mode`
- `schedule_task_id`
---
## 四、测试场景案例
| 编号 | 场景 | 输入情况 | 预期 |
|------|------|----------|------|
| TC-01 | 只有 query,无业务锚点 | `refs=[]` | Dify 进入兜底提示,而非依赖旧私有变量 |
| TC-02 | 当前会话已绑定单个对象 | `refs=[run]` | 画布能识别对象并调用状态查询 Tool |
| TC-03 | 当前会话已绑定多个对象 | `refs=[task,batch]` | 画布可提取所需对象,状态查询可正常工作 |
| TC-04 | 不同 Agent 共享协议 | 一个 Agent 用 `task`,另一个用 `document` | 平台协议不变,画布按需解析 |
| TC-05 | 无旧变量兼容时运行 | 不再传 `current_task_no/current_batch_no` | 新画布仍可通过 `hxops_context` 工作 |
| TC-06 | Tool 返回 needs_human | `stop_agent_turn=true` | 画布停下等待用户,而非继续自动链路 |
| TC-07 | Tool 返回 completed | `checkpoint=completed` | 画布进入完成态总结 |
| TC-08 | 平台未发现任何对象 | `refs=[]` | 画布允许请求用户补充上下文 |
---
## 五、补充说明
### 5.1 本原型不要求一次性删除旧协议
为降低风险,建议采用渐进迁移:
1. 平台先并行注入 `hxops_context`
2. 画布改为优先读取 `hxops_context`
3. Tool 返回补齐状态字段
4. 最后再下线旧私有输入变量
### 5.2 本原型不是某个 Agent 的专属方案
该原型用于所有 HXOPS Agent,因此:
- 不能绑定货代专属字段名
- 不能绑定文件检核专属字段名
- 不能依赖某个业务模型的对象表达方式
### 5.3 一句话总结
HXOPS 统一上下文注入原型的核心是:
**平台统一只传 `hxops_context`,业务对象通过 `refs` 表达,Dify 统一通过状态查询 Tool 获取运行态,再按 Tool 返回进行流程分支。**
@@ -0,0 +1,353 @@
# HXOPS 统一上下文注入实现
> 文件定位:平台级实现方案文档。
> 目标:把 HXOPS -> Dify 的输入与分支逻辑收敛到统一协议,逐步替换现有 Agent 私有注入方式。
> 实现原则:平台统一只传 `hxops_context`,业务对象通过 `refs` 表达,运行态分支靠 Tool 返回。
---
## 1. 实现目标
在不破坏现有 Agent 运行的前提下,逐步完成以下收敛:
1. 平台统一构造 `inputs.hxops_context`
2. 各 Agent 不再定义私有 Start 输入协议
3. Dify 画布统一改为“先查状态,再分支”
4. Tool 返回统一提供状态驱动画布的关键字段
---
## 2. 实现范围
本实现方案覆盖三层:
1. 后端注入端
2. Dify 画布端
3. Tool 返回端
不包含:
- 具体业务 Tool 逻辑重写
- OpenAPI 细节的全面重构
- 具体某一 Agent 的 UI 改版
---
## 3. 后端注入端
### 3.1 平台统一注入出口
后端需要把“向 Dify 注入什么 inputs”的职责,从各 Agent 零散实现中抽出来,统一收敛到平台调用出口。
目标职责:
- 统一构造 `inputs.hxops_context`
- 继续透传 `query` / `files`
- 不再按 Agent 决定不同顶层输入变量名
建议实现一个统一构造函数:
```python
build_hxops_context(
*,
session_id: str,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
refs: list[dict[str, str]] | None = None,
) -> dict
```
输出:
```json
{
"schema_version": "1",
"session": {
"id": "..."
},
"request": {
"id": "...",
"trigger_source": "user_chat",
"locale": "zh-CN"
},
"refs": []
}
```
### 3.2 统一 `refs` 发现器
平台需要一个统一的“业务对象锚点发现器”。
建议实现:
```python
resolve_hxops_refs(
*,
request_data: dict | None = None,
session: object | None = None,
route_context: dict | None = None,
bound_context: dict | None = None,
) -> list[dict[str, str]]
```
职责:
- 收集当前显式上下文中的业务对象
- 收集当前会话绑定对象
- 收集入口页带入对象
- 做合法性过滤
- 转成统一 `refs` 结构
输出示例:
```json
[
{
"field": "task",
"value": "SN-20260623-AB12CD34"
},
{
"field": "batch",
"value": "BATCH-20260623-001"
}
]
```
### 3.3 Agent 适配层职责调整
现有各 Agent 的 `dify_inputs.py` 不应再负责“定义私有输入协议”,而应降级为:
- 帮助发现该 Agent 可识别的业务对象引用
- 补充 `refs`
- 最终仍统一回到平台级 `hxops_context`
也就是说,Agent 适配层职责从:
- “拼 Agent 专属 inputs”
改成:
- “发现 Agent 可提供的业务对象锚点”
### 3.4 与现有系统的兼容策略
建议三阶段兼容:
#### 阶段 1:并行注入
- 保留现有 Agent 私有 inputs
- 新增 `inputs.hxops_context`
- Dify 画布暂时同时兼容新旧两套协议
#### 阶段 2:画布切换
- Dify 画布优先读取 `hxops_context`
- 私有变量只作为兜底
#### 阶段 3:移除旧协议
- 删除旧私有输入变量拼装逻辑
- 平台统一只传 `hxops_context`
### 3.5 推荐后端改造项
建议明确拆成以下任务:
1. 新增 `build_hxops_context(...)`
2. 新增 `resolve_hxops_refs(...)`
3. 在统一 Dify 调用入口接入 `hxops_context`
4. 调整各 Agent `dify_inputs.py` 的职责
5. 增加注入日志,便于排障
---
## 4. Dify 画布端
### 4.1 Start 输入统一收口
画布不再要求平台按应用注入一堆私有变量。
Start 只依赖三类输入:
- `query`
- `files`
- `hxops_context`
### 4.2 上下文标准化节点
每套 Dify 画布建议在 Start 后增加一个 Code 节点:
节点职责:
- 读取 `hxops_context`
- 从 `refs` 中找自己关心的对象
- 输出画布内部统一变量
例如:
- `resolved_task_ref`
- `resolved_run_ref`
- `resolved_document_ref`
注意:
- 这是画布内部变量
- 不属于 HXOPS 对外注入协议
- 不同 Agent 可以选择性解析不同 `field`
### 4.3 画布统一路由原则
画布不再依赖输入变量直接决定主流程。
统一流程应为:
1. 读取 `hxops_context`
2. 解析对象锚点
3. 调状态查询 Tool
4. 按 Tool 返回路由
即:
- `hxops_context` 负责定位对象
- Tool 返回负责决定当前该做什么
### 4.4 画布必须允许 `refs` 为空
如果当前没有任何业务对象锚点,画布必须允许走兜底流程:
- 请用户指定任务号
- 请用户上传文件
- 请用户从工作台选择记录
不能假设:
- 每次都有 `task`
- 每次都有 `run`
- 每次都有 `document`
### 4.5 推荐画布结构
推荐统一结构:
1. Start
2. Code:normalize_hxops_context
3. Code:resolve_ref_by_field
4. Tool:get_*_status
5. Code:normalize_tool_status
6. IF:按 `checkpoint/stage/next_required_action/stop_agent_turn` 路由
7. Tool / Answer:执行动作或等待用户
### 4.6 推荐 Dify 画布改造项
建议统一补这些节点/规则:
1. `Code: normalize_hxops_context`
2. `Code: resolve_ref_by_field`
3. `Tool: get_*_status`
4. `Code: normalize_tool_status`
5. 主分支统一改为基于 Tool 状态路由
6. 缺少 `refs` 时的兜底 Answer
---
## 5. Tool 返回端
### 5.1 Tool 返回从“message 驱动”升级为“状态驱动”
当前很多画布分支依赖 `message` 文案理解流程。
要支撑平台化上下文注入,Tool 返回必须升级为结构化状态。
建议统一字段:
- `status`
- `checkpoint`
- `stage`
- `next_required_action`
- `allowed_tools`
- `forbidden_next_tools`
- `stop_agent_turn`
- `human_options`
- `display_message`
- `display_payload`
### 5.2 优先改造状态查询类 Tool
状态查询 Tool 是画布统一路由的入口,优先级最高。
推荐先统一:
- 货代的 `get_task_status`
- 文件检核的状态查询 Tool
- 其他 Agent 的主状态查询接口
### 5.3 动作 Tool 也要回标准状态
动作类 Tool 在执行完后,也应返回相同风格的状态结构。
例如:
- `parse_notice`
- `submit_decision`
- `apply_inventory_mapping`
- `match_inventory`
- `generate_excel`
- `upload_to_freight`
这样 Dify 画布执行动作后,不必再凭文案判断下一步。
### 5.4 推荐的最小返回结构
```json
{
"status": "ok",
"checkpoint": "parse_review",
"stage": "notice_parse",
"next_required_action": "confirm_parse",
"allowed_tools": ["submit_decision"],
"forbidden_next_tools": ["match_inventory"],
"stop_agent_turn": true,
"human_options": ["confirm", "reject", "reparse"],
"display_message": "当前任务解析完成,但需要人工确认。",
"display_payload": {}
}
```
### 5.5 Tool 返回端改造顺序
建议按以下顺序推进:
1. 状态查询 Tool 标准化
2. 关键动作 Tool 标准化
3. 错误结构标准化
4. `display_payload` 统一
5. `allowed_tools / stop_agent_turn` 补齐
---
## 6. 推荐实施顺序
### 阶段 1:协议铺底
- 后端新增 `hxops_context`
- 统一注入基础字段与 `refs`
- 画布开始读取 `hxops_context`
- 暂不删除旧协议
### 阶段 2:状态驱动画布
- Dify 画布改为“先查状态,再路由”
- 状态查询 Tool 补齐关键字段
- 动作 Tool 逐步返回标准状态
### 阶段 3:清理旧心智
- 移除 Agent 私有 Start 输入协议
- 移除画布对旧变量的依赖
- 平台仅保留 `query/files + hxops_context`
---
## 7. 一句话总结
HXOPS 统一上下文注入实现的核心是:
**后端统一注入 `hxops_context`,Dify 画布统一读取 `hxops_context` 定位对象并先查状态,所有运行态流程判断统一依赖后端 Tool 返回。**
+9 -465
View File
@@ -3,7 +3,7 @@
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。"
"description": "货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:通知理解、字段修订、库存映射建议、人工确认收口与状态查询;不包含由 hxops worker 统一续跑的主推进工具,也不包含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。"
},
"servers": [
{
@@ -11,132 +11,6 @@
}
],
"paths": {
"/tools/create_batch": {
"post": {
"operationId": "create_batch",
"summary": "创建发货批次 batch(一次多文件上传的聚合容器)",
"description": "创建发货批次 batch(一次多文件上传的聚合容器)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "已存在的批次编号(可选)。传入时将直接复用该批次。"
},
"user_id": {
"type": "integer",
"description": "Hxops 用户 ID(可选)"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID,便于工作台关联"
},
"file_count": {
"type": "integer",
"description": "本批通知文件数量"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/create_task": {
"post": {
"operationId": "create_task",
"summary": "创建发货任务 task(可挂到某个 batch)",
"description": "创建发货任务 task(可挂到某个 batch)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
},
"task_id": {
"type": "string",
"description": "已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"
},
"user_id": {
"type": "integer",
"description": "Hxops 用户 ID(可选)"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID,便于工作台关联"
},
"source_type": {
"type": "string",
"description": "来源:manual|email|wecom|pdf",
"enum": [
"manual",
"email",
"wecom",
"pdf"
]
},
"source_file_name": {
"type": "string",
"description": "原始通知文件名(多文件场景建议传)"
},
"source_file_type": {
"type": "string",
"description": "原始通知文件类型(多文件场景建议传)"
},
"batch_index": {
"type": "integer",
"description": "当前任务在批次中的顺序,从 1 开始"
},
"batch_total": {
"type": "integer",
"description": "当前批次总任务数"
},
"raw_content": {
"type": "string",
"description": "原始发货通知文本(可选,后续 parse 也可传入)"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/parse_notice": {
"post": {
"operationId": "parse_notice",
@@ -389,70 +263,11 @@
}
}
},
"/tools/parse_inventory": {
"post": {
"operationId": "parse_inventory",
"summary": "解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
"description": "解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"use_uploaded_file": {
"type": "string",
"description": "true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
"enum": [
"true",
"false"
]
},
"map_json": {
"type": "string",
"description": "可选,列映射 JSON 字符串,如 {\"sku\":\"AWS Sku\",\"available_qty\":\"Qty Available\"}"
},
"raw_inventory_text": {
"type": "string",
"description": "仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
},
"inventory_lines_json": {
"type": "string",
"description": "可选,已整理好的 JSON 数组字符串,如 [{\"sku\":\"A001\",\"available_qty\":10}]"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/get_inventory_schema_preview": {
"post": {
"operationId": "get_inventory_schema_preview",
"summary": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
"description": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
"summary": "读取已上传批次库存快照的表头与样例行(小 payload,供 LLM 推断列映射)",
"description": "读取已上传批次库存快照的表头与样例行(小 payload,供 LLM 推断列映射)",
"parameters": [],
"requestBody": {
"required": true,
@@ -490,8 +305,8 @@
"/tools/apply_inventory_mapping": {
"post": {
"operationId": "apply_inventory_mapping",
"summary": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
"description": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
"summary": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由 hxops worker 独立续跑",
"description": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由 hxops worker 独立续跑",
"parameters": [],
"requestBody": {
"required": true,
@@ -531,145 +346,11 @@
}
}
},
"/tools/ensure_inventory": {
"post": {
"operationId": "ensure_inventory",
"summary": "确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
"description": "确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"mode": {
"type": "string",
"description": "auto=自动/RPA;retry_rpa=重试 RPA",
"enum": [
"auto",
"retry_rpa"
]
},
"inventory_lines_json": {
"type": "string",
"description": "手工库存 JSON 数组字符串,如 [{\"sku\":\"A001\",\"available_qty\":10}]"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/auto_progress": {
"post": {
"operationId": "auto_progress",
"summary": "按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
"description": "按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID(可选,用于仅知道会话时定位任务)"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/match_inventory": {
"post": {
"operationId": "match_inventory",
"summary": "匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;未确认时调用会被拒绝并返回 forbidden_next_tools",
"description": "匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;未确认时调用会被拒绝并返回 forbidden_next_tools",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"inventory_lines_json": {
"type": "string",
"description": "可选,覆盖库存 JSON 数组后再匹配"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/submit_decision": {
"post": {
"operationId": "submit_decision",
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
"parameters": [],
"requestBody": {
"required": true,
@@ -688,11 +369,12 @@
},
"decision": {
"type": "string",
"description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
"description": "confirm=确认继续;reject=驳回;retry_rpa=重试 RPA 库存导出;rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
"enum": [
"confirm",
"confirm_parse",
"reject",
"retry_rpa",
"rematch",
"reparse",
"confirm_inventory_mapping",
@@ -726,97 +408,6 @@
}
}
},
"/tools/generate_shipment_excel": {
"post": {
"operationId": "generate_shipment_excel",
"summary": "生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
"description": "生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/upload_to_freight": {
"post": {
"operationId": "upload_to_freight",
"summary": "上传 Excel 到货代系统(RPA 或手工确认)",
"description": "上传 Excel 到货代系统(RPA 或手工确认)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"mode": {
"type": "string",
"description": "auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
"enum": [
"auto",
"retry_upload",
"manual_confirm"
]
},
"freight_ref_no": {
"type": "string",
"description": "货代系统单号(可选;manual_confirm 通常无需填写)"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/get_task_status": {
"post": {
"operationId": "get_task_status",
@@ -895,53 +486,6 @@
}
}
}
},
"/tools/switch_focus_task": {
"post": {
"operationId": "switch_focus_task",
"summary": "切换当前批次的聚焦任务",
"description": "切换当前批次的聚焦任务",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
},
"task_no": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"target_task_no": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
"batch_no"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
}
}
}
+1453 -2442
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -18,6 +18,13 @@
- Chatflow 编排见 **[docs/file_check.md](file_check.md)**(第二部分);OpenAPI 见 **[docs/openapi/file_check_tools_openapi.json](openapi/file_check_tools_openapi.json)**(`python backend/scripts/export_file_check_openapi.py`)。
- 复用知识库清洗与 Dify 同步链路,将检核报告 Excel 入库。
### 2.x 货代发货通知批次库存能力
- 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。
- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。
### 2.1 已有聊天路由能力
- 后端 `chat` 接口已支持按意图分流
@@ -4,6 +4,8 @@
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。
*/
import i18n from '@/i18n';
/**
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
*/
@@ -16,17 +18,29 @@ export function buildShippingInventoryUploadPrompt(
&& (result.data as { field_alignment?: unknown }).field_alignment
&& typeof (result.data as { field_alignment?: unknown }).field_alignment === 'object');
const suggestOk = Boolean((result?.data as { suggest_ok?: boolean } | undefined)?.suggest_ok);
const prefix = fileName ? `我已上传库存文件《${fileName}》` : '我已上传库存文件';
const batchNo = String(
(result?.batch_no as string | undefined)
|| ((result?.data as { batch_no?: string } | undefined)?.batch_no)
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const prefix = batchNo
? (fileName
? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatchWithFile', { fileName, batchNo }))
: String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatch', { batchNo })))
: (fileName
? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixWithFile', { fileName }))
: String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefix')));
if (checkpoint === 'map_infer') {
if (suggestOk) {
return `${prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferSuggested', { prefix }));
}
return `${prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferPending', { prefix }));
}
if (checkpoint === 'align_review' || hasAlignment) {
return `${prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.alignReview', { prefix }));
}
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.default', { prefix }));
}
/**
@@ -54,16 +68,29 @@ export function buildShippingNoticeUploadPrompt(
: [];
const fileCount = Number(options?.fileCount || 0);
const fileLabel = options?.fileName
? `《${options.fileName}》`
: (fileCount > 1 ? `${fileCount} 份发货通知` : '发货通知');
const parts = [`我已上传${fileLabel}`];
if (batchNo) parts.push(`批次 ${batchNo}`);
if (taskId) parts.push(`当前任务 ${taskId}`);
if (fileCount > 1 || taskIds.length > 1) {
const taskListText = taskIds.length ? `任务列表:${taskIds.join('、')}。` : '';
return `${parts.join(',')}。${taskListText}请立即开始整批处理,不要只处理当前任务。先调用 get_batch_status 查看整批状态,再按批次顺序逐票处理:必要时调用 switch_focus_task 切到对应任务,然后读取该任务 raw_text,用 LLM 抽取结构化字段并调用 parse_notice(structured=...) 落库;若抽取失败可仅传 task_id 让后端用 raw_text 兜底。每处理完一票,都继续切到下一票,直到本批每一票都进入各自下一阶段(待确认、待上传库存、自动推进中的任一状态)。禁止再次询问我“是否开始解析”或只停在第一票。`;
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelSingleFile', { fileName: options.fileName }))
: (fileCount > 1
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelMulti', { fileCount }))
: String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelDefault')));
const parts = [String(i18n.global.t('chat.shippingNoticePrompt.notice.uploadedPrefix', { fileLabel }))];
if (batchNo) {
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.batchLabel', { batchNo })));
}
return `${parts.join(',')}。请立即读取任务 raw_text,用 LLM 抽取结构化字段后直接调用 parse_notice(structured=...) 落库;若抽取失败可仅传 raw_text 走后端规则兜底。禁止再次询问我“是否开始解析”或“是否现在开始解析”。解析完成后,请直接展示解析结果供我确认。`;
if (taskId) {
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.taskLabel', { taskId })));
}
if (fileCount > 1 || taskIds.length > 1) {
const taskListText = taskIds.length
? String(i18n.global.t('chat.shippingNoticePrompt.notice.taskList', { taskIds: taskIds.join('、') }))
: '';
return String(i18n.global.t('chat.shippingNoticePrompt.notice.multiTask', {
summary: parts.join(','),
taskListText,
}));
}
return String(i18n.global.t('chat.shippingNoticePrompt.notice.singleTask', {
summary: parts.join(','),
}));
}
/**
@@ -48,9 +48,6 @@ export interface ShippingUploadHandlerContext {
* @returns 自动上传、文件选择器和建议提示相关处理函数
*/
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
const hasMultipleShippingBatchTasks = () =>
Array.isArray(ctx.shippingBatchTasks.value) && ctx.shippingBatchTasks.value.length > 1;
const resetInventoryTaskSelection = () => {
ctx.shippingInventorySelectionActive.value = false;
ctx.shippingInventorySelectionTaskId.value = '';
@@ -76,22 +73,14 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const uploadInventoryForTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
const result = await uploadWorkspaceShippingInventory(taskId, file);
const batchNo = String(
((result as unknown as { data?: { batch_no?: string } }).data?.batch_no)
|| ((result as unknown as { data?: { batch?: { batch_no?: string } } }).data?.batch?.batch_no)
|| '',
).trim();
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
};
const promptInventoryTaskSelection = async (pendingFile?: File) => {
if (pendingFile) ctx.pendingShippingInventoryFile.value = pendingFile;
ctx.shippingBatchTasksExpanded.value = true;
ctx.pendingShippingUploadTaskId.value = '';
ctx.shippingInventorySelectionTaskId.value = '';
ctx.shippingInventorySelectionActive.value = true;
await ctx.pushShippingLocalAssistantMessage(
ctx.t(
pendingFile
? 'chat.shippingNoticeUi.inventoryTaskPickPendingHint'
: 'chat.shippingNoticeUi.inventoryTaskPickHint',
),
);
void ctx.refreshShippingActions();
};
const selectShippingInventoryUploadTask = (taskId: string): boolean => {
@@ -148,16 +137,13 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const handleShippingAutoUploadFile = async (file: File) => {
const kind = classifyShippingUploadFile(file, extractExt);
if (kind === 'inventory') {
if (hasMultipleShippingBatchTasks()) {
await promptInventoryTaskSelection(file);
return;
}
let taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
const created = await createWorkspaceShippingTask({
source_type: 'manual',
conversation_id: String(ctx.conversationId.value || '').trim() || undefined,
});
syncBatchContextFromNoticeResponse(created as unknown as Record<string, unknown>);
taskId = String(created.task_id || '').trim();
if (!taskId) {
ctx.msg.warning('自动创建发货任务失败');
@@ -250,10 +236,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
};
const openShippingInventoryPicker = (): boolean => {
if (hasMultipleShippingBatchTasks()) {
void promptInventoryTaskSelection();
return true;
}
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
+32 -9
View File
@@ -22,6 +22,29 @@
"shippingNoticeUploadFailed": "Inventory upload failed.",
"shippingNoticePasteHint": "Paste inventory rows in the input box, then send.",
"shippingNoticeDecisionDone": "Action completed.",
"shippingNoticePrompt": {
"inventory": {
"prefix": "I have uploaded the inventory file",
"prefixWithFile": "I have uploaded the inventory file \"{fileName}\"",
"prefixBatch": "I have uploaded the batch inventory snapshot for batch {batchNo}",
"prefixBatchWithFile": "I have uploaded the batch inventory snapshot \"{fileName}\" for batch {batchNo}",
"mapInferSuggested": "{prefix}. Please continue the inventory column mapping. If the system has already identified a complete mapping, apply it directly and show me the field alignment result for confirmation.",
"mapInferPending": "{prefix}. Please continue parsing the inventory column mapping, and after a usable mapping is available, show me the field alignment result for confirmation.",
"alignReview": "{prefix}. Please show the inventory field alignment result and guide me to confirm or correct the mapping.",
"default": "{prefix}. Please continue the inventory import and tell me the next step."
},
"notice": {
"fileLabelSingleFile": "\"{fileName}\"",
"fileLabelMulti": "{fileCount} shipping notices",
"fileLabelDefault": "the shipping notice",
"uploadedPrefix": "I have uploaded {fileLabel}",
"batchLabel": "batch {batchNo}",
"taskLabel": "current task {taskId}",
"taskList": "Task list: {taskIds}.",
"multiTask": "{summary}. {taskListText}Please only handle the current focus task. First call get_task_status to read the current task status; if the current task is still pending parsing, read raw_text, use the LLM to extract structured fields, then call parse_notice(structured=...) to persist them. If the task is already in a later step, directly explain the current status and guide me on the next step for this task. Do not ask me again whether parsing should start, and do not loop through other tasks in the batch.",
"singleTask": "{summary}. Please first call get_task_status to read the current task status; if the current task is still pending parsing, read raw_text, use the LLM to extract structured fields, and directly call parse_notice(structured=...) to persist them. If the task is already in a later step, directly explain the current status and guide me on the next step. Do not ask me again whether parsing should start now."
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "Inventory headers",
"headerRow": "Header row: {row}",
@@ -70,7 +93,7 @@
"inventoryAvailable": "Inventory available",
"shortageQty": "Shortage",
"statusLabel": "Status",
"shortageBanner": "Inventory shortage exists. Do not continue to freight upload yet. Resolve the shortage first, or use the available actions to confirm partial shipment / retry matching.",
"shortageBanner": "Inventory shortage exists. Do not continue to freight upload yet. Resolve the shortage first, or use the available actions to retry matching / revise the input.",
"shortageDetails": "Shortage details",
"shortageRowDetail": "Line {index}: Reservation ID {reservationId}, SKU {sku}, shortage {shortage}",
"availableActions": "Available actions",
@@ -100,13 +123,13 @@
"nextTask": "Next",
"collapseTasks": "Hide tasks",
"viewTasks": "View tasks",
"inventoryTaskPickTitle": "Select inventory target task",
"inventoryTaskPickHint": "This batch contains multiple tasks. To avoid cross-task mistakes, choose which task this inventory belongs to before uploading.",
"inventoryTaskPickPendingHint": "This batch contains multiple tasks. To avoid cross-task mistakes, select the target task first and the pending inventory file will continue uploading after selection.",
"inventoryTaskPickTitle": "Batch inventory snapshot",
"inventoryTaskPickHint": "This batch contains multiple tasks. The inventory file will be uploaded as one batch snapshot, then each task matches independently.",
"inventoryTaskPickPendingHint": "This batch contains multiple tasks. The pending inventory file will be uploaded as one batch snapshot, then each task matches independently.",
"cancelInventoryTaskPick": "Cancel",
"uploadInventoryToTask": "Upload to this task",
"inventoryTargetTask": "Inventory target {taskId}",
"inventoryTargetIdle": "Waiting for target selection",
"uploadInventoryToTask": "Upload batch inventory",
"inventoryTargetTask": "Batch inventory entry {taskId}",
"inventoryTargetIdle": "Waiting for batch inventory",
"fileCount": "Files",
"runningCount": "Running",
"completedCount": "Completed",
@@ -141,13 +164,13 @@
},
"matchStatus": {
"fulfillable": "Fully fulfillable",
"partial": "Partially fulfillable",
"partial": "Shortage exists",
"unfulfillable": "Unfulfillable",
"pending": "Pending match"
},
"rowStatus": {
"ok": "Enough",
"partial": "Partial",
"partial": "Shortage",
"shortage": "Shortage"
},
"stepper": {
+32 -9
View File
@@ -22,6 +22,29 @@
"shippingNoticeUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
"shippingNoticePasteHint": "วางข้อมูลสต็อกในช่องข้อความแล้วส่ง",
"shippingNoticeDecisionDone": "ดำเนินการเสร็จแล้ว",
"shippingNoticePrompt": {
"inventory": {
"prefix": "ฉันได้อัปโหลดไฟล์สต็อกแล้ว",
"prefixWithFile": "ฉันได้อัปโหลดไฟล์สต็อก \"{fileName}\" แล้ว",
"prefixBatch": "ฉันได้อัปโหลดสแนปช็อตสต็อกของชุดงาน {batchNo} แล้ว",
"prefixBatchWithFile": "ฉันได้อัปโหลดสแนปช็อตสต็อก \"{fileName}\" ของชุดงาน {batchNo} แล้ว",
"mapInferSuggested": "{prefix} กรุณาดำเนินการจับคู่คอลัมน์สต็อกต่อ หากระบบรู้จักการจับคู่ครบแล้ว ให้ใช้การจับคู่นั้นได้ทันทีและแสดงผลการจัดแนวฟิลด์ให้ฉันยืนยัน",
"mapInferPending": "{prefix} กรุณาแยกการจับคู่คอลัมน์สต็อกต่อ และเมื่อได้การจับคู่ที่ใช้ได้แล้ว ให้แสดงผลการจัดแนวฟิลด์ให้ฉันยืนยัน",
"alignReview": "{prefix} กรุณาแสดงผลการจัดแนวฟิลด์สต็อก และแนะนำให้ฉันยืนยันหรือแก้ไขการจับคู่",
"default": "{prefix} กรุณาดำเนินการนำเข้าสต็อกต่อ และบอกฉันว่าขั้นตอนถัดไปคืออะไร"
},
"notice": {
"fileLabelSingleFile": "\"{fileName}\"",
"fileLabelMulti": "ใบแจ้งจัดส่ง {fileCount} ฉบับ",
"fileLabelDefault": "ใบแจ้งจัดส่ง",
"uploadedPrefix": "ฉันได้อัปโหลด{fileLabel}แล้ว",
"batchLabel": "ชุดงาน {batchNo}",
"taskLabel": "งานปัจจุบัน {taskId}",
"taskList": "รายการงาน: {taskIds}",
"multiTask": "{summary} {taskListText}กรุณาจัดการเฉพาะงานที่โฟกัสอยู่ในขณะนี้ก่อน เรียก get_task_status เพื่ออ่านสถานะงานปัจจุบันก่อน หากงานปัจจุบันยังรอการแยกข้อมูล ให้读取 raw_text ใช้ LLM แยกฟิลด์แบบมีโครงสร้าง แล้วเรียก parse_notice(structured=...) เพื่อบันทึก หากงานเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปสถานะปัจจุบันและแนะนำขั้นตอนถัดไปของงานนี้โดยตรง ห้ามถามฉันซ้ำว่าจะเริ่มแยกข้อมูลหรือไม่ และไม่ต้องวนประมวลผลงานอื่นทั้งชุด",
"singleTask": "{summary} กรุณาเรียก get_task_status เพื่ออ่านสถานะงานปัจจุบันก่อน หากงานปัจจุบันยังรอการแยกข้อมูล ให้读取 raw_text ใช้ LLM แยกฟิลด์แบบมีโครงสร้าง แล้วเรียก parse_notice(structured=...) โดยตรงเพื่อบันทึก หากงานเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปสถานะปัจจุบันและแนะนำขั้นตอนถัดไปโดยตรง ห้ามถามฉันซ้ำว่าจะเริ่มแยกข้อมูลตอนนี้หรือไม่"
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "หัวคอลัมน์สต็อก",
"headerRow": "แถวหัวตาราง: {row}",
@@ -70,7 +93,7 @@
"inventoryAvailable": "สต็อกที่ใช้ได้",
"shortageQty": "จำนวนที่ขาด",
"statusLabel": "สถานะ",
"shortageBanner": "มีสต็อกขาดอยู่ จึงยังไม่ควรอัปโหลดไปยังผู้ให้บริการขนส่งต่อ กรุณาจัดการส่วนที่ขาดก่อน หรือใช้ปุ่มที่มีให้เพื่อยืนยันการส่งบางส่วน / จับคู่ใหม่",
"shortageBanner": "มีสต็อกขาดอยู่ จึงยังไม่ควรอัปโหลดไปยังผู้ให้บริการขนส่งต่อ กรุณาจัดการส่วนที่ขาดก่อน หรือใช้ปุ่มที่มีให้เพื่อจับคู่ใหม่ / กลับไปแก้ไขข้อมูล",
"shortageDetails": "รายละเอียดส่วนขาด",
"shortageRowDetail": "แถว {index}: Reservation ID {reservationId}, SKU {sku}, ขาด {shortage}",
"availableActions": "การทำงานที่ใช้ได้",
@@ -100,13 +123,13 @@
"nextTask": "ถัดไป",
"collapseTasks": "ซ่อนงาน",
"viewTasks": "ดูงาน",
"inventoryTaskPickTitle": "เลือกงานเป้าหมายของสต็อก",
"inventoryTaskPickHint": "ชุดงานนี้มีหลายงาน เพื่อป้องกันการอัปโหลดผิดงาน โปรดเลือกก่อนว่าสต็อกนี้เป็นของงานใด",
"inventoryTaskPickPendingHint": "ชุดงานนี้มีหลายงาน เพื่อป้องกันการอัปโหลดผิดงาน โปรดเลือกงานเป้าหมายก่อน แล้วระบบจะอัปโหลดไฟล์สต็อกที่เพิ่งเลือกต่อให้",
"inventoryTaskPickTitle": "สแนปช็อตสต็อกของชุดงาน",
"inventoryTaskPickHint": "ชุดงานนี้มีหลายงาน ไฟล์สต็อกจะถูกอัปโหลดเป็นสแนปช็อตเดียวของชุดงาน แล้วแต่ละงานจะจับคู่แยกกัน",
"inventoryTaskPickPendingHint": "ชุดงานนี้มีหลายงาน ไฟล์สต็อกที่รออยู่จะถูกอัปโหลดเป็นสแนปช็อตเดียวของชุดงาน แล้วแต่ละงานจะจับคู่แยกกัน",
"cancelInventoryTaskPick": "ยกเลิก",
"uploadInventoryToTask": "อัปโหลดไปงานนี้",
"inventoryTargetTask": "เป้าหมายสต็อก {taskId}",
"inventoryTargetIdle": "รอเลือกงานเป้าหมาย",
"uploadInventoryToTask": "อัปโหลดสต็อกชุดงาน",
"inventoryTargetTask": "ทางเข้าสต็อกชุดงาน {taskId}",
"inventoryTargetIdle": "รอสต็อกของชุดงาน",
"fileCount": "จำนวนไฟล์",
"runningCount": "กำลังดำเนินการ",
"completedCount": "เสร็จแล้ว",
@@ -141,13 +164,13 @@
},
"matchStatus": {
"fulfillable": "จัดส่งได้ครบ",
"partial": "จัดส่งได้บางส่วน",
"partial": "มีสต็อกขาด",
"unfulfillable": "จัดส่งไม่ได้",
"pending": "รอจับคู่"
},
"rowStatus": {
"ok": "เพียงพอ",
"partial": "บางส่วน",
"partial": "ขาด",
"shortage": "ขาด"
},
"stepper": {
+34 -9
View File
@@ -22,6 +22,31 @@
"shippingNoticeUploadFailed": "库存文件上传失败。",
"shippingNoticePasteHint": "请在输入框粘贴库存小表内容后发送。",
"shippingNoticeDecisionDone": "操作已完成。",
"shippingNoticePrompt": {
"inventory": {
"prefix": "我已上传库存文件",
"prefixWithFile": "我已上传库存文件《{fileName}》",
"prefixBatch": "我已为批次 {batchNo} 上传本批库存快照",
"prefixBatchWithFile": "我已为批次 {batchNo} 上传本批库存快照《{fileName}》",
"mapInferSuggested": "{prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。",
"mapInferPending": "{prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。",
"alignReview": "{prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。",
"default": "{prefix}。请继续处理库存导入,并告诉我下一步。"
},
"notice": {
"fileLabelSingleFile": "《{fileName}》",
"fileLabelMulti": "{fileCount} 份发货通知",
"fileLabelDefault": "发货通知",
"uploadedPrefix": "我已上传{fileLabel}",
"batchLabel": "批次 {batchNo}",
"taskLabel": "当前任务 {taskId}",
"taskList": "任务列表:{taskIds}。",
"autoInventoryAction": "上传库存并进入字段对齐",
"autoNoticeAction": "解析发货通知并创建任务",
"multiTask": "{summary}。{taskListText}请只处理当前焦点任务。先调用 get_task_status 读取当前任务状态;如果当前任务仍待解析,请读取 raw_text,用 LLM 抽取结构化字段后调用 parse_notice(structured=...) 落库;如果已经进入后续步骤,请直接解释当前状态并给出本任务下一步引导。禁止再次询问我“是否开始解析”,也不要整批循环处理其他任务。",
"singleTask": "{summary}。请先调用 get_task_status 读取当前任务状态;如果当前任务仍待解析,请读取 raw_text,用 LLM 抽取结构化字段后直接调用 parse_notice(structured=...) 落库;若已进入后续步骤,请直接解释当前状态并给出下一步引导。禁止再次询问我“是否开始解析”或“是否现在开始解析”。"
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "库存表头",
"headerRow": "表头行:{row}",
@@ -70,7 +95,7 @@
"inventoryAvailable": "库存可用",
"shortageQty": "缺口",
"statusLabel": "状态",
"shortageBanner": "存在库存缺口,当前不能直接继续上传货代。请先处理缺口,或按可用按钮确认部分发货 / 重新匹配。",
"shortageBanner": "存在库存缺口,当前不能继续上传货代。请先处理缺口,或按可用按钮重新匹配 / 返回修订。",
"shortageDetails": "缺口明细",
"shortageRowDetail": "第 {index} 行:预订单号 {reservationId},料号 {sku},缺口 {shortage}",
"availableActions": "可用操作",
@@ -104,13 +129,13 @@
"nextTask": "下一票",
"collapseTasks": "收起任务",
"viewTasks": "查看任务",
"inventoryTaskPickTitle": "请选择库存归属任务",
"inventoryTaskPickHint": "当前批次包含多票。为避免串单,请先明确选择库存要上传到哪一票。",
"inventoryTaskPickPendingHint": "当前批次包含多票。为避免串单,请先选择库存归属任务,系统会在选定后继续上传刚才的库存文件。",
"inventoryTaskPickTitle": "本批库存快照",
"inventoryTaskPickHint": "当前批次包含多票。库存文件将作为本批统一快照,后续每票独立匹配。",
"inventoryTaskPickPendingHint": "当前批次包含多票。系统会把刚才的库存文件作为本批统一快照上传,并由每票独立匹配。",
"cancelInventoryTaskPick": "取消选择",
"uploadInventoryToTask": "上传库存到此票",
"inventoryTargetTask": "库存目标 {taskId}",
"inventoryTargetIdle": "等待选择库存目标",
"uploadInventoryToTask": "上传为本批库存",
"inventoryTargetTask": "本批库存入口 {taskId}",
"inventoryTargetIdle": "等待上传本批库存",
"fileCount": "文件数",
"runningCount": "处理中",
"completedCount": "已完成",
@@ -145,13 +170,13 @@
},
"matchStatus": {
"fulfillable": "可全部发货",
"partial": "部分满足",
"partial": "存在缺口",
"unfulfillable": "无法满足",
"pending": "待匹配"
},
"rowStatus": {
"ok": "充足",
"partial": "部分满足",
"partial": "缺口",
"shortage": "缺口"
},
"stepper": {
+34 -9
View File
@@ -22,6 +22,31 @@
"shippingNoticeUploadFailed": "庫存檔案上傳失敗。",
"shippingNoticePasteHint": "請在輸入框貼上庫存小表內容後送出。",
"shippingNoticeDecisionDone": "操作已完成。",
"shippingNoticePrompt": {
"inventory": {
"prefix": "我已上傳庫存檔案",
"prefixWithFile": "我已上傳庫存檔案《{fileName}》",
"prefixBatch": "我已為批次 {batchNo} 上傳本批庫存快照",
"prefixBatchWithFile": "我已為批次 {batchNo} 上傳本批庫存快照《{fileName}》",
"mapInferSuggested": "{prefix}。請繼續處理庫存欄位映射;如果系統已辨識出完整映射,請直接套用映射,並展示欄位對齊結果給我確認。",
"mapInferPending": "{prefix}。請繼續解析庫存欄位映射,並在取得可用映射後展示欄位對齊結果給我確認。",
"alignReview": "{prefix}。請展示庫存欄位對齊結果,並引導我確認或更正映射。",
"default": "{prefix}。請繼續處理庫存匯入,並告訴我下一步。"
},
"notice": {
"fileLabelSingleFile": "《{fileName}》",
"fileLabelMulti": "{fileCount} 份發貨通知",
"fileLabelDefault": "發貨通知",
"uploadedPrefix": "我已上傳{fileLabel}",
"batchLabel": "批次 {batchNo}",
"taskLabel": "當前任務 {taskId}",
"taskList": "任務列表:{taskIds}。",
"autoInventoryAction": "上傳庫存並進入欄位對齊",
"autoNoticeAction": "解析發貨通知並建立任務",
"multiTask": "{summary}。{taskListText}請只處理目前焦點任務。先呼叫 get_task_status 讀取目前任務狀態;如果目前任務仍待解析,請讀取 raw_text,用 LLM 抽取結構化欄位後呼叫 parse_notice(structured=...) 落庫;如果已進入後續步驟,請直接說明目前狀態並給出本任務下一步引導。禁止再次詢問我「是否開始解析」,也不要整批迴圈處理其他任務。",
"singleTask": "{summary}。請先呼叫 get_task_status 讀取目前任務狀態;如果目前任務仍待解析,請讀取 raw_text,用 LLM 抽取結構化欄位後直接呼叫 parse_notice(structured=...) 落庫;若已進入後續步驟,請直接說明目前狀態並給出下一步引導。禁止再次詢問我「是否開始解析」或「是否現在開始解析」。"
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "庫存表頭",
"headerRow": "表頭列:{row}",
@@ -70,7 +95,7 @@
"inventoryAvailable": "庫存可用",
"shortageQty": "缺口",
"statusLabel": "狀態",
"shortageBanner": "存在庫存缺口,目前不能直接繼續上傳貨代。請先處理缺口,或依可用按鈕確認部分發貨 / 重新匹配。",
"shortageBanner": "存在庫存缺口,目前不能繼續上傳貨代。請先處理缺口,或依可用按鈕重新匹配 / 返回修訂。",
"shortageDetails": "缺口明細",
"shortageRowDetail": "第 {index} 行:預訂單號 {reservationId},料號 {sku},缺口 {shortage}",
"availableActions": "可用操作",
@@ -100,13 +125,13 @@
"nextTask": "下一票",
"collapseTasks": "收起任務",
"viewTasks": "查看任務",
"inventoryTaskPickTitle": "請選擇庫存歸屬任務",
"inventoryTaskPickHint": "當前批次包含多票。為避免串單,請先明確選擇庫存要上傳到哪一票。",
"inventoryTaskPickPendingHint": "當前批次包含多票。為避免串單,請先選擇庫存歸屬任務,系統會在選定後繼續上傳剛才的庫存檔案。",
"inventoryTaskPickTitle": "本批庫存快照",
"inventoryTaskPickHint": "當前批次包含多票。庫存檔案將作為本批統一快照,後續每票獨立匹配。",
"inventoryTaskPickPendingHint": "當前批次包含多票。系統會把剛才的庫存檔案作為本批統一快照上傳,並由每票獨立匹配。",
"cancelInventoryTaskPick": "取消選擇",
"uploadInventoryToTask": "上傳庫存到此票",
"inventoryTargetTask": "庫存目標 {taskId}",
"inventoryTargetIdle": "等待選擇庫存目標",
"uploadInventoryToTask": "上傳為本批庫存",
"inventoryTargetTask": "本批庫存入口 {taskId}",
"inventoryTargetIdle": "等待上傳本批庫存",
"fileCount": "檔案數",
"runningCount": "處理中",
"completedCount": "已完成",
@@ -141,13 +166,13 @@
},
"matchStatus": {
"fulfillable": "可全部發貨",
"partial": "部分滿足",
"partial": "存在缺口",
"unfulfillable": "無法滿足",
"pending": "待匹配"
},
"rowStatus": {
"ok": "充足",
"partial": "部分滿足",
"partial": "缺口",
"shortage": "缺口"
},
"stepper": {