You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
347 lines
13 KiB
347 lines
13 KiB
import 'dart:io';
|
|
import 'package:intl/intl.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:quantity_input/quantity_input.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:youmazgestion/Views/particles.dart' show ParticleBackground;
|
|
import 'package:youmazgestion/Views/produitsCard.dart';
|
|
import 'Components/appDrawer.dart';
|
|
import 'Components/app_bar.dart';
|
|
import 'Components/cartItem.dart';
|
|
import 'Models/produit.dart';
|
|
import 'Services/OrderDatabase.dart';
|
|
import 'Services/productDatabase.dart';
|
|
import 'Views/ticketPage.dart';
|
|
import 'controller/userController.dart';
|
|
import 'my_app.dart';
|
|
import 'Services/workDatabase.dart';
|
|
|
|
class AccueilPage extends StatefulWidget {
|
|
const AccueilPage({super.key});
|
|
|
|
@override
|
|
_AccueilPageState createState() => _AccueilPageState();
|
|
}
|
|
|
|
class _AccueilPageState extends State<AccueilPage> {
|
|
final UserController userController = Get.put(UserController());
|
|
final ProductDatabase productDatabase = ProductDatabase();
|
|
late Future<Map<String, List<Product>>> productsFuture;
|
|
final OrderDatabase orderDatabase = OrderDatabase.instance;
|
|
final WorkDatabase workDatabase = WorkDatabase.instance;
|
|
String? username;
|
|
String? role;
|
|
DateTime? startDate;
|
|
|
|
int orderId = 0;
|
|
List<CartItem> selectedProducts = [];
|
|
int selectedQuantity = 1;
|
|
double totalCartPrice = 0;
|
|
double amountPaid = 0;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
initorder();
|
|
initwork();
|
|
loadUserData();
|
|
productsFuture = _initDatabaseAndFetchProducts();
|
|
}
|
|
|
|
Future<void> loadUserData() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
setState(() {
|
|
username = prefs.getString('username') ?? 'Nom inconnu';
|
|
role = prefs.getString('role') ?? 'Rôle inconnu';
|
|
});
|
|
}
|
|
|
|
Future<void> saveOrderToDatabase() async {
|
|
final totalPrice = calculateTotalPrice();
|
|
final dateTime = DateTime.now().toString();
|
|
String user = userController.username;
|
|
|
|
orderId = await orderDatabase.insertOrder(
|
|
totalPrice, dateTime, MyApp.startDate!, user);
|
|
|
|
for (final cartItem in selectedProducts) {
|
|
final product = cartItem.product;
|
|
final quantity = cartItem.quantity;
|
|
final price = product.price * quantity;
|
|
|
|
await orderDatabase.insertOrderItem(
|
|
orderId, product.name, quantity, price);
|
|
|
|
final updatedStock = product.stock! - quantity;
|
|
await productDatabase.updateStock(product.id!, updatedStock);
|
|
}
|
|
showTicketPage();
|
|
}
|
|
|
|
Future<Map<String, List<Product>>> _initDatabaseAndFetchProducts() async {
|
|
await productDatabase.initDatabase();
|
|
final categories = await productDatabase.getCategories();
|
|
final productsByCategory = <String, List<Product>>{};
|
|
|
|
categories.sort();
|
|
|
|
for (final categoryName in categories) {
|
|
final products =
|
|
await productDatabase.getProductsByCategory(categoryName);
|
|
productsByCategory[categoryName] = products;
|
|
}
|
|
|
|
return productsByCategory;
|
|
}
|
|
|
|
void initorder() async {
|
|
await orderDatabase.initDatabase();
|
|
}
|
|
|
|
void initwork() async {
|
|
await workDatabase.initDatabase();
|
|
}
|
|
|
|
double calculateTotalPrice() {
|
|
double totalPrice = 0;
|
|
for (final cartItem in selectedProducts) {
|
|
totalPrice += cartItem.product.price * cartItem.quantity;
|
|
}
|
|
return totalPrice;
|
|
}
|
|
|
|
void addToCartWithDetails(Product product, int quantity) {
|
|
setState(() {
|
|
final existingCartItem = selectedProducts.firstWhere(
|
|
(cartItem) => cartItem.product.id == product.id,
|
|
orElse: () => CartItem(product, 0),
|
|
);
|
|
if (existingCartItem.quantity == 0) {
|
|
selectedProducts.add(CartItem(product, quantity));
|
|
} else {
|
|
existingCartItem.quantity += quantity;
|
|
}
|
|
});
|
|
|
|
Get.snackbar(
|
|
'Produit ajouté',
|
|
'${product.name} (x$quantity) ajouté au panier',
|
|
snackPosition: SnackPosition.TOP,
|
|
duration: const Duration(seconds: 1),
|
|
backgroundColor: Colors.green,
|
|
colorText: Colors.white,
|
|
);
|
|
}
|
|
|
|
void showTicketPage() {
|
|
final double totalCartPrice = calculateTotalPrice();
|
|
|
|
if (selectedProducts.isNotEmpty) {
|
|
if (amountPaid >= totalCartPrice) {
|
|
Get.offAll(TicketPage(
|
|
businessName: 'Youmaz',
|
|
businessAddress:
|
|
'quartier escale, Diourbel, Sénégal, en face de Sonatel',
|
|
businessPhoneNumber: '77 446 92 68',
|
|
cartItems: selectedProducts,
|
|
totalCartPrice: totalCartPrice,
|
|
amountPaid: amountPaid,
|
|
));
|
|
} else {
|
|
Get.snackbar(
|
|
'Paiement incomplet',
|
|
'Le montant payé est insuffisant.',
|
|
snackPosition: SnackPosition.BOTTOM,
|
|
duration: const Duration(seconds: 3),
|
|
backgroundColor: Colors.red,
|
|
colorText: Colors.white,
|
|
);
|
|
}
|
|
} else {
|
|
Get.snackbar(
|
|
'Panier vide',
|
|
'Ajoutez des produits avant de passer commande.',
|
|
snackPosition: SnackPosition.BOTTOM,
|
|
duration: const Duration(seconds: 3),
|
|
backgroundColor: Colors.red,
|
|
colorText: Colors.white,
|
|
);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: const CustomAppBar(title: "Accueil"),
|
|
drawer: CustomDrawer(),
|
|
body: ParticleBackground(
|
|
child: Container(
|
|
decoration: const BoxDecoration(
|
|
gradient: LinearGradient(
|
|
begin: Alignment.topLeft,
|
|
end: Alignment.bottomRight,
|
|
colors: [Colors.white, Color.fromARGB(255, 4, 54, 95)],
|
|
),
|
|
),
|
|
child: FutureBuilder<Map<String, List<Product>>>(
|
|
future: productsFuture,
|
|
builder: (context, snapshot) {
|
|
if (snapshot.connectionState == ConnectionState.waiting) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
} else if (snapshot.hasError) {
|
|
return const Center(child: Text("Erreur de chargement"));
|
|
} else if (snapshot.hasData) {
|
|
final productsByCategory = snapshot.data!;
|
|
final categories = productsByCategory.keys.toList();
|
|
|
|
if (!MyApp.isRegisterOpen) {
|
|
return Column(
|
|
children: [
|
|
Text('Bienvenue $username ! (Rôle: $role)'),
|
|
Center(
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
setState(() {
|
|
MyApp.isRegisterOpen = true;
|
|
String formattedDate =
|
|
DateFormat('yyyy-MM-dd').format(DateTime.now());
|
|
startDate =
|
|
DateFormat('yyyy-MM-dd').parse(formattedDate);
|
|
MyApp.startDate = startDate;
|
|
workDatabase.insertDate(formattedDate);
|
|
});
|
|
},
|
|
child: const Text('Démarrer la caisse'),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
} else {
|
|
return Row(
|
|
children: [
|
|
Expanded(
|
|
flex: 3,
|
|
child: ListView.builder(
|
|
itemCount: categories.length,
|
|
itemBuilder: (context, index) {
|
|
final category = categories[index];
|
|
final products = productsByCategory[category]!;
|
|
|
|
return Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(10.0),
|
|
child: Text(
|
|
category,
|
|
style: const TextStyle(
|
|
fontSize: 22,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
GridView.builder(
|
|
gridDelegate:
|
|
const SliverGridDelegateWithFixedCrossAxisCount(
|
|
crossAxisCount: 4,
|
|
childAspectRatio: 1,
|
|
),
|
|
shrinkWrap: true,
|
|
physics: const NeverScrollableScrollPhysics(),
|
|
itemCount: products.length,
|
|
itemBuilder: (context, index) {
|
|
final product = products[index];
|
|
return ProductCard(
|
|
product: product,
|
|
onAddToCart: (product, quantity) {
|
|
addToCartWithDetails(product, quantity);
|
|
},
|
|
);
|
|
},
|
|
),
|
|
],
|
|
);
|
|
},
|
|
),
|
|
),
|
|
Expanded(
|
|
flex: 1,
|
|
child: Container(
|
|
color: Colors.grey[200],
|
|
padding: const EdgeInsets.all(16),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
const Text(
|
|
'Panier',
|
|
style: TextStyle(
|
|
fontSize: 20,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
Expanded(
|
|
child: selectedProducts.isEmpty
|
|
? const Center(
|
|
child: Text("Votre panier est vide"),
|
|
)
|
|
: ListView.builder(
|
|
itemCount: selectedProducts.length,
|
|
itemBuilder: (context, index) {
|
|
final cartItem = selectedProducts[index];
|
|
return ListTile(
|
|
title: Text(cartItem.product.name),
|
|
subtitle: Text(
|
|
'${cartItem.product.price} FCFA x ${cartItem.quantity}'),
|
|
trailing: IconButton(
|
|
icon: const Icon(Icons.delete),
|
|
onPressed: () {
|
|
setState(() {
|
|
selectedProducts.removeAt(index);
|
|
});
|
|
},
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
Text(
|
|
'Total: ${calculateTotalPrice().toStringAsFixed(2)} FCFA',
|
|
style: const TextStyle(
|
|
fontSize: 18,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
TextField(
|
|
keyboardType: TextInputType.number,
|
|
decoration: const InputDecoration(
|
|
labelText: 'Montant payé',
|
|
),
|
|
onChanged: (value) {
|
|
amountPaid = double.tryParse(value) ?? 0;
|
|
},
|
|
),
|
|
ElevatedButton(
|
|
onPressed: saveOrderToDatabase,
|
|
child: const Text('Valider la commande'),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
} else {
|
|
return const Center(child: Text("Aucun produit disponible"));
|
|
}
|
|
},
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|