feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载

This commit is contained in:
hugo committed 2026-07-14 09:14:44 +08:00
1 parent 143e054d86
commit 729546a7b7
52 files changed
+3420 -34

No files matched your search

@@ -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>;