1020 lines
39 KiB
TypeScript
1020 lines
39 KiB
TypeScript
/**
|
||
* features/chat/composables/useChatShipping.ts
|
||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||
* 依赖:shipping.api(任务/客户等)、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
|
||
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点)。会话恢复唯一使用 task_no;
|
||
* 批次进度由 shipping-processing projection 承接,不维护已下线 shipping_batches 的本地快照。
|
||
* 对外暴露 isOrderExtractionSubmitting / hasBlockingNoticeIntake,供发送禁用与输入区 loading。
|
||
*/
|
||
|
||
import {
|
||
computed,
|
||
onBeforeUnmount,
|
||
ref,
|
||
watch,
|
||
type ComputedRef,
|
||
type Ref,
|
||
} from 'vue';
|
||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||
import { isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
|
||
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
|
||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||
|
||
import { useShippingNoticeIntakes } from '../shipping/useShippingNoticeIntakes';
|
||
import {
|
||
createShippingActionsRefresher,
|
||
createShippingConversationHelpers,
|
||
createShippingDecisionHandlers,
|
||
createShippingMenuHandlers,
|
||
createShippingParseReviewHandlers,
|
||
createShippingSendHandlers,
|
||
createShippingUploadHandlers,
|
||
useShippingOrderExtractionRuns,
|
||
findLatestShippingTaskId,
|
||
getShippingMatchResultPayload,
|
||
getShippingParseReviewPayload,
|
||
sanitizeShippingConversationText,
|
||
} from '../shipping';
|
||
import { isShippingUiParseReview } from '../shipping/shippingUiPosition';
|
||
import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt';
|
||
import { extractExt } from '../constants/shipping';
|
||
import {
|
||
getWorkspaceShippingTask,
|
||
listWorkspaceShippingCustomerOptions,
|
||
confirmWorkspaceShippingCustomer,
|
||
type ShippingTaskDetail,
|
||
} from '@/features/chat/api/shipping.api';
|
||
import type {
|
||
ShippingCustomerOption,
|
||
} from '../types/shipping.api.types';
|
||
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
|
||
import {
|
||
hasShortageLines,
|
||
isShippingShortageQueryIntent,
|
||
} from '../shipping/shippingShortageDetails';
|
||
|
||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||
import type { SendMessageLifecycleHooks } from './useChat';
|
||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
||
import type { ChatDeps } from './chat.deps';
|
||
import { listChatMessages } from '../api/chat.api';
|
||
|
||
export interface UseChatShippingOptions {
|
||
deps: ChatDeps;
|
||
currentAgent: Ref<AgentRegistryFields | null>;
|
||
currentAgentId: ComputedRef<number>;
|
||
messages: Ref<ChatMessage[]>;
|
||
conversationId: Ref<string | null>;
|
||
isThinking: Ref<boolean>;
|
||
shippingActionBusy: ComputedRef<boolean>;
|
||
activeRunId: Ref<number | null>;
|
||
runs: Ref<ChatRun[]>;
|
||
history: Ref<ChatSessionItem[]>;
|
||
loadHistory: () => Promise<void>;
|
||
input: Ref<string>;
|
||
attachments: Ref<PendingAttachment[]>;
|
||
selectedKb: Ref<string>;
|
||
isUploadingAttachments: Ref<boolean>;
|
||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||
presetQuestion: ComputedRef<string>;
|
||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<boolean>;
|
||
newLocalMessageId: (prefix: string) => string;
|
||
stripReasoningPrelude: (text: string) => string;
|
||
sendMessage: (
|
||
content: string,
|
||
agentId: number,
|
||
kb: string,
|
||
files: ChatUploadFileSpec[],
|
||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||
hooks?: SendMessageLifecycleHooks,
|
||
) => Promise<ChatMessageSendResult>;
|
||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||
createNewChatView: () => void;
|
||
}
|
||
|
||
/**
|
||
* 从单条助手消息中提取工作台恢复锚点。
|
||
* 核心逻辑:只接受 `task_no / shipping_ui_state`;
|
||
* 供实时终态、历史回放与刷新恢复共用。
|
||
*/
|
||
export const resolveShippingMessageRecoveryPayload = (
|
||
message: ChatMessage | null | undefined,
|
||
): ShippingMessageRecoveryPayload | null => {
|
||
const payload = message?.payload && typeof message.payload === 'object'
|
||
? message.payload as ShippingMessageRecoveryPayload
|
||
: null;
|
||
if (!payload) return null;
|
||
const taskNo = String(
|
||
payload.task_no
|
||
|| payload.shipping_ui_state?.task_no
|
||
|| '',
|
||
).trim();
|
||
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
|
||
if (!taskNo && !hasTaskUiState) {
|
||
return null;
|
||
}
|
||
return {
|
||
...payload,
|
||
...(taskNo ? { task_no: taskNo } : {}),
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 从消息列表中选择最近一条可恢复工作台的消息载荷。
|
||
* 核心逻辑:从后往前找最近的权威恢复锚点,允许 `open_existing` 只靠 `task_no/ui_state` 恢复。
|
||
*/
|
||
export const resolveLatestShippingMessageRecoveryPayload = (
|
||
sourceMessages: ChatMessage[],
|
||
): ShippingMessageRecoveryPayload | null => {
|
||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||
const payload = resolveShippingMessageRecoveryPayload(sourceMessages[index]);
|
||
if (payload) return payload;
|
||
}
|
||
return null;
|
||
};
|
||
|
||
/**
|
||
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
|
||
*
|
||
* 核心逻辑:统一管理当前任务/批次上下文,组合上传、解析复核、匹配结果、决策与动作刷新等子模块,并对 ChatView 暴露稳定 API。
|
||
* @param options - 聊天页依赖与响应式状态集合
|
||
* @returns 发货通知聊天场景所需的状态、事件处理器和工具函数
|
||
*/
|
||
export function useChatShipping(options: UseChatShippingOptions) {
|
||
const {
|
||
deps: { t, msg, router, route },
|
||
currentAgent,
|
||
currentAgentId,
|
||
messages,
|
||
conversationId,
|
||
isThinking,
|
||
shippingActionBusy,
|
||
activeRunId,
|
||
runs,
|
||
history,
|
||
loadHistory,
|
||
input,
|
||
attachments,
|
||
selectedKb,
|
||
isUploadingAttachments,
|
||
attachmentPolicy,
|
||
presetQuestion,
|
||
saveLocalMessageToBackend,
|
||
newLocalMessageId,
|
||
stripReasoningPrelude,
|
||
sendMessage,
|
||
startChatTurn,
|
||
buildFileSpecsForSend,
|
||
createNewChatView,
|
||
} = options;
|
||
|
||
const shippingBindSend = (_fn: () => Promise<void>) => {
|
||
void _fn;
|
||
// 保留旧绑定入口,续办链路已改为直接调用 sendMessage 以支持 display_query 上下文。
|
||
};
|
||
|
||
// ── 功能开关与 UI refs ────────────────────────────────────
|
||
const isShippingNoticeAgent = computed(() => resolveShippingNoticeAgent(currentAgent.value));
|
||
const isShippingActionBusy = computed(() => {
|
||
if (shippingActionBusy.value) return true;
|
||
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
|
||
});
|
||
const allowsSendWithAttachmentsOnly = computed(
|
||
() => isShippingNoticeAgent.value && attachments.value.length > 0,
|
||
);
|
||
const shippingAutoFlowRequested = ref(false);
|
||
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
|
||
const shippingNoticePickerRef = ref<HTMLInputElement | null>(null);
|
||
const pendingShippingUploadTaskId = ref('');
|
||
const pendingShippingNoticeTaskId = ref('');
|
||
const pendingShippingInventoryFile = ref<File | null>(null);
|
||
const shippingInventorySelectionActive = ref(false);
|
||
const shippingInventorySelectionTaskId = ref('');
|
||
|
||
const prepareMarkdownDisplayText = (text: string) => {
|
||
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
|
||
};
|
||
|
||
// ── 任务编号状态(单票恢复锚点) ─────────────────────────────
|
||
const shippingTaskIdFromQuery = computed(() => {
|
||
const value = route.query.task_id;
|
||
return typeof value === 'string' ? value.trim() : '';
|
||
});
|
||
const resolvedShippingTaskId = ref('');
|
||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||
const lastConversationSyncKey = ref('');
|
||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||
|
||
/**
|
||
* 按任务锚点恢复聊天工作台。
|
||
*
|
||
* 核心逻辑:`open_existing` 携带 `task_no / shipping_ui_state`;恢复任务锚点后补拉任务详情。
|
||
* @param payload - 从消息中解析出的恢复载荷
|
||
* @returns 是否恢复出任务上下文
|
||
*/
|
||
const applyResolvedShippingMessageRecovery = async (
|
||
payload: ShippingMessageRecoveryPayload | null,
|
||
): Promise<boolean> => {
|
||
if (!payload) return false;
|
||
let recovered = false;
|
||
const taskNo = String(
|
||
payload.task_no
|
||
|| payload.shipping_ui_state?.task_no
|
||
|| '',
|
||
).trim().toUpperCase();
|
||
if (taskNo) {
|
||
resolvedShippingTaskId.value = taskNo;
|
||
}
|
||
if (payload.shipping_ui_state && taskNo) {
|
||
activeShippingTaskDetail.value = {
|
||
...(activeShippingTaskDetail.value || {}),
|
||
task_no: taskNo,
|
||
lines: activeShippingTaskDetail.value?.lines || [],
|
||
events: activeShippingTaskDetail.value?.events || [],
|
||
ui_state: payload.shipping_ui_state,
|
||
} as ShippingTaskDetail;
|
||
recovered = true;
|
||
}
|
||
if (taskNo) {
|
||
await syncActiveShippingTaskDetail(taskNo);
|
||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||
}
|
||
return recovered;
|
||
};
|
||
|
||
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
|
||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||
);
|
||
|
||
/**
|
||
* 清空当前聊天页绑定的发货任务上下文。
|
||
*
|
||
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
|
||
* 避免会话摘要和待上传库存文件残留到下一次新会话。
|
||
*/
|
||
const resetShippingConversationState = () => {
|
||
// 新对话不会触发 onConversationIdChanging;必须在此清掉旧 Run,
|
||
// 否则右侧面板仍会将其作为当前会话的展示条件。
|
||
shippingOrderExtractionRuns.clearActiveRun();
|
||
shippingAutoFlowRequested.value = false;
|
||
pendingShippingUploadTaskId.value = '';
|
||
pendingShippingNoticeTaskId.value = '';
|
||
pendingShippingInventoryFile.value = null;
|
||
shippingInventorySelectionActive.value = false;
|
||
shippingInventorySelectionTaskId.value = '';
|
||
resolvedShippingTaskId.value = '';
|
||
activeShippingTaskDetail.value = null;
|
||
lastConversationSyncKey.value = '';
|
||
};
|
||
|
||
const getActiveShippingTaskId = () =>
|
||
findLatestShippingTaskId(messages.value)
|
||
|| resolvedShippingTaskId.value
|
||
|| shippingTaskIdFromQuery.value
|
||
|| '';
|
||
|
||
const getCurrentShippingChatContext = () => ({
|
||
task_id: getActiveShippingTaskId(),
|
||
});
|
||
|
||
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
|
||
...getCurrentShippingChatContext(),
|
||
display_query: displayQuery,
|
||
});
|
||
|
||
/**
|
||
* 同步当前焦点任务详情。
|
||
*
|
||
* 核心逻辑:仅拉取任务详情;批次进度由独立 processing projection 提供。
|
||
* @param taskId - 可选任务编号;未传时回退到当前激活任务
|
||
*/
|
||
const syncActiveShippingTaskDetail = async (taskId?: string) => {
|
||
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
|
||
if (!normalized) {
|
||
activeShippingTaskDetail.value = null;
|
||
return;
|
||
}
|
||
try {
|
||
const detail = await getWorkspaceShippingTask(normalized);
|
||
activeShippingTaskDetail.value = detail;
|
||
} catch {
|
||
activeShippingTaskDetail.value = null;
|
||
}
|
||
};
|
||
|
||
const syncConversationMessagesIfNeeded = async (taskId?: string) => {
|
||
const conversationKey = String(conversationId.value || '').trim();
|
||
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
|
||
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isShippingActionBusy.value) return;
|
||
const detail = activeShippingTaskDetail.value;
|
||
// 复核同步:优先 review_status / Gate / position(isShippingUiParseReview)。
|
||
if (!isShippingUiParseReview(detail?.ui_state || null)) return;
|
||
const exists = messages.value.some((msg) => {
|
||
if (msg.type !== 'shipping-parse-review' || !msg.payload || typeof msg.payload !== 'object') return false;
|
||
return String((msg.payload as { taskId?: string }).taskId || '').trim().toUpperCase() === normalizedTaskId;
|
||
});
|
||
if (exists) return;
|
||
const syncKey = `${conversationKey}|${normalizedTaskId}|parse_review`;
|
||
if (lastConversationSyncKey.value === syncKey) return;
|
||
const loaded = await listChatMessages(conversationKey, currentAgentId.value);
|
||
if (Array.isArray(loaded) && loaded.length > 0) {
|
||
messages.value = loaded;
|
||
lastConversationSyncKey.value = syncKey;
|
||
}
|
||
};
|
||
|
||
const lastAssistantMessageContent = () => {
|
||
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
|
||
const item = messages.value[i];
|
||
if (item?.role === 'assistant') return String(item.content || '');
|
||
}
|
||
return '';
|
||
};
|
||
|
||
const lastAssistantShippingActions = () => {
|
||
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
|
||
const item = messages.value[i];
|
||
if (item?.role === 'assistant' && Array.isArray(item.shipping_actions)) {
|
||
return item.shipping_actions;
|
||
}
|
||
}
|
||
return [];
|
||
};
|
||
|
||
const { refreshShippingActions } = createShippingActionsRefresher({
|
||
isShippingNoticeAgent,
|
||
messages,
|
||
conversationId,
|
||
isThinking,
|
||
resolvedShippingTaskId,
|
||
shippingTaskIdFromQuery,
|
||
getActiveShippingTaskId,
|
||
});
|
||
|
||
/**
|
||
* Dify SSE 完成后立即净化最后一条回复,并同步后端动作按钮。
|
||
*
|
||
* 核心逻辑:流式过程中只做展示层净化;终态事件到达后消息对象已经完整,
|
||
* 此时调用统一 refreshShippingActions,把 action_buttons 回写到当前 assistant 气泡。
|
||
*/
|
||
const finalizeShippingAssistantMessage = async () => {
|
||
if (!isShippingNoticeAgent.value) return;
|
||
await shippingIntakes.refreshStatuses();
|
||
shippingIntakes.clearConsumedAttachments();
|
||
await refreshShippingActions();
|
||
};
|
||
|
||
/**
|
||
* 为“查询缺口明细”定位任务事实来源。
|
||
*
|
||
* 核心逻辑:优先使用显式任务号或当前聚焦任务,再从批次摘要/当前详情中读取;
|
||
* 摘要缺少逐行缺口时补拉既有任务详情接口,确保聊天回复只基于后端事实数据。
|
||
*/
|
||
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
|
||
const normalizedTaskNo = String(
|
||
taskNo
|
||
|| getActiveShippingTaskId()
|
||
|| '',
|
||
).trim().toUpperCase();
|
||
if (!normalizedTaskNo) return null;
|
||
const detail = activeShippingTaskDetail.value;
|
||
if (String(detail?.task_no || '').trim().toUpperCase() === normalizedTaskNo && hasShortageLines(detail)) {
|
||
return detail;
|
||
}
|
||
try {
|
||
return await getWorkspaceShippingTask(normalizedTaskNo);
|
||
} catch {
|
||
return null;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 在聊天流中输出确定性的缺口明细(Chat Turn SSE)。
|
||
*/
|
||
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
|
||
const task = await resolveShippingTaskForShortageQuery(taskNo);
|
||
if (!task) {
|
||
msg.warning(t('chat.shippingNoticeMissingTaskId'));
|
||
return true;
|
||
}
|
||
const normalizedTaskNo = String(task.task_no || '').trim().toUpperCase();
|
||
const turn = buildShippingQueryShortageTurn(
|
||
normalizedTaskNo,
|
||
displayText || t('chat.shippingNoticeUi.queryShortageDetails'),
|
||
);
|
||
await startChatTurn({
|
||
agentId: currentAgentId.value,
|
||
inputType: 'action',
|
||
displayText: turn.displayText,
|
||
actionType: turn.actionType,
|
||
payload: turn.payload,
|
||
refs: turn.refs,
|
||
});
|
||
return true;
|
||
};
|
||
|
||
const { sendShippingMenuMessage } = createShippingConversationHelpers({
|
||
conversationId,
|
||
history,
|
||
loadHistory,
|
||
getActiveShippingTaskId,
|
||
currentAgentId,
|
||
selectedKb,
|
||
sendMessage,
|
||
});
|
||
|
||
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
|
||
getActiveShippingTaskId,
|
||
refreshShippingActions,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
const {
|
||
syncShippingParseReviewCard,
|
||
updateShippingParseReviewHeader,
|
||
updateShippingParseReviewLine,
|
||
addShippingParseReviewLine,
|
||
removeShippingParseReviewLine,
|
||
} = createShippingParseReviewHandlers({
|
||
messages,
|
||
resolvedShippingTaskId,
|
||
newLocalMessageId,
|
||
saveLocalMessageToBackend,
|
||
refreshShippingActions,
|
||
msg,
|
||
});
|
||
|
||
const shippingIntakes = useShippingNoticeIntakes({
|
||
attachments,
|
||
conversationId,
|
||
msg,
|
||
t,
|
||
});
|
||
const workflowRefreshTrigger = ref(0);
|
||
const bumpWorkflowRefresh = () => {
|
||
workflowRefreshTrigger.value += 1;
|
||
};
|
||
/** 侧栏/提交共用的当前聚焦用户可见任务(OT-…)。 */
|
||
const focusedConversationTaskNo = ref<string | null>(null);
|
||
const showShippingProgressWorkspace = ref(false);
|
||
const clearShippingFocus = () => {
|
||
focusedConversationTaskNo.value = null;
|
||
void router.replace({ path: route.path, query: { ...route.query, focus_task_no: undefined, focus_notice: undefined } });
|
||
};
|
||
const setFocusedConversationTaskNo = (taskNo: string | null) => {
|
||
focusedConversationTaskNo.value = String(taskNo || '').trim() || null;
|
||
};
|
||
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
|
||
messages,
|
||
conversationId,
|
||
currentAgentId,
|
||
newLocalMessageId,
|
||
saveLocalMessageToBackend,
|
||
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
|
||
getOrderExtractionReview: shippingIntakes.getOrderExtractionReview,
|
||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||
refreshShippingActions,
|
||
loadHistory,
|
||
onConversationResolved: async (resolvedConversationId) => {
|
||
const currentRouteId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
|
||
if (currentRouteId === resolvedConversationId) return;
|
||
await router.replace({
|
||
path: route.path,
|
||
query: { ...route.query, conversation_id: resolvedConversationId },
|
||
});
|
||
},
|
||
onRetryError: (message) => msg.error(message),
|
||
onWorkflowRefresh: bumpWorkflowRefresh,
|
||
getFocusedUserTaskNo: () => focusedConversationTaskNo.value,
|
||
setFocusedUserTaskNo: setFocusedConversationTaskNo,
|
||
t,
|
||
});
|
||
|
||
const showShippingDuplicateDialog = ref(false);
|
||
const showShippingCustomerDialog = ref(false);
|
||
const shippingCustomerDialogTaskId = ref('');
|
||
const shippingCustomerOptions = ref<ShippingCustomerOption[]>([]);
|
||
const shippingCustomerLoading = ref(false);
|
||
const shippingDuplicateAttachmentId = ref<string | null>(null);
|
||
const shippingDuplicateAttachment = computed(() => {
|
||
const id = shippingDuplicateAttachmentId.value;
|
||
if (!id) return null;
|
||
return shippingIntakes.noticeAttachments.value.find((item) => item.id === id) || null;
|
||
});
|
||
const canForceCreateShippingDuplicate = computed(() => {
|
||
const user = useAuthStore().user;
|
||
if (!user) return false;
|
||
return Boolean(user.feature_permissions?.shipping_notice_force_create);
|
||
});
|
||
|
||
/**
|
||
* 打开首个(或指定)阻断型重复附件的处理弹窗。
|
||
*/
|
||
const openShippingDuplicateDialog = (attachmentId?: string) => {
|
||
const targetId =
|
||
attachmentId
|
||
|| shippingIntakes.noticeAttachments.value.find(
|
||
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
|
||
)?.id
|
||
|| null;
|
||
if (!targetId) {
|
||
msg.warning(t('chat.shippingNoticeDuplicateNeedsResolution'));
|
||
return;
|
||
}
|
||
shippingDuplicateAttachmentId.value = targetId;
|
||
showShippingDuplicateDialog.value = true;
|
||
};
|
||
|
||
/**
|
||
* 提交重复决策并写回附件状态。
|
||
*/
|
||
const resolveShippingDuplicateDialog = async (payload: {
|
||
action: import('../types/shipping.types').ShippingDuplicateAction;
|
||
targetTaskNo?: string;
|
||
reason?: string;
|
||
}) => {
|
||
const id = shippingDuplicateAttachmentId.value;
|
||
if (!id) return;
|
||
try {
|
||
await shippingIntakes.resolveDuplicateAttachment(
|
||
id,
|
||
payload.action,
|
||
payload.targetTaskNo,
|
||
payload.reason,
|
||
);
|
||
msg.success(t('chat.shippingNoticeDuplicateResolved'));
|
||
} catch (e: unknown) {
|
||
msg.warning(e instanceof Error ? e.message : t('chat.shippingNoticeDuplicateResolveFailed'));
|
||
}
|
||
};
|
||
|
||
const removeShippingDuplicateDialogAttachment = async () => {
|
||
const id = shippingDuplicateAttachmentId.value;
|
||
if (!id) return;
|
||
await shippingIntakes.removeNoticeAttachment(id);
|
||
shippingDuplicateAttachmentId.value = null;
|
||
};
|
||
|
||
/** 打开客户确认对话框并加载启用标准客户。 */
|
||
const openShippingCustomerDialog = async (taskId: string): Promise<void> => {
|
||
shippingCustomerDialogTaskId.value = String(taskId || '').trim().toUpperCase();
|
||
showShippingCustomerDialog.value = true;
|
||
shippingCustomerLoading.value = true;
|
||
try {
|
||
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions();
|
||
} catch (error: unknown) {
|
||
shippingCustomerOptions.value = [];
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||
} finally {
|
||
shippingCustomerLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/** 按关键词刷新客户选项。 */
|
||
const searchShippingCustomers = async (query: string): Promise<void> => {
|
||
shippingCustomerLoading.value = true;
|
||
try {
|
||
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions(query);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||
} finally {
|
||
shippingCustomerLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/** 确认客户后刷新任务详情与动作菜单;业务号仍由后续阶段生成。 */
|
||
const confirmShippingCustomer = async (customerId: number): Promise<void> => {
|
||
const taskId = shippingCustomerDialogTaskId.value;
|
||
if (!taskId) return;
|
||
shippingCustomerLoading.value = true;
|
||
try {
|
||
await confirmWorkspaceShippingCustomer(taskId, customerId);
|
||
showShippingCustomerDialog.value = false;
|
||
await Promise.all([syncActiveShippingTaskDetail(taskId), refreshShippingActions()]);
|
||
msg.success(t('chat.shippingCustomer.confirmed'));
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
|
||
} finally {
|
||
shippingCustomerLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/** 更新 Candidate 选择状态,并将 API 失败统一反馈给用户。 */
|
||
const setShippingCandidateSelected = async (candidateNo: string, selected: boolean) => {
|
||
try {
|
||
await shippingIntakes.setCandidateSelected(candidateNo, selected);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
}
|
||
};
|
||
|
||
/** 保存 Candidate 重复决策,并统一展示权限或目标漂移错误。 */
|
||
const resolveShippingCandidateDuplicate = async (
|
||
candidateNo: string,
|
||
action: import('../types/shipping.types').ShippingDuplicateAction,
|
||
targetTaskNo?: string,
|
||
reason?: string,
|
||
done?: (success: boolean) => void,
|
||
) => {
|
||
try {
|
||
await shippingIntakes.resolveCandidateDuplicate(candidateNo, action, targetTaskNo, reason);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
msg.success(t('chat.shippingNoticeDuplicateResolved'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeDuplicateResolveFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
/** 人工采纳 Dify 兜底 Candidate,并刷新当前 Run 的审核快照。 */
|
||
const promoteShippingCandidate = async (candidateNo: string, done?: (success: boolean) => void) => {
|
||
try {
|
||
await shippingIntakes.promoteCandidate(candidateNo);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
msg.success(t('chat.shippingCandidatePromoted'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
/** 人工驳回 Dify 兜底 Candidate,并刷新当前 Run 的审核快照。 */
|
||
const rejectShippingCandidate = async (candidateNo: string, done?: (success: boolean) => void) => {
|
||
try {
|
||
await shippingIntakes.rejectCandidate(candidateNo);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
msg.success(t('chat.shippingCandidateRejected'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
const {
|
||
handleShippingAutoUploadFile,
|
||
handleShippingAutoUploadNoticeBatch,
|
||
openShippingInventoryPicker,
|
||
openShippingNoticePicker,
|
||
selectShippingInventoryUploadTask,
|
||
cancelShippingInventoryTaskSelection,
|
||
handleShippingInventorySelected,
|
||
shippingSuggestedPrompt,
|
||
useShippingSuggestedPrompt,
|
||
isShippingNoticeBatchSubmitting,
|
||
} = createShippingUploadHandlers({
|
||
conversationId,
|
||
currentAgentId,
|
||
attachments,
|
||
input,
|
||
shippingAutoFlowRequested,
|
||
shippingInventoryPickerRef,
|
||
shippingNoticePickerRef,
|
||
pendingShippingUploadTaskId,
|
||
pendingShippingNoticeTaskId,
|
||
pendingShippingInventoryFile,
|
||
resolvedShippingTaskId,
|
||
shippingInventorySelectionActive,
|
||
shippingInventorySelectionTaskId,
|
||
getActiveShippingTaskId,
|
||
startChatTurn,
|
||
refreshShippingActions,
|
||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||
getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos,
|
||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||
enqueueNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||
startOrderExtractionRun: (...args) => shippingOrderExtractionRuns.startRun(...args),
|
||
sendTemporaryInventoryMessage: async (assetNo, fileName) => sendMessage(
|
||
`我已上传库存文件:${fileName},请先检查文件结构并说明下一步。`,
|
||
currentAgentId.value,
|
||
selectedKb.value,
|
||
[],
|
||
{
|
||
shipping_temporary_inventory_asset_no: assetNo,
|
||
display_query: `上传库存文件:${fileName}`,
|
||
},
|
||
),
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
|
||
isThinking,
|
||
getActiveShippingTaskId,
|
||
messages,
|
||
sendShippingMenuMessage,
|
||
openShippingInventoryPicker,
|
||
openShippingNoticePicker,
|
||
openShippingCustomerDialog,
|
||
executeShippingDecision,
|
||
executeShippingManualUpload,
|
||
refreshShippingActions,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
|
||
isShippingNoticeAgent,
|
||
isThinking,
|
||
isUploadingAttachments,
|
||
messages,
|
||
conversationId,
|
||
history,
|
||
input,
|
||
attachments,
|
||
shippingAutoFlowRequested,
|
||
resolvedShippingTaskId,
|
||
currentAgentId,
|
||
selectedKb,
|
||
attachmentPolicy,
|
||
getActiveShippingTaskId,
|
||
lastAssistantMessageContent,
|
||
lastAssistantShippingActions,
|
||
sendMessage,
|
||
buildFileSpecsForSend,
|
||
loadHistory,
|
||
sendShippingMenuMessage,
|
||
startChatTurn,
|
||
executeShippingDecision,
|
||
executeShippingManualUpload,
|
||
handleShippingMenuAction,
|
||
handleShippingAutoUploadFile,
|
||
handleShippingAutoUploadNoticeBatch,
|
||
isShippingNoticeBatchSubmitting,
|
||
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
|
||
hasNoticeIntakeFailures: () => shippingIntakes.hasParseFailures.value,
|
||
hasBlockingNoticeDuplicates: () => shippingIntakes.hasBlockingDuplicates.value,
|
||
hasCandidateReviewIssues: () => shippingIntakes.hasCandidateReviewIssues.value,
|
||
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
|
||
openShippingDuplicateDialog,
|
||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||
startOrderExtractionRun: shippingOrderExtractionRuns.startRun,
|
||
applyShippingMessageRecovery,
|
||
refreshShippingActions,
|
||
shippingSuggestedPrompt,
|
||
isShippingShortageQueryIntent,
|
||
queryShippingShortageDetails,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
// ── 路由 / 会话生命周期 ───────────────────────────────────
|
||
/**
|
||
* 根据路由中的 `task_id` 恢复发货任务上下文。
|
||
* 核心逻辑:直接基于明确 task_id 发起一次继续任务请求,禁止按历史标题模糊猜测会话。
|
||
* @returns Promise<void>
|
||
*/
|
||
const resumeShippingTaskFromQuery = async () => {
|
||
const taskId = shippingTaskIdFromQuery.value;
|
||
if (!taskId || !isShippingNoticeAgent.value) return;
|
||
if (route.query.conversation_id) return;
|
||
if (presetQuestion.value) return;
|
||
if (autoResumedShippingTasks.value[taskId]) return;
|
||
autoResumedShippingTasks.value[taskId] = true;
|
||
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
|
||
await sendMessage(
|
||
t('chat.shippingNoticeContinue', { taskId }),
|
||
currentAgentId.value,
|
||
selectedKb.value,
|
||
[],
|
||
getCurrentShippingChatContextWithDisplay(displayText),
|
||
);
|
||
await loadHistory();
|
||
};
|
||
|
||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||
shippingIntakes.stopPolling();
|
||
if (nextId && nextId !== prevId) {
|
||
focusedConversationTaskNo.value = null;
|
||
void shippingIntakes.restoreForConversation(nextId);
|
||
void shippingOrderExtractionRuns.restoreForConversation(nextId);
|
||
} else {
|
||
shippingOrderExtractionRuns.clearActiveRun();
|
||
}
|
||
if (prevId !== nextId) {
|
||
resolvedShippingTaskId.value = '';
|
||
}
|
||
};
|
||
|
||
const handleShippingLocalFilesSelected = (event: Event): boolean => {
|
||
if (!isShippingNoticeAgent.value) return false;
|
||
const inputEl = event.target as HTMLInputElement | null;
|
||
const files = inputEl?.files ? Array.from(inputEl.files) : [];
|
||
if (!files.length) return false;
|
||
const noticeFiles = files.filter((file) => !isShippingSpreadsheetFile(file, extractExt));
|
||
const spreadsheetFiles = files.filter((file) => isShippingSpreadsheetFile(file, extractExt));
|
||
if (noticeFiles.length) {
|
||
void shippingIntakes.enqueueNoticeFiles(noticeFiles);
|
||
}
|
||
// 表格附件先留在本地等待用户声明;不能因扩展名直接送订单或库存解析。
|
||
for (const file of spreadsheetFiles) {
|
||
attachments.value = [
|
||
...attachments.value,
|
||
{
|
||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||
kind: 'local',
|
||
file,
|
||
type: 'document',
|
||
uploadStatus: 'waiting',
|
||
uploadProgress: 0,
|
||
},
|
||
];
|
||
}
|
||
if (inputEl) inputEl.value = '';
|
||
return true;
|
||
};
|
||
|
||
const onConversationLoadedEmpty = async () => {
|
||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
|
||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||
await router.replace({ path: route.path, query: nextQuery });
|
||
};
|
||
|
||
const onConversationLoadFailed = async () => {
|
||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
|
||
createNewChatView();
|
||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||
void router.replace({ path: route.path, query: nextQuery });
|
||
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
|
||
await sendMessage(
|
||
t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value }),
|
||
currentAgentId.value,
|
||
selectedKb.value,
|
||
[],
|
||
getCurrentShippingChatContextWithDisplay(displayText),
|
||
);
|
||
await loadHistory();
|
||
};
|
||
|
||
/**
|
||
* 启停发货会话状态短轮询。
|
||
*
|
||
* 核心逻辑:co8 后不再轮询 shipping_batches;仅在存在任务上下文时每 3 秒补拉任务详情与动作按钮,
|
||
* 批次/处理进度改由 shipping-processing projection 承接。
|
||
*/
|
||
const restartShippingStatusPolling = () => {
|
||
if (shippingStatusPollTimer) {
|
||
clearInterval(shippingStatusPollTimer);
|
||
shippingStatusPollTimer = null;
|
||
}
|
||
if (!isShippingNoticeAgent.value) return;
|
||
const taskId = getActiveShippingTaskId();
|
||
if (!taskId) return;
|
||
|
||
shippingStatusPollTimer = setInterval(() => {
|
||
if (!isShippingNoticeAgent.value) return;
|
||
const nextTaskId = getActiveShippingTaskId();
|
||
if (!nextTaskId) return;
|
||
void (async () => {
|
||
await syncActiveShippingTaskDetail(nextTaskId);
|
||
await syncConversationMessagesIfNeeded(nextTaskId);
|
||
await refreshShippingActions();
|
||
if (!isShippingActionBusy.value && shippingStatusPollTimer) {
|
||
clearInterval(shippingStatusPollTimer);
|
||
shippingStatusPollTimer = null;
|
||
}
|
||
})();
|
||
}, 3000);
|
||
};
|
||
|
||
// ── 动作按钮 watch ────────────────────────────────────────
|
||
const shippingActionsWatchKey = computed(() => {
|
||
const msgs = messages.value;
|
||
const last = msgs.length ? msgs[msgs.length - 1] : null;
|
||
return [
|
||
String(conversationId.value || ''),
|
||
String(msgs.length),
|
||
String(last?.role || ''),
|
||
String(last?.content || '').slice(-120),
|
||
].join('|');
|
||
});
|
||
const shippingRecoveryWatchKey = computed(() => {
|
||
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
|
||
const uiState = recovery?.shipping_ui_state;
|
||
return [
|
||
String(conversationId.value || ''),
|
||
String(recovery?.task_no || uiState?.task_no || ''),
|
||
String(uiState?.updated_at || ''),
|
||
].join('|');
|
||
});
|
||
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
|
||
if (!isShippingNoticeAgent.value) return;
|
||
void applyResolvedShippingMessageRecovery(resolveLatestShippingMessageRecoveryPayload(messages.value));
|
||
}, { immediate: true });
|
||
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||
void refreshShippingActions().then(async () => {
|
||
const taskId = getActiveShippingTaskId();
|
||
await Promise.all([
|
||
syncShippingParseReviewCard(taskId),
|
||
syncActiveShippingTaskDetail(taskId),
|
||
]);
|
||
await syncConversationMessagesIfNeeded(taskId);
|
||
});
|
||
});
|
||
watch(
|
||
[isShippingNoticeAgent, conversationId, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||
() => {
|
||
restartShippingStatusPolling();
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
onBeforeUnmount(() => {
|
||
if (shippingStatusPollTimer) {
|
||
clearInterval(shippingStatusPollTimer);
|
||
shippingStatusPollTimer = null;
|
||
}
|
||
});
|
||
|
||
return {
|
||
shippingBindSend,
|
||
isShippingNoticeAgent,
|
||
prepareMarkdownDisplayText,
|
||
shippingAutoFlowRequested,
|
||
shippingInventoryPickerRef,
|
||
shippingNoticePickerRef,
|
||
pendingShippingUploadTaskId,
|
||
shippingInventorySelectionActive,
|
||
shippingInventorySelectionTaskId,
|
||
allowsSendWithAttachmentsOnly,
|
||
shippingTaskIdFromQuery,
|
||
isShippingActionBusy,
|
||
activeShippingTaskDetail,
|
||
getCurrentShippingChatContext,
|
||
queryShippingShortageDetails,
|
||
resetShippingConversationState,
|
||
resumeShippingTaskFromQuery,
|
||
getShippingMatchResultPayload,
|
||
getShippingParseReviewPayload,
|
||
updateShippingParseReviewHeader,
|
||
updateShippingParseReviewLine,
|
||
addShippingParseReviewLine,
|
||
removeShippingParseReviewLine,
|
||
handleShippingActionClick,
|
||
handleShippingInventorySelected,
|
||
finalizeShippingAssistantMessage,
|
||
selectShippingInventoryUploadTask,
|
||
cancelShippingInventoryTaskSelection,
|
||
shippingSuggestedPrompt,
|
||
useShippingSuggestedPrompt,
|
||
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||
handleShippingLocalFilesSelected,
|
||
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
|
||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||
retryOrderExtractionRun: shippingOrderExtractionRuns.retryRun,
|
||
refreshOrderExtractionRun: shippingOrderExtractionRuns.refreshRun,
|
||
cancelOrderExtractionRun: shippingOrderExtractionRuns.cancelRun,
|
||
cancelOrderExtractionUnit: shippingOrderExtractionRuns.cancelUnit,
|
||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
|
||
isOrderExtractionSubmitting: shippingOrderExtractionRuns.isOrderExtractionSubmitting,
|
||
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
|
||
workflowRefreshTrigger,
|
||
bumpWorkflowRefresh,
|
||
focusedConversationTaskNo,
|
||
setFocusedConversationTaskNo,
|
||
clearShippingFocus,
|
||
showShippingProgressWorkspace,
|
||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||
setShippingCandidateSelected,
|
||
resolveShippingCandidateDuplicate,
|
||
promoteShippingCandidate,
|
||
rejectShippingCandidate,
|
||
showShippingDuplicateDialog,
|
||
showShippingCustomerDialog,
|
||
shippingCustomerOptions,
|
||
shippingCustomerLoading,
|
||
openShippingCustomerDialog,
|
||
searchShippingCustomers,
|
||
confirmShippingCustomer,
|
||
closeShippingCustomerDialog: () => {
|
||
showShippingCustomerDialog.value = false;
|
||
},
|
||
shippingDuplicateAttachment,
|
||
canForceCreateShippingDuplicate,
|
||
openShippingDuplicateDialog,
|
||
resolveShippingDuplicateDialog,
|
||
removeShippingDuplicateDialogAttachment,
|
||
closeShippingDuplicateDialog: () => {
|
||
showShippingDuplicateDialog.value = false;
|
||
},
|
||
tryHandleShippingAttachmentAutoFlow,
|
||
tryHandleShippingSend,
|
||
onConversationIdChanging,
|
||
onConversationLoadedEmpty,
|
||
onConversationLoadFailed,
|
||
};
|
||
}
|