Files
mariani_mobile/utils/documentUtils.tsx
leonardo 44d021891f feat: Add document download and upload. Add NFC support and enhance attendance and permits views
- Improved error message handling in LoginScreen for invalid credentials.
- Added new images: mariani-icon.png and mariani-splash.png.
- Updated AddDocumentModal to handle file extensions and improve UI.
- Enhanced CalendarWidget to support month change callbacks.
- Introduced NfcScanModal for NFC tag scanning with animations.
- Revamped QrScanModal to utilize camera for QR code scanning.
- Removed mock data from data.ts and streamlined Office data.
- Updated package dependencies for expo-camera and react-native-nfc-manager.
- Added utility function to parse seconds to time format.
- Refactored document upload logic to use FormData for server uploads.
2026-01-19 18:10:31 +01:00

110 lines
3.6 KiB
TypeScript

import api from '@/utils/api';
import { Directory, File, Paths } from 'expo-file-system';
import * as FileSystem from 'expo-file-system/legacy';
import { StorageAccessFramework } from 'expo-file-system/legacy';
import * as Sharing from 'expo-sharing';
import * as Linking from 'expo-linking';
import { Platform } from 'react-native';
/**
* Gestisce l'upload di un documento verso il server usando FormData
* @param file File da caricare (deve avere almeno la proprietà 'uri')
* @param siteId ID del sito a cui associare il documento (null per registro generale)
* @param customTitle Titolo personalizzato per il documento (opzionale)
*/
export const uploadDocument = async (
file: any,
siteId: number | null,
customTitle?: string
): Promise<void> => {
if (!file || !file.uri) {
throw new Error("File non valido per l'upload.");
}
try {
const formData = new FormData();
formData.append('file', {
uri: file.uri,
name: customTitle || file.name,
type: file.mimeType
} as any);
if (siteId !== null) {
formData.append('siteId', siteId.toString());
}
if (customTitle) {
formData.append('customTitle', customTitle.trim());
}
const response = await api.post('/attachment/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
}
});
console.log("Risposta server:", response.data);
if (response.data?.status === 'error') {
throw new Error(response.data.message || "Errore sconosciuto dal server");
}
} catch (error: any) {
console.error("Errore durante l'upload del documento:", error);
if (error.response) {
const serverMessage = error.response.data?.message || error.message;
throw new Error(`Errore Server (${error.response.status}): ${serverMessage}`);
} else if (error.request) {
throw new Error("Il server non risponde. Controlla la connessione.");
} else {
throw error;
}
}
};
/**
* Scarica un documento e offre di aprirlo/condividerlo (expo-sharing)
* @param attachmentId ID o URL relativo del documento
* @param fileName Nome con cui salvare il file
* @param fileUrl URL completo del file da scaricare
*/
export const downloadAndShareDocument = async (
mimetype: string,
fileName: string,
fileUrl: string
): Promise<void> => {
try {
// TODO: Gestire meglio il download (attualmente si basa su expo-sharing)
if (!fileUrl || !fileName) {
throw new Error("Parametri mancanti per il download del documento.");
}
const destination = new Directory(Paths.cache, 'documents');
destination.exists ? destination.delete() : null;
destination.create({ overwrite: true });
const tmpFile = await File.downloadFileAsync(fileUrl, destination);
console.log("File temporaneo scaricato in:", tmpFile.uri);
const outFile = new File(destination, fileName);
await tmpFile.move(outFile);
console.log("File spostato in:", outFile.uri);
console.log("File type:", mimetype);
if (await Sharing.isAvailableAsync()) {
await Sharing.shareAsync(outFile.uri, {
mimeType: mimetype,
dialogTitle: `Scarica ${fileName}`,
UTI: 'public.item'
});
} else {
throw new Error("Condivisione non supportata su questo dispositivo.");
}
} catch (error) {
console.error("Download Error:", error);
throw error;
}
};