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
@@ -382,6 +382,77 @@ def _remove_path_upload_staged_file(staged_path: str | None):
|
||||
break
|
||||
parent = parent.parent
|
||||
|
||||
|
||||
def _cancel_active_kb_jobs_for_documents(document_ids: list[int], message: str) -> int:
|
||||
"""
|
||||
取消已删除文档关联的后台任务。
|
||||
Args:
|
||||
document_ids: 被软删的知识库文档 id 列表。
|
||||
message: 写入任务状态的取消原因。
|
||||
Returns:
|
||||
被标记为 cancelled 的任务数量。
|
||||
"""
|
||||
ids = [int(item) for item in document_ids if item]
|
||||
if not ids:
|
||||
return 0
|
||||
|
||||
version_ids = [
|
||||
row[0]
|
||||
for row in db.session.query(KbDocumentVersion.id)
|
||||
.filter(KbDocumentVersion.document_id.in_(ids))
|
||||
.all()
|
||||
]
|
||||
query = db.session.query(KbJob).filter(
|
||||
KbJob.status.in_(('queued', 'running')),
|
||||
KbJob.job_type.in_(('clean', 'sync_dify')),
|
||||
)
|
||||
if version_ids:
|
||||
query = query.filter(
|
||||
(KbJob.document_id.in_(ids)) | (KbJob.document_version_id.in_(version_ids))
|
||||
)
|
||||
else:
|
||||
query = query.filter(KbJob.document_id.in_(ids))
|
||||
|
||||
now = datetime.utcnow()
|
||||
cancelled = 0
|
||||
for job in query.all():
|
||||
job.status = 'cancelled'
|
||||
job.progress = 100
|
||||
job.message = message
|
||||
job.error_message = None
|
||||
job.finished_at = job.finished_at or now
|
||||
cancelled += 1
|
||||
return cancelled
|
||||
|
||||
|
||||
def _cancel_active_kb_jobs_for_group(group_id: int, message: str) -> int:
|
||||
"""
|
||||
取消已停用知识库分组下仍未完成的后台任务。
|
||||
Args:
|
||||
group_id: 知识库分组 id。
|
||||
message: 写入任务状态的取消原因。
|
||||
Returns:
|
||||
被标记为 cancelled 的任务数量。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
jobs = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.group_id == group_id,
|
||||
KbJob.status.in_(('draft', 'staging', 'queued', 'running')),
|
||||
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for job in jobs:
|
||||
job.status = 'cancelled'
|
||||
job.progress = 100
|
||||
job.message = message
|
||||
job.error_message = None
|
||||
job.finished_at = job.finished_at or now
|
||||
return len(jobs)
|
||||
|
||||
|
||||
def _soft_delete_document(document_id: int | None, user_id: int | None):
|
||||
if not document_id:
|
||||
return False
|
||||
@@ -394,6 +465,7 @@ def _soft_delete_document(document_id: int | None, user_id: int | None):
|
||||
pass
|
||||
document.is_deleted = True
|
||||
document.updated_by_id = user_id
|
||||
_cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
|
||||
return True
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['GET'])
|
||||
@@ -463,6 +535,7 @@ def delete_group(group_id: int):
|
||||
current_user = get_current_user()
|
||||
group.is_active = False
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
_cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'id': group_id})
|
||||
|
||||
@@ -1009,8 +1082,9 @@ def delete_document(document_id: int):
|
||||
pass
|
||||
document.is_deleted = True
|
||||
document.updated_by_id = getattr(current_user, 'id', None)
|
||||
cancelled_jobs = _cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'id': document_id, 'delete_dify': delete_result})
|
||||
return jsonify({'ok': True, 'id': document_id, 'delete_dify': delete_result, 'cancelled_jobs': cancelled_jobs})
|
||||
|
||||
@knowledge_base_bp.route('/jobs', methods=['GET'])
|
||||
def list_jobs():
|
||||
|
||||
@@ -350,6 +350,20 @@ def workspace_upload_shipping_inventory(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
|
||||
@@ -71,7 +71,7 @@ def _backend_path(env_key: str, *parts: str) -> str:
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_clean.py
|
||||
|
||||
用途:KB 文档清洗任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。
|
||||
用途:KB 文档清洗 / 路径上传任务 handler。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_clean_job / run_path_upload_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -14,11 +14,22 @@ from app.jobs.types import JobType
|
||||
@register_handler(JobType.KB_CLEAN)
|
||||
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单条 KB 清洗任务。
|
||||
执行单条 KB 清洗或路径上传任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 含 document_id 等字段。
|
||||
payload: 须含 job_id;raw_job_type 为 path_upload 时走路径上传分支。
|
||||
"""
|
||||
ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload)
|
||||
# Wave 2: from app.services.knowledge_cleaning.queue_service import process_job
|
||||
raise NotImplementedError('kb_clean handler pending Wave 2')
|
||||
job_id = int(payload['job_id'])
|
||||
raw_type = str(payload.get('raw_job_type') or 'clean').strip()
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if raw_type == 'path_upload':
|
||||
ok, message = run_path_upload_job(job_id)
|
||||
else:
|
||||
ok, message = run_clean_job(job_id)
|
||||
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_clean job_id=%s raw_type=%s ok=%s message=%s', job_id, raw_type, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/jobs/handlers/kb_dify_sync.py
|
||||
|
||||
用途:KB 文档同步至 Dify 任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_sync_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,6 +13,17 @@ from app.jobs.types import JobType
|
||||
|
||||
@register_handler(JobType.KB_DIFY_SYNC)
|
||||
def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""同步已清洗文档到 Dify。"""
|
||||
ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('kb_dify_sync handler pending Wave 2')
|
||||
"""
|
||||
同步已清洗文档到 Dify。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id(KbJob 主键)。
|
||||
"""
|
||||
job_id = int(payload['job_id'])
|
||||
from app.services.knowledge_cleaning.tasks import run_sync_job
|
||||
|
||||
ok, message = run_sync_job(job_id)
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_dify_sync job_id=%s ok=%s message=%s', job_id, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -15,5 +15,12 @@ from app.services.shipping_notice.queue_service import run_shipping_notice_job
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_RUN)
|
||||
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
|
||||
"""消费单票发货后台任务。"""
|
||||
run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
"""
|
||||
消费单票发货后台任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id 或 task_no。
|
||||
"""
|
||||
ok, message = run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -36,6 +36,35 @@ def _worker_id() -> str:
|
||||
return f"{host}:{id(db.session)}"
|
||||
|
||||
|
||||
def _find_shipping_notice_job_id(task_no: str) -> int | None:
|
||||
"""
|
||||
按 task_no 查找发货任务对应的 KbJob。
|
||||
Args:
|
||||
task_no: 发货任务号;由 AI 或业务代码传入时可大小写混用。
|
||||
Returns:
|
||||
匹配到的最新 KbJob 主键;未找到返回 None。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import KbJob
|
||||
|
||||
normalized_task_no = str(task_no or '').strip().upper()
|
||||
candidates = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status.in_(('queued', 'running', 'success', 'failed')),
|
||||
)
|
||||
.order_by(KbJob.id.desc())
|
||||
.limit(50)
|
||||
.all()
|
||||
)
|
||||
for job in candidates:
|
||||
payload_json = job.payload_json or {}
|
||||
if str(payload_json.get('task_no') or '').strip().upper() == normalized_task_no:
|
||||
return job.id
|
||||
return None
|
||||
|
||||
|
||||
def enqueue(
|
||||
job_type: JobType | str,
|
||||
payload: dict[str, Any],
|
||||
|
||||
+33
-16
@@ -2,37 +2,54 @@
|
||||
backend/app/jobs/runner.py
|
||||
|
||||
用途:Worker 主循环 poll → dispatch → ack/fail。
|
||||
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
|
||||
逻辑:worker.py 调用 run_forever(ctx);claim 走 store,执行走 registry handler。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs import store
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.jobs.context import JobContext
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
|
||||
def _resolve_poll_seconds(ctx: JobContext) -> float:
|
||||
"""按队列配置读取轮询间隔。"""
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
if 'shipping' in queues and 'kb' not in queues:
|
||||
return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2))
|
||||
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
|
||||
"""
|
||||
持续轮询并执行任务。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
poll_interval_seconds: 无任务时的休眠秒数。
|
||||
ctx: Worker 上下文(extras.queues 指定消费队列)。
|
||||
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
|
||||
"""
|
||||
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
|
||||
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
|
||||
|
||||
while True:
|
||||
try:
|
||||
job = store.claim_next()
|
||||
except NotImplementedError:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
job = store.claim_next(queues=queues)
|
||||
if not job:
|
||||
time.sleep(poll_interval_seconds)
|
||||
time.sleep(poll)
|
||||
continue
|
||||
|
||||
handler = get_handler(job['job_type'])
|
||||
if not handler:
|
||||
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
|
||||
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
|
||||
store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
|
||||
continue
|
||||
handler(ctx, job.get('payload') or {})
|
||||
|
||||
try:
|
||||
handler(ctx, job.get('payload') or {})
|
||||
except Exception as exc:
|
||||
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
|
||||
store.mark_failed(job['id'], message=str(exc))
|
||||
@@ -1,20 +1,106 @@
|
||||
"""
|
||||
backend/app/jobs/store.py
|
||||
|
||||
用途:Job 表 CRUD(claim、update status)。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
|
||||
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
|
||||
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
|
||||
from app.models import KbJob
|
||||
|
||||
def claim_next() -> dict[str, Any] | None:
|
||||
|
||||
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
|
||||
将 KbJob ORM 实例转为 runner/handler 使用的归一化任务 dict。
|
||||
Args:
|
||||
job: 已 claim 的 KbJob。
|
||||
Returns:
|
||||
job 字典或 None。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
含 id、job_type(handler 键)、payload、raw_job_type 的字典。
|
||||
"""
|
||||
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
|
||||
handler_type = handler_type_for_kb_job(job.job_type)
|
||||
if handler_type is None:
|
||||
raise ValueError(f'unsupported kb job_type={job.job_type!r}')
|
||||
|
||||
return {
|
||||
'id': job.id,
|
||||
'job_type': handler_type,
|
||||
'raw_job_type': job.job_type,
|
||||
'payload': {
|
||||
'job_id': job.id,
|
||||
'raw_job_type': job.job_type,
|
||||
**(job.payload_json or {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping 队列;先 recover 卡死 running 任务。
|
||||
Args:
|
||||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||||
Returns:
|
||||
归一化 job dict 或 None(无任务)。
|
||||
"""
|
||||
queue_names = [q.strip() for q in (queues or ['kb']) if q and q.strip()]
|
||||
if not queue_names:
|
||||
queue_names = ['kb']
|
||||
|
||||
# [STEP 1] 超时回收(按队列涉及的类型)
|
||||
allowed_types: set[str] = set()
|
||||
for name in queue_names:
|
||||
allowed_types.update(QUEUE_KB_JOB_TYPES.get(name, frozenset()))
|
||||
|
||||
if allowed_types & QUEUE_KB_JOB_TYPES['kb']:
|
||||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||||
|
||||
recover_stale_running_jobs()
|
||||
if 'shipping_notice_run' in allowed_types:
|
||||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||||
|
||||
recover_stale_shipping_notice_jobs()
|
||||
|
||||
# [STEP 2] 按队列优先级 claim
|
||||
for name in queue_names:
|
||||
if name == 'kb':
|
||||
from app.services.knowledge_cleaning.queue_service import claim_next_kb_job
|
||||
|
||||
job = claim_next_kb_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
elif name == 'shipping':
|
||||
from app.services.shipping_notice.queue_service import claim_next_shipping_notice_job
|
||||
|
||||
job = claim_next_shipping_notice_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def mark_failed(job_id: int, *, message: str) -> None:
|
||||
"""
|
||||
handler 未捕获异常时,将 KbJob 标记为 failed。
|
||||
Args:
|
||||
job_id: KbJob 主键。
|
||||
message: 失败原因(截断至 1000 字符)。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job or job.status != 'running':
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
job.status = 'failed'
|
||||
job.error_message = message[:1000]
|
||||
job.message = message[:500]
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
db.session.commit()
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/types.py
|
||||
|
||||
用途:Job 类型与状态枚举。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
|
||||
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,7 +10,7 @@ from enum import StrEnum
|
||||
|
||||
|
||||
class JobType(StrEnum):
|
||||
"""后台任务类型。"""
|
||||
"""后台任务类型(handler 注册键)。"""
|
||||
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
@@ -21,10 +21,54 @@ class JobType(StrEnum):
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
"""Job 生命周期状态。"""
|
||||
"""通用 Job 生命周期状态(Wave 4 通用 Job 表预留;当前 KbJob 仍用 queued/running/success/failed)。"""
|
||||
|
||||
PENDING = 'pending'
|
||||
RUNNING = 'running'
|
||||
SUCCEEDED = 'succeeded'
|
||||
FAILED = 'failed'
|
||||
DEAD = 'dead'
|
||||
|
||||
|
||||
# KbJob.job_type 字符串 → handler JobType
|
||||
_KB_JOB_TYPE_TO_HANDLER: dict[str, JobType] = {
|
||||
'clean': JobType.KB_CLEAN,
|
||||
'path_upload': JobType.KB_CLEAN,
|
||||
'sync_dify': JobType.KB_DIFY_SYNC,
|
||||
'shipping_notice_run': JobType.SHIPPING_NOTICE_RUN,
|
||||
}
|
||||
|
||||
# handler JobType → 写入 KbJob 时使用的 job_type
|
||||
_HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
JobType.KB_CLEAN: 'clean',
|
||||
JobType.KB_DIFY_SYNC: 'sync_dify',
|
||||
JobType.SHIPPING_NOTICE_RUN: 'shipping_notice_run',
|
||||
}
|
||||
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run'}),
|
||||
}
|
||||
|
||||
|
||||
def handler_type_for_kb_job(kb_job_type: str) -> JobType | None:
|
||||
"""
|
||||
将 KbJob.job_type 映射为 handler 注册用的 JobType。
|
||||
Args:
|
||||
kb_job_type: KbJob 表 job_type 列值。
|
||||
Returns:
|
||||
对应 JobType;未知类型返回 None。
|
||||
"""
|
||||
return _KB_JOB_TYPE_TO_HANDLER.get(str(kb_job_type or '').strip())
|
||||
|
||||
|
||||
def kb_job_type_for_handler(job_type: JobType) -> str | None:
|
||||
"""
|
||||
将 handler JobType 映射为写入 KbJob 的 job_type 字符串。
|
||||
Args:
|
||||
job_type: handler 注册键。
|
||||
Returns:
|
||||
KbJob.job_type 值;path_upload 等需调用方显式指定时不经此函数。
|
||||
"""
|
||||
return _HANDLER_TO_KB_JOB_TYPE.get(job_type)
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
tests/jobs/test_store.py
|
||||
|
||||
用途:验证 store.claim_next 归一化与空队列行为。
|
||||
"""
|
||||
from app.jobs.store import _normalize_kb_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import KbJob
|
||||
|
||||
|
||||
def test_normalize_kb_job_clean(app):
|
||||
with app.app_context():
|
||||
job = KbJob(
|
||||
job_type='clean',
|
||||
status='running',
|
||||
progress=1,
|
||||
payload_json={'document_version_id': 42},
|
||||
)
|
||||
normalized = _normalize_kb_job(job)
|
||||
assert normalized['id'] == job.id
|
||||
assert normalized['job_type'] == JobType.KB_CLEAN
|
||||
assert normalized['raw_job_type'] == 'clean'
|
||||
assert normalized['payload']['job_id'] == job.id
|
||||
assert normalized['payload']['document_version_id'] == 42
|
||||
|
||||
|
||||
def test_normalize_kb_job_sync_dify(app):
|
||||
with app.app_context():
|
||||
job = KbJob(job_type='sync_dify', status='running', progress=1)
|
||||
normalized = _normalize_kb_job(job)
|
||||
assert normalized['job_type'] == JobType.KB_DIFY_SYNC
|
||||
|
||||
|
||||
def test_claim_next_returns_none_when_empty(app):
|
||||
from app.jobs import store
|
||||
|
||||
with app.app_context():
|
||||
assert store.claim_next(queues=['kb']) is None
|
||||
|
||||
|
||||
def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
from app import db
|
||||
from app.jobs.queue import _find_shipping_notice_job_id
|
||||
|
||||
with app.app_context():
|
||||
target = KbJob(
|
||||
job_type=JobType.SHIPPING_NOTICE_RUN.value,
|
||||
status='queued',
|
||||
progress=0,
|
||||
payload_json={'task_no': 'SHIP-A'},
|
||||
)
|
||||
newer_other = KbJob(
|
||||
job_type=JobType.SHIPPING_NOTICE_RUN.value,
|
||||
status='queued',
|
||||
progress=0,
|
||||
payload_json={'task_no': 'SHIP-B'},
|
||||
)
|
||||
db.session.add_all([target, newer_other])
|
||||
db.session.commit()
|
||||
|
||||
assert _find_shipping_notice_job_id('ship-a') == target.id
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
tests/jobs/test_types.py
|
||||
|
||||
用途:验证 JobType 与 KbJob.job_type 映射。
|
||||
"""
|
||||
from app.jobs.types import JobType, handler_type_for_kb_job, kb_job_type_for_handler
|
||||
|
||||
|
||||
def test_handler_type_for_kb_job_mapping():
|
||||
assert handler_type_for_kb_job('clean') == JobType.KB_CLEAN
|
||||
assert handler_type_for_kb_job('path_upload') == JobType.KB_CLEAN
|
||||
assert handler_type_for_kb_job('sync_dify') == JobType.KB_DIFY_SYNC
|
||||
assert handler_type_for_kb_job('shipping_notice_run') == JobType.SHIPPING_NOTICE_RUN
|
||||
assert handler_type_for_kb_job('unknown') is None
|
||||
|
||||
|
||||
def test_kb_job_type_for_handler_mapping():
|
||||
assert kb_job_type_for_handler(JobType.KB_CLEAN) == 'clean'
|
||||
assert kb_job_type_for_handler(JobType.KB_DIFY_SYNC) == 'sync_dify'
|
||||
assert kb_job_type_for_handler(JobType.SHIPPING_NOTICE_RUN) == 'shipping_notice_run'
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
tests/jobs/test_worker_kb.py
|
||||
|
||||
用途:验证 KB worker 兼容入口读取 Flask config 中的并发配置。
|
||||
"""
|
||||
|
||||
|
||||
def test_main_kb_uses_app_config_concurrency(monkeypatch):
|
||||
import worker_kb
|
||||
|
||||
started: list[str] = []
|
||||
|
||||
class FakeApp:
|
||||
config = {'KB_WORKER_CONCURRENCY': 3}
|
||||
|
||||
class FakeProcess:
|
||||
def __init__(self, *, target, args, name):
|
||||
self.name = name
|
||||
self.target = target
|
||||
self.args = args
|
||||
|
||||
def start(self):
|
||||
started.append(self.name)
|
||||
|
||||
def join(self, timeout=None):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(worker_kb, 'create_app', lambda _config_name: FakeApp())
|
||||
monkeypatch.setattr(worker_kb, '_resolve_config_name', lambda: 'production')
|
||||
monkeypatch.setattr(worker_kb.mp, 'Process', FakeProcess)
|
||||
|
||||
worker_kb.main_kb()
|
||||
|
||||
# 断言多进程数量来自 app.config,而非直接读取环境变量默认值。
|
||||
assert started == ['kb-worker-1', 'kb-worker-2', 'kb-worker-3']
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
tests/test_kb_delete_cancels_jobs.py
|
||||
|
||||
用途:验证知识库文档软删时会取消未完成的后台任务。
|
||||
"""
|
||||
from app import db
|
||||
from app.api.knowledge_base import _cancel_active_kb_jobs_for_documents
|
||||
from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob
|
||||
|
||||
|
||||
def test_cancel_active_kb_jobs_for_deleted_document(app):
|
||||
with app.app_context():
|
||||
group = KbGroup(name='kb-delete-cancel')
|
||||
document = KbDocument(group=group, title='doc.pdf', status='uploaded')
|
||||
version = KbDocumentVersion(
|
||||
document=document,
|
||||
version_no=1,
|
||||
status='uploaded',
|
||||
is_current=True,
|
||||
source_file_name='doc.pdf',
|
||||
source_file_path='data/kb/doc.pdf',
|
||||
)
|
||||
db.session.add_all([group, document, version])
|
||||
db.session.flush()
|
||||
|
||||
queued = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
)
|
||||
running = KbJob(
|
||||
job_type='sync_dify',
|
||||
status='running',
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=20,
|
||||
)
|
||||
done = KbJob(
|
||||
job_type='upload',
|
||||
status='success',
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=100,
|
||||
)
|
||||
db.session.add_all([queued, running, done])
|
||||
db.session.commit()
|
||||
|
||||
cancelled = _cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
|
||||
assert cancelled == 2
|
||||
assert db.session.get(KbJob, queued.id).status == 'cancelled'
|
||||
assert db.session.get(KbJob, running.id).status == 'cancelled'
|
||||
assert db.session.get(KbJob, done.id).status == 'success'
|
||||
@@ -15,6 +15,12 @@ def test_resolve_backend_relative_path_data_prefix():
|
||||
assert resolved == (root / "data" / "shipping_notice").resolve()
|
||||
|
||||
|
||||
def test_resolve_backend_relative_path_kb_storage_legacy_prefix():
|
||||
root = backend_dir()
|
||||
resolved = Path(resolve_backend_relative_path("backend/data/kb"))
|
||||
assert resolved == (root / "data" / "kb").resolve()
|
||||
|
||||
|
||||
def test_resolve_backend_relative_path_default():
|
||||
root = backend_dir()
|
||||
default = root / "data" / "shipping_notice" / "freight_rpa" / "inventory_drop"
|
||||
|
||||
@@ -319,6 +319,14 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app):
|
||||
raw_content="客户:ACME\nA001 x 10",
|
||||
lines_json=[{"sku": "A001", "qty": 10}],
|
||||
current_step="step2_parse_confirm",
|
||||
step_payload_json={
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
|
||||
}
|
||||
},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -353,6 +361,14 @@ def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp
|
||||
parse_confidence=0.95,
|
||||
raw_content="客户:ACME\nA001 x 10",
|
||||
lines_json=[{"sku": "A001", "qty": 10}],
|
||||
step_payload_json={
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
|
||||
}
|
||||
},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -385,6 +401,172 @@ def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp
|
||||
assert task.step_payload_json["current_step_progress"]["current"] == 2
|
||||
|
||||
|
||||
def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_path):
|
||||
"""目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。"""
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
|
||||
with app.app_context():
|
||||
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no="SN-INVENTORY-SOURCE-DUB",
|
||||
user_id=user.id,
|
||||
source_type="pdf",
|
||||
process_status="parsed",
|
||||
parse_confidence=0.95,
|
||||
raw_content="Ship to Dublin DUB\nA001 x 10",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"sku": "A001", "qty": 10}],
|
||||
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
|
||||
|
||||
db.session.refresh(task)
|
||||
assert result["status"] == "running"
|
||||
source = task.step_payload_json["rpa_inventory_source"]
|
||||
assert source["source_code"] == "DSV360_AWSDU"
|
||||
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
|
||||
assert trigger_path.exists()
|
||||
trigger_text = trigger_path.read_text(encoding="utf-8")
|
||||
assert '"source_code": "DSV360_AWSDU"' in trigger_text
|
||||
assert '"source_type": "dsv360"' in trigger_text
|
||||
|
||||
|
||||
def test_inventory_source_rules_cover_dsv360_programs(app):
|
||||
"""截图中的 DSV 360 Program 均应能通过别名解析到对应库存源。"""
|
||||
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
|
||||
|
||||
cases = [
|
||||
("Bison", "DSV360_AWSBI"),
|
||||
("Cincinnati", "DSV360_AWSCV"),
|
||||
("Moerdijk", "DSV360_AWSAMS"),
|
||||
]
|
||||
with app.app_context():
|
||||
for ship_to, expected_code in cases:
|
||||
task = ShippingTask(
|
||||
task_no=f"SN-INVENTORY-SOURCE-{expected_code}",
|
||||
source_type="pdf",
|
||||
process_status="parsed",
|
||||
ship_to=ship_to,
|
||||
lines_json=[{"sku": "A001", "qty": 10}],
|
||||
)
|
||||
resolution = resolve_inventory_source(task)
|
||||
|
||||
assert resolution.status == "resolved"
|
||||
assert resolution.source is not None
|
||||
assert resolution.source["source_code"] == expected_code
|
||||
|
||||
|
||||
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
|
||||
"""无法根据目的地唯一判断库存源时,应停在库存源人工确认检查点。"""
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
with app.app_context():
|
||||
user = User(username="shipping_inventory_source_unknown", email="shipping_inventory_source_unknown@example.com")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no="SN-INVENTORY-SOURCE-UNKNOWN",
|
||||
user_id=user.id,
|
||||
source_type="pdf",
|
||||
process_status="parsed",
|
||||
parse_confidence=0.95,
|
||||
raw_content="Ship to Mystery Port\nA001 x 10",
|
||||
ship_to="Mystery Port",
|
||||
lines_json=[{"sku": "A001", "qty": 10}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
|
||||
|
||||
db.session.refresh(task)
|
||||
assert result["status"] == "needs_human"
|
||||
assert result["checkpoint"] == "inventory_source_review"
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "inventory_source_unresolved"
|
||||
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
|
||||
assert len(result["data"]["inventory_source_candidates"]) >= 4
|
||||
|
||||
|
||||
def test_inventory_source_review_chat_actions_return_source_buttons(app):
|
||||
"""库存源待确认且只有一个候选时,聊天按钮才携带具体 source_code。"""
|
||||
from app.services.shipping_notice.state_machine import build_chat_actions_payload
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-INVENTORY-SOURCE-ACTIONS",
|
||||
source_type="pdf",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
step_payload_json={
|
||||
"inventory_source_resolution": {
|
||||
"status": "unresolved",
|
||||
"candidates": [
|
||||
{
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
payload = build_chat_actions_payload(task)
|
||||
|
||||
assert payload["checkpoint"] == "inventory_source_review"
|
||||
first = payload["action_buttons"][0]
|
||||
assert first["id"] == "confirm_inventory_source"
|
||||
assert first["source_code"] == "DSV360_AWSDU"
|
||||
assert first["label"] == "确认:DSV 360 / Dublin / AWSDU - Prod (JDA)"
|
||||
|
||||
|
||||
def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
|
||||
"""库存源候选很多时,不应把全部数据源铺成按钮。"""
|
||||
from app.services.shipping_notice.state_machine import build_chat_actions_payload
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-INVENTORY-SOURCE-MANY-ACTIONS",
|
||||
source_type="pdf",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
step_payload_json={
|
||||
"inventory_source_resolution": {
|
||||
"status": "unresolved",
|
||||
"candidates": [
|
||||
{
|
||||
"source_code": "DSV360_AWSBI",
|
||||
"display_name": "DSV 360 / Bison / AWSBI",
|
||||
},
|
||||
{
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
payload = build_chat_actions_payload(task)
|
||||
|
||||
source_buttons = [
|
||||
item for item in payload["action_buttons"]
|
||||
if item["id"] == "confirm_inventory_source" and item.get("source_code")
|
||||
]
|
||||
assert source_buttons == []
|
||||
assert [item["id"] for item in payload["action_buttons"]] == [
|
||||
"confirm_inventory_source",
|
||||
"retry_resolve_inventory_source",
|
||||
"upload_inventory_file",
|
||||
]
|
||||
|
||||
|
||||
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
|
||||
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
|
||||
headers = _workspace_headers(app)
|
||||
|
||||
@@ -9,7 +9,7 @@ from app.models import ShippingTask, ShippingTaskEvent
|
||||
|
||||
|
||||
def _tool_headers():
|
||||
return {"Content-Type": "application/json"}
|
||||
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
|
||||
|
||||
|
||||
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
|
||||
@@ -19,6 +19,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
@@ -35,6 +36,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"destination": {"port_code": "DUB", "city": "Dublin"},
|
||||
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
@@ -66,6 +68,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
|
||||
drop = tmp_path / "drop"
|
||||
drop.mkdir()
|
||||
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
@@ -99,3 +102,47 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "inventory_ready"
|
||||
|
||||
|
||||
def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
|
||||
"""确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。"""
|
||||
from app import db
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source
|
||||
|
||||
trigger = tmp_path / "triggers"
|
||||
trigger.mkdir()
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-CONFIRM-SOURCE-RPA",
|
||||
source_type="pdf",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
step_payload_json={
|
||||
"inventory_source_resolution": {
|
||||
"status": "unresolved",
|
||||
"candidates": [
|
||||
{
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
lines_json=[{"sku": "A001", "qty": 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = confirm_inventory_source({"task_id": task.task_no, "source_code": "DSV360_AWSDU"})
|
||||
|
||||
db.session.refresh(task)
|
||||
assert result["status"] == "running"
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.step_payload_json["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
|
||||
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
|
||||
assert len(events) == 1
|
||||
assert list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
|
||||
+41
-42
@@ -3,86 +3,85 @@ backend/worker.py
|
||||
|
||||
用途:统一后台 worker 入口(方案 D)。
|
||||
依赖:app.create_app、app.jobs.runner、app.jobs.handlers。
|
||||
逻辑:Wave 2 替代 worker_kb.py 主循环;Compose/Supervisor 可配置 --queues。
|
||||
逻辑:--queues kb,shipping;Wave 2 经 jobs.runner 统一 poll → dispatch。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from app import create_app
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.runner import run_forever
|
||||
|
||||
_LOG_FORMAT = '%(asctime)s %(levelname)s [worker] %(message)s'
|
||||
|
||||
|
||||
def _configure_logging() -> logging.Logger:
|
||||
logger = logging.getLogger('hxops.worker')
|
||||
def _configure_logging(label: str = 'main') -> logging.Logger:
|
||||
logger = logging.getLogger(f'hxops.worker.{label}')
|
||||
if not logger.handlers:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={label}]'))
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
return logger
|
||||
|
||||
|
||||
def _resolve_processor(queue_name: str):
|
||||
if queue_name == 'kb':
|
||||
from app.services.knowledge_cleaning.queue_service import process_next_kb_job
|
||||
def _resolve_config_name() -> str:
|
||||
"""
|
||||
与 worker_kb 对齐的环境配置解析。
|
||||
FLASK_ENV=test 表示测试部署主机(.env.test),非 pytest;testing 仅 APP_CONFIG 显式指定时使用。
|
||||
"""
|
||||
explicit = (os.getenv('APP_CONFIG') or '').strip().lower()
|
||||
if explicit:
|
||||
if explicit in ('testing', 'test'):
|
||||
return 'test'
|
||||
return explicit
|
||||
|
||||
return process_next_kb_job
|
||||
if queue_name == 'shipping':
|
||||
from app.services.shipping_notice.queue_service import process_next_shipping_notice_job
|
||||
|
||||
return process_next_shipping_notice_job
|
||||
raise ValueError(f'Unsupported queue: {queue_name}')
|
||||
env_name = (os.getenv('ENV_NAME') or os.getenv('FLASK_ENV') or 'production').strip().lower()
|
||||
mapping = {
|
||||
'dev': 'development',
|
||||
'development': 'development',
|
||||
'test': 'production',
|
||||
'env': 'production',
|
||||
'prod': 'production',
|
||||
'production': 'production',
|
||||
'testing': 'test',
|
||||
}
|
||||
return mapping.get(env_name, 'production')
|
||||
|
||||
|
||||
def main(*, queues: list[str] | None = None, config_name: str = 'default') -> None:
|
||||
def main(*, queues: list[str] | None = None, config_name: str | None = None) -> None:
|
||||
"""
|
||||
启动 worker 主循环。
|
||||
Args:
|
||||
queues: 消费的队列名列表(Wave 2 按 JobType 过滤)。
|
||||
config_name: Flask 配置名。
|
||||
queues: 消费的队列名列表,如 ['kb'] 或 ['kb', 'shipping']。
|
||||
config_name: Flask 配置名;默认 _resolve_config_name()。
|
||||
"""
|
||||
resolved_config = config_name or _resolve_config_name()
|
||||
logger = _configure_logging()
|
||||
app = create_app(config_name)
|
||||
app = create_app(resolved_config)
|
||||
queue_names = queues or ['kb']
|
||||
|
||||
with app.app_context():
|
||||
import app.jobs.handlers # noqa: F401
|
||||
import app.jobs.handlers # noqa: F401 — 触发 @register_handler
|
||||
|
||||
ctx = JobContext(
|
||||
config=dict(app.config),
|
||||
logger=logger,
|
||||
extras={'queues': queues or ['kb']},
|
||||
extras={'queues': queue_names},
|
||||
)
|
||||
queue_names = ctx.extras['queues']
|
||||
poll_seconds = 2.0
|
||||
if 'shipping' in queue_names:
|
||||
poll_seconds = float(app.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', poll_seconds))
|
||||
elif 'kb' in queue_names:
|
||||
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', poll_seconds))
|
||||
|
||||
logger.info('Worker starting queues=%s poll_seconds=%s', queue_names, poll_seconds)
|
||||
processors = [_resolve_processor(name) for name in queue_names]
|
||||
|
||||
import time
|
||||
|
||||
while True:
|
||||
handled = False
|
||||
for processor in processors:
|
||||
processed, message = processor()
|
||||
if processed:
|
||||
handled = True
|
||||
logger.info('processed job: %s', message)
|
||||
if not handled:
|
||||
time.sleep(poll_seconds)
|
||||
logger.info('Worker starting config=%s queues=%s', resolved_config, queue_names)
|
||||
run_forever(ctx)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description='HXOPS unified background worker')
|
||||
parser.add_argument('--queues', default='kb', help='Comma-separated queue names')
|
||||
parser.add_argument('--config', default='default', dest='config_name')
|
||||
parser.add_argument('--queues', default='kb', help='Comma-separated queue names (kb, shipping)')
|
||||
parser.add_argument('--config', default=None, dest='config_name', help='Flask config name (optional)')
|
||||
args = parser.parse_args()
|
||||
queue_list = [q.strip() for q in args.queues.split(',') if q.strip()]
|
||||
main(queues=queue_list, config_name=args.config_name)
|
||||
+14
-69
@@ -1,90 +1,35 @@
|
||||
"""
|
||||
backend/worker_kb.py
|
||||
文件用途:知识库最小 worker 入口
|
||||
|
||||
用途:知识库 worker 部署兼容入口(Compose / Supervisor 沿用此路径)。
|
||||
逻辑:Wave 2 转调 worker.py,默认 --queues kb;保留多进程并发配置。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from app import create_app
|
||||
from app.services.knowledge_cleaning.queue_service import process_next_clean_job
|
||||
|
||||
_LOG_FORMAT = '%(asctime)s %(levelname)s [kb-worker] %(message)s'
|
||||
_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
|
||||
from worker import _configure_logging, _resolve_config_name, main
|
||||
|
||||
|
||||
def _configure_logging(worker_label: str = 'main') -> logging.Logger:
|
||||
logger = logging.getLogger(f'kb-worker.{worker_label}')
|
||||
if logger.handlers:
|
||||
return logger
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={worker_label}]', datefmt=_LOG_DATEFMT))
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
return logger
|
||||
def _worker_loop(worker_index: int) -> None:
|
||||
log = _configure_logging(str(worker_index))
|
||||
log.info('kb-worker process started index=%s', worker_index)
|
||||
main(queues=['kb'], config_name=_resolve_config_name())
|
||||
|
||||
|
||||
def _resolve_config_name() -> str:
|
||||
"""Keep the worker aligned with container/runtime environment selection.
|
||||
|
||||
Note: ``FLASK_ENV=test`` / ``ENV_NAME=test`` mean the *test deployment* host
|
||||
(``.env.test``), not pytest. Use ``production`` so DATABASE_URL from env_file
|
||||
is honored. ``testing`` is only for in-memory unit tests (``TestingConfig``).
|
||||
"""
|
||||
explicit = (os.getenv('APP_CONFIG') or '').strip().lower()
|
||||
if explicit:
|
||||
if explicit in ('testing', 'test'):
|
||||
# Allow explicit pytest-style config only when APP_CONFIG is set;
|
||||
# never infer this from FLASK_ENV=test on deploy hosts.
|
||||
return 'test'
|
||||
return explicit
|
||||
|
||||
env_name = (os.getenv('ENV_NAME') or os.getenv('FLASK_ENV') or 'production').strip().lower()
|
||||
mapping = {
|
||||
'dev': 'development',
|
||||
'development': 'development',
|
||||
# Deploy env files: test/prod hosts use real DB via ProductionConfig
|
||||
'test': 'production',
|
||||
'env': 'production',
|
||||
'prod': 'production',
|
||||
'production': 'production',
|
||||
# Pytest-only aliases (not used on deploy unless APP_CONFIG forces it)
|
||||
'testing': 'test',
|
||||
}
|
||||
return mapping.get(env_name, 'production')
|
||||
|
||||
|
||||
def _worker_loop(worker_index: int):
|
||||
worker_label = str(worker_index)
|
||||
log = _configure_logging(worker_label)
|
||||
app = create_app(_resolve_config_name())
|
||||
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
with app.app_context():
|
||||
log.info('started, poll_seconds=%s', poll_seconds)
|
||||
while True:
|
||||
processed, message = process_next_clean_job()
|
||||
if not processed:
|
||||
time.sleep(poll_seconds)
|
||||
continue
|
||||
log.info('processed job: %s', message)
|
||||
|
||||
|
||||
def main():
|
||||
def main_kb() -> None:
|
||||
"""启动 KB worker;KB_WORKER_CONCURRENCY>1 时 fork 多进程。"""
|
||||
bootstrap_app = create_app(_resolve_config_name())
|
||||
concurrency = max(int(bootstrap_app.config.get('KB_WORKER_CONCURRENCY', 1) or 1), 1)
|
||||
|
||||
if concurrency == 1:
|
||||
_worker_loop(1)
|
||||
main(queues=['kb'], config_name=_resolve_config_name())
|
||||
return
|
||||
|
||||
log = _configure_logging('master')
|
||||
log.info('starting %s worker processes', concurrency)
|
||||
log.info('starting %s kb worker processes', concurrency)
|
||||
workers: list[mp.Process] = []
|
||||
for index in range(concurrency):
|
||||
proc = mp.Process(target=_worker_loop, args=(index + 1,), name=f'kb-worker-{index + 1}')
|
||||
@@ -95,7 +40,7 @@ def main():
|
||||
for proc in workers:
|
||||
proc.join()
|
||||
except KeyboardInterrupt:
|
||||
log.info('stopping worker pool')
|
||||
log.info('stopping kb worker pool')
|
||||
for proc in workers:
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
@@ -105,4 +50,4 @@ def main():
|
||||
|
||||
if __name__ == '__main__':
|
||||
mp.freeze_support()
|
||||
main()
|
||||
main_kb()
|
||||
Reference in new issue
Block a user