feat: Intégration du frontend Flutter depuis YNOV

- Framework: Flutter web
- Pages: Login, inscription, dashboards
- Services: API client, authentification, gestion d'état
- Intégration avec backend NestJS
- Dockerfile pour déploiement web
This commit is contained in:
2025-11-24 15:44:15 +01:00
parent 33d6e7b0c3
commit 9cb4162165
62 changed files with 4899 additions and 266 deletions
+32
View File
@@ -0,0 +1,32 @@
class ApiConfig {
// static const String baseUrl = 'http://localhost:3000/api/v1/';
static const String baseUrl = 'https://ynov.ptits-pas.fr/api/v1';
// Auth endpoints
static const String login = '/auth/login';
static const String register = '/auth/register';
static const String refreshToken = '/auth/refresh';
// Users endpoints
static const String users = '/users';
static const String userProfile = '/users/profile';
static const String userChildren = '/users/children';
// Dashboard endpoints
static const String dashboard = '/dashboard';
static const String events = '/events';
static const String contracts = '/contracts';
static const String conversations = '/conversations';
static const String notifications = '/notifications';
// Headers
static Map<String, String> get headers => {
'Content-Type': 'application/json',
'Accept': 'application/json',
};
static Map<String, String> authHeaders(String token) => {
...headers,
'Authorization': 'Bearer $token',
};
}
@@ -0,0 +1,71 @@
import 'package:shared_preferences/shared_preferences.dart';
class TokenService {
// static const _storage = FlutterSecureStorage();
static const _tokenKey = 'access_token';
static const String _refreshTokenKey = 'refresh_token';
static const _roleKey = 'user_role';
// Stockage du token
static Future<void> saveToken(String token) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_tokenKey, token);
}
// Stockage du refresh token
static Future<void> saveRefreshToken(String refreshToken) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_refreshTokenKey, refreshToken);
}
// Stockage du rôle
static Future<void> saveRole(String role) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_roleKey, role);
}
// Récupération du token
static Future<String?> getToken() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_tokenKey);
}
// Récupération du refresh token
static Future<String?> getRefreshToken() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_refreshTokenKey);
}
// Récupération du rôle
static Future<String?> getRole() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_roleKey);
}
// Suppression du token
static Future<void> deleteToken() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_tokenKey);
}
// Suppression du refresh token
static Future<void> deleteRefreshToken() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_refreshTokenKey);
}
// Suppression du rôle
static Future<void> deleteRole() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_roleKey);
}
// Nettoyage complet
static Future<void> clearAll() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_tokenKey);
await prefs.remove(_refreshTokenKey);
await prefs.remove(_roleKey);
}
}
+112 -3
View File
@@ -1,9 +1,118 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:p_tits_pas/services/api/api_config.dart';
import 'package:p_tits_pas/services/api/tokenService.dart';
import '../models/user.dart';
import 'package:http/http.dart' as http;
class AuthService {
static const String _usersKey = 'users';
final String baseUrl = ApiConfig.baseUrl;
//login
Future<Map<String, dynamic>> login(String email, String password) async {
try {
final response = await http.post(
Uri.parse('$baseUrl${ApiConfig.login}'),
headers: ApiConfig.headers,
body: jsonEncode({
'email': email,
'password': password
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
await TokenService.saveToken(data['access_token']);
await TokenService.saveRefreshToken(data['refresh_token']);
final role = _extractRoleFromToken(data['access_token']);
await TokenService.saveRole(role);
return data;
} else {
throw Exception('Failed to login: ${response.body}');
}
} catch (e) {
throw Exception('Failed to login: $e');
}
}
String _extractRoleFromToken(String token) {
try {
final parts = token.split('.');
if (parts.length != 3) return '';
final payload = parts[1];
final normalizedPayload = base64Url.normalize(payload);
final decoded = utf8.decode(base64Url.decode(normalizedPayload));
final Map<String, dynamic> payloadMap = jsonDecode(decoded);
return payloadMap['role'] ?? '';
} catch (e) {
print('Error extracting role from token: $e');
return '';
}
}
Future<void> logout() async {
await TokenService.clearAll();
}
Future<bool> isAuthenticated() async {
final token = await TokenService.getToken();
if (token == null) return false;
return !_isTokenExpired(token);
}
bool _isTokenExpired(String token) {
try {
final parts = token.split('.');
if (parts.length != 3) return true;
final payload = parts[1];
final normalizedPayload = base64Url.normalize(payload);
final decoded = utf8.decode(base64Url.decode(normalizedPayload));
final Map<String, dynamic> payloadMap = jsonDecode(decoded);
final exp = payloadMap['exp'];
if (exp == null) return true;
final expirationDate = DateTime.fromMillisecondsSinceEpoch(exp * 1000);
return DateTime.now().isAfter(expirationDate);
} catch (e) {
return true;
}
}
//register
Future<AppUser> register({
required String email,
required String password,
required String firstName,
required String lastName,
required String role,
}) async {
final response = await http.post(
Uri.parse('$baseUrl${ApiConfig.register}'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'email': email,
'password': password,
'firstName': firstName,
'lastName': lastName,
'role': role,
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
return AppUser.fromJson(data['user']);
} else {
throw Exception('Failed to register');
}
}
/*static const String _usersKey = 'users';
static const String _parentsKey = 'parents';
static const String _childrenKey = 'children';
@@ -38,5 +147,5 @@ class AuthService {
// Méthode pour récupérer l'utilisateur connecté (mode démonstration)
static Future<AppUser?> getCurrentUser() async {
return null; // Aucun utilisateur en mode démonstration
}
}*/
}
@@ -1,8 +1,9 @@
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:p_tits_pas/config/env.dart';
class BugReportService {
static const String _apiUrl = 'https://api.supernounou.local/bug-reports';
static final String _apiUrl = Env.apiV1('/bug-reports');
static Future<void> sendReport(String description) async {
try {
+202
View File
@@ -0,0 +1,202 @@
import 'package:p_tits_pas/models/m_dashbord/assistant_model.dart';
import 'package:p_tits_pas/models/m_dashbord/child_model.dart';
import 'package:p_tits_pas/models/m_dashbord/contract_model.dart';
import 'package:p_tits_pas/models/m_dashbord/conversation_model.dart';
import 'package:p_tits_pas/models/m_dashbord/event_model.dart';
import 'package:p_tits_pas/models/m_dashbord/notification_model.dart';
class DashboardService {
// URL de base de l'API
static const String _baseUrl = 'YOUR_API_BASE_URL';
// Récupérer la liste des enfants
Future<List<ChildModel>> getChildren() async {
try {
// TODO: Implémenter l'appel API
// Exemple de mock data pour le développement
return [
ChildModel(
id: '1',
firstName: 'Emma',
birthDate: DateTime(2020, 5, 15),
photoUrl: 'assets/images/child1.jpg',
status: ChildStatus.onHoliday,
),
ChildModel(
id: '2',
firstName: 'Lucas',
birthDate: DateTime(2021, 3, 10),
photoUrl: 'assets/images/child2.jpg',
status: ChildStatus.searching,
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des enfants: $e');
}
}
// Récupérer l'assistante maternelle pour un enfant
Future<AssistantModel> getAssistantForChild(String childId) async {
try {
// TODO: Implémenter l'appel API
return AssistantModel(
id: 'am1',
firstName: 'Marie',
lastName: 'Dupont',
hourlyRate: 10.0,
dailyFees: 80.0,
status: AssistantStatus.available,
photoUrl: 'assets/images/assistant1.jpg',
address: '123 rue des Lilas',
phone: '0123456789',
);
} catch (e) {
throw Exception('Erreur lors de la récupération de l\'assistante: $e');
}
}
// Récupérer les événements pour un enfant
Future<List<EventModel>> getEventsForChild(String childId) async {
try {
// TODO: Implémenter l'appel API
return [
EventModel(
id: 'evt1',
title: 'Rendez-vous médical',
startDate: DateTime.now().add(const Duration(days: 2)),
type: EventType.parentVacation,
status: EventStatus.pending,
description: 'Visite de routine',
childId: childId,
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des événements: $e');
}
}
// Récupérer tous les événements à venir
Future<List<EventModel>> getUpcomingEvents() async {
try {
// TODO: Implémenter l'appel API
return [
EventModel(
id: 'evt1',
title: 'Activité peinture',
startDate: DateTime.now().add(const Duration(days: 1)),
endDate: DateTime.now().add(const Duration(days: 1, hours: 2)),
type: EventType.parentVacation,
status: EventStatus.pending,
description: 'Atelier créatif',
childId: '1',
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des événements: $e');
}
}
// Récupérer les contrats
Future<List<ContractModel>> getContracts() async {
try {
// TODO: Implémenter l'appel API
return [
ContractModel(
id: 'contract1',
childId: '1',
assistantId: 'am1',
startDate: DateTime(2023, 9, 1),
endDate: DateTime(2024, 8, 31),
status: ContractStatus.pending,
hourlyRate: 10.0,
createdAt: DateTime.now(),
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des contrats: $e');
}
}
// Récupérer les contrats pour un enfant spécifique
Future<List<ContractModel>> getContractsForChild(String childId) async {
try {
// TODO: Implémenter l'appel API
return [
ContractModel(
id: 'contract1',
childId: childId,
assistantId: 'am1',
startDate: DateTime(2023, 9, 1),
endDate: DateTime(2024, 8, 31),
status: ContractStatus.active,
hourlyRate: 10.0,
createdAt: DateTime.now(),
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des contrats: $e');
}
}
// Récupérer les conversations
Future<List<ConversationModel>> getConversations() async {
try {
// TODO: Implémenter l'appel API
return [
ConversationModel(
id: 'conv1',
title: 'Conversation avec Marie Dupont',
participantIds: ['am1'],
messages: [
MessageModel(
id: 'msg1',
content: 'Bonjour, comment ça va ?',
senderId: 'am1',
sentAt: DateTime.now().subtract(const Duration(hours: 2)),
status: MessageStatus.read,
),
MessageModel(
id: 'msg2',
content: 'Tout va bien, merci !',
senderId: 'parent1',
sentAt: DateTime.now().subtract(const Duration(hours: 1, minutes: 30)),
status: MessageStatus.read,
),
],
lastMessageAt: DateTime.now().subtract(const Duration(hours: 2)),
unreadCount: 2,
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des conversations: $e');
}
}
// Récupérer les notifications
Future<List<NotificationModel>> getNotifications() async {
try {
// TODO: Implémenter l'appel API
return [
NotificationModel(
id: 'notif1',
title: 'Nouveau message',
createdAt: DateTime.now(),
isRead: false,
type: NotificationType.contractPending,
content: 'Votre contrat est en attente',
),
];
} catch (e) {
throw Exception('Erreur lors de la récupération des notifications: $e');
}
}
// Marquer une notification comme lue
Future<void> markNotificationAsRead(String notificationId) async {
try {
// TODO: Implémenter l'appel API
} catch (e) {
throw Exception('Erreur lors du marquage de la notification: $e');
}
}
}
@@ -0,0 +1,20 @@
import 'package:flutter/cupertino.dart';
class NavigationService {
static void handleLoginSuccess(BuildContext context, String role) {
switch (role) {
case 'admin':
Navigator.pushReplacementNamed(context, '/admin_dashboard');
break;
case 'gestionnaire':
Navigator.pushReplacementNamed(context, '/gestionnaire_dashboard');
break;
case 'parent':
Navigator.pushReplacementNamed(context, '/parent-dashboard');
break;
case 'assistante_maternelle':
Navigator.pushReplacementNamed(context, '/assistante_maternelle_dashboard');
break;
}
}
}