This commit is contained in:
2026-05-14 16:54:32 +00:00
parent 5b2a2e7ddb
commit 15fcbcc9eb
212 changed files with 18586 additions and 10360 deletions
+27 -27
View File
@@ -1,27 +1,27 @@
class User {
final int id;
final String name;
final String email;
User({
required this.id,
required this.name,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
};
}
}
class User {
final int id;
final String name;
final String email;
User({
required this.id,
required this.name,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
};
}
}
@@ -1,127 +1,127 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/user.dart';
import '../services/auth_service.dart';
class AuthProvider with ChangeNotifier {
final AuthService _authService = AuthService();
static const _platform = MethodChannel('com.cesizen/wearable');
User? _user;
bool _isLoading = false;
String? _errorMessage;
AuthProvider() {
// Écouter les demandes de mise à jour venant de la couche native (montre -> téléphone)
_platform.setMethodCallHandler((call) async {
if (call.method == "requestStatusUpdate") {
_syncWithWear();
}
});
// Tenter de restaurer la session au lancement
_checkInitialAuth();
}
Future<void> _checkInitialAuth() async {
_isLoading = true;
notifyListeners();
final result = await _authService.getProfile();
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
}
_isLoading = false;
notifyListeners();
}
User? get user => _user;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
bool get isAuthenticated => _user != null;
void _syncWithWear() {
try {
_platform.invokeMethod('sendAuthStatus', {
'status': isAuthenticated ? 'authenticated' : 'unauthenticated',
'userName': _user?.name ?? '',
});
} catch (e) {
// Échec silencieux si pas d'appareil Wear OS à proximité
debugPrint("Wear OS sync failed: $e");
}
}
Future<bool> login(String email, String password) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authService.login(email, password);
_isLoading = false;
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
notifyListeners();
return true;
} else {
_errorMessage = result['message'];
notifyListeners();
return false;
}
}
Future<bool> register(String name, String email, String password, String passwordConfirmation) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authService.register(name, email, password, passwordConfirmation);
_isLoading = false;
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
notifyListeners();
return true;
} else {
if (result['errors'] is Map) {
_errorMessage = (result['errors'] as Map).values.first[0];
} else {
_errorMessage = result['errors'].toString();
}
notifyListeners();
return false;
}
}
Future<void> logout() async {
await _authService.logout();
_user = null;
_syncWithWear();
notifyListeners();
}
Future<bool> updateProfile(String name, String email, {String? password}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authService.updateProfile(name, email, password: password);
_isLoading = false;
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
notifyListeners();
return true;
} else {
_errorMessage = result['message'];
notifyListeners();
return false;
}
}
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/user.dart';
import '../services/auth_service.dart';
class AuthProvider with ChangeNotifier {
final AuthService _authService = AuthService();
static const _platform = MethodChannel('com.cesizen/wearable');
User? _user;
bool _isLoading = false;
String? _errorMessage;
AuthProvider() {
// Écouter les demandes de mise à jour venant de la couche native (montre -> téléphone)
_platform.setMethodCallHandler((call) async {
if (call.method == "requestStatusUpdate") {
_syncWithWear();
}
});
// Tenter de restaurer la session au lancement
_checkInitialAuth();
}
Future<void> _checkInitialAuth() async {
_isLoading = true;
notifyListeners();
final result = await _authService.getProfile();
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
}
_isLoading = false;
notifyListeners();
}
User? get user => _user;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
bool get isAuthenticated => _user != null;
void _syncWithWear() {
try {
_platform.invokeMethod('sendAuthStatus', {
'status': isAuthenticated ? 'authenticated' : 'unauthenticated',
'userName': _user?.name ?? '',
});
} catch (e) {
// Échec silencieux si pas d'appareil Wear OS à proximité
debugPrint("Wear OS sync failed: $e");
}
}
Future<bool> login(String email, String password) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authService.login(email, password);
_isLoading = false;
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
notifyListeners();
return true;
} else {
_errorMessage = result['message'];
notifyListeners();
return false;
}
}
Future<bool> register(String name, String email, String password, String passwordConfirmation) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authService.register(name, email, password, passwordConfirmation);
_isLoading = false;
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
notifyListeners();
return true;
} else {
if (result['errors'] is Map) {
_errorMessage = (result['errors'] as Map).values.first[0];
} else {
_errorMessage = result['errors'].toString();
}
notifyListeners();
return false;
}
}
Future<void> logout() async {
await _authService.logout();
_user = null;
_syncWithWear();
notifyListeners();
}
Future<bool> updateProfile(String name, String email, {String? password}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authService.updateProfile(name, email, password: password);
_isLoading = false;
if (result['status'] == 'success') {
_user = result['user'];
_syncWithWear();
notifyListeners();
return true;
} else {
_errorMessage = result['message'];
notifyListeners();
return false;
}
}
}
+124 -124
View File
@@ -1,124 +1,124 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import 'register_screen.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
void _login() async {
if (_formKey.currentState!.validate()) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final success = await authProvider.login(
_emailController.text,
_passwordController.text,
);
if (success) {
// Rediriger vers l'accueil ou le dashboard
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Connexion réussie')),
);
Navigator.of(context).pop(); // Retourne à l'écran précédent (HomeScreen)
}
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(authProvider.errorMessage ?? 'Échec de la connexion')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Connexion CESIZen')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Bienvenue sur CESIZen',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 32),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) return 'Veuillez entrer votre email';
if (!value.contains('@')) return 'Email invalide';
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Mot de passe',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) return 'Veuillez entrer votre mot de passe';
return null;
},
),
const SizedBox(height: 24),
Consumer<AuthProvider>(
builder: (context, auth, child) {
return auth.isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _login,
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text('Se connecter'),
);
},
),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const RegisterScreen()),
);
},
child: const Text("Pas encore de compte ? S'inscrire"),
),
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import 'register_screen.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
void _login() async {
if (_formKey.currentState!.validate()) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final success = await authProvider.login(
_emailController.text,
_passwordController.text,
);
if (success) {
// Rediriger vers l'accueil ou le dashboard
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Connexion réussie')),
);
Navigator.of(context).pop(); // Retourne à l'écran précédent (HomeScreen)
}
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(authProvider.errorMessage ?? 'Échec de la connexion')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Connexion CESIZen')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Bienvenue sur CESIZen',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 32),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) return 'Veuillez entrer votre email';
if (!value.contains('@')) return 'Email invalide';
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Mot de passe',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) return 'Veuillez entrer votre mot de passe';
return null;
},
),
const SizedBox(height: 24),
Consumer<AuthProvider>(
builder: (context, auth, child) {
return auth.isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _login,
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text('Se connecter'),
);
},
),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const RegisterScreen()),
);
},
child: const Text("Pas encore de compte ? S'inscrire"),
),
],
),
),
),
);
}
}
@@ -1,267 +1,267 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../../tracker/providers/emotion_provider.dart';
import 'package:intl/intl.dart';
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
final _formKey = GlobalKey<FormState>();
late TextEditingController _nameController;
late TextEditingController _emailController;
late TextEditingController _passwordController;
late String _currentEmail;
bool _isEditing = false;
@override
void initState() {
super.initState();
final user = Provider.of<AuthProvider>(context, listen: false).user;
_currentEmail = user?.email ?? '';
_nameController = TextEditingController(text: user?.name);
_emailController = TextEditingController(text: _currentEmail);
_passwordController = TextEditingController();
_emailController.addListener(() {
if (mounted) setState(() {});
});
// Charger les émotions pour le journal
WidgetsBinding.instance.addPostFrameCallback((_) {
Provider.of<EmotionProvider>(context, listen: false).loadEmotions();
});
}
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
void _submitUpdate() async {
if (_formKey.currentState!.validate()) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final String newName = _nameController.text.trim();
final String newEmail = _emailController.text.trim();
final String? newPassword = _passwordController.text.isNotEmpty ? _passwordController.text : null;
final success = await authProvider.updateProfile(
newName,
newEmail,
password: newPassword,
);
if (mounted) {
if (success) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Profil mis à jour avec succès')),
);
setState(() {
_isEditing = false;
_currentEmail = newEmail;
_passwordController.clear();
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(authProvider.errorMessage ?? 'Erreur lors de la mise à jour')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
final authProvider = Provider.of<AuthProvider>(context);
final emotionProvider = Provider.of<EmotionProvider>(context);
final user = authProvider.user;
final bool emailChanged = _emailController.text.trim() != _currentEmail.trim();
return Scaffold(
appBar: AppBar(
title: const Text('Mon Espace Santé'),
backgroundColor: Colors.white,
elevation: 0,
actions: [
IconButton(
icon: Icon(_isEditing ? Icons.close : Icons.edit),
onPressed: () {
setState(() {
_isEditing = !_isEditing;
if (!_isEditing) {
_nameController.text = user?.name ?? '';
_emailController.text = user?.email ?? '';
_passwordController.clear();
}
});
},
)
],
),
body: SingleChildScrollView(
child: Column(
children: [
// Section Profil
Padding(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
children: [
const CircleAvatar(
radius: 50,
backgroundColor: Color(0xFF000080),
child: Icon(Icons.person, size: 50, color: Colors.white),
),
const SizedBox(height: 20),
TextFormField(
controller: _nameController,
enabled: _isEditing,
decoration: const InputDecoration(
labelText: 'Nom',
prefixIcon: Icon(Icons.person_outline),
border: OutlineInputBorder(),
),
validator: (value) => (value == null || value.trim().isEmpty) ? 'Veuillez entrer un nom' : null,
),
const SizedBox(height: 15),
TextFormField(
controller: _emailController,
enabled: _isEditing,
decoration: const InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
final email = value?.trim() ?? '';
if (email.isEmpty) return 'Veuillez entrer un email';
if (!email.contains('@')) return 'Email invalide';
return null;
},
),
if (_isEditing) ...[
const SizedBox(height: 15),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: emailChanged ? 'Mot de passe requis' : 'Nouveau mot de passe',
prefixIcon: const Icon(Icons.lock_outline),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: authProvider.isLoading ? null : _submitUpdate,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF000080),
foregroundColor: Colors.white,
minimumSize: const Size.fromHeight(50),
),
child: const Text('ENREGISTRER'),
),
],
],
),
),
),
// Section Journal Émotionnel (Le "Journal Santé")
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
color: Colors.grey.shade50,
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Journal Émotionnel',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF000080)),
),
Text('Historique de vos saisies (Mobile & Montre)', style: TextStyle(color: Colors.grey, fontSize: 12)),
],
),
),
if (emotionProvider.isLoading)
const Padding(
padding: EdgeInsets.all(20.0),
child: CircularProgressIndicator(),
)
else if (emotionProvider.entries.isEmpty)
const Padding(
padding: EdgeInsets.all(40.0),
child: Column(
children: [
Icon(Icons.history, size: 48, color: Colors.grey),
SizedBox(height: 10),
Text('Aucun historique pour le moment.', style: TextStyle(color: Colors.grey)),
],
),
)
else
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: emotionProvider.entries.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = emotionProvider.entries[index];
final dateStr = DateFormat('dd/MM/yyyy HH:mm').format(entry.createdAt);
return ListTile(
leading: _getMoodEmoji(entry.emotion),
title: Text(entry.emotion, style: const TextStyle(fontWeight: FontWeight.bold)),
subtitle: Text(entry.note ?? 'Saisie rapide'),
trailing: Text(dateStr, style: const TextStyle(fontSize: 11, color: Colors.grey)),
);
},
),
const SizedBox(height: 100), // Espace pour le scroll
],
),
),
);
}
Widget _getMoodEmoji(String mood) {
String emoji = "😐";
Color color = Colors.grey;
switch (mood) {
case 'Très bien':
emoji = "😊";
color = const Color(0xFF4CAF50);
break;
case 'Bien':
emoji = "🙂";
color = const Color(0xFF8BC34A);
break;
case 'Neutre':
emoji = "😐";
color = const Color(0xFFFFC107);
break;
case 'Pas top':
emoji = "🙁";
color = const Color(0xFFFF9800);
break;
case 'Stressé':
emoji = "😫";
color = const Color(0xFFF44336);
break;
}
return CircleAvatar(
backgroundColor: color.withOpacity(0.1),
child: Text(emoji, style: const TextStyle(fontSize: 20)),
);
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../../tracker/providers/emotion_provider.dart';
import 'package:intl/intl.dart';
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
final _formKey = GlobalKey<FormState>();
late TextEditingController _nameController;
late TextEditingController _emailController;
late TextEditingController _passwordController;
late String _currentEmail;
bool _isEditing = false;
@override
void initState() {
super.initState();
final user = Provider.of<AuthProvider>(context, listen: false).user;
_currentEmail = user?.email ?? '';
_nameController = TextEditingController(text: user?.name);
_emailController = TextEditingController(text: _currentEmail);
_passwordController = TextEditingController();
_emailController.addListener(() {
if (mounted) setState(() {});
});
// Charger les émotions pour le journal
WidgetsBinding.instance.addPostFrameCallback((_) {
Provider.of<EmotionProvider>(context, listen: false).loadEmotions();
});
}
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
void _submitUpdate() async {
if (_formKey.currentState!.validate()) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final String newName = _nameController.text.trim();
final String newEmail = _emailController.text.trim();
final String? newPassword = _passwordController.text.isNotEmpty ? _passwordController.text : null;
final success = await authProvider.updateProfile(
newName,
newEmail,
password: newPassword,
);
if (mounted) {
if (success) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Profil mis à jour avec succès')),
);
setState(() {
_isEditing = false;
_currentEmail = newEmail;
_passwordController.clear();
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(authProvider.errorMessage ?? 'Erreur lors de la mise à jour')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
final authProvider = Provider.of<AuthProvider>(context);
final emotionProvider = Provider.of<EmotionProvider>(context);
final user = authProvider.user;
final bool emailChanged = _emailController.text.trim() != _currentEmail.trim();
return Scaffold(
appBar: AppBar(
title: const Text('Mon Espace Santé'),
backgroundColor: Colors.white,
elevation: 0,
actions: [
IconButton(
icon: Icon(_isEditing ? Icons.close : Icons.edit),
onPressed: () {
setState(() {
_isEditing = !_isEditing;
if (!_isEditing) {
_nameController.text = user?.name ?? '';
_emailController.text = user?.email ?? '';
_passwordController.clear();
}
});
},
)
],
),
body: SingleChildScrollView(
child: Column(
children: [
// Section Profil
Padding(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
children: [
const CircleAvatar(
radius: 50,
backgroundColor: Color(0xFF000080),
child: Icon(Icons.person, size: 50, color: Colors.white),
),
const SizedBox(height: 20),
TextFormField(
controller: _nameController,
enabled: _isEditing,
decoration: const InputDecoration(
labelText: 'Nom',
prefixIcon: Icon(Icons.person_outline),
border: OutlineInputBorder(),
),
validator: (value) => (value == null || value.trim().isEmpty) ? 'Veuillez entrer un nom' : null,
),
const SizedBox(height: 15),
TextFormField(
controller: _emailController,
enabled: _isEditing,
decoration: const InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
final email = value?.trim() ?? '';
if (email.isEmpty) return 'Veuillez entrer un email';
if (!email.contains('@')) return 'Email invalide';
return null;
},
),
if (_isEditing) ...[
const SizedBox(height: 15),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: emailChanged ? 'Mot de passe requis' : 'Nouveau mot de passe',
prefixIcon: const Icon(Icons.lock_outline),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: authProvider.isLoading ? null : _submitUpdate,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF000080),
foregroundColor: Colors.white,
minimumSize: const Size.fromHeight(50),
),
child: const Text('ENREGISTRER'),
),
],
],
),
),
),
// Section Journal Émotionnel (Le "Journal Santé")
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
color: Colors.grey.shade50,
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Journal Émotionnel',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF000080)),
),
Text('Historique de vos saisies (Mobile & Montre)', style: TextStyle(color: Colors.grey, fontSize: 12)),
],
),
),
if (emotionProvider.isLoading)
const Padding(
padding: EdgeInsets.all(20.0),
child: CircularProgressIndicator(),
)
else if (emotionProvider.entries.isEmpty)
const Padding(
padding: EdgeInsets.all(40.0),
child: Column(
children: [
Icon(Icons.history, size: 48, color: Colors.grey),
SizedBox(height: 10),
Text('Aucun historique pour le moment.', style: TextStyle(color: Colors.grey)),
],
),
)
else
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: emotionProvider.entries.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = emotionProvider.entries[index];
final dateStr = DateFormat('dd/MM/yyyy HH:mm').format(entry.createdAt);
return ListTile(
leading: _getMoodEmoji(entry.emotion),
title: Text(entry.emotion, style: const TextStyle(fontWeight: FontWeight.bold)),
subtitle: Text(entry.note ?? 'Saisie rapide'),
trailing: Text(dateStr, style: const TextStyle(fontSize: 11, color: Colors.grey)),
);
},
),
const SizedBox(height: 100), // Espace pour le scroll
],
),
),
);
}
Widget _getMoodEmoji(String mood) {
String emoji = "😐";
Color color = Colors.grey;
switch (mood) {
case 'Très bien':
emoji = "😊";
color = const Color(0xFF4CAF50);
break;
case 'Bien':
emoji = "🙂";
color = const Color(0xFF8BC34A);
break;
case 'Neutre':
emoji = "😐";
color = const Color(0xFFFFC107);
break;
case 'Pas top':
emoji = "🙁";
color = const Color(0xFFFF9800);
break;
case 'Stressé':
emoji = "😫";
color = const Color(0xFFF44336);
break;
}
return CircleAvatar(
backgroundColor: color.withOpacity(0.1),
child: Text(emoji, style: const TextStyle(fontSize: 20)),
);
}
}
@@ -1,132 +1,132 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
class RegisterScreen extends StatefulWidget {
const RegisterScreen({super.key});
@override
State<RegisterScreen> createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
_confirmPasswordController.dispose();
super.dispose();
}
void _register() async {
if (_formKey.currentState!.validate()) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final success = await authProvider.register(
_nameController.text,
_emailController.text,
_passwordController.text,
_confirmPasswordController.text,
);
if (success) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Compte créé avec succès !')),
);
// On vide la pile et on retourne au menu principal (HomeScreen)
Navigator.of(context).popUntil((route) => route.isFirst);
}
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(authProvider.errorMessage ?? 'Échec de l\'inscription')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inscription CESIZen')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
const SizedBox(height: 20),
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Nom complet',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
validator: (value) => value == null || value.isEmpty ? 'Entrez votre nom' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
validator: (value) => value == null || !value.contains('@') ? 'Email invalide' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Mot de passe',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
validator: (value) => value == null || value.length < 8 ? '8 caractères minimum' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _confirmPasswordController,
decoration: const InputDecoration(
labelText: 'Confirmer le mot de passe',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock_outline),
),
obscureText: true,
validator: (value) {
if (value != _passwordController.text) return 'Les mots de passe ne correspondent pas';
return null;
},
),
const SizedBox(height: 24),
Consumer<AuthProvider>(
builder: (context, auth, child) {
return auth.isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _register,
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text('S\'inscrire'),
);
},
),
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
class RegisterScreen extends StatefulWidget {
const RegisterScreen({super.key});
@override
State<RegisterScreen> createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
_confirmPasswordController.dispose();
super.dispose();
}
void _register() async {
if (_formKey.currentState!.validate()) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final success = await authProvider.register(
_nameController.text,
_emailController.text,
_passwordController.text,
_confirmPasswordController.text,
);
if (success) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Compte créé avec succès !')),
);
// On vide la pile et on retourne au menu principal (HomeScreen)
Navigator.of(context).popUntil((route) => route.isFirst);
}
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(authProvider.errorMessage ?? 'Échec de l\'inscription')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inscription CESIZen')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
const SizedBox(height: 20),
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Nom complet',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
validator: (value) => value == null || value.isEmpty ? 'Entrez votre nom' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
validator: (value) => value == null || !value.contains('@') ? 'Email invalide' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Mot de passe',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
validator: (value) => value == null || value.length < 8 ? '8 caractères minimum' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _confirmPasswordController,
decoration: const InputDecoration(
labelText: 'Confirmer le mot de passe',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock_outline),
),
obscureText: true,
validator: (value) {
if (value != _passwordController.text) return 'Les mots de passe ne correspondent pas';
return null;
},
),
const SizedBox(height: 24),
Consumer<AuthProvider>(
builder: (context, auth, child) {
return auth.isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _register,
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text('S\'inscrire'),
);
},
),
],
),
),
),
);
}
}
@@ -1,130 +1,130 @@
import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../../../core/network/dio_client.dart';
import '../models/user.dart';
class AuthService {
final Dio _dio = DioClient().dio;
final FlutterSecureStorage _storage = const FlutterSecureStorage();
Future<Map<String, dynamic>> login(String email, String password) async {
try {
final response = await _dio.post('/login', data: {
'email': email,
'password': password,
});
if (response.statusCode == 200) {
String token = response.data['token'];
await _storage.write(key: 'token', value: token);
return {
'status': 'success',
'user': User.fromJson(response.data['user']),
};
}
return {'status': 'error', 'message': 'Erreur inconnue'};
} on DioException catch (e) {
return {
'status': 'error',
'message': e.response?.data['message'] ?? 'Erreur de connexion'
};
}
}
Future<Map<String, dynamic>> register(String name, String email, String password, String passwordConfirmation) async {
try {
final response = await _dio.post('/register', data: {
'name': name,
'email': email,
'password': password,
'password_confirmation': passwordConfirmation,
});
if (response.statusCode == 201) {
String token = response.data['token'];
await _storage.write(key: 'token', value: token);
return {
'status': 'success',
'user': User.fromJson(response.data['user']),
};
}
return {'status': 'error', 'message': 'Erreur inconnue'};
} on DioException catch (e) {
return {
'status': 'error',
'errors': e.response?.data['errors'] ?? 'Erreur lors de l\'inscription'
};
}
}
Future<Map<String, dynamic>> updateProfile(String name, String email, {String? password}) async {
try {
String? token = await getToken();
final Map<String, dynamic> data = {
'name': name,
'email': email,
};
if (password != null && password.isNotEmpty) {
data['current_password'] = password;
data['password'] = password;
data['password_confirmation'] = password;
}
final response = await _dio.post(
'/update-profile',
data: data,
options: Options(
headers: {
'Authorization': 'Bearer $token',
'Accept': 'application/json',
'Content-Type': 'application/json',
},
),
);
if (response.statusCode == 200) {
return {
'status': 'success',
'user': User.fromJson(response.data['user']),
};
}
return {'status': 'error', 'message': 'Erreur lors de la mise à jour'};
} on DioException catch (e) {
return {
'status': 'error',
'message': e.response?.data['message'] ?? 'Erreur lors de la modification du profil'
};
}
}
Future<Map<String, dynamic>> getProfile() async {
try {
String? token = await getToken();
if (token == null) return {'status': 'error', 'message': 'No token'};
final response = await _dio.get('/profile', options: Options(
headers: {'Authorization': 'Bearer $token'}
));
if (response.statusCode == 200) {
return {
'status': 'success',
'user': User.fromJson(response.data),
};
}
return {'status': 'error', 'message': 'Session expirée'};
} catch (e) {
return {'status': 'error', 'message': e.toString()};
}
}
Future<void> logout() async {
await _storage.delete(key: 'token');
}
Future<String?> getToken() async {
return await _storage.read(key: 'token');
}
}
import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../../../core/network/dio_client.dart';
import '../models/user.dart';
class AuthService {
final Dio _dio = DioClient().dio;
final FlutterSecureStorage _storage = const FlutterSecureStorage();
Future<Map<String, dynamic>> login(String email, String password) async {
try {
final response = await _dio.post('/login', data: {
'email': email,
'password': password,
});
if (response.statusCode == 200) {
String token = response.data['token'];
await _storage.write(key: 'token', value: token);
return {
'status': 'success',
'user': User.fromJson(response.data['user']),
};
}
return {'status': 'error', 'message': 'Erreur inconnue'};
} on DioException catch (e) {
return {
'status': 'error',
'message': e.response?.data['message'] ?? 'Erreur de connexion'
};
}
}
Future<Map<String, dynamic>> register(String name, String email, String password, String passwordConfirmation) async {
try {
final response = await _dio.post('/register', data: {
'name': name,
'email': email,
'password': password,
'password_confirmation': passwordConfirmation,
});
if (response.statusCode == 201) {
String token = response.data['token'];
await _storage.write(key: 'token', value: token);
return {
'status': 'success',
'user': User.fromJson(response.data['user']),
};
}
return {'status': 'error', 'message': 'Erreur inconnue'};
} on DioException catch (e) {
return {
'status': 'error',
'errors': e.response?.data['errors'] ?? 'Erreur lors de l\'inscription'
};
}
}
Future<Map<String, dynamic>> updateProfile(String name, String email, {String? password}) async {
try {
String? token = await getToken();
final Map<String, dynamic> data = {
'name': name,
'email': email,
};
if (password != null && password.isNotEmpty) {
data['current_password'] = password;
data['password'] = password;
data['password_confirmation'] = password;
}
final response = await _dio.post(
'/update-profile',
data: data,
options: Options(
headers: {
'Authorization': 'Bearer $token',
'Accept': 'application/json',
'Content-Type': 'application/json',
},
),
);
if (response.statusCode == 200) {
return {
'status': 'success',
'user': User.fromJson(response.data['user']),
};
}
return {'status': 'error', 'message': 'Erreur lors de la mise à jour'};
} on DioException catch (e) {
return {
'status': 'error',
'message': e.response?.data['message'] ?? 'Erreur lors de la modification du profil'
};
}
}
Future<Map<String, dynamic>> getProfile() async {
try {
String? token = await getToken();
if (token == null) return {'status': 'error', 'message': 'No token'};
final response = await _dio.get('/profile', options: Options(
headers: {'Authorization': 'Bearer $token'}
));
if (response.statusCode == 200) {
return {
'status': 'success',
'user': User.fromJson(response.data),
};
}
return {'status': 'error', 'message': 'Session expirée'};
} catch (e) {
return {'status': 'error', 'message': e.toString()};
}
}
Future<void> logout() async {
await _storage.delete(key: 'token');
}
Future<String?> getToken() async {
return await _storage.read(key: 'token');
}
}