Newer
Older
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
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:googleapis/sheets/v4.dart' as sheets;
class GoogleSheetsApi {
// 1. Mettez l'ID de votre feuille ici (copié depuis l'URL)
static const _spreadsheetId = '1tbWnNSx3J-OAM7rrAxU_YLM97z2zMFtV055nS66Ig3c';
// 2. Définir les permissions
static const _scopes = [sheets.SheetsApi.spreadsheetsScope];
// 3. Fonction pour s'authentifier (utilise le fichier JSON)
Future<auth.AutoRefreshingAuthClient?> _getAuthClient() async {
try {
final jsonString = await rootBundle.loadString('assets/credentials.json');
final credentialsJson = json.decode(jsonString);
final credentials = auth.ServiceAccountCredentials.fromJson(credentialsJson);
final client = await auth.clientViaServiceAccount(credentials, _scopes);
return client;
} catch (e) {
print('Erreur lors de l\'authentification : $e');
return null;
}
}
// 4. Fonction pour ajouter une nouvelle ligne
Future<bool> appendData(List<dynamic> rowData) async {
final client = await _getAuthClient();
if (client == null) {
print("Erreur d'authentification");
return false;
}
final api = sheets.SheetsApi(client);
// Le nom de votre feuille (ex: 'Feuille1')
final String range = 'données etudiants';
var values = sheets.ValueRange.fromJson({
'values': [ rowData ] // Les données à ajouter
});
try {
await api.spreadsheets.values.append(
values,
_spreadsheetId,
range,
valueInputOption: 'USER_ENTERED'
);
print('Données ajoutées !');
client.close();
return true;
} catch (e) {
print('Erreur lors de l\'ajout des données : $e');
client.close();
return false;
}
}
// 5. Fonction pour lire des données (exemple)
Future<List<List<dynamic>>?> readData() async {
final client = await _getAuthClient();
if (client == null) {
print("Erreur d'authentification");
return null;
}
final api = sheets.SheetsApi(client);
// Exemple : lire la plage A1 à C10 de 'Feuille1'
final String range = 'données etudiants!A1:C10';
try {
final result = await api.spreadsheets.values.get(
_spreadsheetId,
range,
);
print('Données lues : ${result.values}');
client.close();
return result.values;
} catch (e) {
print('Erreur lors de la lecture des données : $e');
client.close();
return null;
}
}
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
// 6. NOUVELLE FONCTION : Lire toutes les valeurs d'une colonne
Future<List<String>> readColumn(String columnName) async {
final client = await _getAuthClient();
if (client == null) {
print("Erreur d'authentification");
return [];
}
final api = sheets.SheetsApi(client);
// IMPORTANT : Mettez le bon nom de votre feuille ici (ex: 'Feuil1')
// Le range 'Feuil1!A:A' signifie "Toute la colonne A de la feuille 'Feuil1'"
final String range = 'données etudiants!$columnName:$columnName';
try {
final result = await api.spreadsheets.values.get(
_spreadsheetId,
range,
);
client.close();
if (result.values == null) {
return []; // La colonne est vide
}
// Convertir la List<List<dynamic>> en une simple List<String>
List<String> columnData = [];
for (var row in result.values!) {
if (row.isNotEmpty) {
columnData.add(row[0].toString());
}
}
return columnData;
} catch (e) {
print('Erreur lors de la lecture de la colonne : $e');
client.close();
return [];
}
}
// 7. FONCTION MODIFIÉE : Trouver un nom par l'UID (stocké en Colonne D)
Future<String?> findStudentNameByNfcUid(String uidToCheck) async {
final client = await _getAuthClient();
if (client == null) {
print("Erreur d'authentification");
return null;
}
final api = sheets.SheetsApi(client);
// On lit les colonnes Nom (C) et Mac (D).
final String range = 'données etudiants!C:D'; // <-- MODIFICATION
try {
final result = await api.spreadsheets.values.get(
_spreadsheetId,
range,
);
client.close();
if (result.values == null) {
print("La feuille est vide ou n'a pas pu être lue.");
return null;
}
final uidUpper = uidToCheck.toUpperCase();
// Parcourt chaque ligne lue.
// row[0] = Nom (Colonne C)
// row[1] = Mac (Colonne D) <-- MODIFICATION
for (int i = 0; i < result.values!.length; i++) {
final row = result.values![i];
// row[0] = Nom, row[1] = Mac
if (row.length == 2 && row[1] != null) {
String nfcUidFromSheet = row[1].toString().toUpperCase();
if (nfcUidFromSheet == uidUpper) {
// ⚡ Mettre à jour la date de scan
await updateLastScan(i + 2); // +2 car on a sauté l'entête et l'index commence à 0
return row[0].toString();
}
}
}
print("UID non trouvé dans la feuille.");
return null;
} catch (e) {
print('Erreur lors de la recherche de l\'UID : $e');
client.close();
return null;
}
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
}
// 8. Récupérer la liste de présence par date (pour le PDF)
Future<List<Map<String, String>>> getPresenceByDate(String date) async {
final client = await _getAuthClient();
if (client == null) return [];
final api = sheets.SheetsApi(client);
final String range = 'données etudiants!A:G';
final result = await api.spreadsheets.values.get(_spreadsheetId, range);
client.close();
if (result.values == null) return [];
List<Map<String, String>> resultList = [];
for (int i = 1; i < result.values!.length; i++) {
final row = result.values![i];
final dateAjout = row.length > 6 ? row[6]?.toString() ?? "" : "";
if (dateAjout.startsWith(date)) {
resultList.add({
'N° Etudiant': row.length > 0 ? row[0]?.toString() ?? '' : '',
'Prénom': row.length > 1 ? row[1]?.toString() ?? '' : '',
'Nom': row.length > 2 ? row[2]?.toString() ?? '' : '',
'Mac NFC': row.length > 3 ? row[3]?.toString() ?? '' : '',
'QR': row.length > 4 ? row[4]?.toString() ?? '' : '',
'date_ajout': dateAjout,
});
}
}
return resultList;
}
Future<void> updateLastScan(int rowIndex) async {
final client = await _getAuthClient();
if (client == null) return;
final api = sheets.SheetsApi(client);
final now = DateTime.now().toIso8601String();
final range = 'données etudiants!F$rowIndex'; // colonne F = date_ajout
final values = sheets.ValueRange.fromJson({
"values": [
[now]
]
});
await api.spreadsheets.values.update(
values,
_spreadsheetId,
range,
valueInputOption: "USER_ENTERED",
);
client.close();
}
}