From 3c07458967149688701aa8f586363e151b4df063 Mon Sep 17 00:00:00 2001 From: andrymodeste Date: Sat, 9 Aug 2025 18:25:54 +0200 Subject: [PATCH] push 09082025 soir --- lib/pages/commande_item_validation.dart | 276 +++++++++++++++--------- 1 file changed, 175 insertions(+), 101 deletions(-) diff --git a/lib/pages/commande_item_validation.dart b/lib/pages/commande_item_validation.dart index bc0b9cb..0a9d483 100644 --- a/lib/pages/commande_item_validation.dart +++ b/lib/pages/commande_item_validation.dart @@ -2,6 +2,8 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:intl/intl.dart'; +import '../services/pdf_impression_commande.dart'; +import 'commandes_screen.dart'; class ValidateAddItemsPage extends StatefulWidget { final int commandeId; @@ -237,17 +239,15 @@ class _ValidateAddItemsPageState extends State { body: json.encode(body), ); - if (response.statusCode == 200 || response.statusCode == 201) { final responseData = json.decode(response.body); - print(responseData); - + if (responseData['success'] == true) { - _showSuccessDialog(); + // Récupérer les détails de la commande mise à jour pour l'impression + await _getUpdatedOrderAndPrint(); } else { throw Exception('API returned success: false'); } - Navigator.pushReplacementNamed(context, '/commandes'); } else { throw Exception('Failed to add items: ${response.statusCode}'); } @@ -260,6 +260,174 @@ class _ValidateAddItemsPageState extends State { } } + // Nouvelle méthode pour récupérer la commande mise à jour et imprimer + Future _getUpdatedOrderAndPrint() async { + try { + // Récupérer les détails mis à jour de la commande + final response = await http.get( + Uri.parse( + 'https://restaurant.careeracademy.mg/api/commandes/${widget.commandeId}', + ), + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + }, + ); + + if (response.statusCode == 200) { + final responseData = json.decode(response.body); + + if (responseData['success'] == true && responseData['data'] != null) { + // Créer l'objet Order à partir des données mises à jour + final order = Order.fromJson(responseData['data']); + + // Afficher le dialog de succès avec impression + _showSuccessDialogWithPrint(order); + } else { + // Si on ne peut pas récupérer la commande mise à jour, afficher le dialog sans impression + _showSuccessDialog(); + } + } else { + // Si erreur, afficher le dialog simple + _showSuccessDialog(); + } + } catch (e) { + print('Erreur lors de la récupération de la commande mise à jour: $e'); + // En cas d'erreur, afficher le dialog simple + _showSuccessDialog(); + } + } + + // Nouveau dialog de succès avec option d'impression + void _showSuccessDialogWithPrint(Order order) { + showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext context) { + return AlertDialog( + title: Row( + children: [ + Icon(Icons.check_circle, color: Colors.green[700]), + SizedBox(width: 8), + Text('Articles ajoutés'), + ], + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Les nouveaux articles ont été ajoutés à la commande avec succès !', + ), + SizedBox(height: 16), + Text( + 'Voulez-vous imprimer la commande mise à jour ?', + style: TextStyle(fontWeight: FontWeight.w600), + ), + ], + ), + actions: [ + TextButton( + onPressed: () { + // Fermer le dialog et retourner sans impression + Navigator.of(context).pop(); + _navigateBackWithSuccess(); + }, + child: Text('Non merci', style: TextStyle(color: Colors.grey[600])), + ), + ElevatedButton( + onPressed: () { + // Fermer le dialog et imprimer + Navigator.of(context).pop(); + _printAndNavigateBack(order); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.green[700], + foregroundColor: Colors.white, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.print, size: 16), + SizedBox(width: 4), + Text('Imprimer'), + ], + ), + ), + ], + ); + }, + ); + } + + // Méthode pour imprimer et naviguer + Future _printAndNavigateBack(Order order) async { + // Afficher un indicateur de chargement + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + content: Row( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(), + SizedBox(width: 16), + Text('Impression en cours...'), + ], + ), + ), + ); + + try { + // Lancer l'impression avec feedback + await printOrderWithFeedback(order, (message, isSuccess) { + print('$message - Success: $isSuccess'); + }); + + // Fermer le dialog d'impression + Navigator.of(context).pop(); + + // Afficher un message de succès + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Commande imprimée avec succès'), + backgroundColor: Colors.green[700], + duration: Duration(seconds: 2), + ), + ); + + // Attendre un peu puis naviguer + await Future.delayed(Duration(milliseconds: 500)); + _navigateBackWithSuccess(); + + } catch (e) { + // Fermer le dialog d'impression + Navigator.of(context).pop(); + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Erreur d\'impression: ${e.toString()}'), + backgroundColor: Colors.orange, + duration: Duration(seconds: 3), + ), + ); + + // Naviguer quand même + await Future.delayed(Duration(milliseconds: 500)); + _navigateBackWithSuccess(); + } + } + + // Méthode pour naviguer avec succès + void _navigateBackWithSuccess() { + Navigator.of(context).pop({ + 'success': true, + 'shouldReload': true, + 'message': 'Articles ajoutés avec succès à la commande ${widget.numeroCommande}' + }); + } + + // Ancien dialog de succès (sans impression) - garde comme fallback void _showSuccessDialog() { showDialog( context: context, @@ -279,15 +447,8 @@ class _ValidateAddItemsPageState extends State { actions: [ ElevatedButton( onPressed: () { - // Fermer le dialog Navigator.of(context).pop(); - - // Retourner à la page précédente avec un indicateur de succès et de rechargement - Navigator.of(context).pop({ - 'success': true, - 'shouldReload': true, - 'message': 'Articles ajoutés avec succès à la commande ${widget.numeroCommande}' - }); + _navigateBackWithSuccess(); }, style: ElevatedButton.styleFrom( backgroundColor: Colors.green[700], @@ -720,91 +881,4 @@ class CartItemModel { required this.quantity, required this.notes, }); -} - -/* -=============================================== -UTILISATION DANS LA PAGE QUI APPELLE ValidateAddItemsPage -=============================================== - -// Exemple d'utilisation dans votre page précédente : - -class CommandeDetailsPage extends StatefulWidget { - // ... vos propriétés -} - -class _CommandeDetailsPageState extends State { - // ... vos variables d'état - bool _isLoading = false; - - // Méthode pour naviguer vers ValidateAddItemsPage - Future _navigateToValidateAddItems() async { - final result = await Navigator.push( - context, - MaterialPageRoute( - builder: (context) => ValidateAddItemsPage( - commandeId: widget.commandeId, - numeroCommande: widget.numeroCommande, - newItems: selectedItems, // vos articles sélectionnés - commandeDetails: commandeDetails, // détails de la commande - ), - ), - ); - - // Vérifier si un rechargement est nécessaire - if (result != null && result is Map && result['shouldReload'] == true) { - // Afficher un message de succès - if (result['message'] != null) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(result['message']), - backgroundColor: Colors.green[700], - duration: Duration(seconds: 3), - ), - ); - } - - // Recharger les données de la commande - await _refreshCommandeData(); - } - } - - // Méthode pour recharger les données - Future _refreshCommandeData() async { - setState(() { - _isLoading = true; - }); - - try { - // Votre logique de rechargement des données ici - // Par exemple : - // await _loadCommandeDetails(); - // await _loadCommandeItems(); - - print('🔄 Données rechargées avec succès'); - } catch (e) { - print('❌ Erreur lors du rechargement : $e'); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Erreur lors du rechargement des données'), - backgroundColor: Colors.red, - ), - ); - } finally { - setState(() { - _isLoading = false; - }); - } - } - - @override - Widget build(BuildContext context) { - return Scaffold( - // ... votre UI - body: _isLoading - ? Center(child: CircularProgressIndicator()) - : // ... votre contenu normal - ); - } -} -*/ \ No newline at end of file +} \ No newline at end of file