feat(queue): 添加旧知识库任务入队兼容入口
- 增加 enqueue_kb_job 和 enqueue_clean_job 函数以支持旧 KB 清洗任务入队 - 在 enqueue 函数中处理 KB_CLEAN 和 KB_DIFY_SYNC 类型的任务 - 引入 ValidationError 以处理 job_id 缺失的情况 feat(shipping_notice): 更新库存 RPA 工作流逻辑 - 修改 ensure_inventory_via_rpa 函数以支持手动重试逻辑 - 优化库存导出触发和状态更新的消息提示 fix(i18n): 更新任务未找到的提示信息 - 修改中文和英文提示,明确用户操作要求 feat(shipping_notice): 增强任务解析逻辑 - 添加缺失 Reservation ID 的检查,阻止任务进入确认阶段 - 更新 get_task_status 函数以处理多票会话的任务解析
This commit is contained in:
1 parent
eb0466245b
commit
4cd987eef6
45 files changed
+2748
-1406
No files matched your search
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.ts
|
||||
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、库存上传、映射确认、人工决策与 Excel 导出。
|
||||
* 依赖:浏览器 fetch、getAuthHeaders、shipping.api.types 类型定义。
|
||||
* 依赖:统一 requestJson / BusinessError、shipping.api.types 类型定义。
|
||||
* 逻辑:上游由 useChatShipping 与 shipping/* handler 调用本文件;本文件统一请求工作台后端 `/api/workspace/*` 路由并抛出标准错误。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingChatActionsResponse,
|
||||
@@ -19,13 +19,38 @@ import type {
|
||||
ShippingTaskSummary,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
async function getJson<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error((body as { error?: string }).error || res.statusText);
|
||||
type ShippingApiStatusPayload = {
|
||||
status?: string;
|
||||
error?: string;
|
||||
message?: string;
|
||||
code?: string;
|
||||
details?: Record<string, unknown>;
|
||||
request_id?: string;
|
||||
};
|
||||
|
||||
export type ShippingChatAgentOption = {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
function jsonPost(body?: unknown): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
function assertShippingOk<T extends ShippingApiStatusPayload>(body: T): T {
|
||||
if (body.status === 'failed') {
|
||||
throw new BusinessError({
|
||||
message: body.error || body.message || 'Shipping request failed',
|
||||
code: body.code || 'SHIPPING.REQUEST_FAILED',
|
||||
details: body.details,
|
||||
requestId: body.request_id,
|
||||
});
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
return body;
|
||||
}
|
||||
|
||||
export const listWorkspaceShippingTasks = (params?: { process_status?: string; limit?: number }) => {
|
||||
@@ -34,7 +59,7 @@ export const listWorkspaceShippingTasks = (params?: { process_status?: string; l
|
||||
if (params?.process_status) sp.set('process_status', params.process_status);
|
||||
if (params?.limit) sp.set('limit', String(params.limit));
|
||||
const qs = sp.toString();
|
||||
return getJson<ShippingTaskSummary[]>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
|
||||
return requestJson<ShippingTaskSummary[]>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
export const listWorkspaceShippingBatches = (params?: { limit?: number }) => {
|
||||
@@ -42,30 +67,33 @@ export const listWorkspaceShippingBatches = (params?: { limit?: number }) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.limit) sp.set('limit', String(params.limit));
|
||||
const qs = sp.toString();
|
||||
return getJson<ShippingBatchSummary[]>(`/api/workspace/shipping-batches${qs ? '?' + qs : ''}`);
|
||||
return requestJson<ShippingBatchSummary[]>(`/api/workspace/shipping-batches${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
/** 拉取用户可见 Agent 列表,供发货工作台跳转 Chat 时定位目标 Agent。 */
|
||||
export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[]>('/api/agents');
|
||||
|
||||
/** 获取批次详情、批次任务列表与当前焦点任务。 */
|
||||
export const getWorkspaceShippingBatch = (batchNo: string) =>
|
||||
getJson<ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null }>(
|
||||
requestJson<ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null }>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
|
||||
);
|
||||
|
||||
/** 获取一个 Agent 会话下的多批次执行工作台快照。 */
|
||||
export const getWorkspaceShippingConversationBatches = (conversationId: string) =>
|
||||
getJson<ShippingConversationWorkspace>(
|
||||
requestJson<ShippingConversationWorkspace>(
|
||||
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/batch-workspace`,
|
||||
);
|
||||
|
||||
/** 获取指定批次当前焦点任务。 */
|
||||
export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
|
||||
getJson<ShippingTaskSummary>(
|
||||
requestJson<ShippingTaskSummary>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
|
||||
);
|
||||
|
||||
/** 获取单个发货任务详情。 */
|
||||
export const getWorkspaceShippingTask = (taskNo: string) =>
|
||||
getJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
|
||||
/** 生成任务导出文件的前端下载 URL。 */
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
@@ -73,7 +101,7 @@ export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
|
||||
/** 获取聊天气泡动作按钮、检查点和 human options。 */
|
||||
export const getShippingChatActions = (taskNo: string) =>
|
||||
getJson<ShippingChatActionsResponse>(
|
||||
requestJson<ShippingChatActionsResponse>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
|
||||
);
|
||||
|
||||
@@ -86,17 +114,11 @@ export const getShippingChatActions = (taskNo: string) =>
|
||||
export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingInventoryUploadResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/upload-inventory`,
|
||||
{ method: 'POST', headers, body: form },
|
||||
{ method: 'POST', body: form },
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,19 +128,11 @@ export async function uploadWorkspaceShippingInventory(taskNo: string, file: Fil
|
||||
* @returns RPA 库存导出触发结果
|
||||
*/
|
||||
export async function confirmWorkspaceShippingInventorySource(taskNo: string, sourceCode: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-inventory-source`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ source_code: sourceCode }),
|
||||
},
|
||||
jsonPost({ 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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,19 +142,11 @@ export async function confirmWorkspaceShippingInventorySource(taskNo: string, so
|
||||
* @returns 映射应用与库存解析结果
|
||||
*/
|
||||
export async function applyWorkspaceShippingInventoryMapping(taskNo: string, columnMappingJson: Record<string, unknown>) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingInventoryUploadResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/apply-inventory-mapping`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ map_json: columnMappingJson }),
|
||||
},
|
||||
jsonPost({ map_json: columnMappingJson }),
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -153,16 +159,11 @@ export async function createWorkspaceShippingTask(params?: {
|
||||
conversation_id?: string;
|
||||
raw_content?: string;
|
||||
}) {
|
||||
const res = await fetch('/api/workspace/shipping-tasks', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(params || {}),
|
||||
});
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingTaskCreateResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
const body = await requestJson<ShippingTaskCreateResponse & ShippingApiStatusPayload>(
|
||||
'/api/workspace/shipping-tasks',
|
||||
jsonPost(params || {}),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,18 +176,11 @@ export async function createWorkspaceShippingTaskFromNotice(file: File, conversa
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (conversationId) form.append('conversation_id', conversationId);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch('/api/workspace/shipping-tasks/create-from-notice', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form,
|
||||
});
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload>(
|
||||
'/api/workspace/shipping-tasks/create-from-notice',
|
||||
{ method: 'POST', body: form },
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,17 +192,11 @@ export async function createWorkspaceShippingTaskFromNotice(file: File, conversa
|
||||
export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: File) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/replace-notice`,
|
||||
{ method: 'POST', headers, body: form },
|
||||
{ method: 'POST', body: form },
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -221,22 +209,12 @@ export async function createWorkspaceShippingBatchFromNotices(files: File[], con
|
||||
const form = new FormData();
|
||||
files.forEach((file) => form.append('files', file));
|
||||
if (conversationId) form.append('conversation_id', conversationId);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch('/api/workspace/shipping-batches/create-from-notices', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form,
|
||||
});
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & {
|
||||
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload & {
|
||||
error?: string;
|
||||
batch_no?: string;
|
||||
data?: unknown;
|
||||
};
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}>('/api/workspace/shipping-batches/create-from-notices', { method: 'POST', body: form });
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -246,23 +224,14 @@ export async function createWorkspaceShippingBatchFromNotices(files: File[], con
|
||||
* @returns 更新后的批次摘要与焦点任务
|
||||
*/
|
||||
export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, taskNo: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ task_no: taskNo }),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as {
|
||||
error?: string;
|
||||
const body = await requestJson<ShippingApiStatusPayload & {
|
||||
batch?: ShippingBatchSummary;
|
||||
focus_task?: ShippingTaskSummary;
|
||||
};
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
|
||||
jsonPost({ task_no: taskNo }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -272,19 +241,11 @@ export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, tas
|
||||
* @returns 重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(comment ? { comment } : {}),
|
||||
},
|
||||
jsonPost(comment ? { comment } : {}),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -293,19 +254,11 @@ export async function retryWorkspaceShippingTask(taskNo: string, comment?: strin
|
||||
* @returns 批次重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingBatchPending(batchNo: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/retry-pending`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
jsonPost(),
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as { status?: string; message?: string; error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -316,19 +269,11 @@ export async function retryWorkspaceShippingBatchPending(batchNo: string) {
|
||||
* @returns 决策执行结果
|
||||
*/
|
||||
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ decision, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
jsonPost({ decision, ...(comment ? { comment } : {}) }),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -343,19 +288,11 @@ export async function updateWorkspaceShippingNoticeFields(
|
||||
fields: Partial<ShippingNoticeHeader>,
|
||||
comment?: string,
|
||||
) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fields, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
jsonPost({ fields, ...(comment ? { comment } : {}) }),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -372,19 +309,11 @@ export async function updateWorkspaceShippingNoticeLine(
|
||||
patch: Partial<ShippingNoticeLine> & { quantity?: number },
|
||||
comment?: string,
|
||||
) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ line_index: lineIndex, patch, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
jsonPost({ line_index: lineIndex, patch, ...(comment ? { comment } : {}) }),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -399,19 +328,11 @@ export async function addWorkspaceShippingNoticeLine(
|
||||
line: Partial<ShippingNoticeLine> & { quantity?: number },
|
||||
comment?: string,
|
||||
) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/add-notice-line`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ line, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
jsonPost({ line, ...(comment ? { comment } : {}) }),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -426,19 +347,11 @@ export async function removeWorkspaceShippingNoticeLine(
|
||||
lineIndex: number,
|
||||
comment?: string,
|
||||
) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/remove-notice-line`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ line_index: lineIndex, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
jsonPost({ line_index: lineIndex, ...(comment ? { comment } : {}) }),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,19 +360,11 @@ export async function removeWorkspaceShippingNoticeLine(
|
||||
* @returns 匹配结果与后续动作提示
|
||||
*/
|
||||
export async function matchWorkspaceShippingInventory(taskNo: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/match-inventory`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
jsonPost(),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -469,41 +374,11 @@ export async function matchWorkspaceShippingInventory(taskNo: string) {
|
||||
* @returns 自动推进结果
|
||||
*/
|
||||
export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/auto-progress`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(lang ? { lang } : {}),
|
||||
},
|
||||
jsonPost(lang ? { lang } : {}),
|
||||
);
|
||||
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 - 发货任务编号
|
||||
* @param lang - 可选语言代码
|
||||
* @returns 解析与可能的自动推进结果
|
||||
*/
|
||||
export async function parseWorkspaceShippingNotice(taskNo: string, lang?: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/parse-notice`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(lang ? { lang } : {}),
|
||||
},
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -512,19 +387,11 @@ export async function parseWorkspaceShippingNotice(taskNo: string, lang?: string
|
||||
* @returns 上传确认结果
|
||||
*/
|
||||
export async function markWorkspaceShippingManualUploaded(taskNo: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
jsonPost(),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -533,19 +400,11 @@ export async function markWorkspaceShippingManualUploaded(taskNo: string) {
|
||||
* @returns RPA 上传触发或等待结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingUpload(taskNo: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry-upload`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
jsonPost(),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -554,19 +413,11 @@ export async function retryWorkspaceShippingUpload(taskNo: string) {
|
||||
* @returns 生成结果,成功时通常会包含下载链接
|
||||
*/
|
||||
export async function generateWorkspaceShippingExcel(taskNo: string) {
|
||||
const res = await fetch(
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
jsonPost(),
|
||||
);
|
||||
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;
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 货代发货 Agent 显示名称,用于聊天路由与 Agent 匹配。 */
|
||||
|
||||
@@ -189,6 +189,7 @@ const page = useChatPageContext();
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@focus-task="page.switchShippingFocusTask"
|
||||
@resume-task="page.resumeShippingTask"
|
||||
@retry-rpa="page.retryShippingInventoryRpa"
|
||||
@query-shortage="page.queryShippingShortageDetails"
|
||||
@retry-pending="page.retryCurrentShippingBatchPendingTasks"
|
||||
/>
|
||||
|
||||
@@ -6,10 +6,11 @@
|
||||
* 逻辑:生成式执行摘要由聊天消息流承载;本组件只提供固定状态 chrome 和明确范围的批次操作。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { List, RefreshCw } from 'lucide-vue-next';
|
||||
import { AlertTriangle, List, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
@@ -35,11 +36,20 @@ const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const retryingPending = ref(false);
|
||||
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed']);
|
||||
const FAILED_PROCESS_STATUSES = new Set(['rejected', 'upload_failed']);
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
const focusedTaskNo = computed(() =>
|
||||
String(
|
||||
props.activeTaskDetail?.task_no
|
||||
|| props.batchSummary?.current_focus_task_no
|
||||
|| props.batchSummary?.process_summary?.current_task_no
|
||||
|| '',
|
||||
).trim(),
|
||||
);
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || null;
|
||||
@@ -53,14 +63,19 @@ const processSummary = computed(() => {
|
||||
(task) => !COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim()),
|
||||
) ? 1 : 0;
|
||||
const running = Number(summary?.running || runningFallback || 0);
|
||||
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running)));
|
||||
return { total, completed, running, pending };
|
||||
const taskAbnormal = props.batchTasks.filter((task) => {
|
||||
const status = String(task.process_status || '').trim();
|
||||
return FAILED_PROCESS_STATUSES.has(status)
|
||||
|| task.upload_status === 'failed'
|
||||
|| Boolean(task.review_status || task.pending_human_reason);
|
||||
}).length;
|
||||
const summaryAbnormal = Number(summary?.failed || 0) + Number((summary as { needs_human?: number })?.needs_human || 0);
|
||||
const abnormal = Math.max(taskAbnormal, summaryAbnormal);
|
||||
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running - abnormal)));
|
||||
return { total, completed, running, pending, abnormal };
|
||||
});
|
||||
|
||||
const abnormalCount = computed(() => {
|
||||
const batchSummary = props.batchSummary?.process_summary || {};
|
||||
return Number(batchSummary.failed || 0) + Number((batchSummary as { needs_human?: number }).needs_human || 0);
|
||||
});
|
||||
const abnormalCount = computed(() => processSummary.value.abnormal);
|
||||
|
||||
const progressPercent = computed(() =>
|
||||
processSummary.value.total
|
||||
@@ -87,6 +102,53 @@ const executionStateMeta = computed(() => {
|
||||
};
|
||||
});
|
||||
|
||||
const activeTaskSteps = computed(() => buildShippingWorkflowSteps(props.activeTaskDetail));
|
||||
const activeStepIndex = computed(() => {
|
||||
const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1);
|
||||
});
|
||||
const activeStepLabel = computed(() => {
|
||||
const step = activeTaskSteps.value[activeStepIndex.value];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: activeStepIndex.value + 1,
|
||||
total: activeTaskSteps.value.length,
|
||||
label: t(step.label),
|
||||
}) : '--';
|
||||
});
|
||||
|
||||
const blockingMeta = computed(() => {
|
||||
const task = props.activeTaskDetail;
|
||||
if (!task) return null;
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
if (processStatus === 'upload_failed' || task.upload_status === 'failed') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedUploadRetryable'),
|
||||
className: 'border-rose-200 bg-rose-50 text-rose-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedShortage'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedParseReview'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason || reviewStatus) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedWaitingHuman'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const handleRetryPending = async () => {
|
||||
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
||||
if (!batchNo || retryingPending.value) return;
|
||||
@@ -107,24 +169,39 @@ const handleRetryPending = async () => {
|
||||
<div
|
||||
class="mx-auto w-full max-w-4xl rounded-2xl border border-default bg-gradient-to-r from-sky-50 via-white to-emerald-50 px-6 py-4 shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2 text-xs text-slate-500">
|
||||
<span class="font-mono font-semibold text-brand-700">{{ activeBatchNo || '--' }}</span>
|
||||
<span>
|
||||
{{ t('chat.shippingNoticeUi.batchChromeSummary', {
|
||||
total: processSummary.total,
|
||||
completed: processSummary.completed,
|
||||
running: processSummary.running,
|
||||
abnormal: abnormalCount,
|
||||
}) }}
|
||||
</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.fileCount') }} {{ processSummary.total }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.completedCount') }} {{ processSummary.completed }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.runningCount') }} {{ processSummary.running }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.pendingCount') }} {{ processSummary.pending }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.needsIntervention') }} {{ abnormalCount }}</span>
|
||||
<span
|
||||
class="rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="executionStateMeta.className"
|
||||
>
|
||||
{{ executionStateMeta.text }}
|
||||
</span>
|
||||
<span
|
||||
v-if="blockingMeta"
|
||||
class="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="blockingMeta.className"
|
||||
>
|
||||
<AlertTriangle class="h-3 w-3" />
|
||||
{{ blockingMeta.text }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-secondary">
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentFocus') }}</span>
|
||||
<span class="font-mono font-semibold text-primary">{{ focusedTaskNo || '--' }}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentStepLabel') }}:</span>
|
||||
<span class="font-medium text-primary">{{ activeStepLabel }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 h-1.5 max-w-md overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
|
||||
@@ -33,12 +33,13 @@ const emit = defineEmits<{
|
||||
'switch-batch': [batchNo: string];
|
||||
'focus-task': [taskNo: string];
|
||||
'resume-task': [taskNo: string];
|
||||
'retry-rpa': [taskNo: string];
|
||||
'query-shortage': [taskNo: string];
|
||||
'retry-pending': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const activeFilter = ref<'all' | 'abnormal' | 'completed'>('all');
|
||||
const activeFilter = ref<'all' | 'abnormal' | 'waitingHuman' | 'resumable' | 'completed'>('all');
|
||||
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed']);
|
||||
|
||||
@@ -59,6 +60,21 @@ const isAbnormalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
|| Boolean(task.review_status || task.pending_human_reason)
|
||||
|| String(task.process_status || '').trim() === 'waiting_inventory');
|
||||
|
||||
const isWaitingHumanTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isFailedTask(task) && Boolean(task.review_status || task.pending_human_reason);
|
||||
|
||||
const isResumableTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isWaitingHumanTask(task) && (
|
||||
isFailedTask(task)
|
||||
|| ['created', 'parsed', 'inventory_ready', 'matched', 'waiting_upload'].includes(String(task.process_status || '').trim())
|
||||
);
|
||||
|
||||
const canRetryInventoryRpa = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const reason = String(task.pending_human_reason || '').trim().toLowerCase();
|
||||
const status = String(task.process_status || '').trim().toLowerCase();
|
||||
return status === 'waiting_inventory' && ['rpa_exhausted', 'rpa_pending', 'inv_unavail'].includes(reason);
|
||||
};
|
||||
|
||||
const batchAbnormalCount = (batch: ShippingBatchSummary) => {
|
||||
const summary = batch.process_summary || {};
|
||||
return Number(summary.failed || 0) + Number((summary as { needs_human?: number }).needs_human || 0);
|
||||
@@ -74,9 +90,13 @@ const taskCounts = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
const completed = tasks.filter(isCompletedTask).length;
|
||||
const abnormal = tasks.filter(isAbnormalTask).length;
|
||||
const waitingHuman = tasks.filter(isWaitingHumanTask).length;
|
||||
const resumable = tasks.filter(isResumableTask).length;
|
||||
return {
|
||||
total: tasks.length,
|
||||
abnormal,
|
||||
waitingHuman,
|
||||
resumable,
|
||||
completed,
|
||||
};
|
||||
});
|
||||
@@ -84,6 +104,8 @@ const taskCounts = computed(() => {
|
||||
const filteredTasks = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
if (activeFilter.value === 'abnormal') return tasks.filter(isAbnormalTask);
|
||||
if (activeFilter.value === 'waitingHuman') return tasks.filter(isWaitingHumanTask);
|
||||
if (activeFilter.value === 'resumable') return tasks.filter(isResumableTask);
|
||||
if (activeFilter.value === 'completed') return tasks.filter(isCompletedTask);
|
||||
return tasks;
|
||||
});
|
||||
@@ -107,6 +129,17 @@ const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
resolveActiveStep(buildShippingWorkflowSteps(task)) + 1;
|
||||
|
||||
const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const steps = buildShippingWorkflowSteps(task);
|
||||
const index = resolveActiveStep(steps);
|
||||
const step = steps[index];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: index + 1,
|
||||
total: steps.length,
|
||||
label: t(step.label),
|
||||
}) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length });
|
||||
};
|
||||
|
||||
const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.step_payload?.current_step_progress || null;
|
||||
|
||||
@@ -192,6 +225,27 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
};
|
||||
};
|
||||
|
||||
const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') {
|
||||
return t('chat.shippingNoticeUi.suggestShortageActions');
|
||||
}
|
||||
if (reason === 'align_review' || reviewStatus === 'align_review') {
|
||||
return t('chat.shippingNoticeUi.suggestConfirmMapping');
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return t('chat.shippingNoticeUi.suggestReviewParse');
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestRetryStep');
|
||||
}
|
||||
if (isCompletedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestViewOnly');
|
||||
}
|
||||
return t('chat.shippingNoticeUi.suggestContinue');
|
||||
};
|
||||
|
||||
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) => {
|
||||
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
|
||||
@@ -258,8 +312,9 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto px-6 py-6">
|
||||
<section class="rounded-2xl border border-default bg-surface p-4 shadow-sm">
|
||||
<h3 class="text-sm font-bold text-primary">{{ t('chat.shippingNoticeUi.batchActionsTitle') }}</h3>
|
||||
<section class="rounded-lg border border-default bg-surface p-4 shadow-sm">
|
||||
<h3 class="text-sm font-bold text-primary">{{ t('chat.shippingNoticeUi.taskQueueTitle') }}</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-muted">{{ t('chat.shippingNoticeUi.taskQueueHint') }}</p>
|
||||
<div class="mt-4">
|
||||
<button
|
||||
type="button"
|
||||
@@ -281,7 +336,7 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
<h3 class="text-sm font-bold text-primary">
|
||||
{{ t('chat.shippingNoticeUi.taskDetailCount', { count: filteredTasks.length }) }}
|
||||
</h3>
|
||||
<div class="flex rounded-lg bg-slate-100 p-1 text-xs">
|
||||
<div class="flex flex-wrap rounded-lg bg-slate-100 p-1 text-xs">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
@@ -298,6 +353,22 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAbnormal', { count: taskCounts.abnormal }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'waitingHuman' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'waitingHuman'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterWaitingHuman', { count: taskCounts.waitingHuman }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'resumable' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'resumable'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterResumable', { count: taskCounts.resumable }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
@@ -313,11 +384,11 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
{{ t('chat.shippingNoticeUi.emptyFilteredTasks') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-4">
|
||||
<div v-else class="space-y-3">
|
||||
<article
|
||||
v-for="task in filteredTasks"
|
||||
:key="task.task_no"
|
||||
class="relative overflow-hidden rounded-2xl border bg-white p-4 shadow-sm transition-colors"
|
||||
class="relative overflow-hidden rounded-lg border bg-white p-3 shadow-sm transition-colors"
|
||||
:class="[
|
||||
isFailedTask(task) ? 'border-rose-100' : isAbnormalTask(task) ? 'border-amber-100' : 'border-default',
|
||||
isCurrentTask(task.task_no) ? 'ring-1 ring-brand-200' : '',
|
||||
@@ -327,19 +398,20 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
class="absolute left-0 top-0 h-full w-1"
|
||||
:class="isFailedTask(task) ? 'bg-rose-500' : isAbnormalTask(task) ? 'bg-amber-500' : 'bg-emerald-500'"
|
||||
></div>
|
||||
<div class="mb-4 flex items-start justify-between gap-3">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-mono text-sm font-bold text-primary">{{ task.task_no }}</div>
|
||||
<div class="mt-0.5 truncate text-xs text-muted">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</div>
|
||||
<div class="mt-1 text-xs font-medium text-secondary">{{ taskStepHeadline(task) }}</div>
|
||||
</div>
|
||||
<span class="rounded border px-2 py-1 text-[10px] font-bold" :class="resolveTaskStateMeta(task).className">
|
||||
{{ resolveTaskStateMeta(task).text }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mb-5 mt-4">
|
||||
<div class="my-3">
|
||||
<div class="scheme-stepper">
|
||||
<template v-for="(step, index) in buildShippingWorkflowSteps(task)" :key="step.id">
|
||||
<div
|
||||
@@ -363,14 +435,18 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="mb-3 rounded-lg border p-2.5 text-xs font-medium leading-5"
|
||||
class="mb-2 rounded-lg border p-2.5 text-xs font-medium leading-5"
|
||||
:class="isFailedTask(task) ? 'border-rose-100 bg-rose-50 text-rose-700' : isAbnormalTask(task) ? 'border-amber-100 bg-amber-50 text-amber-700' : 'border-emerald-100 bg-emerald-50 text-emerald-700'"
|
||||
>
|
||||
<div class="font-semibold">{{ resolveTaskDiagnosis(task).title }}</div>
|
||||
<div class="mt-1 font-normal text-slate-600">{{ resolveTaskDiagnosis(task).advice }}</div>
|
||||
</div>
|
||||
<div class="mb-3 text-xs leading-5 text-muted">
|
||||
<span class="font-semibold text-secondary">{{ t('chat.shippingNoticeUi.suggestedAction') }}</span>
|
||||
{{ resolveSuggestedAction(task) }}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="hasShortageLines(task)"
|
||||
type="button"
|
||||
@@ -381,18 +457,24 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex flex-1 items-center justify-center gap-1.5 rounded-lg border border-transparent bg-surface-soft py-1.5 text-xs font-medium text-secondary transition-colors hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600"
|
||||
class="flex flex-1 items-center justify-center gap-1.5 rounded-lg border border-transparent bg-surface-soft px-2 py-1.5 text-xs font-medium text-secondary transition-colors hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600"
|
||||
@click="emit('focus-task', task.task_no)"
|
||||
>
|
||||
<Target class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingNoticeUi.focusRepair') }}
|
||||
{{ t('chat.shippingNoticeUi.switchCurrentTask') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 rounded-lg border border-default bg-white py-1.5 text-xs font-medium text-secondary transition-colors hover:border-brand-300 hover:text-brand-700"
|
||||
@click="emit('resume-task', task.task_no)"
|
||||
class="flex-1 rounded-lg border border-default bg-white px-2 py-1.5 text-xs font-medium text-secondary transition-colors hover:border-brand-300 hover:text-brand-700"
|
||||
@click="canRetryInventoryRpa(task) ? emit('retry-rpa', task.task_no) : emit('resume-task', task.task_no)"
|
||||
>
|
||||
{{ isCompletedTask(task) ? t('chat.shippingNoticeUi.viewDetail') : t('chat.shippingNoticeUi.retrySingleTask') }}
|
||||
{{
|
||||
isCompletedTask(task)
|
||||
? t('chat.shippingNoticeUi.viewDetail')
|
||||
: canRetryInventoryRpa(task)
|
||||
? t('chat.shippingNoticeUi.retryRpa')
|
||||
: t('chat.shippingNoticeUi.continueTask')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -489,6 +489,7 @@ export function useChatPage() {
|
||||
switchShippingFocusTask: shipping.switchShippingFocusTask,
|
||||
clearShippingFocus: shipping.clearShippingFocus,
|
||||
resumeShippingTask: shipping.resumeShippingTask,
|
||||
retryShippingInventoryRpa: shipping.retryShippingInventoryRpa,
|
||||
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
|
||||
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
||||
|
||||
@@ -595,6 +595,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingInventorySchemaPreviewCache,
|
||||
getActiveShippingTaskId,
|
||||
sendShippingMenuMessage,
|
||||
pushShippingLocalUserMessage,
|
||||
pushShippingLocalAssistantMessage,
|
||||
refreshShippingActions,
|
||||
msg,
|
||||
@@ -727,6 +728,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return true;
|
||||
};
|
||||
|
||||
const retryShippingInventoryRpa = async (taskNo: string) => {
|
||||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||||
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
|
||||
const switched = await switchShippingFocusTask(normalizedTaskNo);
|
||||
if (!switched) return false;
|
||||
const ok = await executeShippingDecision('retry_rpa', t('chat.shippingNoticeUi.retryRpa'));
|
||||
await syncShippingConversationWorkspace();
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
if (batchNo) await syncShippingBatchSummary(batchNo);
|
||||
await refreshShippingActions();
|
||||
return ok;
|
||||
};
|
||||
|
||||
const retryCurrentShippingBatchPendingTasks = async () => {
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
if (!batchNo || retryingShippingPendingTasks.value) return false;
|
||||
@@ -883,6 +897,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
switchShippingFocusTask,
|
||||
clearShippingFocus,
|
||||
resumeShippingTask,
|
||||
retryShippingInventoryRpa,
|
||||
retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails,
|
||||
resetShippingConversationState,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingText.test.ts
|
||||
* 用途:锁定货代发货 Agent 消息净化规则,避免按钮动作列表和工程语言重新泄漏到用户界面。
|
||||
* 依赖:Vitest、shippingText 纯函数。
|
||||
* 逻辑:输入典型 Agent 回复,断言冗余 1/2/3 操作列表被移除,同时普通业务编号列表不受影响。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeShippingConversationText } from './shippingText';
|
||||
|
||||
describe('shippingText', () => {
|
||||
it('removes numbered action lists that duplicate structured shipping buttons', () => {
|
||||
// 关键断言:按钮已经结构化展示时,正文里的 1/2/3 操作清单不能再露给业务用户。
|
||||
const result = sanitizeShippingConversationText(
|
||||
[
|
||||
'⏳ 当前卡点 — 待上传库存',
|
||||
'',
|
||||
'目前任务已进入库存上传环节,您需要提供当前库存数据。请使用下方按钮选择以下任一方式:',
|
||||
'',
|
||||
'1. 📁 选择库存文件 — 在本对话中上传库存 Excel 文件',
|
||||
'2. 🔄 重试 RPA — 让系统重新尝试从 RPA 导出库存快照',
|
||||
'3. 📋 粘贴库存 — 直接粘贴库存小表内容',
|
||||
'',
|
||||
'请使用下方按钮继续操作。',
|
||||
].join('\n'),
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result).toContain('当前卡点');
|
||||
expect(result).not.toContain('1.');
|
||||
expect(result).not.toContain('选择库存文件');
|
||||
expect(result).not.toContain('重试 RPA');
|
||||
expect(result).not.toContain('粘贴库存');
|
||||
expect(result).not.toContain('下方按钮');
|
||||
});
|
||||
|
||||
it('keeps normal numbered business lists', () => {
|
||||
// 关键断言:正常订单/业务明细仍可用编号展示,不能被动作列表规则误删。
|
||||
const result = sanitizeShippingConversationText(
|
||||
[
|
||||
'本次识别到 2 行订单:',
|
||||
'1. SKU A001,数量 10',
|
||||
'2. SKU B002,数量 5',
|
||||
].join('\n'),
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result).toContain('1. SKU A001');
|
||||
expect(result).toContain('2. SKU B002');
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,77 @@ const isActionListContextLine = (line: string) =>
|
||||
const isActionListTailLine = (line: string) =>
|
||||
/(?:选择哪|希望.*(?:处理|执行|操作)|要.*哪一项|点击.*按钮)/.test(line);
|
||||
|
||||
const isShippingActionListContextLine = (line: string) =>
|
||||
/(?:请选择操作|选择操作|操作选项|下方按钮|按钮继续操作|以下.*方式|任一方式|库存上传|提供当前库存|提供.*库存数据)/.test(line);
|
||||
|
||||
const isShippingActionChoiceLine = (line: string) =>
|
||||
/(?:选择库存文件|上传库存|粘贴库存|重试\s*RPA|修改映射|确认字段|继续处理|查看卡点|返回修订|重新匹配|重试当前步骤|切换为当前任务)/i.test(line);
|
||||
|
||||
/**
|
||||
* 移除 Agent 正文里重复描述按钮的 1/2/3 编号动作列表。
|
||||
*
|
||||
* 这些动作已经由结构化按钮承载,正文再展示会显得像提示词/后端兜底泄漏。
|
||||
* 为避免误删订单行,只在“按钮/库存/操作方式”上下文中,且编号行命中动作词时移除。
|
||||
*/
|
||||
export function stripShippingRedundantNumberedActionList(text: string): string {
|
||||
const lines = String(text || '').split('\n');
|
||||
const remove = new Set<number>();
|
||||
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
if (!isNumberedActionLine(lines[index] || '')) continue;
|
||||
|
||||
const block: number[] = [];
|
||||
let cursor = index;
|
||||
while (cursor < lines.length && isNumberedActionLine(lines[cursor] || '')) {
|
||||
block.push(cursor);
|
||||
cursor += 1;
|
||||
}
|
||||
|
||||
const actionLineCount = block.filter((lineIndex) => isShippingActionChoiceLine(lines[lineIndex] || '')).length;
|
||||
if (block.length < 2 || actionLineCount === 0) {
|
||||
index = cursor - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const nearbyStart = Math.max(0, index - 3);
|
||||
const nearbyEnd = Math.min(lines.length - 1, cursor + 2);
|
||||
const hasActionContext = lines
|
||||
.slice(nearbyStart, nearbyEnd + 1)
|
||||
.some((line) => isShippingActionListContextLine(line));
|
||||
if (!hasActionContext) {
|
||||
index = cursor - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
block.forEach((lineIndex) => remove.add(lineIndex));
|
||||
|
||||
for (let before = index - 1; before >= nearbyStart; before -= 1) {
|
||||
const line = lines[before] || '';
|
||||
if (!line.trim() || isShippingActionListContextLine(line)) {
|
||||
remove.add(before);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (let after = cursor; after <= nearbyEnd; after += 1) {
|
||||
const line = lines[after] || '';
|
||||
if (!line.trim() || isShippingActionListContextLine(line)) {
|
||||
remove.add(after);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
index = cursor - 1;
|
||||
}
|
||||
|
||||
return lines
|
||||
.filter((_, index) => !remove.has(index))
|
||||
.join('\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据后端 action_buttons 移除 Agent 正文中重复生成的编号操作列表。
|
||||
*
|
||||
@@ -80,11 +151,11 @@ export function stripShippingActionListByButtons(
|
||||
}
|
||||
}
|
||||
|
||||
return lines
|
||||
return stripShippingRedundantNumberedActionList(lines
|
||||
.filter((_, index) => !remove.has(index))
|
||||
.join('\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,6 +164,18 @@ export function stripShippingActionListByButtons(
|
||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||
if (!enabled) return text;
|
||||
let result = String(text || '')
|
||||
.replace(
|
||||
/已回到列映射步骤。?请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'已回到库存字段确认步骤。请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。',
|
||||
)
|
||||
.replace(
|
||||
/请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。',
|
||||
)
|
||||
.replace(
|
||||
/根据\s*data\.schema_preview\.headers\s*与\s*sample_rows\s*推断\s*JSON[^。.\n]*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'请根据库存表头和样例行确认字段对应关系。',
|
||||
)
|
||||
.replace(/通过\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
|
||||
.replace(/在\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
|
||||
.replace(/(?:Hxops|HXOPS|hxops)\s*聊天区/gi, '当前对话')
|
||||
@@ -112,6 +195,10 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
.replace(/\bupload_to_freight\b/gi, '上传货代系统')
|
||||
.replace(/\bapply_inventory_mapping\b/gi, '应用库存字段映射')
|
||||
.replace(/\bget_inventory_schema_preview\b/gi, '读取库存表头预览')
|
||||
.replace(/\bschema_preview(?:\.headers)?\b/gi, '库存表头预览')
|
||||
.replace(/\bdata\.库存表头预览\b/gi, '库存表头预览')
|
||||
.replace(/\bmap_json\b/gi, '字段映射')
|
||||
.replace(/\bsample_rows\b/gi, '样例行')
|
||||
.replace(/\bretry_rpa\b/gi, '重试库存抓取')
|
||||
.replace(/\bretry_upload\b/gi, '重试上传货代')
|
||||
.replace(/\bstructured\b/gi, '结构化内容')
|
||||
@@ -126,7 +213,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
result = result.replace(quoted, '');
|
||||
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
|
||||
}
|
||||
return result.replace(/\n{3,}/g, '\n\n').trim();
|
||||
return stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface ShippingUploadHandlerContext {
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
pushShippingLocalUserMessage: (text: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
@@ -72,6 +73,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
|
||||
const uploadInventoryForTask = async (taskId: string, file: File) => {
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
await ctx.pushShippingLocalUserMessage(ctx.t('chat.shippingNoticeInventoryUploadStarted', { fileName: file.name }));
|
||||
const result = await uploadWorkspaceShippingInventory(taskId, file);
|
||||
const batchNo = String(
|
||||
((result as unknown as { data?: { batch_no?: string } }).data?.batch_no)
|
||||
|
||||
@@ -2,64 +2,41 @@
|
||||
/**
|
||||
* features/workspace/views/ShippingNoticeView.vue
|
||||
* 用途:货代发货任务只读工作台,提供任务筛选、详情查看与跳转 Chat 继续处理入口。
|
||||
* 依赖:ShippingWorkflowStepper、ShippingParseReviewMessage、ShippingMatchResultCard、shipping.api。
|
||||
* 逻辑:先拉取任务列表与详情,再复用 Chat 区的发货组件展示步骤、匹配结果和 parse review。
|
||||
* 依赖:ShippingWorkflowStepper、ShippingMatchResultCard、shipping.api。
|
||||
* 逻辑:先拉取任务列表与详情,再以只读方式展示步骤、匹配结果和事件记录;所有写操作回到 Chat 主路径完成。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, Download, ExternalLink, RefreshCw } from 'lucide-vue-next';
|
||||
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
|
||||
import ShippingParseReviewMessage, {
|
||||
type ShippingParseReviewHandlers,
|
||||
} from '@/features/chat/components/messages/ShippingParseReviewMessage.vue';
|
||||
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import {
|
||||
addWorkspaceShippingNoticeLine,
|
||||
autoProgressWorkspaceShippingTask,
|
||||
generateWorkspaceShippingExcel,
|
||||
getShippingChatActions,
|
||||
getWorkspaceShippingTask,
|
||||
listShippingChatAgents,
|
||||
listWorkspaceShippingTasks,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
matchWorkspaceShippingInventory,
|
||||
removeWorkspaceShippingNoticeLine,
|
||||
retryWorkspaceShippingTask,
|
||||
SHIPPING_NOTICE_AGENT_NAME,
|
||||
submitWorkspaceShippingDecision,
|
||||
updateWorkspaceShippingNoticeFields,
|
||||
updateWorkspaceShippingNoticeLine,
|
||||
workspaceShippingExportUrl,
|
||||
type ShippingChatAction,
|
||||
type ShippingCurrentStepProgress,
|
||||
type ShippingNoticeHeader,
|
||||
type ShippingNoticeLine,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ChatMessage } from '@/features/chat/types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '@/features/chat/types/shipping.types';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { buildShippingWorkflowSteps, shippingActionButtonClass } from '@/features/chat/shipping';
|
||||
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
|
||||
const props = defineProps<{
|
||||
embedded?: boolean;
|
||||
}>();
|
||||
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const tasks = ref<ShippingTaskSummary[]>([]);
|
||||
const selectedTaskNo = ref<string | null>(null);
|
||||
const detail = ref<ShippingTaskDetail | null>(null);
|
||||
const detailSaving = ref(false);
|
||||
const detailActionBusy = ref(false);
|
||||
const detailRetrying = ref(false);
|
||||
const detailActionButtons = ref<ShippingChatAction[]>([]);
|
||||
const statusFilter = ref('all');
|
||||
const chatAgentId = ref<number | null>(null);
|
||||
const batchProgressLabel = computed(() => {
|
||||
@@ -81,17 +58,54 @@ const statusOptions = computed(() => [
|
||||
{ value: 'upload_failed', label: t('workspace.shippingNotice.status.uploadFailed') },
|
||||
]);
|
||||
|
||||
const statusBadge = (status: string) => {
|
||||
type ShippingStatusSource = Pick<
|
||||
ShippingTaskSummary,
|
||||
'process_status' | 'review_status' | 'pending_human_reason' | 'match_status'
|
||||
>;
|
||||
|
||||
const displayStatusCode = (source: ShippingStatusSource | string) => {
|
||||
if (typeof source === 'string') return source;
|
||||
const reason = String(source.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(source.review_status || '').trim();
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') return 'shortage_review';
|
||||
if (reason === 'align_review' || reviewStatus === 'align_review') return 'align_review';
|
||||
return String(source.process_status || '').trim();
|
||||
};
|
||||
|
||||
const statusBadge = (source: ShippingStatusSource | string) => {
|
||||
const status = displayStatusCode(source);
|
||||
const map: Record<string, { cls: string; label: string }> = {
|
||||
created: { cls: 'bg-slate-100 text-secondary', label: t('workspace.shippingNotice.status.created') },
|
||||
parsed: { cls: 'bg-blue-100 text-blue-700', label: t('workspace.shippingNotice.status.parsed') },
|
||||
pending_review: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.shippingNotice.status.pendingReview') },
|
||||
align_review: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.shippingNotice.status.alignReview') },
|
||||
shortage_review: { cls: 'bg-rose-100 text-rose-700', label: t('workspace.shippingNotice.status.shortageReview') },
|
||||
waiting_inventory: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.shippingNotice.status.waitingInventory') },
|
||||
inventory_ready: { cls: 'bg-blue-100 text-blue-700', label: t('workspace.shippingNotice.status.inventoryReady') },
|
||||
matched: { cls: 'bg-emerald-100 text-emerald-700', label: t('workspace.shippingNotice.status.matched') },
|
||||
waiting_upload: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.shippingNotice.status.waitingUpload') },
|
||||
uploaded: { cls: 'bg-emerald-100 text-emerald-700', label: t('workspace.shippingNotice.status.uploaded') },
|
||||
upload_failed: { cls: 'bg-rose-100 text-rose-700', label: t('workspace.shippingNotice.status.uploadFailed') },
|
||||
rejected: { cls: 'bg-slate-100 text-secondary', label: t('workspace.shippingNotice.status.rejected') },
|
||||
closed: { cls: 'bg-slate-100 text-secondary', label: t('workspace.shippingNotice.status.closed') },
|
||||
};
|
||||
return map[status] || { cls: 'bg-slate-100 text-secondary', label: status };
|
||||
return map[status] || { cls: 'bg-slate-100 text-secondary', label: t('workspace.shippingNotice.status.unknown') };
|
||||
};
|
||||
|
||||
const matchStatusLabel = (status?: string | null) => {
|
||||
const key = String(status || '').trim();
|
||||
const map: Record<string, string> = {
|
||||
fulfillable: t('workspace.shippingNotice.matchStatus.fulfillable'),
|
||||
partial: t('workspace.shippingNotice.matchStatus.partial'),
|
||||
unfulfillable: t('workspace.shippingNotice.matchStatus.unfulfillable'),
|
||||
};
|
||||
return map[key] || (key ? t('workspace.shippingNotice.matchStatus.unknown') : '—');
|
||||
};
|
||||
|
||||
const eventLabel = (eventType: string) => {
|
||||
const normalized = String(eventType || '').trim().replace(/[^a-zA-Z0-9_]/g, '');
|
||||
const key = `workspace.shippingNotice.eventTypes.${normalized}`;
|
||||
return te(key) ? t(key) : t('workspace.shippingNotice.eventTypes.system');
|
||||
};
|
||||
|
||||
const detailWorkflowSteps = computed(() => buildShippingWorkflowSteps(detail.value));
|
||||
@@ -122,15 +136,9 @@ const loadCases = async () => {
|
||||
const loadDetail = async (taskNo: string) => {
|
||||
detailLoading.value = true;
|
||||
try {
|
||||
const [taskDetail, chatActions] = await Promise.all([
|
||||
getWorkspaceShippingTask(taskNo),
|
||||
getShippingChatActions(taskNo).catch(() => null),
|
||||
]);
|
||||
detail.value = taskDetail;
|
||||
detailActionButtons.value = chatActions?.action_buttons || [];
|
||||
detail.value = await getWorkspaceShippingTask(taskNo);
|
||||
} catch {
|
||||
detail.value = null;
|
||||
detailActionButtons.value = [];
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
}
|
||||
@@ -138,9 +146,7 @@ const loadDetail = async (taskNo: string) => {
|
||||
|
||||
const resolveChatAgent = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
|
||||
if (!res.ok) return;
|
||||
const agents = (await res.json()) as Array<{ id: number; name: string }>;
|
||||
const agents = await listShippingChatAgents();
|
||||
const found = agents.find((a) => a.name === SHIPPING_NOTICE_AGENT_NAME);
|
||||
if (found) chatAgentId.value = found.id;
|
||||
} catch {
|
||||
@@ -170,86 +176,6 @@ const downloadExport = async (taskNo: string) => {
|
||||
URL.revokeObjectURL(a.href);
|
||||
};
|
||||
|
||||
const parseReviewPayload = computed<ShippingParseReviewPayload | null>(() => {
|
||||
if (!detail.value || detail.value.review_status !== 'pending_confirm') return null;
|
||||
return {
|
||||
taskId: detail.value.task_no,
|
||||
checkpoint: 'parse_review',
|
||||
header: {
|
||||
customer_name: detail.value.customer_name ?? null,
|
||||
customer_code: detail.value.customer_code ?? null,
|
||||
ship_to: detail.value.ship_to ?? null,
|
||||
po_number: detail.value.po_number ?? null,
|
||||
required_date: detail.value.required_date ?? null,
|
||||
},
|
||||
lines: Array.isArray(detail.value.lines) ? detail.value.lines : [],
|
||||
saving: detailSaving.value,
|
||||
};
|
||||
});
|
||||
|
||||
const parseReviewMessage = computed<ChatMessage>(() => ({
|
||||
role: 'assistant',
|
||||
type: 'shipping-parse-review',
|
||||
content: `${t('chat.shippingNoticeUi.parseReviewIntro')}\n${t('chat.shippingNoticeUi.taskId', { taskId: detail.value?.task_no || '' })}`.trim(),
|
||||
payload: parseReviewPayload.value || undefined,
|
||||
}));
|
||||
|
||||
const parseReviewHandlers: ShippingParseReviewHandlers = {
|
||||
getPayload: () => parseReviewPayload.value,
|
||||
updateHeader: async (_msg, fields: Partial<ShippingNoticeHeader>) => {
|
||||
if (!detail.value || detailSaving.value) return false;
|
||||
detailSaving.value = true;
|
||||
try {
|
||||
await updateWorkspaceShippingNoticeFields(detail.value.task_no, fields, '工作台订单表修订');
|
||||
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
detailSaving.value = false;
|
||||
}
|
||||
},
|
||||
updateLine: async (_msg, lineIndex: number, patch: Partial<ShippingNoticeLine>) => {
|
||||
if (!detail.value || detailSaving.value) return false;
|
||||
detailSaving.value = true;
|
||||
try {
|
||||
await updateWorkspaceShippingNoticeLine(detail.value.task_no, lineIndex, patch, '工作台订单表修订');
|
||||
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
detailSaving.value = false;
|
||||
}
|
||||
},
|
||||
addLine: async (_msg, line: Partial<ShippingNoticeLine>) => {
|
||||
if (!detail.value || detailSaving.value) return false;
|
||||
detailSaving.value = true;
|
||||
try {
|
||||
await addWorkspaceShippingNoticeLine(detail.value.task_no, line, '工作台订单表新增行');
|
||||
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
detailSaving.value = false;
|
||||
}
|
||||
},
|
||||
removeLine: async (_msg, lineIndex: number) => {
|
||||
if (!detail.value || detailSaving.value) return false;
|
||||
detailSaving.value = true;
|
||||
try {
|
||||
await removeWorkspaceShippingNoticeLine(detail.value.task_no, lineIndex, '工作台订单表删除行');
|
||||
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
detailSaving.value = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const shortageLines = computed(() => detail.value?.shortage?.lines || []);
|
||||
const hasMatchCard = computed(() =>
|
||||
!!detail.value && (
|
||||
@@ -258,59 +184,6 @@ const hasMatchCard = computed(() =>
|
||||
),
|
||||
);
|
||||
|
||||
const handleWorkspaceAction = async (action: ShippingChatAction) => {
|
||||
if (!detail.value || detailActionBusy.value) return;
|
||||
const taskNo = detail.value.task_no;
|
||||
detailActionBusy.value = true;
|
||||
try {
|
||||
if (action.id === 'download_excel') {
|
||||
await downloadExport(taskNo);
|
||||
return;
|
||||
}
|
||||
if (action.id === 'generate_excel') {
|
||||
await generateWorkspaceShippingExcel(taskNo);
|
||||
} else if (action.id === 'match_inventory') {
|
||||
await matchWorkspaceShippingInventory(taskNo);
|
||||
} else if (action.id === 'mark_manual_uploaded') {
|
||||
await markWorkspaceShippingManualUploaded(taskNo);
|
||||
} else if (action.id === 'refresh') {
|
||||
await loadDetail(taskNo);
|
||||
return;
|
||||
} else if (action.id === 'confirm_inventory_mapping') {
|
||||
await autoProgressWorkspaceShippingTask(taskNo);
|
||||
} else if ([
|
||||
'confirm',
|
||||
'reject',
|
||||
'reparse',
|
||||
'correct_inventory_mapping',
|
||||
'reparse_inventory',
|
||||
'rematch',
|
||||
].includes(action.id)) {
|
||||
await submitWorkspaceShippingDecision(taskNo, action.id);
|
||||
} else {
|
||||
openInChat(taskNo, detail.value.conversation_id, detail.value.batch_no);
|
||||
return;
|
||||
}
|
||||
await Promise.all([loadDetail(taskNo), loadCases()]);
|
||||
} finally {
|
||||
detailActionBusy.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleRetryCurrentTask = async () => {
|
||||
if (!detail.value || detailRetrying.value) return;
|
||||
detailRetrying.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingTask(detail.value.task_no, '工作台重试当前票');
|
||||
msg.success(result.message || t('workspace.shippingNotice.retryCurrentDone'));
|
||||
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.shippingNotice.retryFailed'));
|
||||
} finally {
|
||||
detailRetrying.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(selectedTaskNo, (val) => {
|
||||
if (val) loadDetail(val);
|
||||
else detail.value = null;
|
||||
@@ -382,13 +255,17 @@ onMounted(async () => {
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ item.task_no }}</span>
|
||||
<span class="rounded-full px-2 py-0.5 text-xs font-medium" :class="statusBadge(item.process_status).cls">
|
||||
{{ statusBadge(item.process_status).label }}
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-xs font-medium"
|
||||
:class="statusBadge(item).cls"
|
||||
:title="item.process_status"
|
||||
>
|
||||
{{ statusBadge(item).label }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 truncate text-sm text-secondary">{{ item.customer_name || '—' }}</div>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted">
|
||||
<span>{{ item.created_at || '' }}</span>
|
||||
<span>{{ formatLocalDateTime(item.created_at) }}</span>
|
||||
<span v-if="item.batch_index && item.batch_total" class="rounded-full bg-sky-50 px-2 py-0.5 font-medium text-sky-700">
|
||||
{{ t('chat.shippingNoticeUi.batchProgress', { index: item.batch_index, total: item.batch_total }) }}
|
||||
</span>
|
||||
@@ -418,15 +295,6 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="detailRetrying"
|
||||
@click="handleRetryCurrentTask"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ detailRetrying ? $t('workspace.shippingNotice.retrying') : $t('workspace.shippingNotice.retryCurrentTask') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
type="button"
|
||||
@@ -486,8 +354,14 @@ onMounted(async () => {
|
||||
</div>
|
||||
|
||||
<dl class="grid gap-3 sm:grid-cols-2 text-sm">
|
||||
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt><dd>{{ detail.process_status }}</dd></div>
|
||||
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt><dd>{{ detail.match_status || '—' }}</dd></div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt>
|
||||
<dd :title="detail.process_status">{{ statusBadge(detail).label }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt>
|
||||
<dd :title="detail.match_status || ''">{{ matchStatusLabel(detail.match_status) }}</dd>
|
||||
</div>
|
||||
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.shipTo') }}</dt><dd>{{ detail.ship_to || '—' }}</dd></div>
|
||||
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.freightRef') }}</dt><dd>{{ detail.freight_ref_no || '—' }}</dd></div>
|
||||
</dl>
|
||||
@@ -502,20 +376,11 @@ onMounted(async () => {
|
||||
:match-status="detail.match_status"
|
||||
:line-results="detail.line_results"
|
||||
:shortage-lines="shortageLines"
|
||||
:action-buttons="detailActionButtons"
|
||||
:action-busy="detailActionBusy"
|
||||
:action-button-class="shippingActionButtonClass"
|
||||
:on-action-click="handleWorkspaceAction"
|
||||
:action-buttons="[]"
|
||||
:action-busy="false"
|
||||
/>
|
||||
|
||||
<div v-if="parseReviewPayload">
|
||||
<ShippingParseReviewMessage
|
||||
:message="parseReviewMessage"
|
||||
:handlers="parseReviewHandlers"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else-if="detail.lines?.length">
|
||||
<div v-if="detail.lines?.length">
|
||||
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.lines') }}</h3>
|
||||
<div class="overflow-x-auto rounded-xl border border-default">
|
||||
<table class="min-w-full text-sm">
|
||||
@@ -539,8 +404,8 @@ onMounted(async () => {
|
||||
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.events') }}</h3>
|
||||
<ul class="max-h-48 space-y-1 overflow-y-auto text-xs text-muted">
|
||||
<li v-for="(ev, idx) in [...detail.events].reverse()" :key="idx">
|
||||
<span class="font-medium text-secondary">{{ ev.event_type }}</span>
|
||||
<span class="ml-2">{{ ev.created_at }}</span>
|
||||
<span class="font-medium text-secondary" :title="ev.event_type">{{ eventLabel(ev.event_type) }}</span>
|
||||
<span class="ml-2">{{ formatLocalDateTime(ev.created_at) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user