feat: ajout de la configuration des émulateurs Firebase et mise à jour des services pour utiliser le backend sécurisé
This commit is contained in:
19
em2rp/lib/config/api_config.dart
Normal file
19
em2rp/lib/config/api_config.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
/// Configuration de l'API backend
|
||||
class ApiConfig {
|
||||
// Mode développement : utilise les émulateurs locaux
|
||||
static const bool isDevelopment = false; // false = utilise Cloud Functions prod
|
||||
|
||||
// URL de base pour les Cloud Functions
|
||||
static const String productionUrl = 'https://us-central1-em2rp-951dc.cloudfunctions.net';
|
||||
static const String developmentUrl = 'http://localhost:5001/em2rp-951dc/us-central1';
|
||||
|
||||
/// Retourne l'URL de base selon l'environnement
|
||||
static String get baseUrl => isDevelopment ? developmentUrl : productionUrl;
|
||||
|
||||
/// Configuration du timeout
|
||||
static const Duration requestTimeout = Duration(seconds: 30);
|
||||
|
||||
/// Nombre de tentatives en cas d'échec
|
||||
static const int maxRetries = 3;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'package:em2rp/views/event_preparation_page.dart';
|
||||
import 'package:em2rp/models/container_model.dart';
|
||||
import 'package:em2rp/models/event_model.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'firebase_options.dart';
|
||||
@@ -26,6 +27,7 @@ import 'providers/local_user_provider.dart';
|
||||
import 'services/user_service.dart';
|
||||
import 'views/reset_password_page.dart';
|
||||
import 'config/env.dart';
|
||||
import 'config/api_config.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
|
||||
void main() async {
|
||||
@@ -33,6 +35,20 @@ void main() async {
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
);
|
||||
|
||||
// Configuration des émulateurs en mode développement
|
||||
if (ApiConfig.isDevelopment) {
|
||||
print('🔧 Mode développement activé - Utilisation des émulateurs');
|
||||
|
||||
// Configurer l'émulateur Auth
|
||||
await FirebaseAuth.instance.useAuthEmulator('localhost', 9199);
|
||||
print('✓ Auth émulateur configuré: localhost:9199');
|
||||
|
||||
// Configurer l'émulateur Firestore
|
||||
FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8088);
|
||||
print('✓ Firestore émulateur configuré: localhost:8088');
|
||||
}
|
||||
|
||||
await FirebaseAuth.instance.setPersistence(Persistence.LOCAL);
|
||||
|
||||
runApp(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
|
||||
enum AlertType {
|
||||
lowStock, // Stock faible
|
||||
@@ -48,12 +48,20 @@ class AlertModel {
|
||||
});
|
||||
|
||||
factory AlertModel.fromMap(Map<String, dynamic> map, String id) {
|
||||
// Fonction helper pour convertir Timestamp ou String ISO en DateTime
|
||||
DateTime _parseDate(dynamic value) {
|
||||
if (value == null) return DateTime.now();
|
||||
if (value is Timestamp) return value.toDate();
|
||||
if (value is String) return DateTime.tryParse(value) ?? DateTime.now();
|
||||
return DateTime.now();
|
||||
}
|
||||
|
||||
return AlertModel(
|
||||
id: id,
|
||||
type: alertTypeFromString(map['type']),
|
||||
message: map['message'] ?? '',
|
||||
equipmentId: map['equipmentId'],
|
||||
createdAt: (map['createdAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
createdAt: _parseDate(map['createdAt']),
|
||||
isRead: map['isRead'] ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -242,6 +242,14 @@ class ContainerModel {
|
||||
|
||||
/// Factory depuis Firestore
|
||||
factory ContainerModel.fromMap(Map<String, dynamic> map, String id) {
|
||||
// Fonction helper pour convertir Timestamp ou String ISO en DateTime
|
||||
DateTime? _parseDate(dynamic value) {
|
||||
if (value == null) return null;
|
||||
if (value is Timestamp) return value.toDate();
|
||||
if (value is String) return DateTime.tryParse(value);
|
||||
return null;
|
||||
}
|
||||
|
||||
final List<dynamic> equipmentIdsRaw = map['equipmentIds'] ?? [];
|
||||
final List<String> equipmentIds = equipmentIdsRaw.map((e) => e.toString()).toList();
|
||||
|
||||
@@ -262,8 +270,8 @@ class ContainerModel {
|
||||
equipmentIds: equipmentIds,
|
||||
eventId: map['eventId'],
|
||||
notes: map['notes'],
|
||||
createdAt: (map['createdAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
updatedAt: (map['updatedAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
createdAt: _parseDate(map['createdAt']) ?? DateTime.now(),
|
||||
updatedAt: _parseDate(map['updatedAt']) ?? DateTime.now(),
|
||||
history: history,
|
||||
);
|
||||
}
|
||||
@@ -342,8 +350,16 @@ class ContainerHistoryEntry {
|
||||
});
|
||||
|
||||
factory ContainerHistoryEntry.fromMap(Map<String, dynamic> map) {
|
||||
// Helper pour parser la date
|
||||
DateTime _parseDate(dynamic value) {
|
||||
if (value == null) return DateTime.now();
|
||||
if (value is Timestamp) return value.toDate();
|
||||
if (value is String) return DateTime.tryParse(value) ?? DateTime.now();
|
||||
return DateTime.now();
|
||||
}
|
||||
|
||||
return ContainerHistoryEntry(
|
||||
timestamp: (map['timestamp'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
timestamp: _parseDate(map['timestamp']),
|
||||
action: map['action'] ?? '',
|
||||
equipmentId: map['equipmentId'],
|
||||
previousValue: map['previousValue'],
|
||||
|
||||
@@ -359,6 +359,14 @@ class EquipmentModel {
|
||||
});
|
||||
|
||||
factory EquipmentModel.fromMap(Map<String, dynamic> map, String id) {
|
||||
// Fonction helper pour convertir Timestamp ou String ISO en DateTime
|
||||
DateTime? _parseDate(dynamic value) {
|
||||
if (value == null) return null;
|
||||
if (value is Timestamp) return value.toDate();
|
||||
if (value is String) return DateTime.tryParse(value);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Gestion des listes
|
||||
final List<dynamic> parentBoxIdsRaw = map['parentBoxIds'] ?? [];
|
||||
final List<String> parentBoxIds = parentBoxIdsRaw.map((e) => e.toString()).toList();
|
||||
@@ -383,13 +391,13 @@ class EquipmentModel {
|
||||
length: map['length']?.toDouble(),
|
||||
width: map['width']?.toDouble(),
|
||||
height: map['height']?.toDouble(),
|
||||
purchaseDate: (map['purchaseDate'] as Timestamp?)?.toDate(),
|
||||
nextMaintenanceDate: (map['nextMaintenanceDate'] as Timestamp?)?.toDate(),
|
||||
purchaseDate: _parseDate(map['purchaseDate']),
|
||||
nextMaintenanceDate: _parseDate(map['nextMaintenanceDate']),
|
||||
maintenanceIds: maintenanceIds,
|
||||
imageUrl: map['imageUrl'],
|
||||
notes: map['notes'],
|
||||
createdAt: (map['createdAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
updatedAt: (map['updatedAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
createdAt: _parseDate(map['createdAt']) ?? DateTime.now(),
|
||||
updatedAt: _parseDate(map['updatedAt']) ?? DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -300,6 +300,14 @@ class EventModel {
|
||||
|
||||
factory EventModel.fromMap(Map<String, dynamic> map, String id) {
|
||||
try {
|
||||
// Fonction helper pour convertir Timestamp ou String ISO en DateTime
|
||||
DateTime _parseDate(dynamic value, DateTime defaultValue) {
|
||||
if (value == null) return defaultValue;
|
||||
if (value is Timestamp) return value.toDate();
|
||||
if (value is String) return DateTime.tryParse(value) ?? defaultValue;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
// Gestion sécurisée des références workforce
|
||||
final List<dynamic> workforceRefs = map['workforce'] ?? [];
|
||||
final List<DocumentReference> safeWorkforce = [];
|
||||
@@ -312,13 +320,9 @@ class EventModel {
|
||||
}
|
||||
}
|
||||
|
||||
// Gestion sécurisée des timestamps
|
||||
final Timestamp? startTimestamp = map['StartDateTime'] as Timestamp?;
|
||||
final Timestamp? endTimestamp = map['EndDateTime'] as Timestamp?;
|
||||
|
||||
final DateTime startDate = startTimestamp?.toDate() ?? DateTime.now();
|
||||
final DateTime endDate = endTimestamp?.toDate() ??
|
||||
startDate.add(const Duration(hours: 1));
|
||||
// Gestion sécurisée des timestamps avec support ISO string
|
||||
final DateTime startDate = _parseDate(map['StartDateTime'], DateTime.now());
|
||||
final DateTime endDate = _parseDate(map['EndDateTime'], startDate.add(const Duration(hours: 1)));
|
||||
|
||||
// Gestion sécurisée des documents
|
||||
final docsRaw = map['documents'] ?? [];
|
||||
@@ -365,7 +369,13 @@ class EventModel {
|
||||
eventTypeRef = map['EventType'] as DocumentReference;
|
||||
eventTypeId = eventTypeRef.id;
|
||||
} else if (map['EventType'] is String) {
|
||||
eventTypeId = map['EventType'] as String;
|
||||
final eventTypeString = map['EventType'] as String;
|
||||
// Si c'est un path (ex: "eventTypes/Mariage"), extraire juste l'ID
|
||||
if (eventTypeString.contains('/')) {
|
||||
eventTypeId = eventTypeString.split('/').last;
|
||||
} else {
|
||||
eventTypeId = eventTypeString;
|
||||
}
|
||||
}
|
||||
|
||||
// Gestion sécurisée du customer
|
||||
@@ -373,7 +383,13 @@ class EventModel {
|
||||
if (map['customer'] is DocumentReference) {
|
||||
customerId = (map['customer'] as DocumentReference).id;
|
||||
} else if (map['customer'] is String) {
|
||||
customerId = map['customer'] as String;
|
||||
final customerString = map['customer'] as String;
|
||||
// Si c'est un path (ex: "clients/abc123"), extraire juste l'ID
|
||||
if (customerString.contains('/')) {
|
||||
customerId = customerString.split('/').last;
|
||||
} else {
|
||||
customerId = customerString;
|
||||
}
|
||||
}
|
||||
|
||||
// Gestion des équipements assignés
|
||||
@@ -495,4 +511,64 @@ class EventModel {
|
||||
'returnStatus': returnStatus != null ? returnStatusToString(returnStatus!) : null,
|
||||
};
|
||||
}
|
||||
|
||||
EventModel copyWith({
|
||||
String? id,
|
||||
String? name,
|
||||
String? description,
|
||||
DateTime? startDateTime,
|
||||
DateTime? endDateTime,
|
||||
double? basePrice,
|
||||
int? installationTime,
|
||||
int? disassemblyTime,
|
||||
String? eventTypeId,
|
||||
DocumentReference? eventTypeRef,
|
||||
String? customerId,
|
||||
String? address,
|
||||
double? latitude,
|
||||
double? longitude,
|
||||
List<DocumentReference>? workforce,
|
||||
List<Map<String, String>>? documents,
|
||||
List<Map<String, dynamic>>? options,
|
||||
EventStatus? status,
|
||||
int? jauge,
|
||||
String? contactEmail,
|
||||
String? contactPhone,
|
||||
List<EventEquipment>? assignedEquipment,
|
||||
List<String>? assignedContainers,
|
||||
PreparationStatus? preparationStatus,
|
||||
LoadingStatus? loadingStatus,
|
||||
UnloadingStatus? unloadingStatus,
|
||||
ReturnStatus? returnStatus,
|
||||
}) {
|
||||
return EventModel(
|
||||
id: id ?? this.id,
|
||||
name: name ?? this.name,
|
||||
description: description ?? this.description,
|
||||
startDateTime: startDateTime ?? this.startDateTime,
|
||||
endDateTime: endDateTime ?? this.endDateTime,
|
||||
basePrice: basePrice ?? this.basePrice,
|
||||
installationTime: installationTime ?? this.installationTime,
|
||||
disassemblyTime: disassemblyTime ?? this.disassemblyTime,
|
||||
eventTypeId: eventTypeId ?? this.eventTypeId,
|
||||
eventTypeRef: eventTypeRef ?? this.eventTypeRef,
|
||||
customerId: customerId ?? this.customerId,
|
||||
address: address ?? this.address,
|
||||
latitude: latitude ?? this.latitude,
|
||||
longitude: longitude ?? this.longitude,
|
||||
workforce: workforce ?? this.workforce,
|
||||
documents: documents ?? this.documents,
|
||||
options: options ?? this.options,
|
||||
status: status ?? this.status,
|
||||
jauge: jauge ?? this.jauge,
|
||||
contactEmail: contactEmail ?? this.contactEmail,
|
||||
contactPhone: contactPhone ?? this.contactPhone,
|
||||
assignedEquipment: assignedEquipment ?? this.assignedEquipment,
|
||||
assignedContainers: assignedContainers ?? this.assignedContainers,
|
||||
preparationStatus: preparationStatus ?? this.preparationStatus,
|
||||
loadingStatus: loadingStatus ?? this.loadingStatus,
|
||||
unloadingStatus: unloadingStatus ?? this.unloadingStatus,
|
||||
returnStatus: returnStatus ?? this.returnStatus,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,14 @@ class MaintenanceModel {
|
||||
});
|
||||
|
||||
factory MaintenanceModel.fromMap(Map<String, dynamic> map, String id) {
|
||||
// Fonction helper pour convertir Timestamp ou String ISO en DateTime
|
||||
DateTime? _parseDate(dynamic value) {
|
||||
if (value == null) return null;
|
||||
if (value is Timestamp) return value.toDate();
|
||||
if (value is String) return DateTime.tryParse(value);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Gestion de la liste des équipements
|
||||
final List<dynamic> equipmentIdsRaw = map['equipmentIds'] ?? [];
|
||||
final List<String> equipmentIds = equipmentIdsRaw.map((e) => e.toString()).toList();
|
||||
@@ -68,15 +76,15 @@ class MaintenanceModel {
|
||||
id: id,
|
||||
equipmentIds: equipmentIds,
|
||||
type: maintenanceTypeFromString(map['type']),
|
||||
scheduledDate: (map['scheduledDate'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
completedDate: (map['completedDate'] as Timestamp?)?.toDate(),
|
||||
scheduledDate: _parseDate(map['scheduledDate']) ?? DateTime.now(),
|
||||
completedDate: _parseDate(map['completedDate']),
|
||||
name: map['name'] ?? '',
|
||||
description: map['description'] ?? '',
|
||||
performedBy: map['performedBy'],
|
||||
cost: map['cost']?.toDouble(),
|
||||
notes: map['notes'],
|
||||
createdAt: (map['createdAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
updatedAt: (map['updatedAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
|
||||
createdAt: _parseDate(map['createdAt']) ?? DateTime.now(),
|
||||
updatedAt: _parseDate(map['updatedAt']) ?? DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
216
em2rp/lib/services/api_service.dart
Normal file
216
em2rp/lib/services/api_service.dart
Normal file
@@ -0,0 +1,216 @@
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'dart:convert';
|
||||
import 'package:em2rp/config/api_config.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
|
||||
/// Interface abstraite pour les opérations API
|
||||
/// Permet de changer facilement de backend (Firebase Functions, REST API personnalisé, etc.)
|
||||
abstract class ApiService {
|
||||
Future<Map<String, dynamic>> call(String functionName, Map<String, dynamic> data);
|
||||
Future<T?> get<T>(String endpoint, {Map<String, dynamic>? params});
|
||||
Future<T> post<T>(String endpoint, Map<String, dynamic> data);
|
||||
Future<T> put<T>(String endpoint, Map<String, dynamic> data);
|
||||
Future<void> delete(String endpoint, {Map<String, dynamic>? data});
|
||||
}
|
||||
|
||||
/// Implémentation pour Firebase Cloud Functions
|
||||
class FirebaseFunctionsApiService implements ApiService {
|
||||
// URL de base - gérée par ApiConfig
|
||||
String get _baseUrl => ApiConfig.baseUrl;
|
||||
|
||||
/// Récupère le token d'authentification Firebase
|
||||
Future<String?> _getAuthToken() async {
|
||||
final user = FirebaseAuth.instance.currentUser;
|
||||
if (user == null) return null;
|
||||
return await user.getIdToken();
|
||||
}
|
||||
|
||||
/// Headers par défaut avec authentification
|
||||
Future<Map<String, String>> _getHeaders() async {
|
||||
final token = await _getAuthToken();
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
if (token != null) 'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
|
||||
/// Convertit récursivement les Timestamps Firestore, DocumentReference et GeoPoint en formats encodables
|
||||
dynamic _convertTimestamps(dynamic value) {
|
||||
if (value == null) return null;
|
||||
|
||||
if (value is Timestamp) {
|
||||
// Convertir Timestamp en ISO string
|
||||
return value.toDate().toIso8601String();
|
||||
} else if (value is DateTime) {
|
||||
// Convertir DateTime en ISO string
|
||||
return value.toIso8601String();
|
||||
} else if (value is DocumentReference) {
|
||||
// Convertir DocumentReference en path string
|
||||
return value.path;
|
||||
} else if (value is GeoPoint) {
|
||||
// Convertir GeoPoint en objet avec latitude et longitude
|
||||
return {
|
||||
'latitude': value.latitude,
|
||||
'longitude': value.longitude,
|
||||
};
|
||||
} else if (value is Map) {
|
||||
// Parcourir récursivement les Maps et créer une nouvelle Map typée
|
||||
final Map<String, dynamic> result = {};
|
||||
value.forEach((key, val) {
|
||||
result[key.toString()] = _convertTimestamps(val);
|
||||
});
|
||||
return result;
|
||||
} else if (value is List) {
|
||||
// Parcourir récursivement les Lists
|
||||
return value.map((item) => _convertTimestamps(item)).toList();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> call(String functionName, Map<String, dynamic> data) async {
|
||||
final url = Uri.parse('$_baseUrl/$functionName');
|
||||
final headers = await _getHeaders();
|
||||
|
||||
// Convertir les Timestamps avant l'envoi
|
||||
final convertedData = _convertTimestamps(data) as Map<String, dynamic>;
|
||||
|
||||
final response = await http.post(
|
||||
url,
|
||||
headers: headers,
|
||||
body: jsonEncode({'data': convertedData}),
|
||||
);
|
||||
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
final responseData = jsonDecode(response.body);
|
||||
return responseData is Map<String, dynamic> ? responseData : {};
|
||||
} else {
|
||||
final error = jsonDecode(response.body);
|
||||
throw ApiException(
|
||||
message: error['error'] ?? 'Unknown error',
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T?> get<T>(String endpoint, {Map<String, dynamic>? params}) async {
|
||||
final url = Uri.parse('$_baseUrl/$endpoint').replace(queryParameters: params);
|
||||
final headers = await _getHeaders();
|
||||
|
||||
final response = await http.get(url, headers: headers);
|
||||
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
final responseData = jsonDecode(response.body);
|
||||
return responseData as T?;
|
||||
} else if (response.statusCode == 404) {
|
||||
return null;
|
||||
} else {
|
||||
final error = jsonDecode(response.body);
|
||||
throw ApiException(
|
||||
message: error['error'] ?? 'Unknown error',
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> post<T>(String endpoint, Map<String, dynamic> data) async {
|
||||
final url = Uri.parse('$_baseUrl/$endpoint');
|
||||
final headers = await _getHeaders();
|
||||
|
||||
// Convertir les Timestamps avant l'envoi
|
||||
final convertedData = _convertTimestamps(data) as Map<String, dynamic>;
|
||||
|
||||
final response = await http.post(
|
||||
url,
|
||||
headers: headers,
|
||||
body: jsonEncode({'data': convertedData}),
|
||||
);
|
||||
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
final responseData = jsonDecode(response.body);
|
||||
return responseData as T;
|
||||
} else {
|
||||
final error = jsonDecode(response.body);
|
||||
throw ApiException(
|
||||
message: error['error'] ?? 'Unknown error',
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> put<T>(String endpoint, Map<String, dynamic> data) async {
|
||||
final url = Uri.parse('$_baseUrl/$endpoint');
|
||||
final headers = await _getHeaders();
|
||||
|
||||
// Convertir les Timestamps avant l'envoi
|
||||
final convertedData = _convertTimestamps(data) as Map<String, dynamic>;
|
||||
|
||||
final response = await http.put(
|
||||
url,
|
||||
headers: headers,
|
||||
body: jsonEncode({'data': convertedData}),
|
||||
);
|
||||
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
final responseData = jsonDecode(response.body);
|
||||
return responseData as T;
|
||||
} else {
|
||||
final error = jsonDecode(response.body);
|
||||
throw ApiException(
|
||||
message: error['error'] ?? 'Unknown error',
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> delete(String endpoint, {Map<String, dynamic>? data}) async {
|
||||
final url = Uri.parse('$_baseUrl/$endpoint');
|
||||
final headers = await _getHeaders();
|
||||
|
||||
// Convertir les Timestamps avant l'envoi si data existe
|
||||
final convertedData = data != null ? _convertTimestamps(data) as Map<String, dynamic> : null;
|
||||
|
||||
final response = await http.delete(
|
||||
url,
|
||||
headers: headers,
|
||||
body: convertedData != null ? jsonEncode({'data': convertedData}) : null,
|
||||
);
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
final error = jsonDecode(response.body);
|
||||
throw ApiException(
|
||||
message: error['error'] ?? 'Unknown error',
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exception personnalisée pour les erreurs API
|
||||
class ApiException implements Exception {
|
||||
final String message;
|
||||
final int statusCode;
|
||||
|
||||
ApiException({
|
||||
required this.message,
|
||||
required this.statusCode,
|
||||
});
|
||||
|
||||
@override
|
||||
String toString() => 'ApiException($statusCode): $message';
|
||||
|
||||
bool get isForbidden => statusCode == 403;
|
||||
bool get isUnauthorized => statusCode == 401;
|
||||
bool get isNotFound => statusCode == 404;
|
||||
bool get isConflict => statusCode == 409;
|
||||
}
|
||||
|
||||
/// Instance singleton du service API
|
||||
final ApiService apiService = FirebaseFunctionsApiService();
|
||||
|
||||
@@ -1,38 +1,44 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:em2rp/models/container_model.dart';
|
||||
import 'package:em2rp/models/equipment_model.dart';
|
||||
import 'package:em2rp/services/api_service.dart';
|
||||
|
||||
class ContainerService {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final ApiService _apiService = apiService;
|
||||
|
||||
// Collection references
|
||||
CollectionReference get _containersCollection => _firestore.collection('containers');
|
||||
CollectionReference get _equipmentCollection => _firestore.collection('equipments');
|
||||
|
||||
// CRUD Operations
|
||||
// ============================================================================
|
||||
// CRUD Operations - Utilise le backend sécurisé
|
||||
// ============================================================================
|
||||
|
||||
/// Créer un nouveau container
|
||||
/// Créer un nouveau container (via Cloud Function)
|
||||
Future<void> createContainer(ContainerModel container) async {
|
||||
try {
|
||||
await _containersCollection.doc(container.id).set(container.toMap());
|
||||
await _apiService.call('createContainer', container.toMap()..['id'] = container.id);
|
||||
} catch (e) {
|
||||
print('Error creating container: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mettre à jour un container
|
||||
/// Mettre à jour un container (via Cloud Function)
|
||||
Future<void> updateContainer(String id, Map<String, dynamic> data) async {
|
||||
try {
|
||||
data['updatedAt'] = Timestamp.fromDate(DateTime.now());
|
||||
await _containersCollection.doc(id).update(data);
|
||||
await _apiService.call('updateContainer', {
|
||||
'containerId': id,
|
||||
'data': data,
|
||||
});
|
||||
} catch (e) {
|
||||
print('Error updating container: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Supprimer un container
|
||||
/// Supprimer un container (via Cloud Function)
|
||||
Future<void> deleteContainer(String id) async {
|
||||
try {
|
||||
// Récupérer le container pour obtenir les équipements
|
||||
@@ -55,7 +61,7 @@ class ContainerService {
|
||||
}
|
||||
}
|
||||
|
||||
await _containersCollection.doc(id).delete();
|
||||
await _apiService.call('deleteContainer', {'containerId': id});
|
||||
} catch (e) {
|
||||
print('Error deleting container: $e');
|
||||
rethrow;
|
||||
|
||||
@@ -2,48 +2,56 @@ import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:em2rp/models/equipment_model.dart';
|
||||
import 'package:em2rp/models/alert_model.dart';
|
||||
import 'package:em2rp/models/maintenance_model.dart';
|
||||
import 'package:em2rp/services/api_service.dart';
|
||||
|
||||
class EquipmentService {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final ApiService _apiService = apiService;
|
||||
|
||||
// Collection references
|
||||
// Collection references (utilisées seulement pour les lectures)
|
||||
CollectionReference get _equipmentCollection => _firestore.collection('equipments');
|
||||
CollectionReference get _alertsCollection => _firestore.collection('alerts');
|
||||
CollectionReference get _eventsCollection => _firestore.collection('events');
|
||||
|
||||
// CRUD Operations
|
||||
// ============================================================================
|
||||
// CRUD Operations - Utilise le backend sécurisé
|
||||
// ============================================================================
|
||||
|
||||
/// Créer un nouvel équipement
|
||||
/// Créer un nouvel équipement (via Cloud Function)
|
||||
Future<void> createEquipment(EquipmentModel equipment) async {
|
||||
try {
|
||||
await _equipmentCollection.doc(equipment.id).set(equipment.toMap());
|
||||
await _apiService.call('createEquipment', equipment.toMap()..['id'] = equipment.id);
|
||||
} catch (e) {
|
||||
print('Error creating equipment: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mettre à jour un équipement
|
||||
/// Mettre à jour un équipement (via Cloud Function)
|
||||
Future<void> updateEquipment(String id, Map<String, dynamic> data) async {
|
||||
try {
|
||||
data['updatedAt'] = Timestamp.fromDate(DateTime.now());
|
||||
await _equipmentCollection.doc(id).update(data);
|
||||
await _apiService.call('updateEquipment', {
|
||||
'equipmentId': id,
|
||||
'data': data,
|
||||
});
|
||||
} catch (e) {
|
||||
print('Error updating equipment: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Supprimer un équipement
|
||||
/// Supprimer un équipement (via Cloud Function)
|
||||
Future<void> deleteEquipment(String id) async {
|
||||
try {
|
||||
await _equipmentCollection.doc(id).delete();
|
||||
await _apiService.call('deleteEquipment', {'equipmentId': id});
|
||||
} catch (e) {
|
||||
print('Error deleting equipment: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// READ Operations - Utilise Firestore streams (temps réel)
|
||||
// ============================================================================
|
||||
|
||||
/// Récupérer un équipement par ID
|
||||
Future<EquipmentModel?> getEquipmentById(String id) async {
|
||||
try {
|
||||
@@ -58,7 +66,7 @@ class EquipmentService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupérer les équipements avec filtres
|
||||
/// Récupérer les équipements avec filtres (stream temps réel)
|
||||
Stream<List<EquipmentModel>> getEquipment({
|
||||
EquipmentCategory? category,
|
||||
EquipmentStatus? status,
|
||||
@@ -106,6 +114,10 @@ class EquipmentService {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Availability & Stock Management - Logique métier côté client
|
||||
// ============================================================================
|
||||
|
||||
/// Vérifier la disponibilité d'un équipement pour une période donnée
|
||||
Future<List<String>> checkAvailability(
|
||||
String equipmentId,
|
||||
@@ -116,7 +128,7 @@ class EquipmentService {
|
||||
final conflicts = <String>[];
|
||||
|
||||
// Récupérer tous les événements qui chevauchent la période
|
||||
final eventsQuery = await _eventsCollection
|
||||
final eventsQuery = await _firestore.collection('events')
|
||||
.where('StartDateTime', isLessThanOrEqualTo: Timestamp.fromDate(endDate))
|
||||
.where('EndDateTime', isGreaterThanOrEqualTo: Timestamp.fromDate(startDate))
|
||||
.get();
|
||||
@@ -150,7 +162,7 @@ class EquipmentService {
|
||||
) async {
|
||||
try {
|
||||
// Récupérer tous les équipements du même modèle
|
||||
final equipmentQuery = await _equipmentCollection
|
||||
final equipmentQuery = await _firestore.collection('equipments')
|
||||
.where('model', isEqualTo: model)
|
||||
.get();
|
||||
|
||||
@@ -209,7 +221,7 @@ class EquipmentService {
|
||||
/// Vérifier les stocks critiques et créer des alertes
|
||||
Future<void> checkCriticalStock() async {
|
||||
try {
|
||||
final equipmentQuery = await _equipmentCollection
|
||||
final equipmentQuery = await _firestore.collection('equipments')
|
||||
.where('category', whereIn: [
|
||||
equipmentCategoryToString(EquipmentCategory.consumable),
|
||||
equipmentCategoryToString(EquipmentCategory.cable),
|
||||
@@ -236,7 +248,7 @@ class EquipmentService {
|
||||
Future<void> _createLowStockAlert(EquipmentModel equipment) async {
|
||||
try {
|
||||
// Vérifier si une alerte existe déjà pour cet équipement
|
||||
final existingAlerts = await _alertsCollection
|
||||
final existingAlerts = await _firestore.collection('alerts')
|
||||
.where('equipmentId', isEqualTo: equipment.id)
|
||||
.where('type', isEqualTo: alertTypeToString(AlertType.lowStock))
|
||||
.where('isRead', isEqualTo: false)
|
||||
@@ -244,14 +256,14 @@ class EquipmentService {
|
||||
|
||||
if (existingAlerts.docs.isEmpty) {
|
||||
final alert = AlertModel(
|
||||
id: _alertsCollection.doc().id,
|
||||
id: _firestore.collection('alerts').doc().id,
|
||||
type: AlertType.lowStock,
|
||||
message: 'Stock critique pour ${equipment.name} (${equipment.model ?? ""}): ${equipment.availableQuantity}/${equipment.criticalThreshold}',
|
||||
equipmentId: equipment.id,
|
||||
createdAt: DateTime.now(),
|
||||
);
|
||||
|
||||
await _alertsCollection.doc(alert.id).set(alert.toMap());
|
||||
await _firestore.collection('alerts').doc(alert.id).set(alert.toMap());
|
||||
}
|
||||
} catch (e) {
|
||||
print('Error creating low stock alert: $e');
|
||||
@@ -269,7 +281,7 @@ class EquipmentService {
|
||||
/// Récupérer tous les modèles uniques (pour l'indexation/autocomplete)
|
||||
Future<List<String>> getAllModels() async {
|
||||
try {
|
||||
final equipmentQuery = await _equipmentCollection.get();
|
||||
final equipmentQuery = await _firestore.collection('equipments').get();
|
||||
final models = <String>{};
|
||||
|
||||
for (var doc in equipmentQuery.docs) {
|
||||
@@ -290,7 +302,7 @@ class EquipmentService {
|
||||
/// Récupérer toutes les marques uniques (pour l'indexation/autocomplete)
|
||||
Future<List<String>> getAllBrands() async {
|
||||
try {
|
||||
final equipmentQuery = await _equipmentCollection.get();
|
||||
final equipmentQuery = await _firestore.collection('equipments').get();
|
||||
final brands = <String>{};
|
||||
|
||||
for (var doc in equipmentQuery.docs) {
|
||||
@@ -311,7 +323,7 @@ class EquipmentService {
|
||||
/// Récupérer les modèles filtrés par marque
|
||||
Future<List<String>> getModelsByBrand(String brand) async {
|
||||
try {
|
||||
final equipmentQuery = await _equipmentCollection
|
||||
final equipmentQuery = await _firestore.collection('equipments')
|
||||
.where('brand', isEqualTo: brand)
|
||||
.get();
|
||||
final models = <String>{};
|
||||
@@ -334,7 +346,7 @@ class EquipmentService {
|
||||
/// Vérifier si un ID existe déjà
|
||||
Future<bool> isIdUnique(String id) async {
|
||||
try {
|
||||
final doc = await _equipmentCollection.doc(id).get();
|
||||
final doc = await _firestore.collection('equipments').doc(id).get();
|
||||
return !doc.exists;
|
||||
} catch (e) {
|
||||
print('Error checking ID uniqueness: $e');
|
||||
@@ -347,7 +359,7 @@ class EquipmentService {
|
||||
try {
|
||||
// Les boîtes sont généralement des équipements de catégorie "structure" ou "other"
|
||||
// On pourrait aussi ajouter un champ spécifique "isBox" dans le modèle
|
||||
final equipmentQuery = await _equipmentCollection
|
||||
final equipmentQuery = await _firestore.collection('equipments')
|
||||
.where('category', whereIn: [
|
||||
equipmentCategoryToString(EquipmentCategory.structure),
|
||||
equipmentCategoryToString(EquipmentCategory.other),
|
||||
@@ -382,7 +394,7 @@ class EquipmentService {
|
||||
// On doit donc diviser en plusieurs requêtes si nécessaire
|
||||
for (int i = 0; i < ids.length; i += 10) {
|
||||
final batch = ids.skip(i).take(10).toList();
|
||||
final query = await _equipmentCollection
|
||||
final query = await _firestore.collection('equipments')
|
||||
.where(FieldPath.documentId, whereIn: batch)
|
||||
.get();
|
||||
|
||||
|
||||
@@ -7,9 +7,16 @@ import 'dart:convert';
|
||||
import 'package:em2rp/models/event_model.dart';
|
||||
import 'package:em2rp/models/event_type_model.dart';
|
||||
import 'package:em2rp/models/user_model.dart';
|
||||
import 'package:em2rp/services/api_service.dart';
|
||||
import 'dart:developer' as developer;
|
||||
|
||||
class EventFormService {
|
||||
static final ApiService _apiService = apiService;
|
||||
|
||||
// ============================================================================
|
||||
// READ Operations - Utilise Firestore (peut rester en lecture directe)
|
||||
// ============================================================================
|
||||
|
||||
static Future<List<EventTypeModel>> fetchEventTypes() async {
|
||||
developer.log('Fetching event types from Firestore...', name: 'EventFormService');
|
||||
try {
|
||||
@@ -33,6 +40,10 @@ class EventFormService {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// STORAGE - Reste inchangé (déjà via Cloud Function)
|
||||
// ============================================================================
|
||||
|
||||
static Future<List<Map<String, String>>> uploadFiles(List<PlatformFile> files) async {
|
||||
List<Map<String, String>> uploadedFiles = [];
|
||||
|
||||
@@ -90,14 +101,39 @@ class EventFormService {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CRUD Operations - Utilise le backend sécurisé
|
||||
// ============================================================================
|
||||
|
||||
static Future<String> createEvent(EventModel event) async {
|
||||
final docRef = await FirebaseFirestore.instance.collection('events').add(event.toMap());
|
||||
return docRef.id;
|
||||
try {
|
||||
final result = await _apiService.call('createEvent', event.toMap());
|
||||
return result['id'] as String;
|
||||
} catch (e) {
|
||||
developer.log('Error creating event', name: 'EventFormService', error: e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> updateEvent(EventModel event) async {
|
||||
final docRef = FirebaseFirestore.instance.collection('events').doc(event.id);
|
||||
await docRef.update(event.toMap());
|
||||
try {
|
||||
await _apiService.call('updateEvent', {
|
||||
'eventId': event.id,
|
||||
'data': event.toMap(),
|
||||
});
|
||||
} catch (e) {
|
||||
developer.log('Error updating event', name: 'EventFormService', error: e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> deleteEvent(String eventId) async {
|
||||
try {
|
||||
await _apiService.call('deleteEvent', {'eventId': eventId});
|
||||
} catch (e) {
|
||||
developer.log('Error deleting event', name: 'EventFormService', error: e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<List<Map<String, String>>> moveFilesToEvent(
|
||||
|
||||
@@ -3,24 +3,28 @@ import 'package:em2rp/models/maintenance_model.dart';
|
||||
import 'package:em2rp/models/alert_model.dart';
|
||||
import 'package:em2rp/models/equipment_model.dart';
|
||||
import 'package:em2rp/services/equipment_service.dart';
|
||||
import 'package:em2rp/services/api_service.dart';
|
||||
|
||||
class MaintenanceService {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final EquipmentService _equipmentService = EquipmentService();
|
||||
final ApiService _apiService = apiService;
|
||||
|
||||
// Collection references
|
||||
CollectionReference get _maintenancesCollection => _firestore.collection('maintenances');
|
||||
CollectionReference get _equipmentCollection => _firestore.collection('equipment');
|
||||
CollectionReference get _equipmentCollection => _firestore.collection('equipments');
|
||||
CollectionReference get _alertsCollection => _firestore.collection('alerts');
|
||||
|
||||
// CRUD Operations
|
||||
// ============================================================================
|
||||
// CRUD Operations - Utilise le backend sécurisé
|
||||
// ============================================================================
|
||||
|
||||
/// Créer une nouvelle maintenance
|
||||
/// Créer une nouvelle maintenance (via Cloud Function)
|
||||
Future<void> createMaintenance(MaintenanceModel maintenance) async {
|
||||
try {
|
||||
await _maintenancesCollection.doc(maintenance.id).set(maintenance.toMap());
|
||||
await _apiService.call('createMaintenance', maintenance.toMap());
|
||||
|
||||
// Mettre à jour les équipements concernés
|
||||
// Mettre à jour les équipements concernés (côté client pour l'instant)
|
||||
for (String equipmentId in maintenance.equipmentIds) {
|
||||
await _updateEquipmentMaintenanceList(equipmentId, maintenance.id);
|
||||
|
||||
@@ -35,11 +39,13 @@ class MaintenanceService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mettre à jour une maintenance
|
||||
/// Mettre à jour une maintenance (via Cloud Function)
|
||||
Future<void> updateMaintenance(String id, Map<String, dynamic> data) async {
|
||||
try {
|
||||
data['updatedAt'] = Timestamp.fromDate(DateTime.now());
|
||||
await _maintenancesCollection.doc(id).update(data);
|
||||
await _apiService.call('updateMaintenance', {
|
||||
'maintenanceId': id,
|
||||
'data': data,
|
||||
});
|
||||
} catch (e) {
|
||||
print('Error updating maintenance: $e');
|
||||
rethrow;
|
||||
|
||||
@@ -400,26 +400,33 @@ class _EquipmentDetailPageState extends State<EquipmentDetailPage> {
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
// Fermer le dialog
|
||||
Navigator.pop(context);
|
||||
|
||||
// Capturer le ScaffoldMessenger avant la suppression
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
final navigator = Navigator.of(context);
|
||||
|
||||
try {
|
||||
await context
|
||||
.read<EquipmentProvider>()
|
||||
.deleteEquipment(widget.equipment.id);
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Équipement supprimé avec succès'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Revenir à la page précédente
|
||||
navigator.pop();
|
||||
|
||||
// Afficher le snackbar (même si le widget est démonté)
|
||||
scaffoldMessenger.showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Équipement supprimé avec succès'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Erreur: $e')),
|
||||
);
|
||||
}
|
||||
// Afficher l'erreur
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text('Erreur: $e')),
|
||||
);
|
||||
}
|
||||
},
|
||||
style: TextButton.styleFrom(foregroundColor: Colors.red),
|
||||
|
||||
@@ -31,10 +31,25 @@ class _EventDetailsHeaderState extends State<EventDetailsHeader> {
|
||||
_fetchEventTypeName();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(EventDetailsHeader oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// Recharger le type d'événement si l'événement a changé
|
||||
if (oldWidget.event.id != widget.event.id ||
|
||||
oldWidget.event.eventTypeId != widget.event.eventTypeId) {
|
||||
_fetchEventTypeName();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _fetchEventTypeName() async {
|
||||
setState(() => _isLoadingEventType = true);
|
||||
|
||||
try {
|
||||
if (widget.event.eventTypeId.isEmpty) {
|
||||
setState(() => _isLoadingEventType = false);
|
||||
setState(() {
|
||||
_eventTypeName = null;
|
||||
_isLoadingEventType = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user