feat(rpa): 实现库存源路由与 RPA Driver 方案
- 添加库存源解析逻辑,根据发货通知目的地解析 RPA 源 - 实现 DSV 360 和 Crane FootPrint 的库存源配置 - 增加自动登录功能,优化浏览器操作 - 更新本地启动脚本,支持跳过 Worker 启动 - 添加后端测试,验证库存源解析与任务取消逻辑 - 编写文档,描述库存源路由与 RPA Driver 方案
This commit is contained in:
commit
1921959fc1
61 files changed
+2347
-473
No files matched your search
@@ -12,10 +12,11 @@ import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import exists
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob
|
||||
|
||||
logger = logging.getLogger('kb-worker')
|
||||
_WORD_EXTENSIONS = {'doc', 'docx'}
|
||||
@@ -144,9 +145,22 @@ def claim_next_kb_job() -> KbJob | None:
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
has_running_word_job = _has_running_word_clean_job()
|
||||
missing_version = exists().where(
|
||||
KbDocumentVersion.id == KbJob.document_version_id,
|
||||
)
|
||||
deleted_document = exists().where(
|
||||
KbDocumentVersion.id == KbJob.document_version_id,
|
||||
KbDocument.id == KbDocumentVersion.document_id,
|
||||
KbDocument.is_deleted.is_(True),
|
||||
)
|
||||
candidates = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
|
||||
.filter(
|
||||
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
|
||||
KbJob.status == 'queued',
|
||||
(KbJob.document_version_id.is_(None)) | missing_version,
|
||||
(KbJob.document_version_id.is_(None)) | (~deleted_document),
|
||||
)
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.limit(20)
|
||||
|
||||
@@ -38,6 +38,7 @@ CP_READY_MATCH = "ready_to_match"
|
||||
CP_READY_EXPORT = "ready_to_export"
|
||||
CP_EXPORT_READY = "export_ready"
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
|
||||
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
|
||||
CP_EXPORT_GENERATED = "export_generated"
|
||||
CP_UPLOADED = "uploaded"
|
||||
CP_COMPLETED = "completed"
|
||||
@@ -59,6 +60,7 @@ PH_SHORTAGE = "shortage"
|
||||
PH_RPA_EXHAUSTED = "rpa_exhausted"
|
||||
PH_RPA_PENDING = "rpa_pending"
|
||||
PH_INV_UNAVAIL = "inv_unavail"
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
|
||||
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
|
||||
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
|
||||
@@ -14,8 +14,15 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
mark_inventory_source_review,
|
||||
resolve_inventory_source,
|
||||
save_task_rpa_inventory_source,
|
||||
task_rpa_inventory_source,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
|
||||
from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task_for_tool,
|
||||
@@ -113,11 +120,97 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works
|
||||
return ensure_inventory_via_rpa(task, mode="auto")
|
||||
|
||||
|
||||
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
确认当前任务的库存 RPA 来源,并继续触发库存导出。
|
||||
【AI 触发时机】:当用户在库存源确认检查点选择一个 source_code 后调用;禁止用自然语言中的任意 URL 直接写入。
|
||||
"""
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
source_code = str(payload.get("source_code") or "").strip().upper()
|
||||
source = build_rpa_inventory_source(source_code)
|
||||
if not source:
|
||||
return tool_response(status="failed", task=task, message="库存源不存在或未启用")
|
||||
|
||||
save_task_rpa_inventory_source(task, source)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": source.get("source_code"),
|
||||
"source_type": source.get("source_type"),
|
||||
"confirmed_by": "user",
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
return ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto"))
|
||||
|
||||
|
||||
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
|
||||
# [STEP 0] 库存 RPA 必须先确定唯一库存源;Dify 只给目的地线索,HXOPS 规则负责最终裁决。
|
||||
rpa_source = task_rpa_inventory_source(task)
|
||||
if not rpa_source:
|
||||
resolution = resolve_inventory_source(task)
|
||||
if resolution.status == "resolved" and resolution.source:
|
||||
rpa_source = resolution.source
|
||||
save_task_rpa_inventory_source(task, rpa_source, resolution=resolution)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_resolved",
|
||||
{
|
||||
"source_code": rpa_source.get("source_code"),
|
||||
"source_type": rpa_source.get("source_type"),
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
else:
|
||||
mark_inventory_source_review(task, resolution)
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
task.error_message = "无法根据发货通知唯一确定库存查询来源"
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="库存查询来源待确认",
|
||||
progress_percent=30,
|
||||
current=len(resolution.candidates),
|
||||
total=len(resolution.candidates),
|
||||
detail="请确认本票应使用哪个 RPA 库存来源后继续。",
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_review_required",
|
||||
{
|
||||
"status": resolution.status,
|
||||
"reason": resolution.reason,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"candidate_source_codes": [item.get("source_code") for item in resolution.candidates],
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="无法根据发货通知唯一确定库存查询来源,请选择库存源后继续 RPA 获取库存。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_source_candidates": resolution.candidates,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
|
||||
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
|
||||
timeout_seconds = rpa_inventory_timeout_seconds()
|
||||
@@ -202,7 +295,14 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
attempt_no = attempts + 1
|
||||
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
|
||||
trigger = write_inventory_export_trigger(
|
||||
task.task_no,
|
||||
{
|
||||
"mode": mode,
|
||||
"attempt": attempt_no,
|
||||
"rpa_inventory_source": rpa_source,
|
||||
},
|
||||
)
|
||||
if trigger:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。
|
||||
依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。
|
||||
逻辑:Dify 只提供候选字段;本模块负责标准化、规则命中、唯一性判断和写入任务上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
|
||||
|
||||
|
||||
ROUTE_RULES: tuple[dict[str, Any], ...] = (
|
||||
{"source_code": "DSV360_AWSBI", "aliases": ("BISON", "AWSBI")},
|
||||
{"source_code": "DSV360_AWSCV", "aliases": ("CINCINNATI", "CVG", "AWSCV")},
|
||||
{"source_code": "DSV360_AWSDU", "aliases": ("DUB", "DUBLIN")},
|
||||
{"source_code": "DSV360_AWSAMS", "aliases": ("MOERDIJK", "AMS", "AWSAMS")},
|
||||
{"source_code": "DSV360_AWSSL", "aliases": ("USLCK", "SALT LAKE CITY", "SALTLAKECITY")},
|
||||
{"source_code": "DSV360_AWSSG", "aliases": ("SINGAPORE", "SG")},
|
||||
{"source_code": "CRANE_TZR2", "aliases": ("TZR2", "THAILAND")},
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventorySourceResolution:
|
||||
"""库存源解析结果。"""
|
||||
|
||||
status: str
|
||||
source: dict[str, Any] | None
|
||||
candidates: list[dict[str, Any]]
|
||||
destination_candidates: list[str]
|
||||
reason: str = ""
|
||||
|
||||
|
||||
def normalize_destination(value: Any) -> str:
|
||||
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
|
||||
|
||||
|
||||
def _append_candidate(candidates: list[str], value: Any) -> None:
|
||||
text = normalize_destination(value)
|
||||
if text and text not in candidates:
|
||||
candidates.append(text)
|
||||
|
||||
|
||||
def _extract_destination_object(candidates: list[str], value: Any) -> None:
|
||||
if not isinstance(value, dict):
|
||||
_append_candidate(candidates, value)
|
||||
return
|
||||
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text"):
|
||||
_append_candidate(candidates, value.get(key))
|
||||
|
||||
|
||||
def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
从任务解析结果提取目的地/港口/仓库候选。
|
||||
【AI 触发时机】:需要根据发货通知判断库存 RPA 源时调用,Dify 输出与后端字段都作为候选证据。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
for item in payload.get("destination_candidates") or []:
|
||||
_append_candidate(candidates, item)
|
||||
_extract_destination_object(candidates, payload.get("destination"))
|
||||
_append_candidate(candidates, task.ship_to)
|
||||
for line in task.lines_json or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
_extract_destination_object(candidates, line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to"):
|
||||
_append_candidate(candidates, line.get(key))
|
||||
return candidates
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
normalized_alias = normalize_destination(alias)
|
||||
return candidate == normalized_alias or normalized_alias in candidate.split() or normalized_alias in candidate
|
||||
|
||||
|
||||
def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
|
||||
"""根据任务目的地候选解析唯一库存源;无法唯一命中时返回人工确认所需候选。"""
|
||||
candidates = extract_destination_candidates(task)
|
||||
matched_codes: list[str] = []
|
||||
for candidate in candidates:
|
||||
for rule in ROUTE_RULES:
|
||||
if any(_matches_alias(candidate, alias) for alias in rule.get("aliases") or []):
|
||||
code = str(rule.get("source_code") or "").strip().upper()
|
||||
if code and code not in matched_codes:
|
||||
matched_codes.append(code)
|
||||
|
||||
if len(matched_codes) == 1:
|
||||
source = build_rpa_inventory_source(matched_codes[0])
|
||||
if source:
|
||||
return InventorySourceResolution(
|
||||
status="resolved",
|
||||
source=source,
|
||||
candidates=[source],
|
||||
destination_candidates=candidates,
|
||||
)
|
||||
if len(matched_codes) > 1:
|
||||
matched_sources = [
|
||||
source
|
||||
for code in matched_codes
|
||||
for source in [build_rpa_inventory_source(code)]
|
||||
if source
|
||||
]
|
||||
return InventorySourceResolution(
|
||||
status="ambiguous",
|
||||
source=None,
|
||||
candidates=matched_sources,
|
||||
destination_candidates=candidates,
|
||||
reason="matched_multiple_sources",
|
||||
)
|
||||
return InventorySourceResolution(
|
||||
status="unresolved",
|
||||
source=None,
|
||||
candidates=list_inventory_sources(),
|
||||
destination_candidates=candidates,
|
||||
reason="no_route_rule_matched",
|
||||
)
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""读取任务当前已确认的 rpa_inventory_source。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
source = payload.get("rpa_inventory_source")
|
||||
return source if isinstance(source, dict) and source.get("source_code") else None
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(
|
||||
task: ShippingTask,
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
resolution: InventorySourceResolution | None = None,
|
||||
) -> None:
|
||||
"""把已确认库存源写入 task.step_payload_json,供后续 RPA trigger 使用。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["rpa_inventory_source"] = source
|
||||
if resolution:
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": resolution.status,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"reason": resolution.reason,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceResolution) -> None:
|
||||
"""库存源无法唯一命中时,把候选项写入 task.step_payload_json 供前端/Agent 展示。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": resolution.status,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"reason": resolution.reason,
|
||||
"candidates": resolution.candidates,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_sources.py
|
||||
|
||||
用途:定义发货通知库存 RPA 源配置,并构造写入 trigger 的标准 rpa_inventory_source。
|
||||
依赖:纯配置与校验逻辑;inventory_source_rules / inventory_rpa_workflow 调用本模块。
|
||||
逻辑:第一版先用代码配置承载 DSV 360 与 Crane FootPrint 的库存入口,后续可迁移到数据库规则表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
|
||||
INVENTORY_SOURCES: dict[str, dict[str, Any]] = {
|
||||
"DSV360_AWSBI": {
|
||||
"source_code": "DSV360_AWSBI",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Bison / AWSBI",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Bison",
|
||||
"program_label": "AWSBI",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory By Location 3lv",
|
||||
"owner_code": "CADU-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSCV": {
|
||||
"source_code": "DSV360_AWSCV",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Cincinnati / AWSCV",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Cincinnati",
|
||||
"program_label": "AWSCV",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CACV-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSDU": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Dublin",
|
||||
"program_label": "AWSDU - Prod (JDA)",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CADU-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSAMS": {
|
||||
"source_code": "DSV360_AWSAMS",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Moerdijk / AWSAMS",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Moerdijk",
|
||||
"program_label": "AWSAMS",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CADU-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSSL": {
|
||||
"source_code": "DSV360_AWSSL",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Salt Lake City / AWSSL",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Salt Lake City",
|
||||
"program_label": "AWSSL",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CACV-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSSG": {
|
||||
"source_code": "DSV360_AWSSG",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Singapore / AWSSG - Prod (JDA)",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Singapore",
|
||||
"program_label": "AWSSG - Prod (JDA)",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CACV-0000000100",
|
||||
},
|
||||
},
|
||||
"CRANE_TZR2": {
|
||||
"source_code": "CRANE_TZR2",
|
||||
"source_type": "crane_footprint",
|
||||
"display_name": "Crane FootPrint / Warehouse TZR2",
|
||||
"enabled": True,
|
||||
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
|
||||
"query": {
|
||||
"owner_code": "0000000100",
|
||||
"project_code": None,
|
||||
"warehouse_code": "TZR2",
|
||||
},
|
||||
"export": {
|
||||
"report_name": "On Hand Details Query",
|
||||
"download_mode": "file_download",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
|
||||
"""按 source_code 返回启用的库存源配置副本。"""
|
||||
code = str(source_code or "").strip().upper()
|
||||
source = INVENTORY_SOURCES.get(code)
|
||||
if not source or not source.get("enabled", True):
|
||||
return None
|
||||
return deepcopy(source)
|
||||
|
||||
|
||||
def list_inventory_sources() -> list[dict[str, Any]]:
|
||||
"""返回所有启用库存源配置副本,供人工检查点展示候选项。"""
|
||||
return [
|
||||
deepcopy(source)
|
||||
for source in INVENTORY_SOURCES.values()
|
||||
if source.get("enabled", True)
|
||||
]
|
||||
|
||||
|
||||
def build_rpa_inventory_source(
|
||||
source_code: str | None,
|
||||
*,
|
||||
query_override: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 RPA trigger 使用的 rpa_inventory_source。
|
||||
【AI 触发时机】:HXOPS 已确定库存源后,写 RPA trigger 或确认人工选择时调用。
|
||||
"""
|
||||
source = get_inventory_source(source_code)
|
||||
if not source:
|
||||
return None
|
||||
if query_override:
|
||||
query = dict(source.get("query") or {})
|
||||
for key, value in query_override.items():
|
||||
if value is not None and str(value).strip():
|
||||
query[key] = value
|
||||
source["query"] = query
|
||||
return source
|
||||
@@ -297,6 +297,8 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"export_file_name": task.export_file_name,
|
||||
"freight_ref_no": task.freight_ref_no,
|
||||
"step_payload": task.step_payload_json or {},
|
||||
"rpa_inventory_source": (task.step_payload_json or {}).get("rpa_inventory_source") if isinstance(task.step_payload_json, dict) else None,
|
||||
"inventory_source_resolution": (task.step_payload_json or {}).get("inventory_source_resolution") if isinstance(task.step_payload_json, dict) else None,
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||||
|
||||
@@ -24,6 +24,7 @@ from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
@@ -38,6 +39,7 @@ from app.services.shipping_notice.constants import (
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_ALIGN_REVIEW,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_MAP_INFER,
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
@@ -73,6 +75,8 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
|
||||
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
|
||||
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
|
||||
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
|
||||
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
"label": "选择库存文件",
|
||||
@@ -121,6 +125,11 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
),
|
||||
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_INVENTORY_SOURCE_REVIEW: (
|
||||
"confirm_inventory_source",
|
||||
"retry_resolve_inventory_source",
|
||||
"upload_inventory_file",
|
||||
),
|
||||
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("reparse_inventory", "correct_inventory_mapping", "rematch", "reject"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
|
||||
@@ -166,6 +175,42 @@ def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
|
||||
return buttons
|
||||
|
||||
|
||||
def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
|
||||
"""
|
||||
将库存源候选项转成聊天区可直接点击的确认按钮。
|
||||
|
||||
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口并触发 RPA,
|
||||
避免先把候选源文本发给 Agent 再等待二次确认。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
resolution = payload.get("inventory_source_resolution")
|
||||
candidates = resolution.get("candidates") if isinstance(resolution, dict) else None
|
||||
normalized_candidates: list[dict[str, Any]] = []
|
||||
if isinstance(candidates, list):
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
continue
|
||||
normalized_candidates.append(item)
|
||||
if len(normalized_candidates) == 1:
|
||||
item = normalized_candidates[0]
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
display_name = str(item.get("display_name") or source_code).strip()
|
||||
return [
|
||||
{
|
||||
"id": "confirm_inventory_source",
|
||||
"label": f"确认:{display_name}",
|
||||
"message": f"确认库存查询来源:{display_name}",
|
||||
"variant": "primary",
|
||||
"source_code": source_code,
|
||||
},
|
||||
*build_action_buttons(["retry_resolve_inventory_source", "upload_inventory_file"]),
|
||||
]
|
||||
return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]))
|
||||
|
||||
|
||||
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
|
||||
"""按静态 checkpoint id 查 CHECKPOINT_REGISTRY 中的默认 human_options。"""
|
||||
if not checkpoint:
|
||||
@@ -304,6 +349,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
|
||||
)
|
||||
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=RS_SHORTAGE_REVIEW,
|
||||
@@ -357,13 +407,18 @@ def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
dict: 含 task_no、checkpoint、process_status、action_buttons 等字段。
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
action_buttons = (
|
||||
inventory_source_action_buttons(task)
|
||||
if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW
|
||||
else ui.action_buttons
|
||||
)
|
||||
return {
|
||||
"task_no": task.task_no,
|
||||
"checkpoint": ui.checkpoint,
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"action_buttons": ui.action_buttons,
|
||||
"action_buttons": action_buttons,
|
||||
}
|
||||
|
||||
|
||||
@@ -424,6 +479,7 @@ class TaskTransition(StrEnum):
|
||||
RPA_EXHAUSTED = "rpa_exhausted"
|
||||
RPA_PENDING = "rpa_pending"
|
||||
INV_UNAVAIL = "inv_unavail"
|
||||
INVENTORY_SOURCE_REVIEW = "inventory_source_review"
|
||||
RSV_REQUIRED = "rsv_required"
|
||||
MATCHED_FULFILLABLE = "matched_fulfillable"
|
||||
MATCH_SHORTAGE = "match_shortage"
|
||||
@@ -487,6 +543,11 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INV_UNAVAIL,
|
||||
),
|
||||
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
),
|
||||
TaskTransition.RSV_REQUIRED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_RSV_REQ,
|
||||
|
||||
@@ -57,6 +57,34 @@ EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to",
|
||||
EDITABLE_NOTICE_LINE_FIELDS = frozenset({"sku", "reservation_id", "qty", "quantity", "required_date", "uom"})
|
||||
|
||||
|
||||
def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lines: list[Any]) -> None:
|
||||
"""保存 Dify/启发式解析出的目的地候选,供 HXOPS 库存源规则解析使用。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
candidates: list[Any] = []
|
||||
destination = parsed.get("destination")
|
||||
if isinstance(destination, dict):
|
||||
payload["destination"] = destination
|
||||
candidates.append(destination)
|
||||
elif destination:
|
||||
candidates.append(destination)
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"):
|
||||
if parsed.get(key):
|
||||
candidates.append(parsed.get(key))
|
||||
if task.ship_to:
|
||||
candidates.append(task.ship_to)
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if line.get("destination"):
|
||||
candidates.append(line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to"):
|
||||
if line.get(key):
|
||||
candidates.append(line.get(key))
|
||||
if candidates:
|
||||
payload["destination_candidates"] = candidates
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _has_parse_review_content(task: ShippingTask, lines: list[Any]) -> bool:
|
||||
"""判断解析结果是否有足够内容进入人工复核卡片。"""
|
||||
if any(isinstance(line, dict) for line in lines):
|
||||
@@ -513,6 +541,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.required_date = required_date or None
|
||||
task.lines_json = lines
|
||||
task.parse_confidence = confidence
|
||||
_capture_destination_context(task, parsed, lines)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
|
||||
@@ -31,6 +31,7 @@ get_inventory_schema_preview = inventory_workflow.get_inventory_schema_preview
|
||||
apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
|
||||
upload_inventory_file = inventory_workflow.upload_inventory_file
|
||||
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
|
||||
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
|
||||
|
||||
# 履约阶段
|
||||
match_inventory = fulfillment_workflow.match_inventory
|
||||
|
||||
Reference in new issue
Block a user