74 lines
2.3 KiB
Dart
74 lines
2.3 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
|
|
import '../config.dart';
|
|
import '../pocketbase_config.dart';
|
|
|
|
/// Réglages globaux du magasin (unique enregistrement de la collection
|
|
/// `reglages` sur PocketBase). [ChangeNotifier] pour rafraîchir les écrans.
|
|
class Reglages extends ChangeNotifier {
|
|
Reglages._();
|
|
static final Reglages instance = Reglages._();
|
|
|
|
String? _recordId;
|
|
bool _abonne = false;
|
|
double _eurosParPoint = Config.eurosParPointParDefaut;
|
|
String _nomMagasin = '';
|
|
|
|
double get eurosParPoint => _eurosParPoint;
|
|
String get nomMagasin => _nomMagasin;
|
|
|
|
Future<void> charger() async {
|
|
try {
|
|
final rows = await pb.collection('reglages').getFullList();
|
|
if (rows.isNotEmpty) {
|
|
final r = rows.first;
|
|
_recordId = r.id;
|
|
_eurosParPoint = (r.toJson()['euros_par_point'] as num?)?.toDouble() ??
|
|
Config.eurosParPointParDefaut;
|
|
_nomMagasin = (r.toJson()['nom_magasin'] as String?) ?? '';
|
|
notifyListeners();
|
|
await _sabonner();
|
|
}
|
|
} catch (_) {
|
|
// Valeurs par défaut si non connecté / serveur injoignable.
|
|
}
|
|
}
|
|
|
|
/// Abonnement temps réel : un changement de ratio/nom se propage aux appareils.
|
|
Future<void> _sabonner() async {
|
|
if (_abonne) return;
|
|
_abonne = true;
|
|
try {
|
|
await pb.collection('reglages').subscribe('*', (e) {
|
|
final rec = e.record;
|
|
if (rec == null) return;
|
|
_recordId = rec.id;
|
|
_eurosParPoint = (rec.toJson()['euros_par_point'] as num?)?.toDouble() ??
|
|
_eurosParPoint;
|
|
_nomMagasin = (rec.toJson()['nom_magasin'] as String?) ?? _nomMagasin;
|
|
notifyListeners();
|
|
});
|
|
} catch (_) {
|
|
_abonne = false;
|
|
}
|
|
}
|
|
|
|
double pointsPour(double euros) =>
|
|
_eurosParPoint > 0 ? euros / _eurosParPoint : 0;
|
|
|
|
Future<void> definirEurosParPoint(double valeur) async {
|
|
if (valeur <= 0 || _recordId == null) return;
|
|
await pb.collection('reglages').update(_recordId!, body: {'euros_par_point': valeur});
|
|
_eurosParPoint = valeur;
|
|
notifyListeners();
|
|
}
|
|
|
|
Future<void> definirNomMagasin(String valeur) async {
|
|
if (_recordId == null) return;
|
|
final v = valeur.trim();
|
|
await pb.collection('reglages').update(_recordId!, body: {'nom_magasin': v});
|
|
_nomMagasin = v;
|
|
notifyListeners();
|
|
}
|
|
}
|