This commit is contained in:
andrymodeste 2025-08-03 10:07:17 +02:00
parent 79d208b69e
commit afbdbe19e7
2 changed files with 470 additions and 352 deletions

View File

@ -2,6 +2,10 @@ import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'dart:convert'; import 'dart:convert';
import 'package:itrimobe/pages/tables.dart';
import '../layouts/main_layout.dart';
class CartPage extends StatefulWidget { class CartPage extends StatefulWidget {
final int tableId; final int tableId;
final int personne; final int personne;
@ -119,30 +123,28 @@ class _CartPageState extends State<CartPage> {
child: Text('Annuler', style: TextStyle(color: Colors.grey[600])), child: Text('Annuler', style: TextStyle(color: Colors.grey[600])),
), ),
ElevatedButton( ElevatedButton(
onPressed: onPressed: _isValidating
_isValidating ? null
? null : () {
: () { Navigator.of(context).pop();
Navigator.of(context).pop(); _validateOrder();
_validateOrder(); },
},
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.green[700], backgroundColor: Colors.green[700],
foregroundColor: Colors.white, foregroundColor: Colors.white,
), ),
child: child: _isValidating
_isValidating ? SizedBox(
? SizedBox( width: 16,
width: 16, height: 16,
height: 16, child: CircularProgressIndicator(
child: CircularProgressIndicator( strokeWidth: 2,
strokeWidth: 2, valueColor: AlwaysStoppedAnimation<Color>(
valueColor: AlwaysStoppedAnimation<Color>( Colors.white,
Colors.white,
),
), ),
) ),
: Text('Valider'), )
: Text('Valider'),
), ),
], ],
); );
@ -163,16 +165,15 @@ class _CartPageState extends State<CartPage> {
"reservation_id": 1, // Peut être null si pas de réservation "reservation_id": 1, // Peut être null si pas de réservation
"serveur": "Serveur par défaut", // Valeur par défaut comme demandé "serveur": "Serveur par défaut", // Valeur par défaut comme demandé
"commentaires": _getOrderComments(), "commentaires": _getOrderComments(),
"items": "items": _cartItems
_cartItems .map(
.map( (item) => {
(item) => { "menu_id": item.id,
"menu_id": item.id, "quantite": item.quantity,
"quantite": item.quantity, "commentaires": item.notes.isNotEmpty ? item.notes : null,
"commentaires": item.notes.isNotEmpty ? item.notes : null, },
}, )
) .toList(),
.toList(),
}; };
// Appel API pour créer la commande // Appel API pour créer la commande
@ -187,7 +188,7 @@ class _CartPageState extends State<CartPage> {
if (response.statusCode == 200 || response.statusCode == 201) { if (response.statusCode == 200 || response.statusCode == 201) {
// Succès // Succès
_updateTableStatus(); _updateTableStatus();
_showSuccessDialog(); _showSuccessDialog();
} else { } else {
// Erreur // Erreur
@ -206,15 +207,15 @@ class _CartPageState extends State<CartPage> {
String _getOrderComments() { String _getOrderComments() {
// Concaténer toutes les notes des articles pour les commentaires généraux // Concaténer toutes les notes des articles pour les commentaires généraux
List<String> allNotes = List<String> allNotes = _cartItems
_cartItems .where((item) => item.notes.isNotEmpty)
.where((item) => item.notes.isNotEmpty) .map((item) => '${item.nom}: ${item.notes}')
.map((item) => '${item.nom}: ${item.notes}') .toList();
.toList();
return allNotes.join('; '); return allNotes.join('; ');
} }
// FONCTION CORRIGÉE POUR LA NAVIGATION VERS LES TABLES
void _showSuccessDialog() { void _showSuccessDialog() {
showDialog( showDialog(
context: context, context: context,
@ -234,14 +235,13 @@ class _CartPageState extends State<CartPage> {
actions: [ actions: [
ElevatedButton( ElevatedButton(
onPressed: () { onPressed: () {
Navigator.of(context).pop(); // Fermer le dialog Navigator.of(context).pushAndRemoveUntil(
Navigator.of(context).pop(); // Retourner au menu MaterialPageRoute(
Navigator.of(context).pop(); // Retourner aux tables builder: (context) => MainLayout(child: TablesScreen()),
),
(route) => false,
);
}, },
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green[700],
foregroundColor: Colors.white,
),
child: Text('OK'), child: Text('OK'),
), ),
], ],
@ -251,17 +251,17 @@ class _CartPageState extends State<CartPage> {
} }
Future<void> _updateTableStatus() async { Future<void> _updateTableStatus() async {
try { try {
final updateResponse = await http.put( final updateResponse = await http.put(
Uri.parse('https://restaurant.careeracademy.mg/api/tables/${widget.tableId}'), Uri.parse(
headers: {'Content-Type': 'application/json'}, 'https://restaurant.careeracademy.mg/api/tables/${widget.tableId}'),
body: json.encode({"status": "occupied"}), headers: {'Content-Type': 'application/json'},
); body: json.encode({"status": "occupied"}),
} catch (e) { );
print("Erreur lors de la mise à jour du statut de la table: $e"); } catch (e) {
print("Erreur lors de la mise à jour du statut de la table: $e");
}
} }
}
void _showErrorDialog(String message) { void _showErrorDialog(String message) {
showDialog( showDialog(
@ -317,297 +317,290 @@ class _CartPageState extends State<CartPage> {
SizedBox(width: 16), SizedBox(width: 16),
], ],
), ),
body: body: _cartItems.isEmpty
_cartItems.isEmpty ? Center(
? Center( child: Column(
child: Column( mainAxisAlignment: MainAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.shopping_cart_outlined,
size: 80,
color: Colors.grey[400],
),
SizedBox(height: 16),
Text(
'Votre panier est vide',
style: TextStyle(fontSize: 18, color: Colors.grey[600]),
),
],
),
)
: Column(
children: [ children: [
// Header avec infos table Icon(
Container( Icons.shopping_cart_outlined,
width: double.infinity, size: 80,
padding: EdgeInsets.all(20), color: Colors.grey[400],
color: Colors.white,
child: Text(
'Table ${widget.tableId}${widget.personne} personne${widget.personne > 1 ? 's' : ''}',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
), ),
SizedBox(height: 16),
Text(
'Votre panier est vide',
style: TextStyle(fontSize: 18, color: Colors.grey[600]),
),
],
),
)
: Column(
children: [
// Header avec infos table
Container(
width: double.infinity,
padding: EdgeInsets.all(20),
color: Colors.white,
child: Text(
'Table ${widget.tableId}${widget.personne} personne${widget.personne > 1 ? 's' : ''}',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
),
// Liste des articles // Liste des articles
Expanded( Expanded(
child: ListView.separated( child: ListView.separated(
padding: EdgeInsets.all(16), padding: EdgeInsets.all(16),
itemCount: _cartItems.length, itemCount: _cartItems.length,
separatorBuilder: separatorBuilder: (context, index) => SizedBox(height: 12),
(context, index) => SizedBox(height: 12), itemBuilder: (context, index) {
itemBuilder: (context, index) { final item = _cartItems[index];
final item = _cartItems[index]; return Container(
return Container( padding: EdgeInsets.all(16),
padding: EdgeInsets.all(16), decoration: BoxDecoration(
decoration: BoxDecoration( color: Colors.white,
color: Colors.white, borderRadius: BorderRadius.circular(12),
borderRadius: BorderRadius.circular(12), boxShadow: [
boxShadow: [ BoxShadow(
BoxShadow( color: Colors.black.withOpacity(0.05),
color: Colors.black.withOpacity(0.05), blurRadius: 5,
blurRadius: 5, offset: Offset(0, 2),
offset: Offset(0, 2), ),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
item.nom,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () => _removeItem(index),
icon: Icon(
Icons.delete_outline,
color: Colors.red,
),
constraints: BoxConstraints(),
padding: EdgeInsets.zero,
),
],
),
Text(
'${item.prix.toStringAsFixed(2)} MGA l\'unité',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
),
),
if (item.notes.isNotEmpty) ...[
SizedBox(height: 8),
Text(
'Notes: ${item.notes}',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontStyle: FontStyle.italic,
),
), ),
], ],
), SizedBox(height: 16),
child: Column( Row(
crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Row( // Contrôles de quantité
mainAxisAlignment: Row(
MainAxisAlignment.spaceBetween, children: [
children: [ IconButton(
Expanded( onPressed: () => _updateQuantity(
child: Text( index,
item.nom, item.quantity - 1,
),
icon: Icon(Icons.remove),
style: IconButton.styleFrom(
backgroundColor: Colors.grey[200],
minimumSize: Size(40, 40),
),
),
SizedBox(width: 16),
Text(
item.quantity.toString(),
style: TextStyle( style: TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
), SizedBox(width: 16),
IconButton( IconButton(
onPressed: () => _removeItem(index), onPressed: () => _updateQuantity(
icon: Icon( index,
Icons.delete_outline, item.quantity + 1,
color: Colors.red, ),
icon: Icon(Icons.add),
style: IconButton.styleFrom(
backgroundColor: Colors.grey[200],
minimumSize: Size(40, 40),
),
), ),
constraints: BoxConstraints(), ],
padding: EdgeInsets.zero,
),
],
),
Text(
'${item.prix.toStringAsFixed(2)} MGA l\'unité',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
), ),
), // Prix total de l'article
if (item.notes.isNotEmpty) ...[
SizedBox(height: 8),
Text( Text(
'Notes: ${item.notes}', '${(item.prix * item.quantity).toStringAsFixed(2)} MGA',
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 18,
color: Colors.grey[600], fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic, color: Colors.green[700],
), ),
), ),
], ],
SizedBox(height: 16), ),
Row( ],
mainAxisAlignment: ),
MainAxisAlignment.spaceBetween, );
children: [ },
// Contrôles de quantité ),
Row( ),
children: [
IconButton( // Récapitulatif
onPressed: Container(
() => _updateQuantity( padding: EdgeInsets.all(20),
index, decoration: BoxDecoration(
item.quantity - 1, color: Colors.white,
), border: Border(top: BorderSide(color: Colors.grey[200]!)),
icon: Icon(Icons.remove), ),
style: IconButton.styleFrom( child: Column(
backgroundColor: Colors.grey[200], crossAxisAlignment: CrossAxisAlignment.start,
minimumSize: Size(40, 40), children: [
), Text(
), 'Récapitulatif',
SizedBox(width: 16), style: TextStyle(
Text( fontSize: 20,
item.quantity.toString(), fontWeight: FontWeight.bold,
style: TextStyle( ),
fontSize: 18, ),
fontWeight: FontWeight.bold, SizedBox(height: 16),
), Row(
), mainAxisAlignment: MainAxisAlignment.spaceBetween,
SizedBox(width: 16), children: [
IconButton( Text('Articles:', style: TextStyle(fontSize: 16)),
onPressed: Text(
() => _updateQuantity( _getTotalArticles().toString(),
index, style: TextStyle(fontSize: 16),
item.quantity + 1, ),
), ],
icon: Icon(Icons.add), ),
style: IconButton.styleFrom( SizedBox(height: 8),
backgroundColor: Colors.grey[200], Row(
minimumSize: Size(40, 40), mainAxisAlignment: MainAxisAlignment.spaceBetween,
), children: [
), Text('Table:', style: TextStyle(fontSize: 16)),
], Text(
), widget.tableId.toString(),
// Prix total de l'article style: TextStyle(fontSize: 16),
Text( ),
'${(item.prix * item.quantity).toStringAsFixed(2)} MGA', ],
style: TextStyle( ),
fontSize: 18, SizedBox(height: 8),
fontWeight: FontWeight.bold, Row(
color: Colors.green[700], mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Personnes:', style: TextStyle(fontSize: 16)),
Text(
widget.personne.toString(),
style: TextStyle(fontSize: 16),
),
],
),
SizedBox(height: 16),
Divider(),
SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total:',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Text(
'${_calculateTotal().toStringAsFixed(2)} MGA',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _cartItems.isNotEmpty && !_isValidating
? _showConfirmationDialog
: null,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green[700],
foregroundColor: Colors.white,
padding: EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
disabledBackgroundColor: Colors.grey[300],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_isValidating) ...[
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
), ),
), ),
], ),
), SizedBox(width: 8),
Text(
'Validation en cours...',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
] else ...[
Icon(Icons.check, size: 20),
SizedBox(width: 8),
Text(
'Valider la commande',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
],
], ],
), ),
); ),
}, ),
), ],
), ),
),
// Récapitulatif ],
Container( ),
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border(top: BorderSide(color: Colors.grey[200]!)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Récapitulatif',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Articles:', style: TextStyle(fontSize: 16)),
Text(
_getTotalArticles().toString(),
style: TextStyle(fontSize: 16),
),
],
),
SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Table:', style: TextStyle(fontSize: 16)),
Text(
widget.tableId.toString(),
style: TextStyle(fontSize: 16),
),
],
),
SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Personnes:', style: TextStyle(fontSize: 16)),
Text(
widget.personne.toString(),
style: TextStyle(fontSize: 16),
),
],
),
SizedBox(height: 16),
Divider(),
SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total:',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Text(
'${_calculateTotal().toStringAsFixed(2)} MGA',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed:
_cartItems.isNotEmpty && !_isValidating
? _showConfirmationDialog
: null,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green[700],
foregroundColor: Colors.white,
padding: EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
disabledBackgroundColor: Colors.grey[300],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_isValidating) ...[
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
),
),
),
SizedBox(width: 8),
Text(
'Validation en cours...',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
] else ...[
Icon(Icons.check, size: 20),
SizedBox(width: 8),
Text(
'Valider la commande',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
],
],
),
),
),
],
),
),
],
),
); );
} }
} }
@ -626,4 +619,4 @@ class CartItemModel {
required this.quantity, required this.quantity,
required this.notes, required this.notes,
}); });
} }

View File

@ -600,37 +600,33 @@ class OrderCard extends StatelessWidget {
// Header row // Header row
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
GestureDetector( Container(
onTap: onViewDetails, padding: const EdgeInsets.symmetric(
child: Text( horizontal: 12,
'Table ${order.tableId}', vertical: 4,
style: const TextStyle( ),
fontSize: 18, decoration: BoxDecoration(
fontWeight: FontWeight.bold, color: _getStatusColor(order.statut),
color: Colors.black87, borderRadius: BorderRadius.circular(12),
),
child: Text(
_getStatusText(order.statut),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
), ),
), const SizedBox(width: 4),
), if (order.statut == 'en_attente')
Container( IconButton(
padding: const EdgeInsets.symmetric( icon: const Icon(Icons.add_circle_outline, size: 20, color: Colors.blue),
horizontal: 12, tooltip: 'Ajouter un article',
vertical: 4, onPressed: () => _showAddItemDialog(context, order),
), ),
decoration: BoxDecoration( ],
color: _getStatusColor(order.statut),
borderRadius: BorderRadius.circular(12),
),
child: Text(
_getStatusText(order.statut),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
@ -821,6 +817,135 @@ class OrderCard extends StatelessWidget {
} }
} }
void _showAddItemDialog(BuildContext context, Order order) async {
List<MenuItem> menuItems = [];
MenuItem? selectedMenuItem;
int quantity = 1;
try {
final response = await http.get(
Uri.parse('https://restaurant.careeracademy.mg/api/menus'),
headers: {'Accept': 'application/json'},
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
final rawItems = data['data']?['menus'] ?? data['data']?['items'];
if (rawItems != null && rawItems is List) {
menuItems = rawItems.map((item) => MenuItem.fromJson(item)).toList();
} else {
throw Exception('Aucun article trouvé dans la réponse de l\'API.');
}
}
} catch (e) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Erreur: $e'),
backgroundColor: Colors.red,
));
return;
}
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return StatefulBuilder(builder: (context, setState) {
return AlertDialog(
title: const Text('Ajouter un article'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
DropdownButton<MenuItem>(
hint: const Text("Sélectionnez un article"),
value: selectedMenuItem,
isExpanded: true,
onChanged: (value) {
setState(() {
selectedMenuItem = value;
});
},
items: menuItems.map((item) {
return DropdownMenuItem<MenuItem>(
value: item,
child: Text(item.nom),
);
}).toList(),
),
const SizedBox(height: 12),
TextFormField(
initialValue: quantity.toString(),
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'Quantité'),
onChanged: (val) {
quantity = int.tryParse(val) ?? 1;
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('Annuler'),
),
ElevatedButton(
onPressed: () async {
if (selectedMenuItem == null || quantity < 1) return;
final body = {
'menu_id': selectedMenuItem!.id,
'quantite': quantity,
'commande_id': order.id,
'table_id': order.tableId,
};
print(body);
final response = await http.post(
Uri.parse('https://restaurant.careeracademy.mg/api/commandes/${order.id}/items'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body),
);
// print(response.body);
if (response.statusCode == 200 || response.statusCode == 201) {
Navigator.pop(dialogContext);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Article ajouté à la commande"),
backgroundColor: Colors.green,
));
} else {
Navigator.pop(dialogContext);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Erreur ajout article: ${response.body}"),
backgroundColor: Colors.red,
));
}
},
child: const Text('Ajouter'),
)
],
);
});
},
);
}
class MenuItem {
final int id;
final String nom;
MenuItem({required this.id, required this.nom});
factory MenuItem.fromJson(Map<String, dynamic> json) {
return MenuItem(
id: json['id'],
nom: json['nom'],
);
}
}
// Updated Order model to include items // Updated Order model to include items
class Order { class Order {
final int id; final int id;