update cart

This commit is contained in:
Phuoc Nguyen
2025-11-14 16:19:25 +07:00
parent 4738553d2e
commit aae3c9d080
30 changed files with 5954 additions and 758 deletions

View File

@@ -1,7 +1,7 @@
/// Cart Page
///
/// Shopping cart screen with items, warehouse selection, discount code,
/// and order summary matching the HTML design.
/// Shopping cart screen with selection and checkout.
/// Features expanded item list with total price at bottom.
library;
import 'package:flutter/material.dart';
@@ -19,12 +19,10 @@ import 'package:worker/features/cart/presentation/widgets/cart_item_widget.dart'
/// Cart Page
///
/// Features:
/// - AppBar with back, title (with count), and clear cart button
/// - Warehouse selection dropdown
/// - Cart items list
/// - Discount code input with apply button
/// - Order summary with breakdown
/// - Checkout button
/// - AppBar with back, title (with count), and delete button
/// - Select all section with count display
/// - Expanded cart items list with checkboxes
/// - Total price and checkout button at bottom
class CartPage extends ConsumerStatefulWidget {
const CartPage({super.key});
@@ -33,40 +31,27 @@ class CartPage extends ConsumerStatefulWidget {
}
class _CartPageState extends ConsumerState<CartPage> {
final TextEditingController _discountController = TextEditingController();
bool _isSyncing = false;
@override
void initState() {
super.initState();
// Initialize cart from API on mount
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(cartProvider.notifier).initialize();
});
}
@override
void dispose() {
_discountController.dispose();
// Force sync any pending quantity updates before leaving cart page
ref.read(cartProvider.notifier).forceSyncPendingUpdates();
super.dispose();
}
void _clearCart() {
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Xóa giỏ hàng'),
content: const Text('Bạn có chắc chắn muốn xóa toàn bộ giỏ hàng?'),
actions: [
TextButton(onPressed: () => context.pop(), child: const Text('Hủy')),
ElevatedButton(
onPressed: () {
ref.read(cartProvider.notifier).clearCart();
context.pop();
context.pop(); // Also go back from cart page
},
style: ElevatedButton.styleFrom(backgroundColor: AppColors.danger),
child: const Text('Xóa'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final cartState = ref.watch(cartProvider);
final itemCount = cartState.itemCount;
final currencyFormatter = NumberFormat.currency(
locale: 'vi_VN',
@@ -74,6 +59,9 @@ class _CartPageState extends ConsumerState<CartPage> {
decimalDigits: 0,
);
final itemCount = cartState.itemCount;
final hasSelection = cartState.selectedCount > 0;
return Scaffold(
backgroundColor: const Color(0xFFF4F6F8),
appBar: AppBar(
@@ -92,48 +80,301 @@ class _CartPageState extends ConsumerState<CartPage> {
actions: [
if (cartState.isNotEmpty)
IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.black),
onPressed: _clearCart,
tooltip: 'Xóa giỏ hàng',
icon: Icon(
Icons.delete_outline,
color: hasSelection ? AppColors.danger : AppColors.grey500,
),
onPressed: hasSelection
? () {
_showDeleteConfirmation(context, ref, cartState);
}
: null,
tooltip: 'Xóa sản phẩm đã chọn',
),
const SizedBox(width: AppSpacing.sm),
],
),
body: cartState.isEmpty
? _buildEmptyCart()
: SingleChildScrollView(
child: Column(
body: cartState.isLoading && cartState.isEmpty
? const Center(child: CircularProgressIndicator())
: cartState.errorMessage != null && cartState.isEmpty
? _buildErrorState(context, cartState.errorMessage!)
: cartState.isEmpty
? _buildEmptyCart(context)
: Column(
children: [
// Error banner if there's an error
if (cartState.errorMessage != null)
_buildErrorBanner(cartState.errorMessage!),
// Select All Section
const SizedBox(height: 8),
_buildSelectAllSection(cartState, ref),
const SizedBox(height: 8),
// Expanded Cart Items List
Expanded(
child: Stack(
children: [
ListView.builder(
itemCount: cartState.items.length,
itemBuilder: (context, index) {
return CartItemWidget(item: cartState.items[index]);
},
),
// Loading overlay
if (cartState.isLoading)
Container(
color: Colors.black.withValues(alpha: 0.1),
child: const Center(
child: CircularProgressIndicator(),
),
),
],
),
),
// Total and Checkout at Bottom
_buildBottomSection(
context,
cartState,
ref,
currencyFormatter,
hasSelection,
),
],
),
);
}
/// Build select all section
Widget _buildSelectAllSection(CartState cartState, WidgetRef ref) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16),
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Checkbox with label
GestureDetector(
onTap: () {
ref.read(cartProvider.notifier).toggleSelectAll();
},
child: Row(
children: [
_CustomCheckbox(
value: cartState.isAllSelected,
onChanged: (value) {
ref.read(cartProvider.notifier).toggleSelectAll();
},
),
const SizedBox(width: 12),
Text(
'Chọn tất cả',
style: AppTypography.titleMedium.copyWith(
fontWeight: FontWeight.w600,
),
),
],
),
),
// Selected count
Text(
'Đã chọn: ${cartState.selectedCount}/${cartState.itemCount}',
style: AppTypography.bodyMedium.copyWith(
color: AppColors.primaryBlue,
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
],
),
);
}
/// Build bottom section with total price and checkout button
Widget _buildBottomSection(
BuildContext context,
CartState cartState,
WidgetRef ref,
NumberFormat currencyFormatter,
bool hasSelection,
) {
return Container(
decoration: BoxDecoration(
color: AppColors.white,
border: const Border(
top: BorderSide(color: Color(0xFFF0F0F0), width: 2),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 10,
offset: const Offset(0, -2),
),
],
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Total Price Row
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const SizedBox(height: 8),
// Warehouse Selection
_buildWarehouseSelection(cartState.selectedWarehouse),
// Cart Items
...cartState.items.map((item) => CartItemWidget(item: item)),
const SizedBox(height: 8),
// Discount Code
_buildDiscountCodeSection(cartState),
// Order Summary
_buildOrderSummary(cartState, currencyFormatter),
const SizedBox(height: 16),
// Checkout Button
_buildCheckoutButton(cartState),
const SizedBox(height: 24),
Text(
'Tổng tạm tính (${cartState.selectedCount} sản phẩm)',
style: AppTypography.bodyMedium.copyWith(
color: AppColors.grey500,
fontSize: 14,
),
),
Text(
currencyFormatter.format(cartState.selectedTotal),
style: AppTypography.headlineSmall.copyWith(
color: AppColors.primaryBlue,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
],
),
const SizedBox(height: 16),
// Checkout Button
SizedBox(
width: double.infinity,
height: 48,
child: ElevatedButton(
onPressed: hasSelection && !_isSyncing
? () async {
// Set syncing state
setState(() {
_isSyncing = true;
});
// Force sync any pending quantity updates before checkout
await ref
.read(cartProvider.notifier)
.forceSyncPendingUpdates();
// Reset syncing state
if (mounted) {
setState(() {
_isSyncing = false;
});
// Navigate to checkout
context.push(RouteNames.checkout);
}
}
: null,
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.primaryBlue,
disabledBackgroundColor: AppColors.grey100,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 0,
),
child: _isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor:
AlwaysStoppedAnimation<Color>(AppColors.white),
),
)
: Text(
'Tiến hành đặt hàng',
style: AppTypography.labelLarge.copyWith(
color: AppColors.white,
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
),
),
],
),
),
),
);
}
/// Build error banner (shown at top when there's an error but cart has items)
Widget _buildErrorBanner(String errorMessage) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
color: AppColors.danger.withValues(alpha: 0.1),
child: Row(
children: [
const Icon(Icons.error_outline, color: AppColors.danger, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
errorMessage,
style: AppTypography.bodySmall.copyWith(color: AppColors.danger),
),
),
],
),
);
}
/// Build error state (shown when cart fails to load and is empty)
Widget _buildErrorState(BuildContext context, String errorMessage) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 64, color: AppColors.danger),
const SizedBox(height: 16),
const Text(
'Không thể tải giỏ hàng',
style: AppTypography.headlineMedium,
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
errorMessage,
style: AppTypography.bodyMedium.copyWith(color: AppColors.grey500),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: () {
ref.read(cartProvider.notifier).initialize();
},
icon: const Icon(Icons.refresh),
label: const Text('Thử lại'),
),
],
),
);
}
/// Build empty cart state
Widget _buildEmptyCart() {
Widget _buildEmptyCart(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
@@ -166,287 +407,76 @@ class _CartPageState extends ConsumerState<CartPage> {
);
}
/// Build warehouse selection card
Widget _buildWarehouseSelection(String selectedWarehouse) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Kho xuất hàng',
style: AppTypography.labelLarge.copyWith(
fontWeight: FontWeight.w600,
color: AppColors.grey900,
),
),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
initialValue: selectedWarehouse,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.grey100),
),
),
items: const [
DropdownMenuItem(
value: 'Kho Hà Nội - Nguyễn Trãi',
child: Text('Kho Hà Nội - Nguyễn Trãi'),
),
DropdownMenuItem(
value: 'Kho TP.HCM - Quận 7',
child: Text('Kho TP.HCM - Quận 7'),
),
DropdownMenuItem(
value: 'Kho Đà Nẵng - Sơn Trà',
child: Text('Kho Đà Nẵng - Sơn Trà'),
),
],
onChanged: (value) {
if (value != null) {
ref.read(cartProvider.notifier).selectWarehouse(value);
}
},
),
],
),
);
}
/// Build discount code section
Widget _buildDiscountCodeSection(CartState cartState) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Mã giảm giá',
style: AppTypography.labelLarge.copyWith(
fontWeight: FontWeight.w600,
color: AppColors.grey900,
),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextField(
controller: _discountController,
decoration: InputDecoration(
hintText: 'Nhập mã giảm giá',
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 12,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.grey100),
),
),
),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: () {
if (_discountController.text.isNotEmpty) {
ref
.read(cartProvider.notifier)
.applyDiscountCode(_discountController.text);
}
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
child: const Text('Áp dụng'),
),
],
),
// Success message for member discount
if (cartState.memberTier.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
children: [
const Icon(
Icons.check_circle,
color: AppColors.success,
size: 16,
),
const SizedBox(width: 4),
Text(
'Bạn được giảm ${cartState.memberDiscountPercent.toStringAsFixed(0)}% (hạng ${cartState.memberTier})',
style: AppTypography.bodySmall.copyWith(
color: AppColors.success,
),
),
],
),
),
],
),
);
}
/// Build order summary section
Widget _buildOrderSummary(
/// Show delete confirmation dialog
void _showDeleteConfirmation(
BuildContext context,
WidgetRef ref,
CartState cartState,
NumberFormat currencyFormatter,
) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Thông tin đơn hàng',
style: AppTypography.titleMedium.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
// Subtotal
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Tạm tính (${cartState.totalQuantity.toStringAsFixed(0)} ${cartState.items.firstOrNull?.product.unit ?? ''})',
style: AppTypography.bodyMedium,
),
Text(
currencyFormatter.format(cartState.subtotal),
style: AppTypography.bodyMedium,
),
],
),
const SizedBox(height: 12),
// Member Discount
if (cartState.memberDiscount > 0)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Giảm giá ${cartState.memberTier} (-${cartState.memberDiscountPercent.toStringAsFixed(0)}%)',
style: AppTypography.bodyMedium,
),
Text(
'-${currencyFormatter.format(cartState.memberDiscount)}',
style: AppTypography.bodyMedium.copyWith(
color: AppColors.success,
),
),
],
),
),
// Shipping Fee
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Phí vận chuyển', style: AppTypography.bodyMedium),
Text(
cartState.shippingFee > 0
? currencyFormatter.format(cartState.shippingFee)
: 'Miễn phí',
style: AppTypography.bodyMedium,
),
],
),
const Divider(height: 24),
// Total
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Tổng cộng',
style: AppTypography.titleMedium.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
currencyFormatter.format(cartState.total),
style: AppTypography.headlineSmall.copyWith(
color: AppColors.primaryBlue,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
);
}
/// Build checkout button
Widget _buildCheckoutButton(CartState cartState) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: SizedBox(
width: double.infinity,
height: 48,
child: ElevatedButton(
onPressed: cartState.isNotEmpty
? () {
context.push(RouteNames.checkout);
}
: null,
child: const Text(
'Tiến hành đặt hàng',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
),
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Xóa sản phẩm'),
content: Text(
'Bạn có chắc muốn xóa ${cartState.selectedCount} sản phẩm đã chọn?',
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: const Text('Hủy'),
),
ElevatedButton(
onPressed: () {
ref.read(cartProvider.notifier).deleteSelected();
context.pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Đã xóa sản phẩm khỏi giỏ hàng'),
backgroundColor: AppColors.success,
duration: Duration(seconds: 2),
),
);
},
style: ElevatedButton.styleFrom(backgroundColor: AppColors.danger),
child: const Text('Xóa'),
),
],
),
);
}
}
/// Custom Checkbox Widget
///
/// Matches HTML design with 22px size, 6px radius, blue when checked.
class _CustomCheckbox extends StatelessWidget {
const _CustomCheckbox({required this.value, this.onChanged});
final bool value;
final ValueChanged<bool?>? onChanged;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => onChanged?.call(!value),
child: Container(
width: 22,
height: 22,
decoration: BoxDecoration(
color: value ? AppColors.primaryBlue : AppColors.white,
border: Border.all(
color: value ? AppColors.primaryBlue : const Color(0xFFCBD5E1),
width: 2,
),
borderRadius: BorderRadius.circular(6),
),
child: value
? const Icon(
Icons.check,
size: 16,
color: AppColors.white,
)
: null,
),
);
}