| 1 |
import { ref } from 'vue' |
| 2 |
import { useApiClient } from '@/composables/useApiClient' |
| 3 |
import { useLabels } from '@/composables/useLabels' |
| 4 |
|
| 5 |
export function useFormImport() { |
| 6 |
const { getLabel } = useLabels() |
| 7 |
const { request } = useApiClient() |
| 8 |
const isImporting = ref(false) |
| 9 |
const importError = ref<string | null>(null) |
| 10 |
|
| 11 |
/** |
| 12 |
* Import forms from JSON file |
| 13 |
* @param file - JSON file containing form data |
| 14 |
* @returns Array of imported forms with { id, name } or false on error |
| 15 |
*/ |
| 16 |
const importForms = async (file: File): Promise<Array<{ id: number; name: string }> | false> => { |
| 17 |
isImporting.value = true |
| 18 |
importError.value = null |
| 19 |
|
| 20 |
try { |
| 21 |
// Read file content |
| 22 |
const fileContent = await readFileAsText(file) |
| 23 |
const importData = JSON.parse(fileContent) |
| 24 |
|
| 25 |
// Validate import data structure |
| 26 |
if (!importData.forms || !Array.isArray(importData.forms)) { |
| 27 |
importError.value = getLabel('invalid_import_file') |
| 28 |
return false |
| 29 |
} |
| 30 |
|
| 31 |
// Send import request |
| 32 |
const { data, error } = await request('forms/import', { |
| 33 |
method: 'POST', |
| 34 |
data: { |
| 35 |
importData, |
| 36 |
}, |
| 37 |
}) |
| 38 |
|
| 39 |
if (error) { |
| 40 |
importError.value = error || getLabel('failed_to_import_forms') |
| 41 |
return false |
| 42 |
} |
| 43 |
|
| 44 |
// API returns: { message: "OK", data: { success: true, data: [...], message: "..." } } |
| 45 |
const response = data?.data |
| 46 |
|
| 47 |
if (response && response.success) { |
| 48 |
// Return the imported forms data |
| 49 |
return response.data || false |
| 50 |
} else { |
| 51 |
importError.value = response?.message || getLabel('failed_to_import_forms') |
| 52 |
return false |
| 53 |
} |
| 54 |
} catch (error) { |
| 55 |
console.error('Import error:', error) |
| 56 |
if (error instanceof SyntaxError) { |
| 57 |
importError.value = getLabel('invalid_import_file') |
| 58 |
} else { |
| 59 |
importError.value = getLabel('failed_to_import_forms') |
| 60 |
} |
| 61 |
return false |
| 62 |
} finally { |
| 63 |
isImporting.value = false |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Read file as text |
| 69 |
*/ |
| 70 |
const readFileAsText = (file: File): Promise<string> => { |
| 71 |
return new Promise((resolve, reject) => { |
| 72 |
const reader = new FileReader() |
| 73 |
reader.onload = (e) => { |
| 74 |
if (e.target?.result) { |
| 75 |
resolve(e.target.result as string) |
| 76 |
} else { |
| 77 |
reject(new Error('Failed to read file')) |
| 78 |
} |
| 79 |
} |
| 80 |
reader.onerror = () => reject(new Error('Failed to read file')) |
| 81 |
reader.readAsText(file) |
| 82 |
}) |
| 83 |
} |
| 84 |
|
| 85 |
return { |
| 86 |
isImporting, |
| 87 |
importError, |
| 88 |
importForms, |
| 89 |
} |
| 90 |
} |
| 91 |
|