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()
|
||||
@@ -0,0 +1,87 @@
|
||||
# 发货通知库存源路由与 RPA Driver 方案
|
||||
|
||||
## 背景
|
||||
|
||||
发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于“未查到库存”。
|
||||
|
||||
## 设计原则
|
||||
|
||||
- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段,不负责最终 RPA URL 决策。
|
||||
- HXOPS 负责标准化、规则匹配、唯一性判断、权限校验、人工确认和审计。
|
||||
- RPA 只消费 HXOPS 给出的 `rpa_inventory_source` 参数,按 `source_type` 分发到不同 Driver。
|
||||
- 通用化范围是 trigger 协议、状态机、超时重试、回调、库存标准化;页面操作逻辑由不同 Driver 独立实现。
|
||||
- 用户对话可以做当前任务级临时覆盖;全局规则变更只能作为建议,需审核后生效。
|
||||
|
||||
## MVP 范围
|
||||
|
||||
第一版不改数据库结构,规则和源配置先放代码中,任务级上下文写入 `ShippingTask.step_payload_json`。
|
||||
|
||||
MVP 包含:
|
||||
|
||||
- 解析 Dify 输出的目的地候选字段,并保存到任务 step payload。
|
||||
- 根据目的地/港口/仓库线索解析库存源。
|
||||
- 唯一命中时自动写入 `rpa_inventory_source`。
|
||||
- 无法命中或多命中时进入 `inventory_source_review` 人工检查点。
|
||||
- RPA trigger JSON 增加 `rpa_inventory_source`。
|
||||
- 后端测试覆盖 DSV 与 Crane 的基本路由。
|
||||
|
||||
暂不包含:
|
||||
|
||||
- 后台规则管理页面。
|
||||
- 数据库规则表。
|
||||
- 批次级对话覆盖。
|
||||
- 全局规则建议审核流。
|
||||
|
||||
## Trigger 协议
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "inventory_export",
|
||||
"task_no": "SN-xxx",
|
||||
"attempt": 1,
|
||||
"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)",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CADU-0000000100"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Crane 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"source_code": "CRANE_TZR",
|
||||
"source_type": "crane_footprint",
|
||||
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
|
||||
"query": {
|
||||
"owner_code": "0000000100",
|
||||
"warehouse_code": "TZR",
|
||||
"project_code": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 初始路由规则
|
||||
|
||||
- `BISON`, `AWSBI` -> `DSV360_AWSBI`
|
||||
- `CINCINNATI`, `CVG`, `AWSCV` -> `DSV360_AWSCV`
|
||||
- `DUB`, `DUBLIN` -> `DSV360_AWSDU`
|
||||
- `MOERDIJK`, `AMS`, `AWSAMS` -> `DSV360_AWSAMS`
|
||||
- `USLCK`, `SALT LAKE CITY` -> `DSV360_AWSSL`
|
||||
- `SINGAPORE`, `SG` -> `DSV360_AWSSG`
|
||||
- `TZR`, `THAILAND` -> `CRANE_TZR`
|
||||
|
||||
## 后续演进
|
||||
|
||||
- 将代码配置迁移到可维护规则表。
|
||||
- 增加管理员审核的规则变更建议。
|
||||
- RPA 侧实现 `dsv360` 与 `crane_footprint` Driver。
|
||||
- 导入库存时校验 source_code、warehouse/program 与任务期望是否一致。
|
||||
@@ -35,6 +35,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
component: () => import('@/features/workspace/pages/KnowledgeBasePage.vue'),
|
||||
meta: { title: '知识库' },
|
||||
},
|
||||
{
|
||||
path: 'knowledge-base/groups/:groupId',
|
||||
name: 'workspace-knowledge-base-group',
|
||||
component: () => import('@/features/workspace/pages/KnowledgeBasePage.vue'),
|
||||
meta: { title: '知识库' },
|
||||
},
|
||||
{
|
||||
path: 'schedule-runs',
|
||||
name: 'workspace-schedule-runs',
|
||||
|
||||
@@ -13,6 +13,8 @@ export const SHIPPING_ACTION_IDS = [
|
||||
'reparse_inventory',
|
||||
'rematch',
|
||||
'retry_rpa',
|
||||
'confirm_inventory_source',
|
||||
'retry_resolve_inventory_source',
|
||||
'upload_inventory_file',
|
||||
'retry_upload',
|
||||
'download_excel',
|
||||
@@ -51,6 +53,8 @@ export const SHIPPING_INTERNAL_STATUS_TOKENS = [
|
||||
'export_ready',
|
||||
'upload_req',
|
||||
'inventory_pending',
|
||||
'inventory_source_review',
|
||||
'inventory_source_unresolved',
|
||||
'map_ok',
|
||||
'parse_ok',
|
||||
'needs_human',
|
||||
|
||||
@@ -99,6 +99,28 @@ export async function uploadWorkspaceShippingInventory(taskNo: string, file: Fil
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认当前任务的库存 RPA 来源。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param sourceCode - 已配置的库存源编码
|
||||
* @returns RPA 库存导出触发结果
|
||||
*/
|
||||
export async function confirmWorkspaceShippingInventorySource(taskNo: string, sourceCode: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-inventory-source`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ source_code: sourceCode }),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交库存字段映射。
|
||||
* @param taskNo - 发货任务编号
|
||||
|
||||
@@ -103,45 +103,24 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
@regenerate="emit('regenerate')"
|
||||
@open-feedback="emit('open-feedback', index)"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
:run="getMessageRunProgress(msg)"
|
||||
:loading="isMessageRunProgressLoading(msg)"
|
||||
:waiting="false"
|
||||
:error="getMessageRunProgressError(msg)"
|
||||
:fallback-title="toolRunProgressTitle"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-for="(msg, index) in messages" :key="index">
|
||||
<ChatMessageBubble
|
||||
v-if="shouldRenderMessage(msg)"
|
||||
:message="msg"
|
||||
:index="index"
|
||||
:message-count="messages.length"
|
||||
:is-thinking="isThinking"
|
||||
:show-chat-rating="showChatRating"
|
||||
:copied-index="copiedIndex"
|
||||
:is-shipping-notice-agent="isShippingNoticeAgent"
|
||||
:handlers="handlers"
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
@copy="emit('copy', { message: msg, index })"
|
||||
@edit="emit('edit', $event)"
|
||||
@resend="emit('resend', $event)"
|
||||
@regenerate="emit('regenerate')"
|
||||
@open-feedback="emit('open-feedback', index)"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
:run="getMessageRunProgress(msg)"
|
||||
:loading="isMessageRunProgressLoading(msg)"
|
||||
:waiting="false"
|
||||
:error="getMessageRunProgressError(msg)"
|
||||
:fallback-title="toolRunProgressTitle"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<ChatThinkingBubble v-if="showThinkingBubble" />
|
||||
<div v-if="messages.length > 0" class="h-2 md:h-3" />
|
||||
</div>
|
||||
<ChatThinkingBubble v-if="showThinkingBubble" />
|
||||
<div v-if="messages.length > 0" class="h-2 md:h-3" />
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="showScrollToBottom"
|
||||
type="button"
|
||||
class="absolute bottom-4 left-1/2 z-10 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-slate-100 bg-white text-[28px] font-light leading-none text-slate-500 shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:shadow-black/30 md:bottom-5"
|
||||
class="sticky bottom-4 left-1/2 z-30 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-slate-100 bg-white text-[28px] font-light leading-none text-slate-500 shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:shadow-black/30 md:bottom-6"
|
||||
:title="$t('chat.scrollToLatest')"
|
||||
@click="emit('scroll-to-bottom')"
|
||||
>
|
||||
|
||||
@@ -290,14 +290,11 @@ export function useChat() {
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => {
|
||||
<<<<<<< HEAD
|
||||
const displayQuery = String(context?.display_query || query || '').trim();
|
||||
=======
|
||||
clearLikelyCompletedStreamTimer();
|
||||
cancelActiveStream();
|
||||
const controller = new AbortController();
|
||||
activeStreamController.value = controller;
|
||||
>>>>>>> dev
|
||||
const runViewId = viewId.value;
|
||||
const runMessages = messages.value;
|
||||
const run: ChatRun = {
|
||||
|
||||
@@ -66,7 +66,7 @@ export function resolveShippingNumericChoice(
|
||||
}
|
||||
|
||||
export function normalizeApiShippingButtons(
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string; source_code?: string }> | null,
|
||||
): ShippingActionButton[] {
|
||||
return (apiButtons || []).map((button) => ({
|
||||
...button,
|
||||
@@ -81,7 +81,7 @@ export function normalizeApiShippingButtons(
|
||||
*/
|
||||
export function resolveShippingActionButtons(
|
||||
content: string,
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string; source_code?: string }> | null,
|
||||
opts?: { apiResolved?: boolean },
|
||||
) {
|
||||
const directive = extractShippingActionsDirective(String(content || ''));
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件根据 action.id 决定触发后端接口、本地消息落库或前端 UI 行为。
|
||||
*/
|
||||
import {
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
generateWorkspaceShippingExcel,
|
||||
getWorkspaceShippingTask,
|
||||
matchWorkspaceShippingInventory,
|
||||
retryWorkspaceShippingUpload,
|
||||
type ShippingDecisionResponse,
|
||||
@@ -14,7 +16,7 @@ import {
|
||||
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingMatchResultPayload } from '../types/shipping.types';
|
||||
import type { ShippingActionButton, ShippingMatchResultPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMenuHandlerContext {
|
||||
@@ -42,9 +44,53 @@ export interface ShippingMenuHandlerContext {
|
||||
* @returns 菜单动作与按钮点击处理函数
|
||||
*/
|
||||
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
const normalizeInventorySourceText = (value: string) =>
|
||||
String(value || '')
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9]+/g, '');
|
||||
|
||||
const recentInventorySourceHint = () => {
|
||||
const parts: string[] = [];
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0 && parts.length < 6; i -= 1) {
|
||||
const content = String(ctx.messages.value[i]?.content || '').trim();
|
||||
if (content) parts.push(content);
|
||||
}
|
||||
return parts.join('\n');
|
||||
};
|
||||
|
||||
const resolveInventorySourceCodeFromContext = async (taskId: string): Promise<string> => {
|
||||
const detail = await getWorkspaceShippingTask(taskId);
|
||||
const resolution = detail.inventory_source_resolution;
|
||||
const candidates = resolution && typeof resolution === 'object'
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
: null;
|
||||
if (!Array.isArray(candidates) || candidates.length === 0) return '';
|
||||
if (candidates.length === 1) {
|
||||
const only = candidates[0];
|
||||
return only && typeof only === 'object'
|
||||
? String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase()
|
||||
: '';
|
||||
}
|
||||
const hint = normalizeInventorySourceText(recentInventorySourceHint());
|
||||
if (!hint) return '';
|
||||
const matches = candidates.filter((item) => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
|
||||
const values = [
|
||||
source.source_code,
|
||||
source.display_name,
|
||||
source.warehouse_code,
|
||||
source.program_name,
|
||||
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
|
||||
return values.some((value) => hint.includes(value) || value.includes(hint));
|
||||
});
|
||||
if (matches.length !== 1) return '';
|
||||
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
||||
};
|
||||
|
||||
const buildMatchResultPayload = (
|
||||
taskId: string,
|
||||
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger' }> },
|
||||
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger'; source_code?: string }> },
|
||||
): ShippingMatchResultPayload => {
|
||||
const data = (result?.data && typeof result.data === 'object') ? result.data as Record<string, unknown> : {};
|
||||
const lineResults = Array.isArray(data.line_results)
|
||||
@@ -68,7 +114,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
|
||||
const handleShippingMenuAction = async (
|
||||
action: { id?: string; message: string },
|
||||
action: ShippingActionButton | { id?: string; message: string },
|
||||
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
||||
) => {
|
||||
if (ctx.isThinking.value) return;
|
||||
@@ -163,6 +209,57 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'confirm_inventory_source') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
||||
if (!sourceCode) {
|
||||
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
|
||||
}
|
||||
if (!sourceCode) {
|
||||
ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。');
|
||||
if (chatMsg) chatMsg.shipping_actions_used = false;
|
||||
return;
|
||||
}
|
||||
const result = await confirmWorkspaceShippingInventorySource(taskId, sourceCode);
|
||||
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
|
||||
const userText = `确认库存查询来源:${label}`;
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${userText}\n任务编号:${taskId}`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: String(result.message || '').trim(),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
if (chatMsg) chatMsg.shipping_actions_used = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'retry_resolve_inventory_source') {
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.info('已重新刷新库存源状态');
|
||||
return;
|
||||
}
|
||||
if (action.id === 'edit_inventory_mapping') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
@@ -246,7 +343,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
|
||||
const handleShippingActionClick = async (
|
||||
chatMsg: ChatMessage & { shipping_actions_used?: boolean },
|
||||
action: { id?: string; message: string },
|
||||
action: ShippingActionButton,
|
||||
) => {
|
||||
await handleShippingMenuAction(action, chatMsg);
|
||||
};
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
*/
|
||||
import {
|
||||
applyWorkspaceShippingInventoryMapping,
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
generateWorkspaceShippingExcel,
|
||||
getWorkspaceShippingBatch,
|
||||
getWorkspaceShippingTask,
|
||||
switchWorkspaceShippingBatchFocusTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
@@ -79,6 +81,59 @@ export interface ShippingSendHandlerContext {
|
||||
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
|
||||
*/
|
||||
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
const normalizeInventorySourceText = (value: string) =>
|
||||
String(value || '')
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9]+/g, '');
|
||||
|
||||
const tryConfirmInventorySourceFromText = async (content: string): Promise<boolean> => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) return false;
|
||||
const normalized = normalizeInventorySourceText(content);
|
||||
if (!normalized) return false;
|
||||
try {
|
||||
const detail = await getWorkspaceShippingTask(taskId);
|
||||
if (detail.pending_human_reason !== 'inventory_source_unresolved') return false;
|
||||
const resolution = detail.inventory_source_resolution;
|
||||
const candidates = resolution && typeof resolution === 'object'
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
: null;
|
||||
if (!Array.isArray(candidates) || candidates.length === 0) return false;
|
||||
const hit = candidates.find((item) => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
|
||||
const values = [
|
||||
source.source_code,
|
||||
source.display_name,
|
||||
source.warehouse_code,
|
||||
source.program_name,
|
||||
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
|
||||
return values.some((value) => normalized === value || normalized.includes(value) || value.includes(normalized));
|
||||
}) as { source_code?: unknown; display_name?: unknown } | undefined;
|
||||
const sourceCode = String(hit?.source_code || '').trim().toUpperCase();
|
||||
if (!sourceCode) return false;
|
||||
if (typeof content !== 'string') return false;
|
||||
ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
const label = String(hit?.display_name || sourceCode).trim();
|
||||
await ctx.pushShippingLocalUserMessage(content.trim());
|
||||
const result = await confirmWorkspaceShippingInventorySource(taskId, sourceCode);
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
String(result.message || '').trim(),
|
||||
`已确认库存查询来源:${label}`,
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
|
||||
const intent = parseShippingTaskSwitchIntent(content);
|
||||
if (!intent) return false;
|
||||
@@ -187,6 +242,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
ctx.attachments.value = [];
|
||||
return true;
|
||||
}
|
||||
if (await tryConfirmInventorySourceFromText(content)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
return true;
|
||||
}
|
||||
const assistantCtx = ctx.lastAssistantMessageContent();
|
||||
const numericText = content.trim();
|
||||
if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) {
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface ShippingTaskSummary {
|
||||
step_payload?: Record<string, unknown> & {
|
||||
current_step_progress?: ShippingCurrentStepProgress;
|
||||
};
|
||||
rpa_inventory_source?: Record<string, unknown> | null;
|
||||
inventory_source_resolution?: Record<string, unknown> | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
@@ -104,6 +106,7 @@ export interface ShippingChatAction {
|
||||
label: string;
|
||||
message: string;
|
||||
variant: 'primary' | 'secondary' | 'danger';
|
||||
source_code?: string;
|
||||
}
|
||||
|
||||
export interface ShippingChatActionsResponse {
|
||||
|
||||
@@ -82,6 +82,7 @@ export interface ShippingMatchResultPayload {
|
||||
label: string;
|
||||
message: string;
|
||||
variant: 'primary' | 'secondary' | 'danger';
|
||||
source_code?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
@@ -90,4 +91,5 @@ export interface ShippingActionButton {
|
||||
label: string;
|
||||
message: string;
|
||||
variant?: ShippingActionVariant;
|
||||
source_code?: string;
|
||||
}
|
||||
@@ -77,9 +77,9 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
||||
const failureModalPage = ref(1);
|
||||
const retryingFailureKey = ref('');
|
||||
|
||||
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
|
||||
const documentStageFilter = ref<'all' | 'pending_clean' | 'cleaning' | 'pending_sync' | 'failed'>('all');
|
||||
const documentListPage = ref(1);
|
||||
const documentListPageSize = ref(20);
|
||||
const documentListPageSize = ref(10);
|
||||
const documentKeyword = ref('');
|
||||
const batchSubmitting = ref(false);
|
||||
const selectedDocumentIds = ref<number[]>([]);
|
||||
|
||||
@@ -98,17 +98,20 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
|
||||
|
||||
const matchesDocumentStageFilter = (
|
||||
doc: KbDocumentItem,
|
||||
filter: 'all' | 'upload' | 'clean' | 'sync',
|
||||
filter: 'all' | 'pending_clean' | 'cleaning' | 'pending_sync' | 'failed',
|
||||
) => {
|
||||
const workflow = resolveWorkflowState(doc);
|
||||
if (filter === 'all') return true;
|
||||
if (filter === 'upload') {
|
||||
return workflow.upload.code !== 'success';
|
||||
if (filter === 'pending_clean') {
|
||||
return workflow.clean.code === 'pending';
|
||||
}
|
||||
if (filter === 'clean') {
|
||||
return ['pending', 'queued', 'running', 'failed'].includes(workflow.clean.code);
|
||||
if (filter === 'cleaning') {
|
||||
return ['queued', 'running'].includes(workflow.clean.code);
|
||||
}
|
||||
return ['pending', 'running', 'failed'].includes(workflow.sync.code);
|
||||
if (filter === 'pending_sync') {
|
||||
return workflow.sync.code === 'pending';
|
||||
}
|
||||
return [workflow.upload.code, workflow.clean.code, workflow.sync.code].includes('failed');
|
||||
};
|
||||
|
||||
const matchesDocumentKeyword = (doc: KbDocumentItem, keyword: string) => {
|
||||
@@ -125,11 +128,12 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
|
||||
};
|
||||
|
||||
const stageFilterTabs = computed(() => {
|
||||
const filters: Array<{ key: 'all' | 'upload' | 'clean' | 'sync'; label: string }> = [
|
||||
const filters: Array<{ key: 'all' | 'pending_clean' | 'cleaning' | 'pending_sync' | 'failed'; label: string }> = [
|
||||
{ key: 'all', label: t('kbWorkspace.filters.all') },
|
||||
{ key: 'upload', label: t('kbWorkspace.filters.upload') },
|
||||
{ key: 'clean', label: t('kbWorkspace.filters.clean') },
|
||||
{ key: 'sync', label: t('kbWorkspace.filters.sync') },
|
||||
{ key: 'pending_clean', label: t('kbWorkspace.filters.pendingClean') },
|
||||
{ key: 'cleaning', label: t('kbWorkspace.filters.cleaning') },
|
||||
{ key: 'pending_sync', label: t('kbWorkspace.filters.pendingSync') },
|
||||
{ key: 'failed', label: t('kbWorkspace.filters.failed') },
|
||||
];
|
||||
return filters.map((item) => ({
|
||||
...item,
|
||||
|
||||
@@ -46,6 +46,7 @@ export function useKbWorkspaceData(
|
||||
selectedDocumentIds,
|
||||
showPathUploadDetails,
|
||||
selectedPathUploadHistoryJobId,
|
||||
router,
|
||||
} = state;
|
||||
|
||||
const { t } = state;
|
||||
@@ -189,6 +190,9 @@ export function useKbWorkspaceData(
|
||||
};
|
||||
|
||||
const openGroupDetail = async (groupId: number) => {
|
||||
if (viewMode.value === 'group_overview') {
|
||||
await router.push({ name: 'workspace-knowledge-base-group', params: { groupId } });
|
||||
}
|
||||
selectedGroupId.value = groupId;
|
||||
viewMode.value = 'group_detail';
|
||||
feedback.value = '';
|
||||
@@ -197,6 +201,9 @@ export function useKbWorkspaceData(
|
||||
};
|
||||
|
||||
const backToGroupOverview = () => {
|
||||
if (viewMode.value === 'group_detail') {
|
||||
void router.push({ name: 'workspace-knowledge-base' });
|
||||
}
|
||||
viewMode.value = 'group_overview';
|
||||
selectedGroupId.value = null;
|
||||
documents.value = [];
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 知识库作业面编排入口:组合 state / computed / data / pathUpload / documents / modals。
|
||||
*/
|
||||
import { onMounted, onUnmounted, reactive, watch } from 'vue';
|
||||
import { computed as vueComputed, onMounted, onUnmounted, reactive, watch } from 'vue';
|
||||
import {
|
||||
DOCUMENT_PAGE_SIZE_OPTIONS,
|
||||
FAILURE_PAGE_SIZE,
|
||||
@@ -76,6 +76,29 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
|
||||
} = computed;
|
||||
|
||||
const { applyPathUploadJob } = pathUpload;
|
||||
const routeGroupId = vueComputed(() => {
|
||||
const raw = state.router.currentRoute.value.params.groupId;
|
||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
});
|
||||
|
||||
const syncViewModeFromRoute = () => {
|
||||
const groupId = routeGroupId.value;
|
||||
if (groupId) {
|
||||
state.viewMode.value = 'group_detail';
|
||||
if (selectedGroupId.value !== groupId) {
|
||||
selectedGroupId.value = groupId;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (state.embedded) {
|
||||
state.viewMode.value = 'group_overview';
|
||||
if (selectedGroupId.value !== null) {
|
||||
selectedGroupId.value = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// --- 筛选/分页/路径上传历史联动 ---
|
||||
watch(selectedGroupId, (groupId) => {
|
||||
@@ -90,6 +113,10 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
|
||||
applyPathUploadJob(latestPathUploadJob.value);
|
||||
});
|
||||
|
||||
watch(routeGroupId, () => {
|
||||
syncViewModeFromRoute();
|
||||
});
|
||||
|
||||
watch(documentStageFilter, () => {
|
||||
documentListPage.value = 1;
|
||||
});
|
||||
@@ -117,6 +144,7 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
syncViewModeFromRoute();
|
||||
await Promise.all([data.loadGroups(), data.loadJobs()]);
|
||||
if (state.viewMode.value === 'group_detail') {
|
||||
await data.loadDocuments(selectedGroupId.value);
|
||||
|
||||
@@ -52,7 +52,7 @@ export const FAILURE_PAGE_SIZE = 15;
|
||||
export const PATH_UPLOAD_BATCH_SIZE = 30;
|
||||
export const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
|
||||
export const PATH_UPLOAD_CONCURRENCY = 3;
|
||||
export const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
|
||||
export const DOCUMENT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
|
||||
|
||||
/** 未开始阶段的徽标样式,与 getStatusBadgeClass 默认一致 */
|
||||
export const IDLE_BADGE_CLASS = 'border-default bg-surface-soft text-muted';
|
||||
@@ -46,11 +46,12 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
v-if="kb.viewMode !== 'group_overview'"
|
||||
@click="kb.refreshCurrentView"
|
||||
class="btn-secondary"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.actions.refreshGroups') : kb.t('kbWorkspace.actions.refreshDocuments') }}
|
||||
{{ kb.t('kbWorkspace.actions.refreshDocuments') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="kb.viewMode === 'group_overview'"
|
||||
@@ -66,9 +67,8 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
|
||||
<template v-if="kb.viewMode === 'group_overview'">
|
||||
<section class="kb-ws-section">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<div class="mb-4 flex items-center">
|
||||
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.overview.title') }}</h2>
|
||||
<span class="text-xs text-muted">`/api/kb/groups`</span>
|
||||
</div>
|
||||
<div v-if="kb.isLoading" class="py-10 text-center text-sm text-muted">{{ kb.t('kbWorkspace.overview.loadingGroups') }}</div>
|
||||
<div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center text-sm text-muted">
|
||||
@@ -101,29 +101,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="kb-ws-stat-grid">
|
||||
<div
|
||||
v-for="item in kb.groupSummaryItems"
|
||||
:key="item.label"
|
||||
class="kb-ws-stat-tile "
|
||||
:class="[
|
||||
item.wide ? 'col-span-2 xl:col-span-2' : '',
|
||||
item.clickable
|
||||
? 'cursor-pointer hover:bg-rose-50 hover:bg-rose-50'
|
||||
: '',
|
||||
]"
|
||||
@click="item.clickable && item.failureType ? kb.openFailureModal(item.failureType) : undefined"
|
||||
>
|
||||
<div
|
||||
class="text-base font-semibold text-primary break-words"
|
||||
:style="item.wide ? '-webkit-line-clamp: 2; -webkit-box-orient: vertical; display: -webkit-box; overflow: hidden;' : undefined"
|
||||
>
|
||||
{{ item.value }}
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-muted">{{ item.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
|
||||
<input
|
||||
:ref="(el) => { kb.fileInputRef = el as HTMLInputElement | null }"
|
||||
type="file"
|
||||
@@ -140,54 +117,49 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
class="hidden"
|
||||
@change="kb.handlePathFilesSelected"
|
||||
/>
|
||||
<section class="kb-ws-section">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.sidebar.groupsTitle') }}</h2>
|
||||
</div>
|
||||
|
||||
<div v-if="kb.isLoading" class="py-10 text-center text-sm text-muted">{{ kb.t('kbWorkspace.sidebar.loadingGroups') }}</div>
|
||||
<div v-else-if="kb.groups.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-8 text-center text-sm text-muted ">
|
||||
{{ kb.t('kbWorkspace.sidebar.emptyGroups') }}
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<button
|
||||
v-for="group in kb.groups"
|
||||
:key="group.id"
|
||||
@click="kb.selectedGroupId = group.id"
|
||||
class="kb-ws-group-list-btn"
|
||||
:class="{ 'kb-ws-group-list-btn--active': kb.selectedGroupId === group.id }"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-semibold">{{ group.name }}</div>
|
||||
<div class="mt-1 text-sm opacity-80">{{ group.description || kb.t('kbWorkspace.sidebar.noDescription') }}</div>
|
||||
</div>
|
||||
<span class="rounded-full bg-surface/70 px-2 py-1 text-xs ">
|
||||
{{ group.document_count ?? 0 }}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-6">
|
||||
<div class="kb-ws-section">
|
||||
<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs font-medium text-muted">{{ kb.t('kbWorkspace.summary.currentGroup') }}</div>
|
||||
<h2 class="mt-1 text-2xl font-bold text-primary break-words">{{ kb.selectedGroup?.name || '--' }}</h2>
|
||||
<p class="mt-2 max-w-3xl text-sm text-muted">
|
||||
{{ kb.selectedGroup?.description || kb.t('kbWorkspace.overview.noDescription') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid min-w-full grid-cols-2 gap-2 sm:grid-cols-5 lg:min-w-[520px]">
|
||||
<button
|
||||
v-for="item in kb.groupSummaryItems.filter((summary) => !summary.wide)"
|
||||
:key="item.label"
|
||||
type="button"
|
||||
class="rounded-2xl border border-default bg-surface-soft px-3 py-3 text-left transition-colors"
|
||||
:class="item.clickable ? 'hover:border-rose-200 hover:bg-rose-50' : ''"
|
||||
@click="item.clickable && item.failureType ? kb.openFailureModal(item.failureType) : undefined"
|
||||
>
|
||||
<div class="text-lg font-semibold text-primary">{{ item.value }}</div>
|
||||
<div class="mt-1 text-xs text-muted">{{ item.label }}</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kb-ws-section">
|
||||
<div class="mb-4 space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.documents.title') }}</h2>
|
||||
<div class="group relative">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-500 hover:border-brand-300 hover:text-brand-600"
|
||||
>
|
||||
<Info class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
|
||||
{{ kb.t('kbWorkspace.documents.infoTip') }}
|
||||
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.documents.title') }}</h2>
|
||||
<div class="group relative">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-600"
|
||||
>
|
||||
<Info class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
|
||||
{{ kb.t('kbWorkspace.documents.infoTip') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
v-if="kb.selectedGroupId"
|
||||
@@ -209,62 +181,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
v-if="kb.isKbAdmin && kb.selectedGroupId"
|
||||
@click="kb.handleBatchClean"
|
||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-amber-200 px-4 py-2.5 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="kb.isKbAdmin && kb.selectedGroupId"
|
||||
@click="kb.handleBatchSync"
|
||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-emerald-200 px-4 py-2.5 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="kb.selectedGroupId"
|
||||
@click="kb.handleBatchDelete"
|
||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-rose-200 px-4 py-2.5 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="kb.selectedGroupId"
|
||||
@click="kb.openPathUploadHistoryModal()"
|
||||
class="btn-secondary"
|
||||
>
|
||||
<FileText class="h-4 w-4" />
|
||||
{{ kb.t('kbWorkspace.documents.historyBatches') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="kb.selectedGroupId" class="flex flex-wrap items-center gap-3">
|
||||
<label class="relative w-full max-w-md">
|
||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
|
||||
<input
|
||||
v-model.trim="kb.documentKeyword"
|
||||
type="text"
|
||||
class="w-full rounded-2xl border border-default bg-surface py-2.5 pl-10 pr-4 text-sm text-primary outline-none transition-colors focus:border-brand-300"
|
||||
:placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
v-if="kb.documentKeyword"
|
||||
type="button"
|
||||
@click="kb.documentKeyword = ''"
|
||||
class="inline-flex items-center rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
|
||||
>
|
||||
{{ kb.t('kbWorkspace.documents.clearSearch') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p
|
||||
@@ -373,41 +289,99 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</div>
|
||||
<div
|
||||
v-if="kb.selectedGroupId"
|
||||
class="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-surface-soft px-4 py-3 "
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
@click="kb.toggleSelectAllFiltered"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-default bg-surface px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
|
||||
>
|
||||
{{ kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="tab in kb.stageFilterTabs"
|
||||
:key="tab.key"
|
||||
@click="kb.documentStageFilter = tab.key"
|
||||
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
|
||||
:class="kb.documentStageFilter === tab.key
|
||||
? 'border-brand-200 bg-brand-50 text-brand-700 border-brand-200 '
|
||||
: 'border-default bg-surface text-secondary hover:bg-surface-soft hover-surface-soft'"
|
||||
>
|
||||
<span>{{ tab.label }}</span>
|
||||
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs ">{{ tab.count }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
|
||||
<label class="inline-flex items-center gap-2">
|
||||
<span>{{ kb.t('kbWorkspace.common.perPage') }}</span>
|
||||
<select
|
||||
v-model.number="kb.documentListPageSize"
|
||||
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
|
||||
class="mb-4 space-y-3 rounded-2xl bg-surface-soft px-4 py-3"
|
||||
>
|
||||
<div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
v-for="tab in kb.stageFilterTabs"
|
||||
:key="tab.key"
|
||||
@click="kb.documentStageFilter = tab.key"
|
||||
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
|
||||
:class="kb.documentStageFilter === tab.key
|
||||
? 'border-brand-200 bg-brand-50 text-brand-700'
|
||||
: 'border-default bg-surface text-secondary hover:bg-surface-soft'"
|
||||
>
|
||||
<option v-for="size in kb.DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
|
||||
</select>
|
||||
<span>{{ kb.t('kbWorkspace.common.countUnit') }}</span>
|
||||
</label>
|
||||
<span>{{ kb.t('kbWorkspace.documents.selectedCount', { selected: kb.selectedDocuments.length, total: kb.filteredDocuments.length }) }}</span>
|
||||
<span v-if="kb.filteredDocuments.length > 0">{{ kb.t('kbWorkspace.documents.showingRange', { start: kb.pagedDocumentRange.start, end: kb.pagedDocumentRange.end }) }}</span>
|
||||
<span>{{ tab.label }}</span>
|
||||
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs">{{ tab.count }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
|
||||
<label class="relative min-w-[260px] flex-1 xl:w-80 xl:flex-none">
|
||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
|
||||
<input
|
||||
v-model.trim="kb.documentKeyword"
|
||||
type="text"
|
||||
class="w-full rounded-2xl border border-default bg-surface py-2.5 pl-10 pr-4 text-sm text-primary outline-none transition-colors focus:border-brand-300"
|
||||
:placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
v-if="kb.documentKeyword"
|
||||
type="button"
|
||||
@click="kb.documentKeyword = ''"
|
||||
class="inline-flex items-center rounded-xl border border-default bg-surface px-3 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
|
||||
>
|
||||
{{ kb.t('kbWorkspace.documents.clearSearch') }}
|
||||
</button>
|
||||
<label class="inline-flex items-center gap-2">
|
||||
<span>{{ kb.t('kbWorkspace.common.perPage') }}</span>
|
||||
<select
|
||||
v-model.number="kb.documentListPageSize"
|
||||
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
|
||||
>
|
||||
<option v-for="size in kb.DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
|
||||
</select>
|
||||
<span>{{ kb.t('kbWorkspace.common.countUnit') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-3 border-t border-default pt-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
@click="kb.toggleSelectAllFiltered"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-default bg-surface px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
|
||||
>
|
||||
{{ kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="kb.isKbAdmin"
|
||||
@click="kb.handleBatchClean"
|
||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-amber-200 bg-surface px-4 py-2 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="kb.isKbAdmin"
|
||||
@click="kb.handleBatchSync"
|
||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-surface px-4 py-2 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||
</button>
|
||||
<button
|
||||
@click="kb.handleBatchDelete"
|
||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-rose-200 bg-surface px-4 py-2 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||
</button>
|
||||
<button
|
||||
@click="kb.openPathUploadHistoryModal()"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-default bg-surface px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
|
||||
>
|
||||
<FileText class="h-4 w-4" />
|
||||
{{ kb.t('kbWorkspace.documents.historyBatches') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
|
||||
<span>{{ kb.t('kbWorkspace.documents.selectedCount', { selected: kb.selectedDocuments.length, total: kb.filteredDocuments.length }) }}</span>
|
||||
<span v-if="kb.filteredDocuments.length > 0">{{ kb.t('kbWorkspace.documents.showingRange', { start: kb.pagedDocumentRange.start, end: kb.pagedDocumentRange.end }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -424,13 +398,13 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
<div
|
||||
v-for="doc in kb.pagedFilteredDocuments"
|
||||
:key="doc.id"
|
||||
class="rounded-2xl border px-4 py-4 transition-colors"
|
||||
class="rounded-2xl border px-4 py-3 transition-colors"
|
||||
:class="kb.selectedDocumentId === doc.id
|
||||
? 'border-brand-200 bg-brand-50/50 border-brand-200'
|
||||
: 'border-default'"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 flex-1 gap-3">
|
||||
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.3fr)_minmax(360px,0.9fr)_auto] xl:items-center">
|
||||
<div class="flex min-w-0 gap-3">
|
||||
<label class="mt-1 inline-flex shrink-0 cursor-pointer items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -440,35 +414,53 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
/>
|
||||
</label>
|
||||
<div class="min-w-0 flex-1">
|
||||
<button
|
||||
@click="kb.openMarkdownEditor(doc)"
|
||||
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600"
|
||||
>
|
||||
{{ kb.getDocumentDisplayTitle(doc) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="kb.openSourceInfo(doc)"
|
||||
class="mt-1 block max-w-full text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
|
||||
>
|
||||
{{ kb.getDocumentDisplayDescription(doc) }}
|
||||
</button>
|
||||
<div class="mt-2 text-xs text-muted">
|
||||
<span>{{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}</span>
|
||||
<span v-if="doc.latest_version">
|
||||
<span>{{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}</span>
|
||||
<button
|
||||
@click="kb.openMarkdownEditor(doc)"
|
||||
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600"
|
||||
>
|
||||
{{ kb.getDocumentDisplayTitle(doc) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="kb.openSourceInfo(doc)"
|
||||
class="mt-1 block max-w-full truncate text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
|
||||
>
|
||||
{{ kb.getDocumentDisplayDescription(doc) }}
|
||||
</button>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
|
||||
<span>{{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}</span>
|
||||
<span v-if="doc.latest_version">{{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}</span>
|
||||
<button
|
||||
v-if="doc.latest_version"
|
||||
type="button"
|
||||
@click="kb.openSourceInfo(doc)"
|
||||
class="inline text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
|
||||
>
|
||||
class="max-w-full truncate text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
|
||||
>
|
||||
{{ doc.latest_version.source_file_name }}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<span>{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="kb.getDocumentWorkflowState(doc).primaryError"
|
||||
class="mt-1 max-w-xl text-xs text-rose-500"
|
||||
>
|
||||
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 xl:justify-end">
|
||||
<div
|
||||
v-for="badge in kb.getWorkflowBadges(doc)"
|
||||
:key="`${doc.id}-${badge.label}`"
|
||||
class="inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold"
|
||||
:class="badge.className"
|
||||
>
|
||||
{{ badge.label }}:{{ badge.value }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 xl:justify-end">
|
||||
<button
|
||||
@click="kb.openDocumentDetail(doc.id)"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
|
||||
@@ -501,32 +493,9 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex items-end justify-between gap-3 border-t border-default pt-3 ">
|
||||
<div class="space-y-1">
|
||||
<div class="text-xs text-muted">
|
||||
{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="kb.getDocumentWorkflowState(doc).primaryError"
|
||||
class="max-w-xl text-xs text-rose-500"
|
||||
>
|
||||
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<div
|
||||
v-for="badge in kb.getWorkflowBadges(doc)"
|
||||
:key="`${doc.id}-${badge.label}`"
|
||||
class="inline-flex items-center rounded-full border px-3 py-1 text-sm font-semibold"
|
||||
:class="badge.className"
|
||||
>
|
||||
{{ badge.label }}:{{ badge.value }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="kb.filteredDocuments.length > kb.documentListPageSize"
|
||||
v-if="kb.filteredDocuments.length > 0"
|
||||
class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
|
||||
>
|
||||
<div class="text-sm text-muted">
|
||||
@@ -552,7 +521,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,11 +6,15 @@
|
||||
import { inject } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import {
|
||||
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package,
|
||||
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
|
||||
defineProps<{
|
||||
collapsed?: boolean;
|
||||
}>();
|
||||
|
||||
const ws = inject(WORKSPACE_KEY)! as any;
|
||||
const route = useRoute();
|
||||
|
||||
@@ -30,54 +34,97 @@ function isActive(match: readonly string[]) {
|
||||
|
||||
<template>
|
||||
<aside class="lg:sticky lg:top-0 lg:h-screen">
|
||||
<div class="flex h-full flex-col border-r border-default bg-surface px-5 py-6 shadow-sm">
|
||||
<div class="border-b border-subtle pb-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-white shadow-lg shadow-brand-500/25">
|
||||
<Bot class="h-6 w-6" />
|
||||
<div
|
||||
class="flex h-full flex-col border-r border-default bg-surface shadow-sm transition-all duration-200"
|
||||
:class="collapsed ? 'px-3 py-4' : 'px-4 py-4'"
|
||||
>
|
||||
<template v-if="collapsed">
|
||||
<button
|
||||
type="button"
|
||||
class="mb-6 inline-flex h-10 w-full items-center justify-center rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
|
||||
:title="$t('workspace.expandSidebar')"
|
||||
@click="ws.toggleSidebarCollapsed"
|
||||
>
|
||||
<PanelLeftOpen class="h-5 w-5" />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<div class="border-b border-subtle pb-4">
|
||||
<div class="flex items-center gap-3" :class="collapsed ? 'justify-center' : ''">
|
||||
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">
|
||||
AI
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-2xl font-extrabold tracking-tight text-primary">{{ $t('workspace.brandTitle') }}</div>
|
||||
<div class="truncate text-xs font-medium text-muted">
|
||||
<div v-if="!collapsed" class="min-w-0 flex-1">
|
||||
<div class="truncate text-lg font-bold text-primary">{{ $t('workspace.brandTitle') }}</div>
|
||||
<div class="mt-1 truncate text-[11px] text-muted">
|
||||
{{ ws.currentUser?.username }} / {{ ws.currentUser?.role }}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="!collapsed"
|
||||
type="button"
|
||||
class="ml-2 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
|
||||
:title="$t('workspace.collapseSidebar')"
|
||||
@click="ws.toggleSidebarCollapsed"
|
||||
>
|
||||
<PanelLeftClose class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 py-6">
|
||||
<div class="flex-1 py-4">
|
||||
<nav class="space-y-2">
|
||||
<RouterLink
|
||||
v-for="item in linkItems"
|
||||
:key="item.path"
|
||||
:to="item.path"
|
||||
class="ws-nav-btn"
|
||||
:class="{ 'ws-nav-btn--active': isActive(item.match) }"
|
||||
:class="[
|
||||
{ 'ws-nav-btn--active': isActive(item.match) },
|
||||
collapsed ? 'justify-center px-0' : '',
|
||||
]"
|
||||
:title="$t(item.labelKey)"
|
||||
>
|
||||
<component :is="item.icon" class="h-4 w-4" />
|
||||
<span>{{ $t(item.labelKey) }}</span>
|
||||
<component :is="item.icon" class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed">{{ $t(item.labelKey) }}</span>
|
||||
</RouterLink>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-nav-btn w-full"
|
||||
:class="{ 'ws-nav-btn--active': isActive(['workspace-knowledge-base']) }"
|
||||
:class="[
|
||||
{ 'ws-nav-btn--active': isActive(['workspace-knowledge-base', 'workspace-knowledge-base-group']) },
|
||||
collapsed ? 'justify-center px-0' : '',
|
||||
]"
|
||||
:title="$t('workspace.nav.knowledgeBase')"
|
||||
@click="ws.navigateToKnowledgeBase"
|
||||
>
|
||||
<FileText class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.knowledgeBase') }}</span>
|
||||
<FileText class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed">{{ $t('workspace.nav.knowledgeBase') }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-subtle pt-6">
|
||||
<div class="border-t border-subtle pt-4">
|
||||
<div class="space-y-2">
|
||||
<button type="button" @click="ws.navigateToGeneralChat" class="ws-nav-btn">
|
||||
<Bot class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.backToChat') }}</span>
|
||||
<button
|
||||
type="button"
|
||||
@click="ws.navigateToGeneralChat"
|
||||
class="ws-nav-btn"
|
||||
:class="collapsed ? 'justify-center px-0' : ''"
|
||||
:title="$t('workspace.nav.backToChat')"
|
||||
>
|
||||
<Bot class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed">{{ $t('workspace.nav.backToChat') }}</span>
|
||||
</button>
|
||||
<button type="button" @click="ws.handleLogout" class="ws-nav-btn ws-nav-btn--danger">
|
||||
<LogOut class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.logout') }}</span>
|
||||
<button
|
||||
type="button"
|
||||
@click="ws.handleLogout"
|
||||
class="ws-nav-btn ws-nav-btn--danger"
|
||||
:class="collapsed ? 'justify-center px-0' : ''"
|
||||
:title="$t('workspace.nav.logout')"
|
||||
>
|
||||
<LogOut class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed">{{ $t('workspace.nav.logout') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -30,6 +30,7 @@ export function useWorkspace() {
|
||||
const deps = { t, locale, msg, router, route, setThemePreference, appliedTheme };
|
||||
const isLoading = ref(true);
|
||||
const currentUser = ref<WorkspaceUser | null>(null);
|
||||
const isSidebarCollapsed = ref(false);
|
||||
|
||||
const sessionRef: { handleLogout?: () => void } = {};
|
||||
const home = useWorkspaceHome(deps, {
|
||||
@@ -65,6 +66,7 @@ export function useWorkspace() {
|
||||
onMounted(async () => {
|
||||
window.addEventListener('hxops:logout', session.onAuthLogout);
|
||||
localeApi.loadLanguagePreference();
|
||||
isSidebarCollapsed.value = localStorage.getItem('hxops.workspace.sidebarCollapsed') === 'true';
|
||||
|
||||
session.loadAuthUser();
|
||||
if (!session.isLoggedIn.value) {
|
||||
@@ -88,6 +90,11 @@ export function useWorkspace() {
|
||||
window.removeEventListener('hxops:logout', session.onAuthLogout);
|
||||
});
|
||||
|
||||
const toggleSidebarCollapsed = () => {
|
||||
isSidebarCollapsed.value = !isSidebarCollapsed.value;
|
||||
localStorage.setItem('hxops.workspace.sidebarCollapsed', String(isSidebarCollapsed.value));
|
||||
};
|
||||
|
||||
return reactive({
|
||||
config,
|
||||
msg,
|
||||
@@ -95,6 +102,8 @@ export function useWorkspace() {
|
||||
route,
|
||||
isMobile,
|
||||
isLoading,
|
||||
isSidebarCollapsed,
|
||||
toggleSidebarCollapsed,
|
||||
...localeApi,
|
||||
...session,
|
||||
...home,
|
||||
|
||||
@@ -17,6 +17,7 @@ const ROUTE_NAME_TO_SIDEBAR: Record<string, WorkspaceSidebarItem> = {
|
||||
'workspace-applications': 'applications',
|
||||
'workspace-updates': 'updates',
|
||||
'workspace-knowledge-base': 'knowledge_base',
|
||||
'workspace-knowledge-base-group': 'knowledge_base',
|
||||
'workspace-schedule-runs': 'schedule_runs',
|
||||
'workspace-shipping-notice': 'shipping_notice',
|
||||
'workspace-feedback': 'feedback',
|
||||
@@ -173,7 +174,7 @@ export function useWorkspaceNavigation(deps: WorkspaceDeps, options: NavigationO
|
||||
if (name === 'workspace-schedule-runs') {
|
||||
await loadWorkspaceScheduleRuns();
|
||||
}
|
||||
if (name === 'workspace-knowledge-base' && !hasKnowledgeBaseAccess.value) {
|
||||
if (['workspace-knowledge-base', 'workspace-knowledge-base-group'].includes(name) && !hasKnowledgeBaseAccess.value) {
|
||||
showKnowledgeBaseAccessDenied();
|
||||
await router.replace(WORKSPACE_PATHS.applications);
|
||||
}
|
||||
|
||||
@@ -42,8 +42,11 @@ const mobileTabs = [
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)]">
|
||||
<WorkspaceSidebar v-if="!ws.isMobile" />
|
||||
<div
|
||||
class="grid min-h-screen gap-0 transition-[grid-template-columns] duration-200"
|
||||
:class="ws.isMobile ? '' : (ws.isSidebarCollapsed ? 'lg:grid-cols-[72px_minmax(0,1fr)]' : 'lg:grid-cols-[320px_minmax(0,1fr)]')"
|
||||
>
|
||||
<WorkspaceSidebar v-if="!ws.isMobile" :collapsed="ws.isSidebarCollapsed" />
|
||||
|
||||
<section class="ws-main" :class="ws.isMobile ? 'pb-20' : ''">
|
||||
<RouterView />
|
||||
|
||||
@@ -144,9 +144,10 @@
|
||||
},
|
||||
"filters": {
|
||||
"all": "All",
|
||||
"upload": "Upload",
|
||||
"clean": "Clean",
|
||||
"sync": "Sync"
|
||||
"pendingClean": "Pending clean",
|
||||
"cleaning": "Cleaning",
|
||||
"pendingSync": "Pending sync",
|
||||
"failed": "Failed"
|
||||
},
|
||||
"common": {
|
||||
"processing": "Processing...",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"title": "AI Workspace",
|
||||
"brandTitle": "Hexin AI Workspace",
|
||||
"collapseSidebar": "Collapse sidebar",
|
||||
"expandSidebar": "Expand sidebar",
|
||||
"languageLabel": "Language",
|
||||
"userTitle": "{username}'s AI Workspace",
|
||||
"subtitle": "Choose an agent or click a quick question to start",
|
||||
|
||||
@@ -144,9 +144,10 @@
|
||||
},
|
||||
"filters": {
|
||||
"all": "ทั้งหมด",
|
||||
"upload": "อัปโหลด",
|
||||
"clean": "ทำความสะอาด",
|
||||
"sync": "ซิงค์"
|
||||
"pendingClean": "รอทำความสะอาด",
|
||||
"cleaning": "กำลังทำความสะอาด",
|
||||
"pendingSync": "รอซิงค์",
|
||||
"failed": "ผิดปกติ"
|
||||
},
|
||||
"common": {
|
||||
"processing": "กำลังดำเนินการ...",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"title": "พื้นที่ทำงาน AI",
|
||||
"brandTitle": "Hexin AI Workspace",
|
||||
"collapseSidebar": "ยุบแถบนำทาง",
|
||||
"expandSidebar": "ขยายแถบนำทาง",
|
||||
"languageLabel": "ภาษา",
|
||||
"userTitle": "พื้นที่ทำงาน AI ของ {username}",
|
||||
"subtitle": "เลือกผู้ช่วยหรือคลิกคำถามด่วนเพื่อเริ่ม",
|
||||
|
||||
@@ -144,9 +144,10 @@
|
||||
},
|
||||
"filters": {
|
||||
"all": "全部",
|
||||
"upload": "上传",
|
||||
"clean": "清洗",
|
||||
"sync": "同步"
|
||||
"pendingClean": "待清洗",
|
||||
"cleaning": "清洗中",
|
||||
"pendingSync": "待同步",
|
||||
"failed": "异常"
|
||||
},
|
||||
"common": {
|
||||
"processing": "处理中...",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"title": "AI 工作台",
|
||||
"brandTitle": "AI工作台",
|
||||
"collapseSidebar": "折叠导航栏",
|
||||
"expandSidebar": "展开导航栏",
|
||||
"languageLabel": "语言",
|
||||
"userTitle": "{username} 的 AI 工作台",
|
||||
"subtitle": "选择一个助手,或点击常用问题快速开始",
|
||||
|
||||
@@ -144,9 +144,10 @@
|
||||
},
|
||||
"filters": {
|
||||
"all": "全部",
|
||||
"upload": "上傳",
|
||||
"clean": "清洗",
|
||||
"sync": "同步"
|
||||
"pendingClean": "待清洗",
|
||||
"cleaning": "清洗中",
|
||||
"pendingSync": "待同步",
|
||||
"failed": "異常"
|
||||
},
|
||||
"common": {
|
||||
"processing": "處理中...",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"title": "AI 工作台",
|
||||
"brandTitle": "AI工作台",
|
||||
"collapseSidebar": "折疊導航欄",
|
||||
"expandSidebar": "展開導航欄",
|
||||
"languageLabel": "語言",
|
||||
"userTitle": "{username} 的 AI 工作台",
|
||||
"subtitle": "選擇一個助手,或點擊常用問題快速開始",
|
||||
|
||||
@@ -765,7 +765,7 @@
|
||||
}
|
||||
|
||||
.ws-nav-btn {
|
||||
@apply flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all;
|
||||
@apply flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left text-sm font-medium transition-all;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
|
||||
+63
-3
@@ -29,9 +29,69 @@ python scripts/rpa/freight_rpa_worker.py
|
||||
|
||||
## 生产 RPA
|
||||
|
||||
`FREIGHT_RPA_MOCK=false` 时 worker **不会**自动处理触发文件,需业务按 SOP 用 UiPath / Power Automate 等:
|
||||
`FREIGHT_RPA_MOCK=false` 时 worker 会尝试用 Playwright 打开货代网站并下载库存 Excel。首次使用需要在 RPA 终端安装浏览器驱动:
|
||||
|
||||
1. 监听 `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 新 JSON → 登录货代 UI 导出库存 → 保存到 `FREIGHT_INVENTORY_DROP_DIR` → POST `inventory-ready`。
|
||||
2. 监听 `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` → 读取 `file_path` 在货代 UI 上传 → POST `upload-complete`。
|
||||
```powershell
|
||||
pip install playwright
|
||||
python -m playwright install chromium
|
||||
```
|
||||
|
||||
可以使用两种登录方式:
|
||||
|
||||
1. 自动登录:RPA worker 从本机环境变量读取账号密码,打开库存源 URL 后如检测到登录页则自动填写。
|
||||
2. 登录态复用:使用非 headless 模式先手工登录一次,登录态会保存在 `FREIGHT_RPA_BROWSER_PROFILE_DIR`。
|
||||
|
||||
账号密码不要写入 trigger JSON,也不要提交到代码仓库。建议配置为 Windows 用户级环境变量或企业凭据管理器注入的进程环境变量。
|
||||
|
||||
```powershell
|
||||
$env:FREIGHT_RPA_MOCK = "false"
|
||||
$env:FREIGHT_RPA_HEADLESS = "false"
|
||||
$env:FREIGHT_RPA_BROWSER_PROFILE_DIR = "backend/data/freight_rpa/browser_profile"
|
||||
|
||||
$env:FREIGHT_RPA_DSV_USERNAME = "<DSV账号>"
|
||||
$env:FREIGHT_RPA_DSV_PASSWORD = "<DSV密码>"
|
||||
$env:FREIGHT_RPA_CRANE_USERNAME = "<Crane账号>"
|
||||
$env:FREIGHT_RPA_CRANE_PASSWORD = "<Crane密码>"
|
||||
|
||||
python scripts/rpa/freight_rpa_worker.py
|
||||
```
|
||||
|
||||
如果登录框默认识别不稳定,可覆盖登录 selector:
|
||||
|
||||
| 环境变量 | 用途 |
|
||||
|---------|------|
|
||||
| `FREIGHT_RPA_DSV_USERNAME_SELECTOR` | DSV 用户名输入框 |
|
||||
| `FREIGHT_RPA_DSV_PASSWORD_SELECTOR` | DSV 密码输入框 |
|
||||
| `FREIGHT_RPA_DSV_LOGIN_BUTTON_SELECTOR` | DSV 登录按钮 |
|
||||
| `FREIGHT_RPA_CRANE_USERNAME_SELECTOR` | Crane 用户名输入框 |
|
||||
| `FREIGHT_RPA_CRANE_PASSWORD_SELECTOR` | Crane 密码输入框 |
|
||||
| `FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR` | Crane 登录按钮 |
|
||||
|
||||
若页面出现 MFA、验证码或 SSO 二次确认,worker 会失败并回调错误,需要人工处理后重试。
|
||||
|
||||
库存 trigger 需要包含 `rpa_inventory_source`,worker 会按 `source_type` 分发:
|
||||
|
||||
| source_type | Driver |
|
||||
|-------------|--------|
|
||||
| `dsv360` | 打开 DSV 360,进入 Reports / Program / Inventory 报表并下载 |
|
||||
| `crane_footprint` | 打开 Crane FootPrint On Hand Details Query,选择 Owner/Project/Warehouse 后下载 |
|
||||
|
||||
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
|
||||
|
||||
| 环境变量 | 用途 |
|
||||
|---------|------|
|
||||
| `FREIGHT_RPA_DSV_REPORTS_SELECTOR` | DSV Reports 菜单 |
|
||||
| `FREIGHT_RPA_DSV_PROGRAM_SELECTOR` | DSV Program 项 |
|
||||
| `FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR` | DSV Inventory 分组 |
|
||||
| `FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR` | DSV On Hand Inventory by Location |
|
||||
| `FREIGHT_RPA_DSV_OWNER_SELECTOR` | DSV Owner 输入框 |
|
||||
| `FREIGHT_RPA_DSV_EXPORT_SELECTOR` | DSV 导出按钮 |
|
||||
| `FREIGHT_RPA_CRANE_OWNER_SELECTOR` | Crane Owner 下拉/输入 |
|
||||
| `FREIGHT_RPA_CRANE_PROJECT_SELECTOR` | Crane Project 下拉/输入 |
|
||||
| `FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR` | Crane Warehouse 下拉/输入 |
|
||||
| `FREIGHT_RPA_CRANE_RUN_SELECTOR` | Crane Run Report 按钮 |
|
||||
| `FREIGHT_RPA_CRANE_EXPORT_SELECTOR` | Crane 下载按钮 |
|
||||
|
||||
发货 Excel 上传仍保留原 PoC 行为:`FREIGHT_RPA_MOCK=false` 时不会自动上传,需后续实现上传 Driver 或接入 UiPath / Power Automate。
|
||||
|
||||
回调 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`。
|
||||
@@ -18,6 +18,10 @@ Optional:
|
||||
FREIGHT_RPA_MOCK=true
|
||||
FREIGHT_RPA_POLL_SECONDS=3
|
||||
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/freight_rpa/browser_profile
|
||||
FREIGHT_RPA_HEADLESS=false
|
||||
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
|
||||
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -30,6 +34,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
@@ -105,6 +110,279 @@ def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
|
||||
return dest
|
||||
|
||||
|
||||
def _download_name(task_no: str, source_code: str, suffix: str = ".xlsx") -> str:
|
||||
safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN"
|
||||
stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
|
||||
return f"inventory_{task_no}_{safe_source}_{stamp}{suffix}"
|
||||
|
||||
|
||||
def _require_playwright():
|
||||
try:
|
||||
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"Playwright is required for real RPA. Install it on the RPA terminal with: "
|
||||
"pip install playwright && python -m playwright install chromium"
|
||||
) from exc
|
||||
return sync_playwright, PlaywrightTimeoutError
|
||||
|
||||
|
||||
def _browser_timeout_ms() -> int:
|
||||
return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000"))
|
||||
|
||||
|
||||
def _click_text(page: Any, text: str, *, exact: bool = True) -> None:
|
||||
page.get_by_text(text, exact=exact).click(timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None:
|
||||
selector = _env(selector_env)
|
||||
if selector:
|
||||
page.locator(selector).first.click(timeout=_browser_timeout_ms())
|
||||
return
|
||||
if fallback_text:
|
||||
_click_text(page, fallback_text, exact=True)
|
||||
return
|
||||
raise RuntimeError(f"Missing selector env: {selector_env}")
|
||||
|
||||
|
||||
def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
if selector:
|
||||
page.locator(selector).first.fill(text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
page.get_by_label(label).fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label)
|
||||
try:
|
||||
locator.select_option(label=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.select_option(value=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
locator = page.locator(selector).first
|
||||
try:
|
||||
return locator if locator.is_visible(timeout=2_000) else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool:
|
||||
value = _env(value_env)
|
||||
if not value:
|
||||
return False
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.fill(value, timeout=_browser_timeout_ms())
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
page.get_by_role("button", name=text).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.get_by_text(text, exact=True).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _maybe_auto_login(page: Any, prefix: str) -> None:
|
||||
"""
|
||||
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
|
||||
"""
|
||||
username_env = f"FREIGHT_RPA_{prefix}_USERNAME"
|
||||
password_env = f"FREIGHT_RPA_{prefix}_PASSWORD"
|
||||
if not _env(username_env) or not _env(password_env):
|
||||
return
|
||||
|
||||
user_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_{prefix}_USERNAME_SELECTOR",
|
||||
username_env,
|
||||
(
|
||||
'input[name="username"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="email"]',
|
||||
'input[type="email"]',
|
||||
'input[type="text"]',
|
||||
),
|
||||
)
|
||||
password_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_{prefix}_PASSWORD_SELECTOR",
|
||||
password_env,
|
||||
('input[name="password"]', 'input[type="password"]'),
|
||||
)
|
||||
if not user_filled and not password_filled:
|
||||
return
|
||||
if user_filled != password_filled:
|
||||
raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors")
|
||||
|
||||
if not _click_login_submit(
|
||||
page,
|
||||
f"FREIGHT_RPA_{prefix}_LOGIN_BUTTON_SELECTOR",
|
||||
("Sign in", "Login", "Log in", "登录"),
|
||||
):
|
||||
raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required")
|
||||
|
||||
|
||||
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
|
||||
suggested = str(download.suggested_filename or "")
|
||||
suffix = Path(suggested).suffix or ".xlsx"
|
||||
dest = drop_dir / _download_name(task_no, source_code, suffix=suffix)
|
||||
download.save_as(str(dest))
|
||||
return dest
|
||||
|
||||
|
||||
def _open_browser(download_dir: Path):
|
||||
sync_playwright, _timeout = _require_playwright()
|
||||
playwright = sync_playwright().start()
|
||||
profile = _env("FREIGHT_RPA_BROWSER_PROFILE_DIR")
|
||||
if not profile:
|
||||
profile = str(Path(__file__).resolve().parents[2] / "backend" / "data" / "freight_rpa" / "browser_profile")
|
||||
profile_dir = Path(profile)
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
headless = _env("FREIGHT_RPA_HEADLESS", "false").lower() == "true"
|
||||
context = playwright.chromium.launch_persistent_context(
|
||||
str(profile_dir),
|
||||
headless=headless,
|
||||
accept_downloads=True,
|
||||
downloads_path=str(download_dir),
|
||||
)
|
||||
page = context.pages[0] if context.pages else context.new_page()
|
||||
page.set_default_timeout(_browser_timeout_ms())
|
||||
return playwright, context, page
|
||||
|
||||
|
||||
def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||||
entry_url = str(source.get("entry_url") or "").strip()
|
||||
if not entry_url:
|
||||
raise RuntimeError("DSV360 inventory source missing entry_url")
|
||||
|
||||
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||||
_maybe_auto_login(page, "DSV")
|
||||
_click_selector_or_text(page, "FREIGHT_RPA_DSV_REPORTS_SELECTOR", "Reports")
|
||||
_click_selector_or_text(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_PROGRAM_SELECTOR",
|
||||
str(query.get("program_label") or ""),
|
||||
)
|
||||
_click_selector_or_text(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR",
|
||||
str(query.get("report_group") or "Inventory"),
|
||||
)
|
||||
_click_selector_or_text(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR",
|
||||
str(query.get("report_name") or "On Hand Inventory by Location"),
|
||||
)
|
||||
_fill_selector_or_label(page, "FREIGHT_RPA_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"))
|
||||
_fill_selector_or_label(page, "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"))
|
||||
|
||||
export_selector = _env("FREIGHT_RPA_DSV_EXPORT_SELECTOR")
|
||||
export_text = _env("FREIGHT_RPA_DSV_EXPORT_TEXT", "file_download")
|
||||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||||
if export_selector:
|
||||
page.locator(export_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
try:
|
||||
_click_text(page, export_text, exact=True)
|
||||
except Exception:
|
||||
_click_text(page, "Download", exact=True)
|
||||
return download_info.value
|
||||
|
||||
|
||||
def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||||
entry_url = str(source.get("entry_url") or "").strip()
|
||||
if not entry_url:
|
||||
raise RuntimeError("Crane inventory source missing entry_url")
|
||||
|
||||
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||||
_maybe_auto_login(page, "CRANE")
|
||||
_select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
|
||||
_select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
|
||||
_select_or_fill(page, "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", "Choose Warehouse ..", query.get("warehouse_code"))
|
||||
_click_selector_or_text(page, "FREIGHT_RPA_CRANE_RUN_SELECTOR", "Run Report")
|
||||
|
||||
export_selector = _env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR")
|
||||
export_text = _env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download")
|
||||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||||
if export_selector:
|
||||
page.locator(export_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
_click_text(page, export_text, exact=True)
|
||||
return download_info.value
|
||||
|
||||
|
||||
def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> Path:
|
||||
task_no = str(trigger.get("task_no") or "").strip()
|
||||
source = trigger.get("rpa_inventory_source")
|
||||
if not isinstance(source, dict):
|
||||
raise RuntimeError("inventory trigger missing rpa_inventory_source")
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
source_code = str(source.get("source_code") or "").strip() or source_type or "UNKNOWN"
|
||||
if not source_type:
|
||||
raise RuntimeError("inventory source missing source_type")
|
||||
|
||||
playwright = context = None
|
||||
try:
|
||||
playwright, context, page = _open_browser(drop_dir)
|
||||
if source_type == "dsv360":
|
||||
download = _download_dsv360_inventory(page, trigger, source)
|
||||
elif source_type == "crane_footprint":
|
||||
download = _download_crane_inventory(page, trigger, source)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported inventory source_type: {source_type}")
|
||||
return _save_download(download, drop_dir, task_no, source_code)
|
||||
finally:
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
|
||||
|
||||
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
@@ -114,21 +392,19 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
|
||||
if not mock:
|
||||
print(f"[inventory] real RPA not implemented; trigger kept: {trigger_path.name}")
|
||||
return
|
||||
|
||||
try:
|
||||
out_file = _write_sample_inventory(drop_dir, task_no)
|
||||
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||||
"task_no": task_no,
|
||||
"success": True,
|
||||
"file_path": str(out_file),
|
||||
"source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None),
|
||||
})
|
||||
processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
done = processed_dir / trigger_path.name
|
||||
trigger_path.replace(done)
|
||||
print(f"[inventory] mock export done for {task_no} -> {out_file.name}")
|
||||
mode = "mock" if mock else "browser"
|
||||
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
|
||||
except Exception as exc:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||||
"task_no": task_no,
|
||||
|
||||
+28
-2
@@ -2,7 +2,8 @@ param(
|
||||
[ValidateSet("sqlite", "postgres")]
|
||||
[string]$DbMode = "sqlite",
|
||||
[string]$DatabaseUrl = "",
|
||||
[switch]$SkipInstall
|
||||
[switch]$SkipInstall,
|
||||
[switch]$SkipWorker
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -132,6 +133,23 @@ function Start-BackendWindow {
|
||||
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
|
||||
}
|
||||
|
||||
function Start-KbWorkerWindow {
|
||||
param(
|
||||
[string]$BackendPath,
|
||||
[string]$Mode,
|
||||
[string]$DbUrl
|
||||
)
|
||||
|
||||
$dbExport = ""
|
||||
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
|
||||
$escaped = $DbUrl.Replace("'", "''")
|
||||
$dbExport = "`$env:DATABASE_URL='$escaped'; "
|
||||
}
|
||||
|
||||
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\worker_kb.py"
|
||||
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
|
||||
}
|
||||
|
||||
function Start-FrontendWindow {
|
||||
param([string]$FrontendPath)
|
||||
$cmd = "Set-Location '$FrontendPath'; npm run dev"
|
||||
@@ -155,9 +173,17 @@ Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $
|
||||
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
|
||||
|
||||
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
|
||||
if (-not $SkipWorker.IsPresent) {
|
||||
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
|
||||
}
|
||||
Start-FrontendWindow -FrontendPath $frontendDir
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
|
||||
if ($SkipWorker.IsPresent) {
|
||||
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
|
||||
}
|
||||
else {
|
||||
Write-Host "Started in three new PowerShell windows." -ForegroundColor Green
|
||||
}
|
||||
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
|
||||
Write-Host "Default local admin (sqlite/init scripts): admin / Hxit@54321" -ForegroundColor Green
|
||||
Reference in new issue
Block a user