refacto: Exporting is now in CSV the values + auto gestion of perfusion

This commit is contained in:
gauvainboiche
2026-08-02 14:44:03 +02:00
parent c0843ed083
commit abe44eca1d
9 changed files with 646 additions and 217 deletions
+118
View File
@@ -0,0 +1,118 @@
import { t } from './i18n.js';
/**
* Formate la date au format strict : YYYY_DD_MM_HH_MM_SS
*/
function getFormattedTimestamp() {
const now = new Date();
const YYYY = now.getFullYear();
const DD = String(now.getDate()).padStart(2, '0');
const MM = String(now.getMonth() + 1).padStart(2, '0');
const HH = String(now.getHours()).padStart(2, '0');
const Min = String(now.getMinutes()).padStart(2, '0');
const SS = String(now.getSeconds()).padStart(2, '0');
return `${YYYY}_${DD}_${MM}_${HH}_${Min}_${SS}`;
}
/**
* Transforme le nom saisi en slug propre (ex: "DUPONT Jean" -> "dupont_jean")
*/
function slugify(text) {
if (!text) return '';
return text
.toString()
.trim()
.toLowerCase()
.normalize("NFD").replace(/[\u0300-\u036f]/g, "") // Enlève les accents
.replace(/[^a-z0-9]+/g, "_") // Remplace les caractères spéciaux par _
.replace(/^_+|_+$/g, ""); // Nettoie les _ aux bornes
}
/**
* Exporte les données de simulation au format CSV
*/
export async function exportSimulationToCSV(simulationData, patientInfo) {
if (!simulationData || !simulationData.timeline) return;
// \uFEFF (BOM UTF-8) pour qu'Excel ouvre le CSV directement avec les accents
let csvContent = "\uFEFF";
// Métadonnées du rapport
csvContent += `${t('csv.title')}\n`;
if (patientInfo.name) {
csvContent += `${t('patient.name_label') || 'Patient'}:,${patientInfo.name}\n`;
}
csvContent += `${t('csv.weight')}:,${patientInfo.weight}\n`;
csvContent += `${t('csv.unit')}:,${patientInfo.infusionUnit}\n\n`;
// En-têtes du tableau selon la langue active
const headers = [
t('csv.col_time'),
t('csv.col_bolus'),
t('csv.col_infusion'),
t('csv.col_domino'),
t('csv.col_clements'),
t('csv.col_kamp')
];
csvContent += headers.join(",") + "\n";
// Lignes de données (0 à 300 min)
simulationData.timeline.forEach((item, index) => {
const dominoCp = (simulationData.domino && simulationData.domino[index]) ? Math.round(simulationData.domino[index].cp) : "N/A";
const clementsCp = (simulationData.clements && simulationData.clements[index]) ? Math.round(simulationData.clements[index].cp) : "N/A";
const kampCp = (simulationData.kamp && simulationData.kamp[index]) ? Math.round(simulationData.kamp[index].cp) : "N/A";
const row = [
item.time,
item.bolusMg ? item.bolusMg : "0",
item.infusionRate !== null && item.infusionRate !== undefined ? item.infusionRate : "0",
dominoCp,
clementsCp,
kampCp
];
csvContent += row.join(",") + "\n";
});
// Construction du nom de fichier : ketapk_YYYY_DD_MM_HH_MM_SS.csv ou ketapk_nom_prenom_YYYY_DD_MM_HH_MM_SS.csv
const timestamp = getFormattedTimestamp();
const slugName = slugify(patientInfo.name);
const fileName = slugName
? `ketapk_${slugName}_${timestamp}.csv`
: `ketapk_${timestamp}.csv`;
// 1. Solution principale : API Native File System (Parfait sous WebView2 / Tauri Desktop)
if (window.showSaveFilePicker) {
try {
const handle = await window.showSaveFilePicker({
suggestedName: fileName,
types: [{
description: 'Fichier CSV',
accept: { 'text/csv': ['.csv'] }
}]
});
const writable = await handle.createWritable();
await writable.write(csvContent);
await writable.close();
return;
} catch (err) {
if (err.name === 'AbortError') return; // Annulation utilisateur
console.warn('Fallback vers Data URI suite à lerreur native :', err);
}
}
// 2. Fallback Data URI (Compatibilité web directe sans passer par Blob)
const encodedUri = "data:text/csv;charset=utf-8," + encodeURIComponent(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", fileName);
link.style.display = "none";
document.body.appendChild(link);
link.click();
setTimeout(() => {
if (document.body.contains(link)) {
document.body.removeChild(link);
}
}, 200);
}