feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载
This commit is contained in:
1 parent
143e054d86
commit
729546a7b7
52 files changed
+3420
-34
No files matched your search
@@ -15,6 +15,8 @@ import type {
|
||||
ShippingNoticeHeader,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeUploadResponse,
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingCreateBatchFromIntakesResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
@@ -471,6 +473,66 @@ export async function generateWorkspaceShippingExcel(taskNo: string) {
|
||||
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
|
||||
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
|
||||
|
||||
export const createShippingNoticeIntake = (
|
||||
assetNo: string,
|
||||
conversationId?: string | null,
|
||||
) => requestJson<ShippingNoticeIntakeResponse>('/api/workspace/shipping-notice/intakes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
asset_no: assetNo,
|
||||
conversation_id: conversationId || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
export const getShippingNoticeIntake = (intakeNo: string) =>
|
||||
requestJson<ShippingNoticeIntakeResponse>(`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`);
|
||||
|
||||
export const getShippingNoticeIntakeStatuses = (intakeNos: string[]) =>
|
||||
requestJson<{ items: ShippingNoticeIntakeResponse[] }>('/api/workspace/shipping-notice/intakes/status', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ intake_nos: intakeNos }),
|
||||
});
|
||||
|
||||
export const listActiveShippingNoticeIntakes = (conversationId?: string | null) => {
|
||||
const sp = new URLSearchParams({ status: 'active' });
|
||||
if (conversationId) sp.set('conversation_id', conversationId);
|
||||
return requestJson<{ items: ShippingNoticeIntakeResponse[] }>(
|
||||
`/api/workspace/shipping-notice/intakes?${sp.toString()}`,
|
||||
);
|
||||
};
|
||||
|
||||
export const retryShippingNoticeIntake = (intakeNo: string) =>
|
||||
requestJson<ShippingNoticeIntakeResponse>(
|
||||
`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/retry`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
export const cancelShippingNoticeIntake = (intakeNo: string) =>
|
||||
requestJson<{ cancelled: boolean }>(
|
||||
`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
|
||||
export const createWorkspaceShippingBatchFromIntakes = (
|
||||
intakeNos: string[],
|
||||
conversationId?: string | null,
|
||||
idempotencyKey?: string,
|
||||
) =>
|
||||
requestJson<ShippingCreateBatchFromIntakesResponse>('/api/workspace/shipping-batches/create-from-intakes', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
intake_nos: intakeNos,
|
||||
conversation_id: conversationId || undefined,
|
||||
idempotency_key: idempotencyKey,
|
||||
}),
|
||||
});
|
||||
|
||||
export type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
@@ -485,6 +547,8 @@ export type {
|
||||
ShippingNoticeHeader,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeUploadResponse,
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingCreateBatchFromIntakesResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
Loader2,
|
||||
Mic,
|
||||
Paperclip,
|
||||
RefreshCw,
|
||||
Send,
|
||||
Square,
|
||||
X,
|
||||
@@ -57,6 +59,7 @@ const emit = defineEmits<{
|
||||
stop: [];
|
||||
'voice-click': [];
|
||||
'remove-attachment': [id: string];
|
||||
'retry-shipping-notice-attachment': [id: string];
|
||||
'local-files-selected': [event: Event];
|
||||
'add-remote-url': [url: string];
|
||||
'shipping-inventory-selected': [event: Event];
|
||||
@@ -67,6 +70,7 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||
const { t } = useI18n();
|
||||
const textareaRef = ref<HTMLTextAreaElement | null>(null);
|
||||
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
||||
const kbMenuRef = ref<HTMLElement | null>(null);
|
||||
@@ -238,8 +242,26 @@ watch(
|
||||
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
|
||||
>
|
||||
<span class="max-w-[220px] truncate">
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
<template v-if="a.kind === 'shipping_notice'">
|
||||
{{ a.originalFilename }}
|
||||
<span v-if="a.uploadStatus === 'uploading'" class="text-muted"> · {{ t('chat.shippingNoticeUploading') }}</span>
|
||||
<span v-else-if="a.parseStatus === 'queued' || a.parseStatus === 'parsing'" class="text-muted"> · {{ t('chat.shippingNoticeParsing') }}</span>
|
||||
<span v-else-if="a.parseStatus === 'parsed'" class="text-muted"> · {{ t('chat.shippingNoticeParsed') }}</span>
|
||||
<span v-else-if="a.parseStatus === 'failed'" class="text-muted"> · {{ t('chat.shippingNoticeParseFailed') }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
</template>
|
||||
</span>
|
||||
<button
|
||||
v-if="a.kind === 'shipping_notice' && a.parseStatus === 'failed'"
|
||||
type="button"
|
||||
class="text-muted hover:text-primary"
|
||||
:title="t('chat.shippingNoticeRetryParse')"
|
||||
@click="emit('retry-shipping-notice-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button type="button" class="text-muted hover:text-red-500" @click="emit('remove-attachment', a.id)">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -257,7 +279,7 @@ watch(
|
||||
>
|
||||
{{ shippingSuggestedPrompt || '推荐问题' }}
|
||||
</button>
|
||||
<span>点发送开始处理</span>
|
||||
<span>{{ t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
|
||||
|
||||
@@ -286,6 +286,7 @@ watch(() => page.currentAgentId, () => {
|
||||
@stop="page.stopActiveGeneration()"
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
@remove-attachment="page.removeAttachment"
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
@local-files-selected="page.handleLocalFilesSelected"
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
|
||||
@@ -538,6 +538,19 @@ export function useChatPage() {
|
||||
showGuideSidebar: chatGuides.showSidebar,
|
||||
openGuideModal: chatGuides.openModal,
|
||||
...attachmentApi,
|
||||
handleLocalFilesSelected: (event: Event) => {
|
||||
if (shipping.handleShippingLocalFilesSelected(event)) return;
|
||||
attachmentApi.handleLocalFilesSelected(event);
|
||||
},
|
||||
removeAttachment: (id: string) => {
|
||||
const target = attachmentApi.attachments.value.find((item) => item.id === id);
|
||||
if (target?.kind === 'shipping_notice') {
|
||||
void shipping.removeShippingNoticeAttachment(id);
|
||||
return;
|
||||
}
|
||||
attachmentApi.removeAttachment(id);
|
||||
},
|
||||
retryShippingNoticeAttachment: shipping.retryShippingNoticeAttachment,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
previewFiles,
|
||||
|
||||
@@ -18,6 +18,7 @@ import { agentUsesWorkspaceStepperProgress, isShippingNoticeAgent as resolveShip
|
||||
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
|
||||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||||
|
||||
import { useShippingNoticeIntakes } from '../shipping/useShippingNoticeIntakes';
|
||||
import {
|
||||
createShippingActionsRefresher,
|
||||
createShippingConversationHelpers,
|
||||
@@ -40,6 +41,8 @@ import {
|
||||
shippingActionButtonClass,
|
||||
} from '../shipping';
|
||||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||||
import { classifyShippingUploadFile } from '../shipping/shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import {
|
||||
getWorkspaceShippingConversationBatches,
|
||||
getWorkspaceShippingBatch,
|
||||
@@ -657,6 +660,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
msg,
|
||||
});
|
||||
|
||||
const shippingIntakes = useShippingNoticeIntakes({
|
||||
attachments,
|
||||
conversationId,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const {
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
@@ -689,6 +699,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getActiveShippingTaskId,
|
||||
startChatTurn,
|
||||
refreshShippingActions,
|
||||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
@@ -741,6 +753,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
isShippingNoticeBatchSubmitting,
|
||||
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
|
||||
hasNoticeIntakeFailures: () => shippingIntakes.hasParseFailures.value,
|
||||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||||
refreshShippingActions,
|
||||
shippingSuggestedPrompt,
|
||||
isShippingShortageQueryIntent,
|
||||
@@ -782,6 +797,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||
onNoticeBatchConversationChanging(nextId, prevId);
|
||||
shippingIntakes.stopPolling();
|
||||
if (nextId && nextId !== prevId) {
|
||||
void shippingIntakes.restoreForConversation(nextId);
|
||||
}
|
||||
if (prevId !== nextId) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
if (!shippingBatchNoFromQuery.value) {
|
||||
@@ -855,6 +874,33 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
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) => classifyShippingUploadFile(file, extractExt) === 'notice');
|
||||
const otherFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) !== 'notice');
|
||||
if (noticeFiles.length) {
|
||||
void shippingIntakes.enqueueNoticeFiles(noticeFiles);
|
||||
}
|
||||
// 同一次选择中的库存/其他文件直接落入本地附件,避免清空 input 后通用 handler 丢失 FileList
|
||||
for (const file of otherFiles) {
|
||||
const kind = classifyShippingUploadFile(file, extractExt);
|
||||
attachments.value = [
|
||||
...attachments.value,
|
||||
{
|
||||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
kind: 'local',
|
||||
file,
|
||||
type: kind === 'inventory' ? 'document' : 'document',
|
||||
},
|
||||
];
|
||||
}
|
||||
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 };
|
||||
@@ -1017,6 +1063,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingActionButtonClass,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||||
handleShippingLocalFilesSelected,
|
||||
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
|
||||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||||
tryHandleShippingAttachmentAutoFlow,
|
||||
tryHandleShippingSend,
|
||||
onConversationIdChanging,
|
||||
|
||||
@@ -29,3 +29,10 @@ export async function computeNoticeFilesContentFingerprint(files: File[]): Promi
|
||||
.join('')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 intake 编号列表转为建批重试指纹(排序去重后拼接)。
|
||||
*/
|
||||
export function computeNoticeIntakeNosFingerprint(intakeNos: string[]): string {
|
||||
return [...new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean))].sort().join('|');
|
||||
}
|
||||
@@ -96,6 +96,29 @@ export function buildShippingCreateBatchTurn(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造发货通知建批 Chat Turn(基于已解析 intake,不再携带 files)。
|
||||
*/
|
||||
export function buildShippingCreateBatchFromIntakesTurn(
|
||||
intakeNos: string[],
|
||||
conversationId?: string | null,
|
||||
idempotencyKey?: string,
|
||||
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
|
||||
const count = intakeNos.length;
|
||||
const displayText = count === 1
|
||||
? `确认建单:${intakeNos[0]}`
|
||||
: `确认建单:${count} 份发货通知`;
|
||||
return {
|
||||
actionType: 'shipping.create_batch_from_intakes',
|
||||
displayText,
|
||||
payload: {
|
||||
intake_nos: intakeNos,
|
||||
conversation_id: conversationId || undefined,
|
||||
idempotency_key: idempotencyKey,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
|
||||
*/
|
||||
|
||||
@@ -62,6 +62,9 @@ export interface ShippingSendHandlerContext {
|
||||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
||||
isShippingNoticeBatchSubmitting?: () => boolean;
|
||||
hasBlockingNoticeIntake?: () => boolean;
|
||||
hasNoticeIntakeFailures?: () => boolean;
|
||||
getParsedIntakeNos?: () => string[];
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
@@ -187,6 +190,30 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
_content: string,
|
||||
trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return false;
|
||||
const noticeItems = ctx.attachments.value.filter((item) => item.kind === 'shipping_notice');
|
||||
if (noticeItems.length > 0) {
|
||||
if (ctx.hasBlockingNoticeIntake?.()) {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeWaitingForParse'));
|
||||
return true;
|
||||
}
|
||||
if (ctx.hasNoticeIntakeFailures?.()) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeParseFailedHint'));
|
||||
return true;
|
||||
}
|
||||
const intakeNos = ctx.getParsedIntakeNos?.() || [];
|
||||
if (intakeNos.length && (!trimmed || ctx.shippingAutoFlowRequested.value)) {
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
try {
|
||||
await ctx.handleShippingAutoUploadNoticeBatch([]);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
|
||||
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
|
||||
import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
|
||||
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
|
||||
import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
@@ -119,6 +119,8 @@ export interface ShippingUploadHandlerContext {
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
getParsedIntakeNos?: () => string[];
|
||||
clearConsumedNoticeAttachments?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -308,6 +310,61 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
return ok;
|
||||
};
|
||||
|
||||
const runNoticeBatchFromIntakes = async (intakeNos: string[]) => {
|
||||
if (noticeBatchSubmitting) {
|
||||
return true;
|
||||
}
|
||||
noticeBatchSubmitting = true;
|
||||
try {
|
||||
const conversationKey = normalizeConversationId(ctx.conversationId.value);
|
||||
const intakeFingerprint = computeNoticeIntakeNosFingerprint(intakeNos);
|
||||
if (pendingNoticeBatchRetry) {
|
||||
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
|
||||
}
|
||||
if (
|
||||
pendingNoticeBatchRetry
|
||||
&& pendingNoticeBatchRetry.fileFingerprint !== intakeFingerprint
|
||||
) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
if (!pendingNoticeBatchRetry) {
|
||||
pendingNoticeBatchRetry = {
|
||||
conversationId: conversationKey,
|
||||
idempotencyKey: crypto.randomUUID(),
|
||||
fileFingerprint: intakeFingerprint,
|
||||
};
|
||||
} else {
|
||||
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
|
||||
}
|
||||
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
|
||||
const turn = buildShippingCreateBatchFromIntakesTurn(intakeNos, ctx.conversationId.value, idempotencyKey);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'upload_followup',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
syncBatchContextFromTurnMessage(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
if (ok) {
|
||||
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
ctx.clearConsumedNoticeAttachments?.();
|
||||
} else {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
}
|
||||
return ok;
|
||||
} finally {
|
||||
noticeBatchSubmitting = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => {
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
await runReplaceNoticeChatTurn(taskId, file);
|
||||
@@ -344,6 +401,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
|
||||
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
|
||||
const noticeFiles = files.filter(Boolean);
|
||||
const intakeNos = ctx.getParsedIntakeNos?.() || [];
|
||||
if (!noticeFiles.length && intakeNos.length) {
|
||||
await runNoticeBatchFromIntakes(intakeNos);
|
||||
return;
|
||||
}
|
||||
if (!noticeFiles.length) return;
|
||||
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
|
||||
ctx.pendingShippingNoticeTaskId.value = '';
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingNoticeIntakes.ts
|
||||
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
|
||||
* 依赖:file-assets.api、shipping.api、shipping.types。
|
||||
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import {
|
||||
cancelShippingNoticeIntake,
|
||||
createShippingNoticeIntake,
|
||||
getShippingNoticeIntakeStatuses,
|
||||
listActiveShippingNoticeIntakes,
|
||||
retryShippingNoticeIntake,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type {
|
||||
PendingAttachment,
|
||||
ShippingNoticeParseSummary,
|
||||
ShippingNoticePendingAttachment,
|
||||
} from '../types/shipping.types';
|
||||
|
||||
const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
|
||||
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
|
||||
|
||||
function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] {
|
||||
const normalized = String(status || '').trim().toLowerCase();
|
||||
if (normalized === 'parsed') return 'parsed';
|
||||
if (normalized === 'queued' || normalized === 'created') return 'queued';
|
||||
if (normalized === 'parsing') return 'parsing';
|
||||
if (normalized === 'parse_failed') return 'failed';
|
||||
if (normalized === 'consumed') return 'consumed';
|
||||
if (normalized === 'cancelled') return 'cancelled';
|
||||
if (normalized === 'expired') return 'expired';
|
||||
return 'waiting';
|
||||
}
|
||||
|
||||
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
|
||||
return {
|
||||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
kind: 'shipping_notice',
|
||||
file,
|
||||
type: 'document',
|
||||
uploadStatus: 'waiting',
|
||||
parseStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
originalFilename: file.name,
|
||||
fileSize: file.size,
|
||||
};
|
||||
}
|
||||
|
||||
export interface UseShippingNoticeIntakesOptions {
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
|
||||
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pollRound = ref(0);
|
||||
|
||||
const noticeAttachments = computed(() =>
|
||||
options.attachments.value.filter(
|
||||
(item): item is ShippingNoticePendingAttachment => item.kind === 'shipping_notice',
|
||||
),
|
||||
);
|
||||
|
||||
const hasBlockingUploadOrParse = computed(() =>
|
||||
noticeAttachments.value.some((item) =>
|
||||
item.uploadStatus === 'uploading'
|
||||
|| item.uploadStatus === 'waiting'
|
||||
|| ACTIVE_PARSE.has(item.parseStatus)
|
||||
|| item.parseStatus === 'queued'
|
||||
|| item.parseStatus === 'parsing',
|
||||
),
|
||||
);
|
||||
|
||||
const hasParseFailures = computed(() =>
|
||||
noticeAttachments.value.some((item) => item.parseStatus === 'failed'),
|
||||
);
|
||||
|
||||
const allParsedReady = computed(() =>
|
||||
noticeAttachments.value.length > 0
|
||||
&& noticeAttachments.value.every((item) => item.parseStatus === 'parsed'),
|
||||
);
|
||||
|
||||
const stopPolling = () => {
|
||||
if (pollTimer.value) {
|
||||
clearTimeout(pollTimer.value);
|
||||
pollTimer.value = null;
|
||||
}
|
||||
pollRound.value = 0;
|
||||
};
|
||||
|
||||
const schedulePoll = () => {
|
||||
stopPolling();
|
||||
const intakeNos = noticeAttachments.value
|
||||
.map((item) => item.intakeNo)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
if (!intakeNos.length) return;
|
||||
if (intakeNos.every((no) => {
|
||||
const item = noticeAttachments.value.find((entry) => entry.intakeNo === no);
|
||||
return item != null && TERMINAL_PARSE.has(item.parseStatus);
|
||||
})) {
|
||||
return;
|
||||
}
|
||||
const delayMs = pollRound.value >= 8 ? 5000 : 2000;
|
||||
pollTimer.value = setTimeout(() => {
|
||||
void refreshStatuses().finally(() => {
|
||||
pollRound.value += 1;
|
||||
schedulePoll();
|
||||
});
|
||||
}, delayMs);
|
||||
};
|
||||
|
||||
const patchAttachment = (id: string, patch: Partial<ShippingNoticePendingAttachment>) => {
|
||||
options.attachments.value = options.attachments.value.map((item) =>
|
||||
item.id === id && item.kind === 'shipping_notice'
|
||||
? { ...item, ...patch }
|
||||
: item,
|
||||
);
|
||||
};
|
||||
|
||||
const refreshStatuses = async () => {
|
||||
const intakeNos = noticeAttachments.value
|
||||
.map((item) => item.intakeNo)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
if (!intakeNos.length) return;
|
||||
const { items } = await getShippingNoticeIntakeStatuses(intakeNos);
|
||||
for (const remote of items) {
|
||||
const local = noticeAttachments.value.find((item) => item.intakeNo === remote.intake_no);
|
||||
if (!local) continue;
|
||||
patchAttachment(local.id, {
|
||||
parseStatus: mapServerParseStatus(remote.parse_status),
|
||||
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: remote.error_code || undefined,
|
||||
errorMessage: remote.error_message || undefined,
|
||||
expiresAt: remote.expires_at || undefined,
|
||||
assetNo: remote.asset_no || local.assetNo,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const processSingleFile = async (attachment: ShippingNoticePendingAttachment) => {
|
||||
if (!attachment.file) return;
|
||||
patchAttachment(attachment.id, { uploadStatus: 'uploading', uploadProgress: 10 });
|
||||
try {
|
||||
const asset = await uploadFileAsset(attachment.file);
|
||||
patchAttachment(attachment.id, {
|
||||
assetNo: asset.asset_no,
|
||||
uploadStatus: 'uploaded',
|
||||
uploadProgress: 100,
|
||||
parseStatus: 'queued',
|
||||
});
|
||||
const intake = await createShippingNoticeIntake(
|
||||
asset.asset_no,
|
||||
options.conversationId.value,
|
||||
);
|
||||
patchAttachment(attachment.id, {
|
||||
intakeNo: intake.intake_no,
|
||||
parseStatus: mapServerParseStatus(intake.parse_status),
|
||||
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: intake.error_code || undefined,
|
||||
errorMessage: intake.error_message || undefined,
|
||||
expiresAt: intake.expires_at || undefined,
|
||||
});
|
||||
schedulePoll();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : options.t('chat.shippingNoticeUploadFailed');
|
||||
patchAttachment(attachment.id, {
|
||||
uploadStatus: 'failed',
|
||||
parseStatus: 'failed',
|
||||
errorMessage: message,
|
||||
});
|
||||
options.msg.warning(message);
|
||||
}
|
||||
};
|
||||
|
||||
const enqueueNoticeFiles = async (files: File[]) => {
|
||||
for (const file of files) {
|
||||
const attachment = createPendingAttachment(file);
|
||||
options.attachments.value = [...options.attachments.value, attachment];
|
||||
await processSingleFile(attachment);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 移除待建单附件:先从 UI 删除,再取消后端未消费的 intake(含已 parsed)。
|
||||
* @param id - 本地附件临时 ID
|
||||
*/
|
||||
const removeNoticeAttachment = async (id: string) => {
|
||||
const target = noticeAttachments.value.find((item) => item.id === id);
|
||||
options.attachments.value = options.attachments.value.filter((item) => item.id !== id);
|
||||
// parsed 且未建单的 intake 也应取消,否则刷新后会经 listActive 再次出现
|
||||
if (target?.intakeNo && target.parseStatus !== 'consumed') {
|
||||
try {
|
||||
await cancelShippingNoticeIntake(target.intakeNo);
|
||||
} catch {
|
||||
// 移除 UI 优先,取消失败由后端 TTL 兜底
|
||||
}
|
||||
}
|
||||
if (!noticeAttachments.value.length) stopPolling();
|
||||
};
|
||||
|
||||
const retryNoticeAttachment = async (id: string) => {
|
||||
const target = noticeAttachments.value.find((item) => item.id === id);
|
||||
if (!target?.intakeNo) return;
|
||||
patchAttachment(id, { parseStatus: 'queued', errorCode: undefined, errorMessage: undefined });
|
||||
const intake = await retryShippingNoticeIntake(target.intakeNo);
|
||||
patchAttachment(id, {
|
||||
parseStatus: mapServerParseStatus(intake.parse_status),
|
||||
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: intake.error_code || undefined,
|
||||
errorMessage: intake.error_message || undefined,
|
||||
});
|
||||
schedulePoll();
|
||||
};
|
||||
|
||||
const getParsedIntakeNos = () =>
|
||||
noticeAttachments.value
|
||||
.filter((item) => item.parseStatus === 'parsed' && item.intakeNo)
|
||||
.map((item) => String(item.intakeNo));
|
||||
|
||||
const clearConsumedAttachments = () => {
|
||||
options.attachments.value = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
|
||||
stopPolling();
|
||||
};
|
||||
|
||||
const restoreForConversation = async (conversationId?: string | null) => {
|
||||
const { items } = await listActiveShippingNoticeIntakes(conversationId);
|
||||
const restored: ShippingNoticePendingAttachment[] = items
|
||||
.filter((item) => !TERMINAL_PARSE.has(String(item.parse_status || '').toLowerCase()) || item.parse_status === 'parsed')
|
||||
.filter((item) => item.parse_status !== 'consumed')
|
||||
.map((item) => ({
|
||||
id: `restored_${item.intake_no}`,
|
||||
kind: 'shipping_notice',
|
||||
type: 'document',
|
||||
assetNo: item.asset_no || undefined,
|
||||
intakeNo: item.intake_no,
|
||||
uploadStatus: 'uploaded',
|
||||
parseStatus: mapServerParseStatus(item.parse_status),
|
||||
uploadProgress: 100,
|
||||
originalFilename: item.original_filename || item.intake_no,
|
||||
fileSize: Number(item.file_size || 0),
|
||||
parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: item.error_code || undefined,
|
||||
errorMessage: item.error_message || undefined,
|
||||
expiresAt: item.expires_at || undefined,
|
||||
}));
|
||||
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
|
||||
options.attachments.value = [...nonNotice, ...restored];
|
||||
if (restored.some((item) => item.parseStatus === 'queued' || item.parseStatus === 'parsing')) {
|
||||
schedulePoll();
|
||||
}
|
||||
};
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopPolling();
|
||||
});
|
||||
|
||||
return {
|
||||
noticeAttachments,
|
||||
hasBlockingUploadOrParse,
|
||||
hasParseFailures,
|
||||
allParsedReady,
|
||||
enqueueNoticeFiles,
|
||||
removeNoticeAttachment,
|
||||
retryNoticeAttachment,
|
||||
getParsedIntakeNos,
|
||||
clearConsumedAttachments,
|
||||
restoreForConversation,
|
||||
stopPolling,
|
||||
};
|
||||
}
|
||||
|
||||
export type ShippingNoticeIntakesApi = ReturnType<typeof useShippingNoticeIntakes>;
|
||||
@@ -303,6 +303,27 @@ export interface ShippingNoticeUploadResponse {
|
||||
human_options?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingNoticeIntakeResponse {
|
||||
intake_no: string;
|
||||
asset_no?: string | null;
|
||||
conversation_id?: string | null;
|
||||
parse_status: string;
|
||||
parser_version?: string;
|
||||
parse_summary?: Record<string, unknown> | null;
|
||||
warnings?: string[];
|
||||
error_code?: string | null;
|
||||
error_message?: string | null;
|
||||
expires_at?: string | null;
|
||||
consumed_at?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
original_filename?: string;
|
||||
file_size?: number;
|
||||
content_hash?: string;
|
||||
}
|
||||
|
||||
export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
|
||||
|
||||
export interface ShippingDecisionResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
|
||||
@@ -11,10 +11,49 @@ export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' |
|
||||
|
||||
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
/** 待发送附件(本地文件或远程 URL) */
|
||||
export type ShippingNoticeUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
|
||||
export type ShippingNoticeParseStatus =
|
||||
| 'waiting'
|
||||
| 'queued'
|
||||
| 'parsing'
|
||||
| 'parsed'
|
||||
| 'failed'
|
||||
| 'consumed'
|
||||
| 'cancelled'
|
||||
| 'expired';
|
||||
|
||||
export interface ShippingNoticeParseSummary {
|
||||
filename?: string;
|
||||
source_type?: string;
|
||||
text_length?: number;
|
||||
line_count?: number;
|
||||
warnings?: string[];
|
||||
parser_version?: string;
|
||||
}
|
||||
|
||||
export type ShippingNoticePendingAttachment = {
|
||||
id: string;
|
||||
kind: 'shipping_notice';
|
||||
file?: File;
|
||||
type: 'document';
|
||||
assetNo?: string;
|
||||
intakeNo?: string;
|
||||
uploadStatus: ShippingNoticeUploadStatus;
|
||||
parseStatus: ShippingNoticeParseStatus;
|
||||
uploadProgress: number;
|
||||
originalFilename: string;
|
||||
fileSize: number;
|
||||
parseSummary?: ShippingNoticeParseSummary;
|
||||
errorCode?: string;
|
||||
errorMessage?: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
/** 待发送附件(本地文件、远程 URL 或货代通知预解析) */
|
||||
export type PendingAttachment =
|
||||
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
|
||||
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType };
|
||||
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType }
|
||||
| ShippingNoticePendingAttachment;
|
||||
|
||||
export type ChatUploadFileSpec =
|
||||
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
|
||||
|
||||
Reference in new issue
Block a user