openOfficeFile.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { getFilePathApi } from '@/core/api/sys/login';
  2. import { resolveDownloadErrorMessage } from '@/core/utils/file/download';
  3. import { isDesktopDialogAvailable, openLocalPath } from '@/core/utils/desktop/openFile';
  4. const normalizeOfficeFileKey = (value: string) =>
  5. value
  6. .trim()
  7. .toLowerCase()
  8. .replace(/[_\-\s]/g, '');
  9. const OFFICE_FILE_ID_KEY_SET = new Set(['fileid']);
  10. export const normalizeOfficeFileId = (value: unknown) => {
  11. const text = String(value ?? '').trim();
  12. if (!text || text === '-' || text === 'null' || text === 'undefined') return undefined;
  13. return text;
  14. };
  15. const readOfficeFileIdFromRecord = (record: Record<string, any>) => {
  16. for (const [key, value] of Object.entries(record)) {
  17. if (OFFICE_FILE_ID_KEY_SET.has(normalizeOfficeFileKey(key))) {
  18. const fileId = normalizeOfficeFileId(value);
  19. if (fileId) return fileId;
  20. }
  21. }
  22. return undefined;
  23. };
  24. export const resolveOfficeFileId = (source: unknown): string | undefined => {
  25. if (!source || typeof source !== 'object') return undefined;
  26. const queue: Array<Record<string, any>> = [source as Record<string, any>];
  27. const visited = new Set<Record<string, any>>();
  28. while (queue.length) {
  29. const current = queue.shift();
  30. if (!current || visited.has(current)) continue;
  31. visited.add(current);
  32. const directFileId = readOfficeFileIdFromRecord(current);
  33. if (directFileId) return directFileId;
  34. ['raw', 'record', 'source', 'data'].forEach((key) => {
  35. const nested = current[key];
  36. if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
  37. queue.push(nested as Record<string, any>);
  38. }
  39. });
  40. }
  41. return undefined;
  42. };
  43. /**
  44. * 按文件ID打开文件:后端查库解析出本机绝对路径,再交给系统默认关联程序打开。
  45. *
  46. * <p>只传文件ID,服务端路径由后端定位(工作表行没有 filePath 时后端自动回退到所属文件根)。
  47. * 非桌面端直接抛「请在桌面客户端内打开」,不做浏览器另存回退。
  48. *
  49. * @param fileId 文件/工作表ID(file_info.id)
  50. */
  51. export const openOfficeFileById = async (fileId: string | number) => {
  52. if (!isDesktopDialogAvailable()) {
  53. throw new Error('当前环境不可用:请在桌面客户端内打开');
  54. }
  55. try {
  56. const { path } = await getFilePathApi(fileId);
  57. await openLocalPath(path);
  58. } catch (error: any) {
  59. // 后端以 JSON 报错时(如文件不存在),把原始 message 提取出来
  60. throw new Error(await resolveDownloadErrorMessage(error, '文件打开失败'));
  61. }
  62. };
  63. export const getOpenOfficeFileErrorMessage = (error: any, fallback = '文件打开失败') =>
  64. error?.response?.data?.message || error?.message || fallback;