File size: 9,508 Bytes
791a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8216787
791a20d
 
 
b310430
791a20d
 
 
 
 
 
 
 
b6cb528
 
 
 
 
 
 
 
791a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8216787
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// main.js

Chart.defaults.color = '#a0aabf';
Chart.defaults.font.family = "'Outfit', sans-serif";

let rawData = [];
let voltageChart = null;
let currentChart = null;

const colors = {
    app1: 'rgba(0, 240, 255, 1)',   // Neon Blue
    app2: 'rgba(189, 0, 255, 1)',   // Purple
    app3: 'rgba(0, 255, 102, 1)',   // Neon Green
    alert: 'rgba(255, 0, 85, 0.8)'  // Red for alert
};

document.addEventListener('DOMContentLoaded', () => {
    loadCSVData();
    document.getElementById('apply-btn').addEventListener('click', updateDashboard);
    document.getElementById('csv-upload').addEventListener('change', handleFileUpload);
});

function loadCSVData() {
    Papa.parse('donnees_appareils (1).csv', {
        download: true,
        header: true,
        dynamicTyping: true,
        skipEmptyLines: true,
        complete: function(results) {
            console.log("CSV Parsed:", results.data);
            rawData = results.data;
            
            // Vérifier si le CSV est valide (s'il contient bien la colonne 'Date')
            // PapaParse peut parfois lire une page d'erreur 404 comme un CSV
            if (rawData.length === 0 || !rawData[0] || !rawData[0].hasOwnProperty('Date')) {
                console.warn("Le fichier CSV est introuvable ou invalide. Affichage de l'upload manuel.");
                document.getElementById('upload-group').style.display = 'block';
                return;
            }
            
            if (rawData.length > 0) {
                // Initialiser les dates min et max
                const dates = rawData.map(d => d.Date).filter(d => d);
                if (dates.length > 0) {
                    const minDate = dates[0];
                    const maxDate = dates[dates.length - 1];
                    
                    document.getElementById('start-date').value = minDate;
                    document.getElementById('end-date').value = maxDate;
                    document.getElementById('start-date').min = minDate;
                    document.getElementById('start-date').max = maxDate;
                    document.getElementById('end-date').min = minDate;
                    document.getElementById('end-date').max = maxDate;
                }
            }

            initializeCharts();
            updateDashboard();
        },
        error: function(err) {
            console.error("Erreur CSV:", err);
            document.getElementById('upload-group').style.display = 'block';
            console.log("Affichage du champ de chargement manuel activé.");
        }
    });
}

function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    Papa.parse(file, {
        header: true,
        dynamicTyping: true,
        skipEmptyLines: true,
        complete: function(results) {
            console.log("Uploaded CSV Parsed:", results.data);
            rawData = results.data;
            
            if (rawData.length > 0) {
                const dates = rawData.map(d => d.Date).filter(d => d);
                if (dates.length > 0) {
                    const minDate = dates[0];
                    const maxDate = dates[dates.length - 1];
                    
                    document.getElementById('start-date').value = minDate;
                    document.getElementById('end-date').value = maxDate;
                    document.getElementById('start-date').min = minDate;
                    document.getElementById('start-date').max = maxDate;
                    document.getElementById('end-date').min = minDate;
                    document.getElementById('end-date').max = maxDate;
                }
            }

            if (!voltageChart || !currentChart) {
                initializeCharts();
            }
            updateDashboard();
            
            document.getElementById('upload-label').innerText = "Fichier chargé avec succès !";
            document.getElementById('upload-label').style.color = "#00ff66";
        },
        error: function(err) {
            console.error("Erreur lors du parse du fichier uploadé:", err);
            alert("Erreur lors de la lecture du fichier uploadé.");
        }
    });
}

function initializeCharts() {
    const ctxVoltage = document.getElementById('voltageChart').getContext('2d');
    const ctxCurrent = document.getElementById('currentChart').getContext('2d');

    const commonOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { position: 'top', labels: { color: '#fff', usePointStyle: true, boxWidth: 8 } },
            tooltip: { mode: 'index', intersect: false, backgroundColor: 'rgba(20, 25, 40, 0.9)', titleColor: '#fff', bodyColor: '#a0aabf', borderColor: 'rgba(255,255,255,0.1)', borderWidth: 1 },
            annotation: { annotations: {} }
        },
        scales: {
            x: { grid: { color: 'rgba(255, 255, 255, 0.05)' }, title: { display: true, text: 'Date / Heure' } },
            y: { grid: { color: 'rgba(255, 255, 255, 0.05)' } }
        },
        elements: { line: { tension: 0.4, borderWidth: 2 }, point: { radius: 0, hitRadius: 10, hoverRadius: 6 } },
        interaction: { mode: 'nearest', axis: 'x', intersect: false }
    };

    voltageChart = new Chart(ctxVoltage, {
        type: 'line', data: { labels: [], datasets: [] },
        options: { ...commonOptions, scales: { ...commonOptions.scales, y: { ...commonOptions.scales.y, title: { display: true, text: 'Tension (V)' } } } }
    });

    currentChart = new Chart(ctxCurrent, {
        type: 'line', data: { labels: [], datasets: [] },
        options: { ...commonOptions, scales: { ...commonOptions.scales, y: { ...commonOptions.scales.y, title: { display: true, text: 'Intensité (A)' } } } }
    });
}

function updateDashboard() {
    if (!rawData || rawData.length === 0) return;

    const startDateStr = document.getElementById('start-date').value;
    const endDateStr = document.getElementById('end-date').value;
    const selectedAppareil = document.querySelector('input[name="appareil"]:checked').value;
    const threshVol = parseFloat(document.getElementById('threshold-voltage').value);
    const threshCur = parseFloat(document.getElementById('threshold-current').value);

    // Filtrer par date
    let filteredData = rawData;
    if (startDateStr && endDateStr) {
        filteredData = rawData.filter(d => {
            if (!d.Date) return false;
            // On peut comparer directement les strings YYYY-MM-DD
            return d.Date >= startDateStr && d.Date <= endDateStr;
        });
    }

    const labels = filteredData.map(d => `${d.Date} ${d.Heure}`);

    // Calcul des sommes et préparation des datasets
    let sumVoltage = 0;
    let sumCurrent = 0;
    
    let voltDatasets = [];
    let currDatasets = [];

    // Fonction d'aide pour ajouter un dataset et cumuler les sommes
    const processAppareil = (appNum, color) => {
        const keyVol = `Tension_Appareil_${appNum}`;
        const keyCur = `Intensite_Appareil_${appNum}`;
        
        const volData = filteredData.map(d => {
            const val = parseFloat(d[keyVol]) || 0;
            sumVoltage += val;
            return val;
        });
        
        const curData = filteredData.map(d => {
            const val = parseFloat(d[keyCur]) || 0;
            sumCurrent += val;
            return val;
        });

        voltDatasets.push(createDataset(`Tension App ${appNum}`, volData, color));
        currDatasets.push(createDataset(`Intensité App ${appNum}`, curData, color));
    };

    if (selectedAppareil === '1' || selectedAppareil === 'all') processAppareil(1, colors.app1);
    if (selectedAppareil === '2' || selectedAppareil === 'all') processAppareil(2, colors.app2);
    if (selectedAppareil === '3' || selectedAppareil === 'all') processAppareil(3, colors.app3);

    // Mise à jour de l'UI des sommes
    document.getElementById('sum-voltage').innerText = sumVoltage.toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' V';
    document.getElementById('sum-current').innerText = sumCurrent.toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' A';

    // Mise à jour des graphiques
    voltageChart.data.labels = labels;
    voltageChart.data.datasets = voltDatasets;
    setAlertAnnotation(voltageChart, threshVol);
    voltageChart.update();

    currentChart.data.labels = labels;
    currentChart.data.datasets = currDatasets;
    setAlertAnnotation(currentChart, threshCur);
    currentChart.update();
}

function createDataset(label, data, color) {
    return {
        label: label,
        data: data,
        borderColor: color,
        backgroundColor: color.replace('1)', '0.1)'),
        fill: true,
        pointBackgroundColor: color,
        pointBorderColor: '#fff',
    };
}

function setAlertAnnotation(chartInstance, thresholdValue) {
    if (!isNaN(thresholdValue) && thresholdValue > 0) {
        chartInstance.options.plugins.annotation.annotations = {
            line1: {
                type: 'line', yMin: thresholdValue, yMax: thresholdValue,
                borderColor: colors.alert, borderWidth: 2, borderDash: [5, 5],
                label: { display: true, content: 'SEUIL ALERTE', position: 'end', backgroundColor: colors.alert, color: '#fff', font: { size: 10, weight: 'bold' } }
            }
        };
    } else {
        chartInstance.options.plugins.annotation.annotations = {};
    }
}