(Feat) Migration PocketBase
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../config.dart';
|
||||
import '../models/client.dart';
|
||||
import '../models/mouvement.dart';
|
||||
import '../models/recompense.dart';
|
||||
import '../supabase_config.dart';
|
||||
import '../pocketbase_config.dart';
|
||||
import '../utils/format.dart';
|
||||
import 'reglages.dart';
|
||||
|
||||
@@ -15,9 +18,10 @@ class SoldeInsuffisant implements Exception {
|
||||
String toString() => 'Solde insuffisant (${points(manquant)} manquants)';
|
||||
}
|
||||
|
||||
/// Source de vérité des clients (côté staff), adossée à Supabase.
|
||||
/// Le solde de points est tenu à jour côté base (trigger) à chaque mouvement ;
|
||||
/// on reflète le delta en mémoire pour un affichage immédiat.
|
||||
/// Source de vérité des clients (côté staff), adossée à PocketBase.
|
||||
/// Comme PocketBase n'a pas de trigger, le solde de points est maintenu par
|
||||
/// l'app : à chaque mouvement, on crée l'enregistrement ET on met à jour le
|
||||
/// solde du client. Seul le staff (la tablette) écrit → pas de concurrence.
|
||||
class ClientRepository extends ChangeNotifier {
|
||||
ClientRepository._();
|
||||
static final ClientRepository instance = ClientRepository._();
|
||||
@@ -25,11 +29,13 @@ class ClientRepository extends ChangeNotifier {
|
||||
final List<Client> _clients = [];
|
||||
bool _charge = false;
|
||||
bool _enCours = false;
|
||||
bool _abonne = false;
|
||||
String? _erreur;
|
||||
|
||||
List<Client> get clients => List.unmodifiable(_clients);
|
||||
bool get charge => _charge;
|
||||
bool get enCours => _enCours;
|
||||
bool get tempsReelActif => _abonne;
|
||||
String? get erreur => _erreur;
|
||||
|
||||
Future<void> charger() async {
|
||||
@@ -37,11 +43,12 @@ class ClientRepository extends ChangeNotifier {
|
||||
_erreur = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final rows = await supabase.from('clients').select().order('nom');
|
||||
final rows = await pb.collection('clients').getFullList(sort: 'nom');
|
||||
_clients
|
||||
..clear()
|
||||
..addAll((rows as List).map((e) => Client.fromMap(e)));
|
||||
..addAll(rows.map((r) => Client.fromMap(r.toJson())));
|
||||
_charge = true;
|
||||
await _sabonner();
|
||||
} catch (e) {
|
||||
_erreur = e.toString();
|
||||
} finally {
|
||||
@@ -50,6 +57,34 @@ class ClientRepository extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// Abonnement temps réel : la liste et les soldes se synchronisent en direct
|
||||
/// entre tous les appareils (autre tablette, app client…).
|
||||
Future<void> _sabonner() async {
|
||||
if (_abonne) return;
|
||||
_abonne = true;
|
||||
try {
|
||||
await pb.collection('clients').subscribe('*', (e) {
|
||||
final rec = e.record;
|
||||
if (rec == null) return;
|
||||
if (e.action == 'delete') {
|
||||
_clients.removeWhere((x) => x.id == rec.id);
|
||||
} else {
|
||||
final c = Client.fromMap(rec.toJson());
|
||||
final i = _clients.indexWhere((x) => x.id == c.id);
|
||||
if (i == -1) {
|
||||
_clients.add(c);
|
||||
} else {
|
||||
_clients[i] = c;
|
||||
}
|
||||
_trier();
|
||||
}
|
||||
notifyListeners();
|
||||
});
|
||||
} catch (_) {
|
||||
_abonne = false; // on réessaiera au prochain chargement
|
||||
}
|
||||
}
|
||||
|
||||
Client? parCode(String code) {
|
||||
for (final c in _clients) {
|
||||
if (c.code == code) return c;
|
||||
@@ -64,7 +99,6 @@ class ClientRepository extends ChangeNotifier {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Filtre par nom, téléphone ou code (recherche insensible à la casse).
|
||||
List<Client> rechercher(String requete) {
|
||||
final q = requete.trim().toLowerCase();
|
||||
if (q.isEmpty) return clients;
|
||||
@@ -77,36 +111,41 @@ class ClientRepository extends ChangeNotifier {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Crée un client « au comptoir » (sans compte de connexion). Le code unique
|
||||
/// et le QR sont générés côté base.
|
||||
/// Crée un client « au comptoir » avec un code unique généré par l'app.
|
||||
Future<Client> creer({
|
||||
required String nom,
|
||||
String? prenom,
|
||||
String? telephone,
|
||||
}) async {
|
||||
final row = await supabase
|
||||
.from('clients')
|
||||
.insert({
|
||||
// Quelques essais en cas de collision (peu probable) sur le code.
|
||||
Object? derniereErreur;
|
||||
for (var essai = 0; essai < 8; essai++) {
|
||||
try {
|
||||
final rec = await pb.collection('clients').create(body: {
|
||||
'code': _genererCode(),
|
||||
'nom': nom.trim(),
|
||||
'prenom': _ouNull(prenom),
|
||||
'telephone': _ouNull(telephone),
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
final cree = Client.fromMap(row);
|
||||
_clients.add(cree);
|
||||
_trier();
|
||||
notifyListeners();
|
||||
return cree;
|
||||
'points': 0,
|
||||
});
|
||||
final cree = Client.fromMap(rec.toJson());
|
||||
_clients.add(cree);
|
||||
_trier();
|
||||
notifyListeners();
|
||||
return cree;
|
||||
} catch (e) {
|
||||
derniereErreur = e; // probable conflit d'index unique → on régénère
|
||||
}
|
||||
}
|
||||
throw Exception('Création du client impossible : $derniereErreur');
|
||||
}
|
||||
|
||||
/// Modifie nom / prénom / téléphone (pas le solde : il évolue via facture).
|
||||
Future<void> modifier(Client c) async {
|
||||
await supabase.from('clients').update({
|
||||
await pb.collection('clients').update(c.id, body: {
|
||||
'nom': c.nom.trim(),
|
||||
'prenom': _ouNull(c.prenom),
|
||||
'telephone': _ouNull(c.telephone),
|
||||
}).eq('id', c.id);
|
||||
});
|
||||
final i = _clients.indexWhere((e) => e.id == c.id);
|
||||
if (i != -1) {
|
||||
_clients[i] =
|
||||
@@ -116,35 +155,29 @@ class ClientRepository extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Renvoie null si la chaîne est vide/espaces, sinon la valeur nettoyée.
|
||||
String? _ouNull(String? v) =>
|
||||
(v == null || v.trim().isEmpty) ? null : v.trim();
|
||||
|
||||
Future<void> supprimer(String id) async {
|
||||
await supabase.from('clients').delete().eq('id', id);
|
||||
await pb.collection('clients').delete(id);
|
||||
_clients.removeWhere((e) => e.id == id);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Ajoute une facture : crédite les points correspondant au montant dépensé.
|
||||
/// Retourne le nombre de points gagnés.
|
||||
Future<double> ajouterFacture({
|
||||
required String clientId,
|
||||
required double montantEuros,
|
||||
}) async {
|
||||
final gagnes = Reglages.instance.pointsPour(montantEuros);
|
||||
await supabase.from('mouvements').insert({
|
||||
'client_id': clientId,
|
||||
await pb.collection('mouvements').create(body: {
|
||||
'client': clientId,
|
||||
'type': TypeMouvement.facture,
|
||||
'montant_euros': montantEuros,
|
||||
'points': gagnes,
|
||||
'libelle': 'Facture ${euro(montantEuros)}',
|
||||
});
|
||||
_majSoldeMemoire(clientId, gagnes);
|
||||
await _ecrireSolde(clientId, gagnes);
|
||||
return gagnes;
|
||||
}
|
||||
|
||||
/// Utilise une récompense : débite son coût. Lève [SoldeInsuffisant] si besoin.
|
||||
Future<void> utiliserRecompense({
|
||||
required String clientId,
|
||||
required Recompense recompense,
|
||||
@@ -154,70 +187,77 @@ class ClientRepository extends ChangeNotifier {
|
||||
if (client.points < recompense.coutPoints) {
|
||||
throw SoldeInsuffisant(recompense.coutPoints - client.points);
|
||||
}
|
||||
await supabase.from('mouvements').insert({
|
||||
'client_id': clientId,
|
||||
await pb.collection('mouvements').create(body: {
|
||||
'client': clientId,
|
||||
'type': TypeMouvement.recompense,
|
||||
'points': -recompense.coutPoints,
|
||||
'libelle': recompense.nom,
|
||||
});
|
||||
_majSoldeMemoire(clientId, -recompense.coutPoints);
|
||||
await _ecrireSolde(clientId, -recompense.coutPoints);
|
||||
}
|
||||
|
||||
/// Correction manuelle du solde (ajout ou retrait de points).
|
||||
Future<void> ajuster({
|
||||
required String clientId,
|
||||
required double points,
|
||||
required String libelle,
|
||||
}) async {
|
||||
await supabase.from('mouvements').insert({
|
||||
'client_id': clientId,
|
||||
await pb.collection('mouvements').create(body: {
|
||||
'client': clientId,
|
||||
'type': TypeMouvement.ajustement,
|
||||
'points': points,
|
||||
'libelle': libelle,
|
||||
});
|
||||
_majSoldeMemoire(clientId, points);
|
||||
await _ecrireSolde(clientId, points);
|
||||
}
|
||||
|
||||
/// Historique d'un client, du plus récent au plus ancien.
|
||||
Future<List<Mouvement>> mouvements(String clientId) async {
|
||||
final rows = await supabase
|
||||
.from('mouvements')
|
||||
.select()
|
||||
.eq('client_id', clientId)
|
||||
.order('created_at', ascending: false);
|
||||
return (rows as List).map((e) => Mouvement.fromMap(e)).toList();
|
||||
}
|
||||
|
||||
/// Corrige le montant d'une facture existante : recalcule les points au ratio
|
||||
/// courant et réajuste le solde du client (via le trigger côté base).
|
||||
/// Corrige le montant d'une facture (recalcule les points au ratio courant).
|
||||
Future<void> modifierFacture({
|
||||
required Mouvement mouvement,
|
||||
required double nouveauMontant,
|
||||
}) async {
|
||||
final nouveauxPoints = Reglages.instance.pointsPour(nouveauMontant);
|
||||
await supabase.from('mouvements').update({
|
||||
await pb.collection('mouvements').update(mouvement.id, body: {
|
||||
'montant_euros': nouveauMontant,
|
||||
'points': nouveauxPoints,
|
||||
'libelle': 'Facture ${euro(nouveauMontant)}',
|
||||
}).eq('id', mouvement.id);
|
||||
_majSoldeMemoire(mouvement.clientId, nouveauxPoints - mouvement.points);
|
||||
});
|
||||
await _ecrireSolde(mouvement.clientId, nouveauxPoints - mouvement.points);
|
||||
}
|
||||
|
||||
/// Supprime un mouvement (facture, récompense ou ajustement). Le solde du
|
||||
/// client est réajusté automatiquement (trigger côté base).
|
||||
Future<void> supprimerMouvement(Mouvement mouvement) async {
|
||||
await supabase.from('mouvements').delete().eq('id', mouvement.id);
|
||||
_majSoldeMemoire(mouvement.clientId, -mouvement.points);
|
||||
await pb.collection('mouvements').delete(mouvement.id);
|
||||
await _ecrireSolde(mouvement.clientId, -mouvement.points);
|
||||
}
|
||||
|
||||
void _majSoldeMemoire(String clientId, double delta) {
|
||||
Future<List<Mouvement>> mouvements(String clientId) async {
|
||||
final rows = await pb.collection('mouvements').getFullList(
|
||||
filter: 'client = "$clientId"',
|
||||
sort: '-created',
|
||||
);
|
||||
return rows.map((r) => Mouvement.fromMap(r.toJson())).toList();
|
||||
}
|
||||
|
||||
/// Applique un delta au solde du client : met à jour la base ET la mémoire.
|
||||
Future<void> _ecrireSolde(String clientId, double delta) async {
|
||||
final i = _clients.indexWhere((c) => c.id == clientId);
|
||||
if (i != -1) {
|
||||
_clients[i] = _clients[i].copyWith(points: _clients[i].points + delta);
|
||||
}
|
||||
final actuel = i != -1 ? _clients[i].points : 0.0;
|
||||
final nouveau = actuel + delta;
|
||||
await pb.collection('clients').update(clientId, body: {'points': nouveau});
|
||||
if (i != -1) _clients[i] = _clients[i].copyWith(points: nouveau);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
String _genererCode() {
|
||||
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // sans I, O, 0, 1
|
||||
final rnd = Random();
|
||||
final suffixe =
|
||||
List.generate(6, (_) => alphabet[rnd.nextInt(alphabet.length)]).join();
|
||||
return '${Config.prefixeCode}$suffixe';
|
||||
}
|
||||
|
||||
String? _ouNull(String? v) =>
|
||||
(v == null || v.trim().isEmpty) ? null : v.trim();
|
||||
|
||||
void _trier() => _clients
|
||||
.sort((a, b) => a.nom.toLowerCase().compareTo(b.nom.toLowerCase()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user