(Feat) Add google
This commit is contained in:
@@ -1,9 +1,13 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
import 'package:pocketbase/pocketbase.dart';
|
||||
|
||||
import '../models/client.dart';
|
||||
import '../models/mouvement.dart';
|
||||
import '../models/recompense.dart';
|
||||
import '../supabase_config.dart';
|
||||
import '../pocketbase_config.dart';
|
||||
|
||||
/// Données du client connecté (son compte, ses points, son historique) + le
|
||||
/// contexte magasin (nom, récompenses proposées). Source de vérité côté client.
|
||||
@@ -34,47 +38,46 @@ class SessionClient extends ChangeNotifier {
|
||||
_erreur = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final uid = supabase.auth.currentUser?.id;
|
||||
final uid = pb.authStore.record?.id;
|
||||
if (uid == null) {
|
||||
_monClient = null;
|
||||
return;
|
||||
}
|
||||
|
||||
final row = await supabase
|
||||
.from('clients')
|
||||
.select()
|
||||
.eq('user_id', uid)
|
||||
.maybeSingle();
|
||||
_monClient = row == null ? null : Client.fromMap(row);
|
||||
|
||||
// Contexte magasin (lisible par tout compte connecté).
|
||||
final reglages = await supabase
|
||||
.from('reglages')
|
||||
.select('euros_par_point, nom_magasin')
|
||||
.eq('id', 1)
|
||||
.maybeSingle();
|
||||
if (reglages != null) {
|
||||
_eurosParPoint =
|
||||
(reglages['euros_par_point'] as num?)?.toDouble() ?? 0;
|
||||
_nomMagasin = (reglages['nom_magasin'] as String?) ?? '';
|
||||
// Fiche fidélité du compte (une par utilisateur). Absente → profil à créer.
|
||||
try {
|
||||
final row = await pb
|
||||
.collection('clients')
|
||||
.getFirstListItem('user = "$uid"');
|
||||
_monClient = Client.fromMap(row.toJson());
|
||||
} on ClientException catch (e) {
|
||||
if (e.statusCode == 404) {
|
||||
_monClient = null;
|
||||
} else {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
final recs = await supabase
|
||||
.from('recompenses')
|
||||
.select()
|
||||
.eq('actif', true)
|
||||
.order('cout_points');
|
||||
_recompenses =
|
||||
(recs as List).map((e) => Recompense.fromMap(e)).toList();
|
||||
// Contexte magasin (lisible par tout compte connecté) : ligne unique.
|
||||
final reglages = await pb.collection('reglages').getList(perPage: 1);
|
||||
if (reglages.items.isNotEmpty) {
|
||||
final r = reglages.items.first;
|
||||
_eurosParPoint = (r.data['euros_par_point'] as num?)?.toDouble() ?? 0;
|
||||
_nomMagasin = (r.data['nom_magasin'] as String?) ?? '';
|
||||
}
|
||||
|
||||
final recs = await pb.collection('recompenses').getFullList(
|
||||
filter: 'actif = true',
|
||||
sort: 'cout_points',
|
||||
);
|
||||
_recompenses = recs.map((e) => Recompense.fromMap(e.toJson())).toList();
|
||||
|
||||
if (_monClient != null) {
|
||||
final mvts = await supabase
|
||||
.from('mouvements')
|
||||
.select()
|
||||
.eq('client_id', _monClient!.id)
|
||||
.order('created_at', ascending: false);
|
||||
_mouvements =
|
||||
(mvts as List).map((e) => Mouvement.fromMap(e)).toList();
|
||||
final mvts = await pb.collection('mouvements').getFullList(
|
||||
filter: 'client = "${_monClient!.id}"',
|
||||
sort: '-created',
|
||||
);
|
||||
_mouvements = mvts.map((e) => Mouvement.fromMap(e.toJson())).toList();
|
||||
} else {
|
||||
_mouvements = [];
|
||||
}
|
||||
@@ -86,26 +89,72 @@ class SessionClient extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée le profil fidélité du compte connecté (nom + téléphone). Le code et le
|
||||
/// QR sont générés côté base. Utilisé à l'inscription / finalisation de profil.
|
||||
/// Crée le profil fidélité du compte connecté (nom + téléphone). Le code de
|
||||
/// fidélité (encodé dans le QR) est généré ici, côté client, car le backend
|
||||
/// n'en fournit pas. Utilisé à l'inscription / finalisation de profil.
|
||||
Future<void> creerProfil({
|
||||
required String nom,
|
||||
String? prenom,
|
||||
String? telephone,
|
||||
}) async {
|
||||
final uid = supabase.auth.currentUser?.id;
|
||||
final uid = pb.authStore.record?.id;
|
||||
if (uid == null) throw Exception('Non connecté');
|
||||
String? ouNull(String? v) =>
|
||||
(v == null || v.trim().isEmpty) ? null : v.trim();
|
||||
await supabase.from('clients').insert({
|
||||
'user_id': uid,
|
||||
await pb.collection('clients').create(body: {
|
||||
'user': uid,
|
||||
'code': _genererCode(),
|
||||
'nom': nom.trim(),
|
||||
'prenom': ouNull(prenom),
|
||||
'telephone': ouNull(telephone),
|
||||
if (ouNull(prenom) != null) 'prenom': ouNull(prenom),
|
||||
if (ouNull(telephone) != null) 'telephone': ouNull(telephone),
|
||||
});
|
||||
await charger();
|
||||
}
|
||||
|
||||
bool _googleInit = false;
|
||||
|
||||
/// Connexion / inscription native avec Google (sélecteur de compte in-app).
|
||||
///
|
||||
/// Récupère l'ID token Google via Credential Manager, l'envoie au hook
|
||||
/// PocketBase `/api/google-native-auth` qui vérifie le token et renvoie une
|
||||
/// session PocketBase. Un nouveau compte n'a pas encore de fiche fidélité →
|
||||
/// l'AuthGate affichera l'écran « Finaliser mon profil ».
|
||||
Future<void> connexionGoogleNative() async {
|
||||
if (!_googleInit) {
|
||||
await GoogleSignIn.instance
|
||||
.initialize(serverClientId: googleWebClientId);
|
||||
_googleInit = true;
|
||||
}
|
||||
|
||||
final account = await GoogleSignIn.instance.authenticate();
|
||||
final idToken = account.authentication.idToken;
|
||||
if (idToken == null) {
|
||||
throw Exception('Jeton Google introuvable');
|
||||
}
|
||||
|
||||
final reponse = await pb.send(
|
||||
'/api/google-native-auth',
|
||||
method: 'POST',
|
||||
body: {'idToken': idToken},
|
||||
);
|
||||
final map = reponse as Map<String, dynamic>;
|
||||
pb.authStore.save(
|
||||
map['token'] as String,
|
||||
RecordModel.fromJson(map['record'] as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
|
||||
/// Génère un code de fidélité lisible, ex. « FID-3F9K2A ».
|
||||
static String _genererCode() {
|
||||
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // sans I,O,0,1
|
||||
final rnd = Random.secure();
|
||||
final suffixe = List.generate(
|
||||
6,
|
||||
(_) => alphabet[rnd.nextInt(alphabet.length)],
|
||||
).join();
|
||||
return 'FID-$suffixe';
|
||||
}
|
||||
|
||||
void vider() {
|
||||
_monClient = null;
|
||||
_mouvements = [];
|
||||
|
||||
Reference in New Issue
Block a user