Browse Source

database

28062025_02
Stephane 5 months ago
parent
commit
6b83a1ab5e
  1. 11
      lib/Components/colors.dart
  2. 3002
      lib/Services/stock_managementDatabase.dart
  3. 108
      lib/config/DatabaseConfig.dart
  4. 72
      lib/controller/userController.dart

11
lib/Components/colors.dart

@ -0,0 +1,11 @@
import 'package:flutter/material.dart';
class AppColors {
static const primaryBlue =
Color(0xFF04365F); // Replace with your exact logo tone
static const secondaryBlue =
Color(0xFF1976D2); // Replace if your logo has a secondary tone
static const neutralGrey = Color(0xFF8A8A8A);
static const accent =
Color(0xFFF7941D); // Example: if your logo has an orange or accent
}

3002
lib/Services/stock_managementDatabase.dart

File diff suppressed because it is too large

108
lib/config/DatabaseConfig.dart

@ -1,18 +1,22 @@
// Config/database_config.dart - Version améliorée
// Config/database_config.dart
import 'dart:io';
import 'dart:async';
class DatabaseConfig {
// static const String host = '10.0.2.2';
//static const String host = '172.20.10.5';
static const String host = 'localhost';
static const int port = 3306;
static const String username = 'root';
static const String? password = null;
static const String database = 'gico';
// Local MySQL settings
static const String localHost = '192.168.88.73';
static const String localUsername = 'guycom';
static const String? localPassword = '3iV59wjRdbuXAPR';
static const String localDatabase = 'guycom';
// Production (public) MySQL settings
static const String prodHost = '185.70.105.157';
static const String prodUsername = 'guycom';
static const String prodPassword = '3iV59wjRdbuXAPR';
static const String prodDatabase = 'guycom';
static const int port = 3306;
static const Duration connectionTimeout = Duration(seconds: 30);
static const Duration queryTimeout = Duration(seconds: 15);
@ -21,46 +25,72 @@ class DatabaseConfig {
static bool get isDevelopment => false;
static Map<String, dynamic> getConfig() {
if (isDevelopment) {
return {
'host': host,
'port': port,
'user': username,
'password': password,
'database': database,
'timeout': connectionTimeout.inSeconds,
};
/// Build config map for connection
static Map<String, dynamic> _buildConfig({
required String host,
required String user,
required String? password,
required String database,
}) {
return {
'host': host,
'port': port,
'user': user,
'password': password,
'database': database,
'timeout': connectionTimeout.inSeconds,
};
}
/// TCP check if MySQL server is reachable
static Future<bool> isServerReachable(String host, {int port = 3306}) async {
try {
final socket =
await Socket.connect(host, port, timeout: Duration(seconds: 2));
socket.destroy();
return true;
} catch (_) {
return false;
}
}
/// Get smart config (local if reachable, otherwise public)
static Future<Map<String, dynamic>> getSmartConfig() async {
if (await isServerReachable(localHost, port: port)) {
return _buildConfig(
host: localHost,
user: localUsername,
password: localPassword,
database: localDatabase,
);
} else {
return {
'host': prodHost,
'port': port,
'user': prodUsername,
'password': prodPassword,
'database': prodDatabase,
'timeout': connectionTimeout.inSeconds,
};
return _buildConfig(
host: prodHost,
user: prodUsername,
password: prodPassword,
database: prodDatabase,
);
}
}
// Validation de la configuration
static bool validateConfig() {
/// Validate any config
static bool validateConfig(Map<String, dynamic> config) {
try {
final config = getConfig();
return config['host']?.toString().isNotEmpty == true &&
config['database']?.toString().isNotEmpty == true &&
config['user'] != null;
return config['host']?.toString().isNotEmpty == true &&
config['database']?.toString().isNotEmpty == true &&
config['user'] != null;
} catch (e) {
print("Erreur de validation de la configuration: $e");
return false;
}
}
// Configuration avec retry automatique
static Map<String, dynamic> getConfigWithRetry() {
final config = getConfig();
config['retryCount'] = 3;
config['retryDelay'] = 5000; // ms
return config;
/// Add retry config
static Map<String, dynamic> addRetry(Map<String, dynamic> config) {
return {
...config,
'retryCount': 3,
'retryDelay': 5000, // ms
};
}
}
}

72
lib/controller/userController.dart

@ -14,7 +14,7 @@ class UserController extends GetxController {
final _userId = 0.obs;
final _pointDeVenteId = 0.obs;
final _pointDeVenteDesignation = ''.obs;
// Cache service
final PermissionCacheService _cacheService = PermissionCacheService.instance;
@ -39,17 +39,18 @@ class UserController extends GetxController {
Future<void> loadUserData() async {
try {
final prefs = await SharedPreferences.getInstance();
final storedUsername = prefs.getString('username') ?? '';
final storedRole = prefs.getString('role') ?? '';
final storedUserId = prefs.getInt('user_id') ?? 0;
final storedPointDeVenteId = prefs.getInt('point_de_vente_id') ?? 0;
final storedPointDeVenteDesignation = prefs.getString('point_de_vente_designation') ?? '';
final storedPointDeVenteDesignation =
prefs.getString('point_de_vente_designation') ?? '';
if (storedUsername.isNotEmpty) {
try {
Users user = await AppDatabase.instance.getUser(storedUsername);
_username.value = user.username;
_email.value = user.email;
_name.value = user.name;
@ -59,14 +60,14 @@ class UserController extends GetxController {
_userId.value = storedUserId;
_pointDeVenteId.value = storedPointDeVenteId;
_pointDeVenteDesignation.value = storedPointDeVenteDesignation;
if (_pointDeVenteDesignation.value.isEmpty && _pointDeVenteId.value > 0) {
if (_pointDeVenteDesignation.value.isEmpty &&
_pointDeVenteId.value > 0) {
await loadPointDeVenteDesignation();
}
// Précharger les permissions en arrière-plan (non bloquant)
_preloadPermissionsInBackground();
} catch (dbError) {
print("❌ Erreur BDD, utilisation du fallback: $dbError");
_username.value = storedUsername;
@ -77,7 +78,7 @@ class UserController extends GetxController {
_userId.value = storedUserId;
_pointDeVenteId.value = storedPointDeVenteId;
_pointDeVenteDesignation.value = storedPointDeVenteDesignation;
// Précharger quand même
_preloadPermissionsInBackground();
}
@ -103,15 +104,17 @@ class UserController extends GetxController {
Future<void> loadPointDeVenteDesignation() async {
if (_pointDeVenteId.value <= 0) return;
try {
final pointDeVente = await AppDatabase.instance.getPointDeVenteById(_pointDeVenteId.value);
final pointDeVente =
await AppDatabase.instance.getPointDeVenteById(_pointDeVenteId.value);
if (pointDeVente != null) {
_pointDeVenteDesignation.value = pointDeVente['nom'] as String;
await saveUserData();
}
} catch (e) {
print('❌ Erreur lors du chargement de la désignation du point de vente: $e');
print(
'❌ Erreur lors du chargement de la désignation du point de vente: $e');
}
}
@ -125,14 +128,14 @@ class UserController extends GetxController {
_password.value = user.password;
_userId.value = userId;
_pointDeVenteId.value = user.pointDeVenteId ?? 0;
print("✅ Utilisateur mis à jour avec credentials:");
print(" Username: ${_username.value}");
print(" Role: ${_role.value}");
print(" UserID: ${_userId.value}");
saveUserData();
// Précharger immédiatement les permissions après connexion
_preloadPermissionsInBackground();
}
@ -144,7 +147,7 @@ class UserController extends GetxController {
_name.value = user.name;
_lastname.value = user.lastName;
_password.value = user.password;
saveUserData();
_preloadPermissionsInBackground();
}
@ -152,7 +155,7 @@ class UserController extends GetxController {
Future<void> saveUserData() async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', _username.value);
await prefs.setString('email', _email.value);
await prefs.setString('role', _role.value);
@ -160,8 +163,9 @@ class UserController extends GetxController {
await prefs.setString('lastname', _lastname.value);
await prefs.setInt('user_id', _userId.value);
await prefs.setInt('point_de_vente_id', _pointDeVenteId.value);
await prefs.setString('point_de_vente_designation', _pointDeVenteDesignation.value);
await prefs.setString(
'point_de_vente_designation', _pointDeVenteDesignation.value);
print("✅ Données sauvegardées avec succès");
} catch (e) {
print('❌ Erreur lors de la sauvegarde: $e');
@ -172,10 +176,10 @@ class UserController extends GetxController {
Future<void> clearUserData() async {
try {
final prefs = await SharedPreferences.getInstance();
// IMPORTANT: Vider le cache de session
_cacheService.clearAllCache();
// Effacer SharedPreferences
await prefs.remove('username');
await prefs.remove('email');
@ -185,7 +189,7 @@ class UserController extends GetxController {
await prefs.remove('user_id');
await prefs.remove('point_de_vente_id');
await prefs.remove('point_de_vente_designation');
// Effacer les observables
_username.value = '';
_email.value = '';
@ -196,9 +200,8 @@ class UserController extends GetxController {
_userId.value = 0;
_pointDeVenteId.value = 0;
_pointDeVenteDesignation.value = '';
print("✅ Données utilisateur et cache de session vidés");
} catch (e) {
print('❌ Erreur lors de l\'effacement: $e');
}
@ -215,28 +218,28 @@ class UserController extends GetxController {
print('⚠️ Username vide, rechargement...');
await loadUserData();
}
if (_username.value.isEmpty) {
print('❌ Utilisateur non connecté');
return false;
}
// Essayer d'abord le cache
if (_cacheService.isLoaded) {
return _cacheService.hasPermission(_username.value, permission, route);
}
// Si pas encore chargé, charger et essayer de nouveau
print("🔄 Cache non chargé, chargement des permissions...");
await _cacheService.loadUserPermissions(_username.value);
return _cacheService.hasPermission(_username.value, permission, route);
} catch (e) {
print('❌ Erreur vérification permission: $e');
// Fallback vers la méthode originale en cas d'erreur
try {
return await AppDatabase.instance.hasPermission(_username.value, permission, route);
return await AppDatabase.instance
.hasPermission(_username.value, permission, route);
} catch (fallbackError) {
print('❌ Erreur fallback permission: $fallbackError');
return false;
@ -245,7 +248,8 @@ class UserController extends GetxController {
}
/// Vérification de permissions multiples
Future<bool> hasAnyPermission(List<String> permissionNames, String menuRoute) async {
Future<bool> hasAnyPermission(
List<String> permissionNames, String menuRoute) async {
for (String permissionName in permissionNames) {
if (await hasPermission(permissionName, menuRoute)) {
return true;
@ -286,8 +290,8 @@ class UserController extends GetxController {
print("IsLoggedIn: $isLoggedIn");
print("Cache Ready: $isCacheReady");
print("========================");
// Debug du cache
_cacheService.debugPrintCache();
}
}
}

Loading…
Cancel
Save