feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载
This commit is contained in:
1 parent
143e054d86
commit
729546a7b7
52 files changed
+3420
-34
No files matched your search
@@ -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>;
|
||||
Reference in new issue
Block a user