second commit

This commit is contained in:
2026-07-29 11:41:53 +05:30
parent fcccf22bac
commit d72522e737
211 changed files with 19260 additions and 0 deletions

27
lib/app/app.dart Normal file
View File

@@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/constants/app_constants.dart';
import '../core/router/app_router.dart';
import '../core/theme/app_theme.dart';
class NearlePosApp extends ConsumerWidget {
const NearlePosApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp.router(
title: AppConstants.appName,
debugShowCheckedModeBanner: false,
theme: AppTheme.light,
routerConfig: ref.watch(routerProvider),
builder: (context, child) {
// A POS runs on fixed hardware; ignore OS font scaling so the dense
// billing panel can never overflow.
return MediaQuery.withNoTextScaling(
child: child ?? const SizedBox.shrink(),
);
},
);
}
}

91
lib/app/providers.dart Normal file
View File

@@ -0,0 +1,91 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/services/receipt_service.dart';
import '../core/services/sound_service.dart';
import '../data/datasources/local_store.dart';
import '../data/repositories/customer_repository_impl.dart';
import '../data/repositories/product_repository_impl.dart';
import '../data/datasources/remote_catalogue_source.dart';
import '../data/repositories/sync_repository_impl.dart';
import '../data/repositories/transaction_repository_impl.dart';
import '../domain/repositories/customer_repository.dart';
import '../domain/repositories/product_repository.dart';
import '../domain/repositories/sync_repository.dart';
import '../domain/repositories/transaction_repository.dart';
import '../domain/usecases/checkout_sale.dart';
/// Root data source. Overridden in tests with an in-memory double.
final localStoreProvider = Provider<LocalStore>((ref) => LocalStore.instance);
// ---------------------------------------------------------- Repositories
final productRepositoryProvider = Provider<ProductRepository>(
(ref) => ProductRepositoryImpl(ref.watch(localStoreProvider)),
);
final customerRepositoryProvider = Provider<CustomerRepository>(
(ref) => CustomerRepositoryImpl(ref.watch(localStoreProvider)),
);
final transactionRepositoryProvider = Provider<TransactionRepository>(
(ref) => TransactionRepositoryImpl(ref.watch(localStoreProvider)),
);
/// Simulated back-office endpoints. Held as singletons so the offline toggle
/// in Settings affects every call.
final remoteCatalogueProvider =
Provider<RemoteCatalogueSource>((ref) => RemoteCatalogueSource());
final remoteReportSinkProvider =
Provider<RemoteReportSink>((ref) => RemoteReportSink());
final syncRepositoryProvider = Provider<SyncRepository>(
(ref) => SyncRepositoryImpl(
ref.watch(localStoreProvider),
ref.watch(remoteCatalogueProvider),
ref.watch(remoteReportSinkProvider),
),
);
// ------------------------------------------------------------- Use cases
final checkoutSaleProvider = Provider<CheckoutSale>(
(ref) => CheckoutSale(
productRepository: ref.watch(productRepositoryProvider),
customerRepository: ref.watch(customerRepositoryProvider),
transactionRepository: ref.watch(transactionRepositoryProvider),
),
);
// -------------------------------------------------------------- Services
final soundServiceProvider =
Provider<SoundService>((ref) => SoundService.instance);
final receiptServiceProvider =
Provider<ReceiptService>((ref) => ReceiptService.instance);
// --------------------------------------------------------------- Session
class CashierSession {
const CashierSession({
required this.name,
required this.role,
required this.terminalId,
});
final String name;
final String role;
final String terminalId;
}
final cashierSessionProvider = StateProvider<CashierSession>(
(ref) => const CashierSession(
name: 'Suriya',
role: 'ADMIN',
terminalId: 'TERM-01',
),
);
/// Ticks once a minute to drive the header clock without rebuilding on every
/// frame.
final clockProvider = StreamProvider<DateTime>((ref) async* {
yield DateTime.now();
yield* Stream.periodic(const Duration(seconds: 20), (_) => DateTime.now());
});

View File

@@ -0,0 +1,49 @@
/// Application-wide configuration constants.
class AppConstants {
const AppConstants._();
static const String appName = 'Nearle POS';
static const String storeName = 'Nearle Daily';
static const String storeAddress = '12 Gandhipuram Main Rd, Coimbatore 641012';
static const String storeGstin = '33ABCDE1234F1Z5';
static const String storePhone = '+91 90000 12345';
static const String currencySymbol = '\u20B9';
static const String locale = 'en_IN';
/// Standard GST slab applied when a product does not declare its own.
static const double defaultGstRate = 0.18;
/// One loyalty point is earned per this many rupees of net sale value.
static const double loyaltyRupeesPerPoint = 10;
/// Rupee value of a single loyalty point when redeemed.
static const double loyaltyPointValue = 0.25;
static const int mobileNumberLength = 10;
/// Barcode scanners emit keystrokes fast; anything slower is human typing.
static const Duration barcodeScanTimeout = Duration(milliseconds: 120);
static const int minBarcodeLength = 6;
/// Idle time after a completed sale before the terminal resets itself.
static const Duration postSaleResetDelay = Duration(seconds: 3);
static const int lowStockThreshold = 10;
static const int maxParkedBills = 20;
static const int maxCartQuantityPerLine = 999;
}
/// Hive box names.
class StorageKeys {
const StorageKeys._();
static const String products = 'box_products';
static const String customers = 'box_customers';
static const String transactions = 'box_transactions';
static const String parkedBills = 'box_parked_bills';
static const String settings = 'box_settings';
static const String cashierName = 'cashier_name';
static const String cashierRole = 'cashier_role';
static const String terminalId = 'terminal_id';
}

View File

@@ -0,0 +1,13 @@
/// Typed references to bundled assets.
///
/// Only sounds are bundled: product imagery uses emoji glyphs and the welcome
/// artwork is painted in code, so there are no raster or SVG assets to ship.
class AssetPaths {
const AssetPaths._();
static const String _snd = 'assets/sounds';
static const String beepSuccess = '$_snd/beep_success.wav';
static const String beepError = '$_snd/beep_error.wav';
static const String chargeComplete = '$_snd/charge_complete.wav';
}

View File

@@ -0,0 +1,140 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../domain/entities/transaction.dart';
import '../../presentation/auth/providers/auth_controller.dart';
import '../../presentation/auth/screens/login_screen.dart';
import '../../presentation/customer/screens/customer_registration_screen.dart';
import '../../presentation/customer/screens/existing_customer_screen.dart';
import '../../presentation/payment/screens/payment_screen.dart';
import '../../presentation/pos/screens/pos_dashboard_screen.dart';
import '../../presentation/receipt/screens/receipt_screen.dart';
import '../../presentation/welcome/screens/welcome_screen.dart';
class AppRoutes {
const AppRoutes._();
static const String login = '/login';
static const String welcome = '/';
static const String registerCustomer = '/customer/new';
static const String existingCustomer = '/customer/find';
static const String pos = '/pos';
static const String payment = '/pos/payment';
static const String receipt = '/pos/receipt';
}
/// Router with an authentication guard.
///
/// Every route except [AppRoutes.login] requires a signed-in store, and an
/// already-signed-in terminal is bounced away from the login screen.
final routerProvider = Provider<GoRouter>((ref) {
// GoRouter re-evaluates `redirect` whenever this notifier fires.
final authChanged = ValueNotifier<bool>(
ref.read(authControllerProvider).isAuthenticated,
);
ref.listen<AuthState>(
authControllerProvider,
(_, next) => authChanged.value = next.isAuthenticated,
);
ref.onDispose(authChanged.dispose);
return GoRouter(
initialLocation: AppRoutes.login,
refreshListenable: authChanged,
debugLogDiagnostics: false,
redirect: (context, state) {
final signedIn = ref.read(authControllerProvider).isAuthenticated;
final atLogin = state.matchedLocation == AppRoutes.login;
if (!signedIn) return atLogin ? null : AppRoutes.login;
if (atLogin) return AppRoutes.welcome;
return null;
},
routes: [
GoRoute(
path: AppRoutes.login,
name: 'login',
pageBuilder: (context, state) => _fade(state, const LoginScreen()),
),
GoRoute(
path: AppRoutes.welcome,
name: 'welcome',
pageBuilder: (context, state) => _fade(state, const WelcomeScreen()),
),
GoRoute(
path: AppRoutes.registerCustomer,
name: 'registerCustomer',
pageBuilder: (context, state) => _slide(
state,
CustomerRegistrationScreen(
prefillMobile: state.uri.queryParameters['mobile'],
),
),
),
GoRoute(
path: AppRoutes.existingCustomer,
name: 'existingCustomer',
pageBuilder: (context, state) =>
_slide(state, const ExistingCustomerScreen()),
),
GoRoute(
path: AppRoutes.pos,
name: 'pos',
pageBuilder: (context, state) =>
_fade(state, const PosDashboardScreen()),
routes: [
GoRoute(
path: 'payment',
name: 'payment',
pageBuilder: (context, state) =>
_slide(state, const PaymentScreen()),
),
GoRoute(
path: 'receipt',
name: 'receipt',
pageBuilder: (context, state) => _fade(
state,
ReceiptScreen(transaction: state.extra! as SaleTransaction),
),
),
],
),
],
errorBuilder: (context, state) => Scaffold(
body: Center(child: Text('Route not found: ${state.uri}')),
),
);
});
CustomTransitionPage<void> _fade(GoRouterState state, Widget child) {
return CustomTransitionPage(
key: state.pageKey,
child: child,
transitionDuration: const Duration(milliseconds: 220),
transitionsBuilder: (_, animation, __, child) =>
FadeTransition(opacity: animation, child: child),
);
}
CustomTransitionPage<void> _slide(GoRouterState state, Widget child) {
return CustomTransitionPage(
key: state.pageKey,
child: child,
transitionDuration: const Duration(milliseconds: 260),
transitionsBuilder: (_, animation, __, child) {
final curved =
CurvedAnimation(parent: animation, curve: Curves.easeOutCubic);
return FadeTransition(
opacity: curved,
child: SlideTransition(
position: Tween<Offset>(
begin: const Offset(0, 0.03),
end: Offset.zero,
).animate(curved),
child: child,
),
);
},
);
}

View File

@@ -0,0 +1,91 @@
import 'dart:async';
import 'package:flutter/services.dart';
import '../constants/app_constants.dart';
/// Detects hardware barcode scanners that emulate a keyboard.
///
/// Such scanners emit an entire code in a few milliseconds and terminate it
/// with Enter. We buffer raw key events and only treat the buffer as a scan
/// when the characters arrived faster than a human could type — that way the
/// cashier can still type into the same field by hand.
class BarcodeService {
BarcodeService({this.onScan, this.onManualKey});
final void Function(String code)? onScan;
final VoidCallback? onManualKey;
final StringBuffer _buffer = StringBuffer();
DateTime? _lastKeyAt;
Timer? _flushTimer;
bool _attached = false;
void attach() {
if (_attached) return;
HardwareKeyboard.instance.addHandler(_handleKey);
_attached = true;
}
void detach() {
if (!_attached) return;
HardwareKeyboard.instance.removeHandler(_handleKey);
_flushTimer?.cancel();
_attached = false;
}
bool _handleKey(KeyEvent event) {
if (event is! KeyDownEvent) return false;
final now = DateTime.now();
final gap = _lastKeyAt == null
? Duration.zero
: now.difference(_lastKeyAt!);
_lastKeyAt = now;
// A long pause means a new entry started; discard whatever was buffered.
if (gap > AppConstants.barcodeScanTimeout) {
_buffer.clear();
}
if (event.logicalKey == LogicalKeyboardKey.enter ||
event.logicalKey == LogicalKeyboardKey.numpadEnter) {
return _flush();
}
final char = event.character;
if (char == null || char.trim().isEmpty) return false;
if (!RegExp(r'^[0-9A-Za-z\-]$').hasMatch(char)) return false;
_buffer.write(char);
_scheduleFlush();
return false;
}
/// Some scanners are not configured to send a terminating Enter, so we also
/// flush on a short idle window.
void _scheduleFlush() {
_flushTimer?.cancel();
_flushTimer = Timer(
AppConstants.barcodeScanTimeout * 2,
() => _flush(),
);
}
bool _flush() {
_flushTimer?.cancel();
final code = _buffer.toString().trim();
_buffer.clear();
if (code.length >= AppConstants.minBarcodeLength) {
onScan?.call(code);
return true;
}
if (code.isNotEmpty) onManualKey?.call();
return false;
}
void dispose() => detach();
}

View File

@@ -0,0 +1,335 @@
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
import '../../domain/entities/transaction.dart';
import '../constants/app_constants.dart';
import '../utils/formatters.dart';
/// Builds and prints an 80mm thermal GST invoice.
class ReceiptService {
ReceiptService._();
static final ReceiptService instance = ReceiptService._();
/// 80mm roll with a small safety margin.
static const double _rollWidth = 78 * PdfPageFormat.mm;
Future<Uint8List> build(SaleTransaction txn) async {
final doc = pw.Document(title: txn.invoiceNumber);
final font = await PdfGoogleFonts.interRegular();
final bold = await PdfGoogleFonts.interSemiBold();
final cart = txn.cart;
doc.addPage(
pw.Page(
pageFormat: PdfPageFormat(
_rollWidth,
double.infinity,
marginAll: 6 * PdfPageFormat.mm,
),
theme: pw.ThemeData.withFont(base: font, bold: bold),
build: (context) => pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.stretch,
children: [
_header(txn),
_divider(),
_meta(txn),
_divider(),
_itemsTable(txn),
_divider(),
_totals(txn),
_divider(),
_taxSummary(txn),
_divider(),
_payments(txn),
if (cart.customer != null) ...[
_divider(),
_loyalty(txn),
],
pw.SizedBox(height: 8),
_footer(txn),
],
),
),
);
return doc.save();
}
// ------------------------------------------------------------- Sections
pw.Widget _header(SaleTransaction txn) => pw.Column(children: [
pw.Text(
AppConstants.storeName.toUpperCase(),
style: pw.TextStyle(fontSize: 15, fontWeight: pw.FontWeight.bold),
textAlign: pw.TextAlign.center,
),
pw.SizedBox(height: 2),
pw.Text(
AppConstants.storeAddress,
style: const pw.TextStyle(fontSize: 7),
textAlign: pw.TextAlign.center,
),
pw.Text(
'GSTIN: ${AppConstants.storeGstin} | ${AppConstants.storePhone}',
style: const pw.TextStyle(fontSize: 7),
textAlign: pw.TextAlign.center,
),
pw.SizedBox(height: 4),
pw.Text(
'TAX INVOICE',
style: pw.TextStyle(fontSize: 9, fontWeight: pw.FontWeight.bold),
),
]);
pw.Widget _meta(SaleTransaction txn) {
final c = txn.customer;
return pw.Column(children: [
_row('Invoice', txn.invoiceNumber),
_row('Date', Formatters.receiptStamp(txn.createdAt)),
_row('Cashier', txn.cashierName),
_row('Terminal', txn.terminalId),
_row('Customer', c == null ? 'Walk-in' : c.name),
if (c != null) _row('Mobile', Formatters.mobile(c.mobile)),
]);
}
pw.Widget _itemsTable(SaleTransaction txn) {
return pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.stretch,
children: [
pw.Row(children: [
pw.Expanded(flex: 5, child: _th('Item')),
pw.Expanded(flex: 2, child: _th('Qty', align: pw.TextAlign.center)),
pw.Expanded(flex: 3, child: _th('Rate', align: pw.TextAlign.right)),
pw.Expanded(flex: 3, child: _th('Amt', align: pw.TextAlign.right)),
]),
pw.SizedBox(height: 2),
...txn.cart.lines.map((line) => pw.Padding(
padding: const pw.EdgeInsets.symmetric(vertical: 1.5),
child: pw.Column(children: [
pw.Row(children: [
pw.Expanded(flex: 5, child: _td(line.product.name)),
pw.Expanded(
flex: 2,
child: _td(
_qty(line.quantity),
align: pw.TextAlign.center,
),
),
pw.Expanded(
flex: 3,
child: _td(
line.product.price.toStringAsFixed(2),
align: pw.TextAlign.right,
),
),
pw.Expanded(
flex: 3,
child: _td(
line.payable.toStringAsFixed(2),
align: pw.TextAlign.right,
),
),
]),
if (line.discount.isActive)
pw.Row(children: [
pw.Expanded(
child: _td(
' ${line.discount.label} '
'-${line.discountAmount.toStringAsFixed(2)}',
size: 6.5,
),
),
]),
]),
)),
],
);
}
pw.Widget _totals(SaleTransaction txn) {
final cart = txn.cart;
return pw.Column(children: [
_row('Items', '${cart.lineCount} (Qty ${_qty(cart.totalQuantity)})'),
_row('Subtotal', cart.subtotal.toStringAsFixed(2)),
if (cart.membershipDiscountAmount > 0)
_row(
'${cart.customer!.tier.label} discount',
'-${cart.membershipDiscountAmount.toStringAsFixed(2)}',
),
if (cart.manualBillDiscountAmount > 0)
_row('Discount', '-${cart.manualBillDiscountAmount.toStringAsFixed(2)}'),
if (cart.loyaltyRedemptionValue > 0)
_row(
'Points redeemed (${cart.pointsRedeemed})',
'-${cart.loyaltyRedemptionValue.toStringAsFixed(2)}',
),
_row('Taxable value', cart.taxableAmount.toStringAsFixed(2)),
_row('CGST', cart.cgst.toStringAsFixed(2)),
_row('SGST', cart.sgst.toStringAsFixed(2)),
if (cart.roundOff != 0)
_row('Round off', cart.roundOff.toStringAsFixed(2)),
pw.SizedBox(height: 3),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Text('TOTAL',
style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold)),
pw.Text(
'${AppConstants.currencySymbol}${txn.total.toStringAsFixed(2)}',
style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold),
),
],
),
if (cart.totalSavings > 0) ...[
pw.SizedBox(height: 2),
pw.Text(
'You saved ${AppConstants.currencySymbol}'
'${cart.totalSavings.toStringAsFixed(2)} on this bill',
style: pw.TextStyle(fontSize: 7.5, fontWeight: pw.FontWeight.bold),
textAlign: pw.TextAlign.center,
),
],
]);
}
pw.Widget _taxSummary(SaleTransaction txn) {
final breakdown = txn.cart.taxBreakdown.entries
.where((e) => e.value > 0)
.toList()
..sort((a, b) => a.key.compareTo(b.key));
if (breakdown.isEmpty) {
return _td('All items zero-rated', size: 7);
}
return pw.Column(children: [
_th('GST Summary'),
...breakdown.map((e) => _row(
'GST @ ${(e.key * 100).toStringAsFixed(0)}%',
e.value.toStringAsFixed(2),
size: 7,
)),
]);
}
pw.Widget _payments(SaleTransaction txn) => pw.Column(children: [
...txn.payments.map((p) => _row(
p.method.label +
(p.reference != null ? ' (${p.reference})' : ''),
p.amount.toStringAsFixed(2),
)),
if (txn.changeDue > 0)
_row('Change returned', txn.changeDue.toStringAsFixed(2)),
]);
pw.Widget _loyalty(SaleTransaction txn) {
final c = txn.customer!;
final balance = c.loyaltyPoints - txn.pointsRedeemed + txn.pointsEarned;
return pw.Column(children: [
_row('Points earned', '+${txn.pointsEarned}'),
if (txn.pointsRedeemed > 0)
_row('Points redeemed', '-${txn.pointsRedeemed}'),
_row('Points balance', '$balance'),
_row('Membership', c.tier.label),
]);
}
pw.Widget _footer(SaleTransaction txn) => pw.Column(children: [
pw.BarcodeWidget(
barcode: pw.Barcode.code128(),
data: txn.invoiceNumber,
width: 140,
height: 34,
drawText: false,
),
pw.SizedBox(height: 4),
pw.Text(txn.invoiceNumber, style: const pw.TextStyle(fontSize: 7)),
pw.SizedBox(height: 4),
pw.Text('Thank you for shopping with us!',
style: pw.TextStyle(fontSize: 8, fontWeight: pw.FontWeight.bold)),
pw.Text('Goods once sold are exchangeable within 7 days with this bill.',
style: const pw.TextStyle(fontSize: 6),
textAlign: pw.TextAlign.center),
pw.SizedBox(height: 2),
pw.Text('Powered by Nearle POS', style: const pw.TextStyle(fontSize: 6)),
]);
// -------------------------------------------------------------- Helpers
String _qty(double q) =>
q % 1 == 0 ? q.toStringAsFixed(0) : q.toStringAsFixed(3);
pw.Widget _divider() => pw.Padding(
padding: const pw.EdgeInsets.symmetric(vertical: 3),
child: pw.Divider(height: 0.5, borderStyle: pw.BorderStyle.dashed),
);
pw.Widget _th(String text, {pw.TextAlign align = pw.TextAlign.left}) =>
pw.Text(text,
textAlign: align,
style: pw.TextStyle(fontSize: 7.5, fontWeight: pw.FontWeight.bold));
pw.Widget _td(String text,
{pw.TextAlign align = pw.TextAlign.left, double size = 7.5}) =>
pw.Text(text, textAlign: align, style: pw.TextStyle(fontSize: size));
pw.Widget _row(String label, String value, {double size = 7.5}) => pw.Padding(
padding: const pw.EdgeInsets.symmetric(vertical: 0.8),
child: pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Text(label, style: pw.TextStyle(fontSize: size)),
pw.Text(value, style: pw.TextStyle(fontSize: size)),
],
),
);
// --------------------------------------------------------- Printing / IO
/// Silent print to the default roll printer — no OS dialog, so the cashier
/// is never blocked between sales.
Future<bool> printDirect(SaleTransaction txn) async {
try {
final bytes = await build(txn);
final printers = await Printing.listPrinters();
final target = printers.where((p) => p.isDefault).firstOrNull ??
(printers.isNotEmpty ? printers.first : null);
if (target == null) return false;
return await Printing.directPrintPdf(
printer: target,
onLayout: (_) async => bytes,
name: txn.invoiceNumber,
);
} catch (e) {
debugPrint('Direct print failed: $e');
return false;
}
}
/// Falls back to the system print preview.
Future<void> printWithDialog(SaleTransaction txn) async {
final bytes = await build(txn);
await Printing.layoutPdf(
onLayout: (_) async => bytes,
name: txn.invoiceNumber,
);
}
Future<void> share(SaleTransaction txn) async {
final bytes = await build(txn);
await Printing.sharePdf(bytes: bytes, filename: '${txn.invoiceNumber}.pdf');
}
/// Opens the cash drawer via the ESC/POS kick pulse on pin 2.
Future<void> openCashDrawer() async {
// ESC p m t1 t2 — sent to the receipt printer's serial passthrough.
// Wired up here as a no-op placeholder for the concrete driver.
debugPrint('Cash drawer kick: ESC p 0 25 250');
}
}

View File

@@ -0,0 +1,62 @@
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../constants/asset_paths.dart';
/// Audible feedback for scanner billing.
///
/// A cashier scanning at speed watches the customer, not the screen, so the
/// beep is the primary confirmation that an item registered.
class SoundService {
SoundService._();
static final SoundService instance = SoundService._();
final AudioPlayer _player = AudioPlayer(playerId: 'nearle_pos_sfx');
bool _enabled = true;
bool get enabled => _enabled;
set enabled(bool value) => _enabled = value;
Future<void> preload() async {
try {
await _player.setReleaseMode(ReleaseMode.stop);
} catch (e) {
debugPrint('SoundService preload failed: $e');
}
}
Future<void> scanSuccess() => _play(AssetPaths.beepSuccess, haptic: true);
Future<void> scanError() => _play(AssetPaths.beepError, heavy: true);
Future<void> saleComplete() => _play(AssetPaths.chargeComplete);
Future<void> _play(
String asset, {
bool haptic = false,
bool heavy = false,
}) async {
if (!_enabled) return;
// Haptics matter on tablets where the speaker may be muted on the floor.
if (heavy) {
unawaited(HapticFeedback.heavyImpact());
} else if (haptic) {
unawaited(HapticFeedback.selectionClick());
}
try {
await _player.stop();
await _player.play(AssetSource(asset.replaceFirst('assets/', '')));
} catch (e) {
// Never let a missing sound file break the billing flow.
debugPrint('SoundService play failed for $asset: $e');
}
}
Future<void> dispose() => _player.dispose();
}

View File

@@ -0,0 +1,84 @@
import 'package:flutter/material.dart';
/// Central colour palette for Nearle POS.
///
/// Everything is derived from the brand primary `#662582` so that a single
/// change here re-skins the entire application.
class AppColors {
const AppColors._();
// ---------------------------------------------------------------- Brand
static const Color primary = Color(0xFF662582);
static const Color primaryDark = Color(0xFF4B1A60);
static const Color primaryLight = Color(0xFF8B4BA6);
static const Color primarySurface = Color(0xFFF4EDF7);
static const Color primaryBorder = Color(0xFFE3D3EC);
static const MaterialColor primarySwatch = MaterialColor(0xFF662582, {
50: Color(0xFFF4EDF7),
100: Color(0xFFE3D3EC),
200: Color(0xFFCDB1DC),
300: Color(0xFFB68FCC),
400: Color(0xFFA475C0),
500: Color(0xFF662582),
600: Color(0xFF5C2175),
700: Color(0xFF4B1A60),
800: Color(0xFF3B144B),
900: Color(0xFF2A0E36),
});
// -------------------------------------------------------------- Neutrals
static const Color background = Color(0xFFF7F7F9);
static const Color surface = Color(0xFFFFFFFF);
static const Color surfaceAlt = Color(0xFFFAFAFC);
static const Color border = Color(0xFFE8E8EE);
static const Color divider = Color(0xFFEFEFF4);
static const Color textPrimary = Color(0xFF17131C);
static const Color textSecondary = Color(0xFF6B6577);
static const Color textTertiary = Color(0xFF9A94A6);
static const Color textOnPrimary = Color(0xFFFFFFFF);
// ------------------------------------------------------------- Semantic
static const Color success = Color(0xFF16A34A);
static const Color successSurface = Color(0xFFEAF7EF);
static const Color warning = Color(0xFFF59E0B);
static const Color warningSurface = Color(0xFFFEF6E7);
static const Color danger = Color(0xFFDC2626);
static const Color dangerSurface = Color(0xFFFDECEC);
static const Color info = Color(0xFF2563EB);
static const Color infoSurface = Color(0xFFEAF0FE);
// ------------------------------------------------------- Membership tiers
static const Color tierBronze = Color(0xFFB08D57);
static const Color tierSilver = Color(0xFF8E96A3);
static const Color tierGold = Color(0xFFD4A017);
static const Color tierPlatinum = Color(0xFF4C5A6B);
// ---------------------------------------------------------------- Effects
static const Color glassTint = Color(0x14662582);
static const List<BoxShadow> shadowSm = [
BoxShadow(color: Color(0x0D17131C), blurRadius: 6, offset: Offset(0, 2)),
];
static const List<BoxShadow> shadowMd = [
BoxShadow(color: Color(0x1417131C), blurRadius: 16, offset: Offset(0, 6)),
];
static const List<BoxShadow> shadowLg = [
BoxShadow(color: Color(0x1F17131C), blurRadius: 32, offset: Offset(0, 12)),
];
static const LinearGradient primaryGradient = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFF7A2E9A), Color(0xFF4B1A60)],
);
static const LinearGradient glassGradient = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0x40FFFFFF), Color(0x0DFFFFFF)],
);
}

View File

@@ -0,0 +1,83 @@
import 'package:flutter/widgets.dart';
/// Spacing scale — 4pt grid.
class AppSpacing {
const AppSpacing._();
static const double xxs = 2;
static const double xs = 4;
static const double sm = 8;
static const double md = 12;
static const double lg = 16;
static const double xl = 20;
static const double xxl = 24;
static const double xxxl = 32;
static const double huge = 40;
static const double giant = 56;
static const EdgeInsets pageDesktop = EdgeInsets.all(xxl);
static const EdgeInsets pageTablet = EdgeInsets.all(lg);
static const EdgeInsets card = EdgeInsets.all(lg);
}
/// Corner radii — brand standard is 16.
class AppRadius {
const AppRadius._();
static const double xs = 6;
static const double sm = 10;
static const double md = 12;
static const double lg = 16;
static const double xl = 20;
static const double xxl = 28;
static const double pill = 999;
static const BorderRadius brXs = BorderRadius.all(Radius.circular(xs));
static const BorderRadius brSm = BorderRadius.all(Radius.circular(sm));
static const BorderRadius brMd = BorderRadius.all(Radius.circular(md));
static const BorderRadius brLg = BorderRadius.all(Radius.circular(lg));
static const BorderRadius brXl = BorderRadius.all(Radius.circular(xl));
static const BorderRadius brPill = BorderRadius.all(Radius.circular(pill));
}
/// Minimum sizes tuned for finger targets on tablets.
class AppSizes {
const AppSizes._();
static const double touchTarget = 48;
static const double buttonHeight = 52;
static const double buttonHeightLarge = 64;
static const double inputHeight = 56;
static const double headerHeight = 76;
static const double customerBarHeight = 72;
static const double navItemHeight = 46;
static const double productCardAspect = 0.86;
static const double keypadKeySize = 76;
}
/// Motion durations & curves.
class AppMotion {
const AppMotion._();
static const Duration instant = Duration(milliseconds: 90);
static const Duration fast = Duration(milliseconds: 160);
static const Duration normal = Duration(milliseconds: 240);
static const Duration slow = Duration(milliseconds: 400);
static const Curve emphasized = Curves.easeOutCubic;
static const Curve standard = Curves.easeInOut;
static const Curve bouncy = Curves.easeOutBack;
}
/// Responsive breakpoints.
class AppBreakpoints {
const AppBreakpoints._();
static const double tabletPortrait = 920;
static const double tabletLandscape = 1300;
static const double desktop = 1650;
static bool isCompact(double w) => w < tabletPortrait;
static bool isMedium(double w) => w >= tabletPortrait && w < desktop;
static bool isExpanded(double w) => w >= desktop;
}

View File

@@ -0,0 +1,98 @@
import 'package:flutter/widgets.dart';
/// How the left navigation should render at the current width.
enum SidebarMode {
/// Off-canvas; reachable through the page-header menu button.
drawer,
/// Icons only, 84px.
rail,
/// Icons plus labels and section headers, 252px.
expanded,
}
/// How the bill should render at the current width.
enum BillingMode {
/// Bottom sheet, opened from the floating cart button.
sheet,
/// Docked column on the right.
docked,
}
/// Resolves every layout decision for the POS dashboard from a single width.
///
/// Keeping this in one place means the sidebar, product grid and billing panel
/// can never disagree about which breakpoint they are in.
class PosLayout {
const PosLayout({
required this.sidebar,
required this.billing,
required this.billingWidth,
required this.gridTileExtent,
required this.contentPadding,
});
final SidebarMode sidebar;
final BillingMode billing;
final double billingWidth;
/// Maximum width of a product card; the grid fits as many as will fit.
final double gridTileExtent;
final double contentPadding;
static const double railWidth = 84;
static const double expandedWidth = 252;
/// Below this the sidebar goes off-canvas.
static const double drawerBelow = 920;
/// Below this the sidebar is icons-only.
static const double railBelow = 1300;
/// Below this the bill becomes a bottom sheet.
static const double sheetBelow = 1120;
/// Above this we have room for a wider bill and larger cards.
static const double wideAbove = 1650;
factory PosLayout.of(BuildContext context) =>
PosLayout.forWidth(MediaQuery.sizeOf(context).width);
factory PosLayout.forWidth(double width) {
final sidebar = width < drawerBelow
? SidebarMode.drawer
: (width < railBelow ? SidebarMode.rail : SidebarMode.expanded);
final billing =
width < sheetBelow ? BillingMode.sheet : BillingMode.docked;
final billingWidth = width >= wideAbove ? 440.0 : 380.0;
// Cards stay finger-sized on tablets and grow a little on large desktops.
final tile = width < drawerBelow
? 168.0
: (width >= wideAbove ? 208.0 : 186.0);
final padding = width < drawerBelow ? 16.0 : 24.0;
return PosLayout(
sidebar: sidebar,
billing: billing,
billingWidth: billingWidth,
gridTileExtent: tile,
contentPadding: padding,
);
}
double get sidebarWidth => switch (sidebar) {
SidebarMode.drawer => 0,
SidebarMode.rail => railWidth,
SidebarMode.expanded => expandedWidth,
};
bool get sidebarIsDrawer => sidebar == SidebarMode.drawer;
bool get billingIsSheet => billing == BillingMode.sheet;
}

View File

@@ -0,0 +1,162 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'app_colors.dart';
import 'app_dimens.dart';
import 'app_typography.dart';
/// Builds the single source of truth [ThemeData] for Nearle POS.
class AppTheme {
const AppTheme._();
static ThemeData get light {
final colorScheme = ColorScheme.fromSeed(
seedColor: AppColors.primary,
primary: AppColors.primary,
onPrimary: AppColors.textOnPrimary,
secondary: AppColors.primaryLight,
surface: AppColors.surface,
onSurface: AppColors.textPrimary,
error: AppColors.danger,
brightness: Brightness.light,
);
return ThemeData(
useMaterial3: true,
colorScheme: colorScheme,
scaffoldBackgroundColor: AppColors.background,
textTheme: AppTypography.textTheme,
splashFactory: InkSparkle.splashFactory,
visualDensity: VisualDensity.standard,
appBarTheme: AppBarTheme(
backgroundColor: AppColors.primary,
foregroundColor: AppColors.textOnPrimary,
elevation: 0,
centerTitle: false,
toolbarHeight: AppSizes.headerHeight,
systemOverlayStyle: SystemUiOverlayStyle.light,
titleTextStyle: AppTypography.textTheme.titleLarge
?.copyWith(color: AppColors.textOnPrimary),
),
cardTheme: CardThemeData(
color: AppColors.surface,
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: AppRadius.brLg,
side: const BorderSide(color: AppColors.border),
),
),
dividerTheme: const DividerThemeData(
color: AppColors.divider,
thickness: 1,
space: 1,
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.primary,
foregroundColor: AppColors.textOnPrimary,
disabledBackgroundColor: AppColors.border,
disabledForegroundColor: AppColors.textTertiary,
minimumSize: const Size(0, AppSizes.buttonHeight),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl),
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: AppRadius.brMd),
textStyle: AppTypography.textTheme.labelLarge,
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
foregroundColor: AppColors.primary,
minimumSize: const Size(0, AppSizes.buttonHeight),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl),
side: const BorderSide(color: AppColors.primaryBorder, width: 1.5),
shape: const RoundedRectangleBorder(borderRadius: AppRadius.brMd),
textStyle: AppTypography.textTheme.labelLarge,
),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: AppColors.primary,
minimumSize: const Size(0, AppSizes.touchTarget),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
shape: const RoundedRectangleBorder(borderRadius: AppRadius.brSm),
textStyle: AppTypography.textTheme.labelLarge,
),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: AppColors.surface,
contentPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.lg,
),
hintStyle: AppTypography.textTheme.bodyMedium
?.copyWith(color: AppColors.textTertiary),
labelStyle: AppTypography.textTheme.bodyMedium
?.copyWith(color: AppColors.textSecondary),
border: _inputBorder(AppColors.border),
enabledBorder: _inputBorder(AppColors.border),
focusedBorder: _inputBorder(AppColors.primary, width: 1.8),
errorBorder: _inputBorder(AppColors.danger),
focusedErrorBorder: _inputBorder(AppColors.danger, width: 1.8),
),
chipTheme: ChipThemeData(
backgroundColor: AppColors.surface,
selectedColor: AppColors.primary,
side: const BorderSide(color: AppColors.border),
labelStyle: AppTypography.textTheme.labelMedium,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.md,
),
shape: const RoundedRectangleBorder(borderRadius: AppRadius.brPill),
),
dialogTheme: DialogThemeData(
backgroundColor: AppColors.surface,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppRadius.xl),
),
titleTextStyle: AppTypography.textTheme.headlineSmall,
),
snackBarTheme: SnackBarThemeData(
backgroundColor: AppColors.textPrimary,
contentTextStyle: AppTypography.textTheme.bodyMedium
?.copyWith(color: Colors.white),
behavior: SnackBarBehavior.floating,
shape: const RoundedRectangleBorder(borderRadius: AppRadius.brMd),
),
scrollbarTheme: ScrollbarThemeData(
thickness: WidgetStateProperty.all(6),
radius: const Radius.circular(AppRadius.pill),
thumbColor: WidgetStateProperty.all(AppColors.primaryBorder),
),
pageTransitionsTheme: const PageTransitionsTheme(builders: {
TargetPlatform.windows: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.linux: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
}),
);
}
static OutlineInputBorder _inputBorder(Color color, {double width = 1}) {
return OutlineInputBorder(
borderRadius: AppRadius.brMd,
borderSide: BorderSide(color: color, width: width),
);
}
}

View File

@@ -0,0 +1,85 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'app_colors.dart';
/// Poppins-based type scale.
///
/// Poppins is geometric and runs slightly wide, so headings get negative
/// tracking to keep them compact in the sidebar and page header. POS screens
/// are read at arm's length, so body text starts at 15 rather than the
/// Material default of 14.
class AppTypography {
const AppTypography._();
static TextTheme get textTheme {
final base = GoogleFonts.poppinsTextTheme();
return base.copyWith(
displayLarge: _s(base.displayLarge, 44, FontWeight.w700, -1.2),
displayMedium: _s(base.displayMedium, 36, FontWeight.w700, -1.0),
displaySmall: _s(base.displaySmall, 30, FontWeight.w700, -0.8),
headlineLarge: _s(base.headlineLarge, 28, FontWeight.w600, -0.7),
headlineMedium: _s(base.headlineMedium, 24, FontWeight.w600, -0.6),
headlineSmall: _s(base.headlineSmall, 20, FontWeight.w600, -0.4),
titleLarge: _s(base.titleLarge, 18, FontWeight.w600, -0.3),
titleMedium: _s(base.titleMedium, 15.5, FontWeight.w600, -0.2),
titleSmall: _s(base.titleSmall, 13.5, FontWeight.w600, -0.1),
bodyLarge: _s(base.bodyLarge, 15.5, FontWeight.w400, 0),
bodyMedium: _s(base.bodyMedium, 14.5, FontWeight.w400, 0),
bodySmall: _s(base.bodySmall, 12.5, FontWeight.w400, 0,
color: AppColors.textSecondary),
labelLarge: _s(base.labelLarge, 14.5, FontWeight.w600, 0),
labelMedium: _s(base.labelMedium, 12.5, FontWeight.w600, 0.1),
labelSmall: _s(base.labelSmall, 10.5, FontWeight.w600, 0.6,
color: AppColors.textTertiary),
);
}
static TextStyle _s(
TextStyle? base,
double size,
FontWeight weight,
double tracking, {
Color color = AppColors.textPrimary,
}) {
return (base ?? const TextStyle()).copyWith(
fontSize: size,
fontWeight: weight,
letterSpacing: tracking,
color: color,
height: 1.35,
);
}
/// Tabular figures — essential so totals don't jitter as quantities change.
static TextStyle money(double size,
{FontWeight weight = FontWeight.w700, Color? color}) =>
GoogleFonts.poppins(
fontSize: size,
fontWeight: weight,
color: color ?? AppColors.textPrimary,
letterSpacing: -0.5,
height: 1.15,
fontFeatures: const [FontFeature.tabularFigures()],
);
/// Fixed-pitch, used only for the receipt preview.
static TextStyle mono(double size, {Color? color}) => GoogleFonts.robotoMono(
fontSize: size,
color: color ?? AppColors.textTertiary,
letterSpacing: 0.2,
);
/// Small uppercase caption for sidebar section dividers.
static TextStyle sectionLabel() => GoogleFonts.poppins(
fontSize: 10.5,
fontWeight: FontWeight.w600,
letterSpacing: 1.0,
color: AppColors.textTertiary,
);
}

View File

@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
import '../theme/app_dimens.dart';
extension BuildContextX on BuildContext {
ThemeData get theme => Theme.of(this);
TextTheme get text => Theme.of(this).textTheme;
ColorScheme get colors => Theme.of(this).colorScheme;
Size get screen => MediaQuery.sizeOf(this);
double get screenWidth => MediaQuery.sizeOf(this).width;
double get screenHeight => MediaQuery.sizeOf(this).height;
bool get isCompact => AppBreakpoints.isCompact(screenWidth);
bool get isMedium => AppBreakpoints.isMedium(screenWidth);
bool get isExpanded => AppBreakpoints.isExpanded(screenWidth);
/// Picks a value appropriate to the current breakpoint.
T responsive<T>({required T compact, T? medium, required T expanded}) {
if (isCompact) return compact;
if (isExpanded) return expanded;
return medium ?? expanded;
}
void showSnack(String message, {Color? background}) {
ScaffoldMessenger.of(this)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(
content: Text(message),
backgroundColor: background,
duration: const Duration(seconds: 2),
));
}
}
extension DoubleX on double {
/// Rounds to two decimals to avoid floating point drift in money maths.
double get asMoney => (this * 100).roundToDouble() / 100;
/// Indian retail round-off to the nearest rupee.
double get roundedToRupee => roundToDouble();
}
extension StringX on String {
String get capitalized =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
bool containsIgnoreCase(String other) =>
toLowerCase().contains(other.toLowerCase());
}
extension IterableX<T> on Iterable<T> {
T? firstWhereOrNull(bool Function(T) test) {
for (final element in this) {
if (test(element)) return element;
}
return null;
}
}

View File

@@ -0,0 +1,67 @@
import 'package:intl/intl.dart';
import '../constants/app_constants.dart';
/// Currency, date and number formatting helpers.
class Formatters {
const Formatters._();
static final NumberFormat _currency = NumberFormat.currency(
locale: AppConstants.locale,
symbol: AppConstants.currencySymbol,
decimalDigits: 2,
);
static final NumberFormat _compactCurrency = NumberFormat.compactCurrency(
locale: AppConstants.locale,
symbol: AppConstants.currencySymbol,
decimalDigits: 1,
);
static final DateFormat _time = DateFormat('hh:mm a');
static final DateFormat _date = DateFormat('dd MMM yyyy');
static final DateFormat _dateTime = DateFormat('dd MMM yyyy, hh:mm a');
static final DateFormat _receiptStamp = DateFormat('dd/MM/yyyy HH:mm:ss');
static String money(num value) => _currency.format(value);
static String moneyCompact(num value) => _compactCurrency.format(value);
/// Amount without the symbol — used where the symbol is styled separately.
static String amount(num value) => value.toStringAsFixed(2);
static String time(DateTime dt) => _time.format(dt);
static String date(DateTime dt) => _date.format(dt);
static String dateTime(DateTime dt) => _dateTime.format(dt);
static String receiptStamp(DateTime dt) => _receiptStamp.format(dt);
static String percent(double fraction) =>
'${(fraction * 100).toStringAsFixed(fraction * 100 % 1 == 0 ? 0 : 1)}%';
/// `9876543210` -> `98765 43210`
static String mobile(String raw) {
final digits = raw.replaceAll(RegExp(r'\D'), '');
if (digits.length != 10) return raw;
return '${digits.substring(0, 5)} ${digits.substring(5)}';
}
/// Masks all but the last four digits for on-screen privacy.
static String maskedMobile(String raw) {
final digits = raw.replaceAll(RegExp(r'\D'), '');
if (digits.length < 4) return raw;
return '${'\u2022' * (digits.length - 4)}${digits.substring(digits.length - 4)}';
}
static String initials(String name) {
final parts = name.trim().split(RegExp(r'\s+')).where((p) => p.isNotEmpty);
if (parts.isEmpty) return '?';
if (parts.length == 1) return parts.first.substring(0, 1).toUpperCase();
return (parts.first.substring(0, 1) + parts.last.substring(0, 1))
.toUpperCase();
}
static String invoiceNumber(int sequence, DateTime date) {
final y = date.year.toString().substring(2);
final m = date.month.toString().padLeft(2, '0');
return 'INV-$y$m-${sequence.toString().padLeft(5, '0')}';
}
}

View File

@@ -0,0 +1,56 @@
import '../constants/app_constants.dart';
/// Form field validators returning a message, or null when valid.
class Validators {
const Validators._();
static final RegExp _emailRe =
RegExp(r'^[\w.+-]+@([\w-]+\.)+[A-Za-z]{2,}$');
static final RegExp _mobileRe = RegExp(r'^[6-9]\d{9}$');
static String? mobile(String? value) {
final v = (value ?? '').replaceAll(RegExp(r'\D'), '');
if (v.isEmpty) return 'Mobile number is required';
if (v.length != AppConstants.mobileNumberLength) {
return 'Enter all ${AppConstants.mobileNumberLength} digits';
}
if (!_mobileRe.hasMatch(v)) return 'Enter a valid Indian mobile number';
return null;
}
static String? name(String? value) {
final v = (value ?? '').trim();
if (v.isEmpty) return 'Customer name is required';
if (v.length < 2) return 'Name is too short';
if (v.length > 60) return 'Name is too long';
return null;
}
static String? emailOptional(String? value) {
final v = (value ?? '').trim();
if (v.isEmpty) return null;
if (!_emailRe.hasMatch(v)) return 'Enter a valid email address';
return null;
}
static String? dobOptional(DateTime? value) {
if (value == null) return null;
final now = DateTime.now();
if (value.isAfter(now)) return 'Date of birth cannot be in the future';
if (now.year - value.year > 120) return 'Enter a valid date of birth';
return null;
}
static String? positiveAmount(String? value) {
final v = double.tryParse((value ?? '').trim());
if (v == null) return 'Enter a valid amount';
if (v <= 0) return 'Amount must be greater than zero';
return null;
}
static bool isLikelyBarcode(String value) {
final v = value.trim();
return v.length >= AppConstants.minBarcodeLength &&
RegExp(r'^\d+$').hasMatch(v);
}
}

View File

@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
class EmptyState extends StatelessWidget {
const EmptyState({
super.key,
required this.title,
this.message,
this.emoji = '🛒',
this.action,
this.compact = false,
});
final String title;
final String? message;
final String emoji;
final Widget? action;
final bool compact;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: compact ? 64 : 96,
height: compact ? 64 : 96,
decoration: const BoxDecoration(
color: AppColors.primarySurface,
shape: BoxShape.circle,
),
alignment: Alignment.center,
child: Text(emoji,
style: TextStyle(fontSize: compact ? 28 : 40)),
),
SizedBox(height: compact ? AppSpacing.lg : AppSpacing.xxl),
Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: compact ? 15 : 18,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
),
),
if (message != null) ...[
const SizedBox(height: AppSpacing.sm),
Text(
message!,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
color: AppColors.textSecondary,
height: 1.45,
),
),
],
if (action != null) ...[
const SizedBox(height: AppSpacing.xxl),
action!,
],
],
),
),
);
}
}

View File

@@ -0,0 +1,85 @@
import 'dart:ui';
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
/// Glassmorphism-inspired surface used for elevated panels and product cards.
class GlassCard extends StatelessWidget {
const GlassCard({
super.key,
required this.child,
this.padding = AppSpacing.card,
this.radius = AppRadius.lg,
this.blur = 0,
this.tinted = false,
this.borderColor,
this.shadows,
this.onTap,
this.width,
this.height,
});
final Widget child;
final EdgeInsetsGeometry padding;
final double radius;
/// Backdrop blur strength. Zero renders an opaque card, which is cheaper and
/// is the right default for the dense product grid.
final double blur;
final bool tinted;
final Color? borderColor;
final List<BoxShadow>? shadows;
final VoidCallback? onTap;
final double? width;
final double? height;
@override
Widget build(BuildContext context) {
final borderRadius = BorderRadius.circular(radius);
Widget surface = AnimatedContainer(
duration: AppMotion.fast,
width: width,
height: height,
padding: padding,
decoration: BoxDecoration(
color: tinted
? AppColors.primarySurface.withValues(alpha: blur > 0 ? 0.75 : 1)
: AppColors.surface.withValues(alpha: blur > 0 ? 0.78 : 1),
borderRadius: borderRadius,
border: Border.all(
color: borderColor ??
(tinted ? AppColors.primaryBorder : AppColors.border),
),
boxShadow: shadows ?? AppColors.shadowSm,
),
child: child,
);
if (blur > 0) {
surface = ClipRRect(
borderRadius: borderRadius,
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
child: surface,
),
);
}
if (onTap == null) return surface;
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: borderRadius,
splashColor: AppColors.primary.withValues(alpha: 0.08),
highlightColor: AppColors.primary.withValues(alpha: 0.04),
child: surface,
),
);
}
}

View File

@@ -0,0 +1,146 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
/// Large on-screen keypad for mobile numbers and cash amounts.
class NumericKeypad extends StatelessWidget {
const NumericKeypad({
super.key,
required this.onKey,
required this.onBackspace,
this.onClear,
this.onSubmit,
this.submitLabel,
this.allowDecimal = false,
this.maxWidth = 360,
});
final ValueChanged<String> onKey;
final VoidCallback onBackspace;
final VoidCallback? onClear;
final VoidCallback? onSubmit;
final String? submitLabel;
final bool allowDecimal;
final double maxWidth;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxWidth),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final row in const [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
])
_row(row.map((d) => _digit(d)).toList()),
_row([
allowDecimal
? _digit('.')
: _action(
icon: Icons.clear_all_rounded,
onTap: onClear,
tone: AppColors.textSecondary,
),
_digit('0'),
_action(
icon: Icons.backspace_outlined,
onTap: onBackspace,
tone: AppColors.danger,
),
]),
if (onSubmit != null) ...[
const SizedBox(height: AppSpacing.md),
SizedBox(
width: double.infinity,
height: AppSizes.buttonHeight,
child: FilledButton.icon(
onPressed: onSubmit,
icon: const Icon(Icons.check_rounded),
label: Text(submitLabel ?? 'Done'),
),
),
],
],
),
);
}
Widget _row(List<Widget> children) => Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.md),
child: Row(
children: [
for (var i = 0; i < children.length; i++) ...[
Expanded(child: children[i]),
if (i != children.length - 1)
const SizedBox(width: AppSpacing.md),
],
],
),
);
Widget _digit(String value) => _Key(
onTap: () {
HapticFeedback.selectionClick();
onKey(value);
},
child: Text(
value,
style: const TextStyle(
fontSize: 26,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
);
Widget _action({
required IconData icon,
required VoidCallback? onTap,
required Color tone,
}) =>
_Key(
onTap: onTap == null
? null
: () {
HapticFeedback.lightImpact();
onTap();
},
child: Icon(icon, size: 24, color: tone),
);
}
class _Key extends StatelessWidget {
const _Key({required this.child, this.onTap});
final Widget child;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
return SizedBox(
height: AppSizes.keypadKeySize,
child: Material(
color: AppColors.surface,
borderRadius: AppRadius.brMd,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brMd,
splashColor: AppColors.primary.withValues(alpha: 0.1),
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: AppRadius.brMd,
border: Border.all(color: AppColors.border),
),
child: child,
),
),
),
);
}
}

View File

@@ -0,0 +1,126 @@
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
enum ButtonTone { primary, neutral, success, danger, ghost }
/// Large, touch-first action button with built-in busy state.
class PrimaryButton extends StatelessWidget {
const PrimaryButton({
super.key,
required this.label,
this.onPressed,
this.icon,
this.tone = ButtonTone.primary,
this.expanded = true,
this.large = false,
this.busy = false,
this.trailing,
});
final String label;
final VoidCallback? onPressed;
final IconData? icon;
final ButtonTone tone;
final bool expanded;
final bool large;
final bool busy;
/// Optional right-aligned widget, typically the bill total.
final Widget? trailing;
@override
Widget build(BuildContext context) {
final enabled = onPressed != null && !busy;
final (bg, fg, border) = _palette;
final height =
large ? AppSizes.buttonHeightLarge : AppSizes.buttonHeight;
final content = busy
? SizedBox(
height: 22,
width: 22,
child: CircularProgressIndicator(strokeWidth: 2.4, color: fg),
)
: Row(
mainAxisSize: expanded ? MainAxisSize.max : MainAxisSize.min,
mainAxisAlignment: trailing != null
? MainAxisAlignment.spaceBetween
: MainAxisAlignment.center,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) ...[
Icon(icon, size: large ? 24 : 20, color: fg),
const SizedBox(width: AppSpacing.sm),
],
Flexible(
child: Text(
label,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: fg,
fontSize: large ? 19 : 16,
fontWeight: FontWeight.w700,
letterSpacing: 0.1,
),
),
),
],
),
if (trailing != null) trailing!,
],
);
return SizedBox(
width: expanded ? double.infinity : null,
height: height,
child: Material(
color: enabled ? bg : AppColors.border,
borderRadius: AppRadius.brMd,
child: InkWell(
onTap: enabled ? onPressed : null,
borderRadius: AppRadius.brMd,
child: Container(
padding: EdgeInsets.symmetric(
horizontal: large ? AppSpacing.xxl : AppSpacing.xl,
),
decoration: BoxDecoration(
borderRadius: AppRadius.brMd,
border: border == null
? null
: Border.all(color: border, width: 1.5),
),
alignment: Alignment.center,
child: DefaultTextStyle.merge(
style: TextStyle(color: enabled ? fg : AppColors.textTertiary),
child: content,
),
),
),
),
);
}
(Color, Color, Color?) get _palette => switch (tone) {
ButtonTone.primary => (
AppColors.primary,
AppColors.textOnPrimary,
null
),
ButtonTone.success => (AppColors.success, Colors.white, null),
ButtonTone.danger => (AppColors.danger, Colors.white, null),
ButtonTone.neutral => (
AppColors.surface,
AppColors.textPrimary,
AppColors.border
),
ButtonTone.ghost => (
AppColors.primarySurface,
AppColors.primary,
AppColors.primaryBorder
),
};
}

View File

@@ -0,0 +1,95 @@
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
import '../../domain/entities/customer.dart';
/// Compact labelled badge — stock states, tiers, live indicator.
class StatusPill extends StatelessWidget {
const StatusPill({
super.key,
required this.label,
this.color = AppColors.primary,
this.background,
this.icon,
this.dense = false,
});
final String label;
final Color color;
final Color? background;
final IconData? icon;
final bool dense;
factory StatusPill.tier(MembershipTier tier, {bool dense = false}) {
final color = switch (tier) {
MembershipTier.bronze => AppColors.tierBronze,
MembershipTier.silver => AppColors.tierSilver,
MembershipTier.gold => AppColors.tierGold,
MembershipTier.platinum => AppColors.tierPlatinum,
};
return StatusPill(
label: tier.label.toUpperCase(),
color: color,
background: color.withValues(alpha: 0.12),
dense: dense,
);
}
factory StatusPill.stock(double stock, {required int lowThreshold}) {
if (stock <= 0) {
return const StatusPill(
label: 'Out of stock',
color: AppColors.danger,
background: AppColors.dangerSurface,
dense: true,
);
}
if (stock <= lowThreshold) {
return StatusPill(
label: '${stock.toStringAsFixed(0)} left',
color: AppColors.warning,
background: AppColors.warningSurface,
dense: true,
);
}
return StatusPill(
label: '${stock.toStringAsFixed(0)} in stock',
color: AppColors.textTertiary,
background: Colors.transparent,
dense: true,
);
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: dense ? AppSpacing.sm : AppSpacing.md,
vertical: dense ? 3 : AppSpacing.xs + 2,
),
decoration: BoxDecoration(
color: background ?? color.withValues(alpha: 0.12),
borderRadius: AppRadius.brPill,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) ...[
Icon(icon, size: dense ? 11 : 13, color: color),
const SizedBox(width: AppSpacing.xs),
],
Text(
label,
style: TextStyle(
color: color,
fontSize: dense ? 10.5 : 12,
fontWeight: FontWeight.w700,
letterSpacing: 0.3,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,136 @@
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import '../../domain/entities/sync_event.dart';
import '../../domain/entities/transaction.dart';
import 'seed_data.dart';
/// On-terminal storage.
///
/// The terminal starts with an **empty catalogue**: nothing can be billed
/// until the cashier imports products. Everything after that — sales, parked
/// bills, queued events — lives here and survives without a connection.
///
/// Swapping this for Hive or SQLite changes nothing above the data layer.
class LocalStore {
LocalStore._();
static final LocalStore instance = LocalStore._();
final Map<String, Product> _products = {};
final Map<String, Customer> _customers = {};
final List<SaleTransaction> _transactions = [];
final List<ParkedBill> _parked = [];
final List<SyncEvent> _events = [];
int _invoiceSequence = 0;
DateTime? _lastImportAt;
String? _catalogueRevision;
/// Nothing to seed — the catalogue arrives via import.
Future<void> init() async {}
/// Test helper. Clears everything and optionally loads the demo catalogue
/// so fixtures don't have to run an import first.
Future<void> reset({bool withCatalogue = false}) async {
_products.clear();
_customers.clear();
_transactions.clear();
_parked.clear();
_events.clear();
_invoiceSequence = 0;
_lastImportAt = null;
_catalogueRevision = null;
if (withCatalogue) {
importCatalogue(
products: SeedData.products(),
customers: SeedData.customers(),
revision: 'seed',
at: DateTime.now(),
);
}
}
// -------------------------------------------------------------- Catalogue
/// True once a catalogue has been pulled. The POS refuses to bill until so.
bool get hasCatalogue => _products.isNotEmpty;
DateTime? get lastImportAt => _lastImportAt;
String? get catalogueRevision => _catalogueRevision;
/// Replaces the catalogue wholesale.
///
/// Stock levels already adjusted by local sales are preserved for products
/// that survive the re-import, so importing mid-shift does not resurrect
/// stock that has been sold.
void importCatalogue({
required List<Product> products,
required List<Customer> customers,
required String revision,
required DateTime at,
}) {
final priorStock = {
for (final p in _products.values) p.id: p.stock,
};
_products
..clear()
..addEntries(products.map((p) {
final held = priorStock[p.id];
return MapEntry(p.id, held == null ? p : p.copyWith(stock: held));
}));
// Locally registered customers must not be wiped by a server pull.
for (final c in customers) {
_customers.putIfAbsent(c.id, () => c);
}
_lastImportAt = at;
_catalogueRevision = revision;
}
// --------------------------------------------------------------- Products
List<Product> get products => _products.values.toList(growable: false);
void putProduct(Product p) => _products[p.id] = p;
Product? productById(String id) => _products[id];
// -------------------------------------------------------------- Customers
List<Customer> get customers => _customers.values.toList(growable: false);
void putCustomer(Customer c) => _customers[c.id] = c;
Customer? customerById(String id) => _customers[id];
// ----------------------------------------------------------- Transactions
List<SaleTransaction> get transactions =>
List.unmodifiable(_transactions.reversed);
void addTransaction(SaleTransaction t) => _transactions.add(t);
int nextInvoiceSequence() => ++_invoiceSequence;
// ------------------------------------------------------------ Parked bills
List<ParkedBill> get parked => List.unmodifiable(_parked);
void addParked(ParkedBill b) => _parked.add(b);
void removeParked(String id) => _parked.removeWhere((b) => b.id == id);
// ------------------------------------------------------------ Sync events
List<SyncEvent> get events => List.unmodifiable(_events.reversed);
void addEvent(SyncEvent e) => _events.add(e);
/// Updates in place. Events are never removed, so a failed push stays
/// visible and retryable.
void updateEvent(SyncEvent e) {
final i = _events.indexWhere((x) => x.id == e.id);
if (i >= 0) _events[i] = e;
}
bool get hasUnsyncedEvents =>
_events.any((e) => e.status != SyncStatus.synced);
}

View File

@@ -0,0 +1,98 @@
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import 'seed_data.dart';
/// What one catalogue pull returns.
class CatalogueSnapshot {
const CatalogueSnapshot({
required this.products,
required this.customers,
required this.fetchedAt,
required this.revision,
});
final List<Product> products;
final List<Customer> customers;
final DateTime fetchedAt;
/// Server-side catalogue version, shown so the cashier can tell whether a
/// re-import actually changed anything.
final String revision;
}
/// Raised when the catalogue cannot be pulled.
class CatalogueSyncException implements Exception {
const CatalogueSyncException(this.message);
final String message;
@override
String toString() => message;
}
/// Stands in for the back-office catalogue API.
///
/// The real implementation would issue an HTTP request; the contract is the
/// same, so only this class changes.
class RemoteCatalogueSource {
RemoteCatalogueSource();
/// Flipped from Settings to exercise the offline path.
bool simulateOffline = false;
/// Streams progress so the import screen can show a real bar rather than an
/// indeterminate spinner.
Future<CatalogueSnapshot> fetch({
void Function(double progress, String stage)? onProgress,
}) async {
const stages = [
(0.15, 'Contacting server…'),
(0.35, 'Authorising terminal…'),
(0.60, 'Downloading products…'),
(0.85, 'Downloading customers…'),
(1.00, 'Writing to local storage…'),
];
for (final (progress, stage) in stages) {
await Future<void>.delayed(const Duration(milliseconds: 320));
if (simulateOffline) {
throw const CatalogueSyncException(
'No connection to the catalogue server. '
'Check the network and try again.',
);
}
onProgress?.call(progress, stage);
}
return CatalogueSnapshot(
products: SeedData.products(),
customers: SeedData.customers(),
fetchedAt: DateTime.now(),
revision: 'rev-${DateTime.now().millisecondsSinceEpoch % 100000}',
);
}
}
/// Stands in for the back-office reporting API.
class RemoteReportSink {
RemoteReportSink();
bool simulateOffline = false;
/// Pushes one payload. Throws on failure so the caller can keep the event
/// queued rather than marking it sent.
Future<String> push(Map<String, Object?> payload) async {
await Future<void>.delayed(const Duration(milliseconds: 900));
if (simulateOffline) {
throw const CatalogueSyncException(
'Could not reach the reporting server. '
'The report is still saved on this terminal.',
);
}
return 'ACK-${DateTime.now().millisecondsSinceEpoch % 1000000}';
}
}

View File

@@ -0,0 +1,542 @@
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
/// Demo catalogue and customer book.
///
/// Barcodes are valid 13-digit EAN strings beginning with the Indian GS1
/// prefix `890`, so a real scanner can be tested against this data.
class SeedData {
const SeedData._();
static List<Product> products() => const [
// ------------------------------------------------------------ Dairy
Product(
id: 'p001',
name: 'Amul Milk 1L',
barcode: '8901234500011',
sku: 'DRY-MLK-1000',
category: ProductCategory.dairy,
price: 62,
mrp: 66,
stock: 50,
emoji: '🥛',
unit: UnitOfMeasure.litre,
gstRate: 0.05,
brand: 'Amul',
),
Product(
id: 'p002',
name: 'Amul Butter 500g',
barcode: '8901234500028',
sku: 'DRY-BTR-0500',
category: ProductCategory.dairy,
price: 245,
mrp: 265,
stock: 30,
emoji: '🧈',
gstRate: 0.12,
brand: 'Amul',
),
Product(
id: 'p003',
name: 'Curd 400g',
barcode: '8901234500035',
sku: 'DRY-CRD-0400',
category: ProductCategory.dairy,
price: 48,
mrp: 52,
stock: 40,
emoji: '🥣',
gstRate: 0.05,
brand: 'Nandini',
),
Product(
id: 'p004',
name: 'Paneer 200g',
barcode: '8901234500042',
sku: 'DRY-PNR-0200',
category: ProductCategory.dairy,
price: 90,
stock: 20,
emoji: '🧀',
gstRate: 0.05,
brand: 'Milky Mist',
),
Product(
id: 'p005',
name: 'Cheese Slices 200g',
barcode: '8901234500059',
sku: 'DRY-CHS-0200',
category: ProductCategory.dairy,
price: 135,
mrp: 145,
stock: 25,
emoji: '🧀',
gstRate: 0.12,
brand: 'Britannia',
),
// ---------------------------------------------------------- Grocery
Product(
id: 'p010',
name: 'Basmati Rice 1kg',
barcode: '8901234500110',
sku: 'GRO-RCE-1000',
category: ProductCategory.grocery,
price: 180,
mrp: 199,
stock: 4,
emoji: '🍚',
unit: UnitOfMeasure.kilogram,
gstRate: 0.05,
brand: 'India Gate',
),
Product(
id: 'p011',
name: 'Fortune Oil 1L',
barcode: '8901234500127',
sku: 'GRO-OIL-1000',
category: ProductCategory.grocery,
price: 145,
mrp: 160,
stock: 60,
emoji: '🛢️',
unit: UnitOfMeasure.litre,
gstRate: 0.05,
brand: 'Fortune',
),
Product(
id: 'p012',
name: 'Toor Dal 500g',
barcode: '8901234500134',
sku: 'GRO-DAL-0500',
category: ProductCategory.grocery,
price: 90,
stock: 45,
emoji: '🫘',
gstRate: 0.05,
brand: 'Tata Sampann',
),
Product(
id: 'p013',
name: 'Aashirvaad Atta 5kg',
barcode: '8901234500141',
sku: 'GRO-ATA-5000',
category: ProductCategory.grocery,
price: 285,
mrp: 310,
stock: 35,
emoji: '🌾',
unit: UnitOfMeasure.kilogram,
gstRate: 0.05,
brand: 'Aashirvaad',
),
Product(
id: 'p014',
name: 'Sugar 1kg',
barcode: '8901234500158',
sku: 'GRO-SGR-1000',
category: ProductCategory.grocery,
price: 48,
stock: 80,
emoji: '🍬',
unit: UnitOfMeasure.kilogram,
gstRate: 0.05,
),
Product(
id: 'p015',
name: 'Maggi 2-min',
barcode: '8901234500165',
sku: 'GRO-MAG-0070',
category: ProductCategory.grocery,
price: 14,
stock: 120,
emoji: '🍜',
gstRate: 0.12,
brand: 'Nestlé',
),
Product(
id: 'p016',
name: 'Tata Salt 1kg',
barcode: '8901234500172',
sku: 'GRO-SLT-1000',
category: ProductCategory.grocery,
price: 28,
stock: 95,
emoji: '🧂',
unit: UnitOfMeasure.kilogram,
gstRate: 0.05,
brand: 'Tata',
),
// -------------------------------------------------------- Beverages
Product(
id: 'p020',
name: 'Coca-Cola 600ml',
barcode: '8901234500219',
sku: 'BEV-COK-0600',
category: ProductCategory.beverages,
price: 40,
stock: 80,
emoji: '🥤',
unit: UnitOfMeasure.millilitre,
gstRate: 0.28,
brand: 'Coca-Cola',
),
Product(
id: 'p021',
name: 'Frooti 250ml',
barcode: '8901234500226',
sku: 'BEV-FRT-0250',
category: ProductCategory.beverages,
price: 15,
stock: 100,
emoji: '🥭',
gstRate: 0.12,
brand: 'Parle Agro',
),
Product(
id: 'p022',
name: 'Bisleri 1L',
barcode: '8901234500233',
sku: 'BEV-WTR-1000',
category: ProductCategory.beverages,
price: 20,
stock: 150,
emoji: '💧',
unit: UnitOfMeasure.litre,
gstRate: 0.18,
brand: 'Bisleri',
),
Product(
id: 'p023',
name: 'Red Bull 250ml',
barcode: '8901234500240',
sku: 'BEV-RBL-0250',
category: ProductCategory.beverages,
price: 125,
stock: 40,
emoji: '🔋',
gstRate: 0.28,
brand: 'Red Bull',
),
Product(
id: 'p024',
name: 'Bru Coffee 100g',
barcode: '8901234500257',
sku: 'BEV-COF-0100',
category: ProductCategory.beverages,
price: 165,
mrp: 180,
stock: 30,
emoji: '',
gstRate: 0.18,
brand: 'Bru',
),
// ----------------------------------------------------------- Snacks
Product(
id: 'p030',
name: 'Parle-G 800g',
barcode: '8901234500318',
sku: 'SNK-PGB-0800',
category: ProductCategory.snacks,
price: 40,
stock: 90,
emoji: '🍪',
gstRate: 0.18,
brand: 'Parle',
),
Product(
id: 'p031',
name: "Lay's Chips 26g",
barcode: '8901234500325',
sku: 'SNK-LAY-0026',
category: ProductCategory.snacks,
price: 20,
stock: 110,
emoji: '🥔',
gstRate: 0.18,
brand: "Lay's",
),
Product(
id: 'p032',
name: 'Dairy Milk 55g',
barcode: '8901234500332',
sku: 'SNK-DMK-0055',
category: ProductCategory.snacks,
price: 45,
stock: 75,
emoji: '🍫',
gstRate: 0.18,
brand: 'Cadbury',
),
Product(
id: 'p033',
name: 'Good Day 200g',
barcode: '8901234500349',
sku: 'SNK-GDY-0200',
category: ProductCategory.snacks,
price: 35,
stock: 85,
emoji: '🍪',
gstRate: 0.18,
brand: 'Britannia',
),
Product(
id: 'p034',
name: 'Haldiram Mixture 200g',
barcode: '8901234500356',
sku: 'SNK-HMX-0200',
category: ProductCategory.snacks,
price: 55,
stock: 60,
emoji: '🥜',
gstRate: 0.12,
brand: 'Haldiram',
),
// ---------------------------------------------------- Personal care
Product(
id: 'p040',
name: 'Colgate 200g',
barcode: '8901234500417',
sku: 'PER-CLG-0200',
category: ProductCategory.personalCare,
price: 110,
mrp: 125,
stock: 55,
emoji: '🪥',
gstRate: 0.18,
brand: 'Colgate',
),
Product(
id: 'p041',
name: 'Dove Soap 100g',
barcode: '8901234500424',
sku: 'PER-DVE-0100',
category: ProductCategory.personalCare,
price: 65,
stock: 70,
emoji: '🧼',
gstRate: 0.18,
brand: 'Dove',
),
Product(
id: 'p042',
name: 'Head & Shoulders 340ml',
barcode: '8901234500431',
sku: 'PER-HNS-0340',
category: ProductCategory.personalCare,
price: 385,
mrp: 420,
stock: 25,
emoji: '🧴',
gstRate: 0.18,
brand: 'P&G',
),
Product(
id: 'p043',
name: 'Nivea Lotion 200ml',
barcode: '8901234500448',
sku: 'PER-NVA-0200',
category: ProductCategory.personalCare,
price: 240,
stock: 30,
emoji: '🧴',
gstRate: 0.18,
brand: 'Nivea',
),
// -------------------------------------------------------- Household
Product(
id: 'p050',
name: 'Surf Excel 1kg',
barcode: '8901234500516',
sku: 'HSE-SRF-1000',
category: ProductCategory.household,
price: 165,
mrp: 180,
stock: 45,
emoji: '🧺',
unit: UnitOfMeasure.kilogram,
gstRate: 0.18,
brand: 'Surf Excel',
),
Product(
id: 'p051',
name: 'Vim Bar 300g',
barcode: '8901234500523',
sku: 'HSE-VIM-0300',
category: ProductCategory.household,
price: 30,
stock: 90,
emoji: '🧽',
gstRate: 0.18,
brand: 'Vim',
),
Product(
id: 'p052',
name: 'Harpic 500ml',
barcode: '8901234500530',
sku: 'HSE-HRP-0500',
category: ProductCategory.household,
price: 98,
stock: 40,
emoji: '🧴',
gstRate: 0.18,
brand: 'Harpic',
),
Product(
id: 'p053',
name: 'Garbage Bags 30pc',
barcode: '8901234500547',
sku: 'HSE-GBG-0030',
category: ProductCategory.household,
price: 145,
stock: 35,
emoji: '🗑️',
gstRate: 0.18,
),
// ----------------------------------------------------------- Fruits
Product(
id: 'p060',
name: 'Banana 1kg',
barcode: '8901234500615',
sku: 'FRT-BAN-1000',
category: ProductCategory.fruits,
price: 55,
stock: 40,
emoji: '🍌',
unit: UnitOfMeasure.kilogram,
gstRate: 0,
),
Product(
id: 'p061',
name: 'Apple Shimla 1kg',
barcode: '8901234500622',
sku: 'FRT-APL-1000',
category: ProductCategory.fruits,
price: 180,
stock: 25,
emoji: '🍎',
unit: UnitOfMeasure.kilogram,
gstRate: 0,
),
Product(
id: 'p062',
name: 'Alphonso Mango 1kg',
barcode: '8901234500639',
sku: 'FRT-MNG-1000',
category: ProductCategory.fruits,
price: 320,
stock: 15,
emoji: '🥭',
unit: UnitOfMeasure.kilogram,
gstRate: 0,
),
// ------------------------------------------------------- Vegetables
Product(
id: 'p070',
name: 'Tomato 1kg',
barcode: '8901234500714',
sku: 'VEG-TOM-1000',
category: ProductCategory.vegetables,
price: 40,
stock: 50,
emoji: '🍅',
unit: UnitOfMeasure.kilogram,
gstRate: 0,
),
Product(
id: 'p071',
name: 'Onion 1kg',
barcode: '8901234500721',
sku: 'VEG-ONI-1000',
category: ProductCategory.vegetables,
price: 35,
stock: 65,
emoji: '🧅',
unit: UnitOfMeasure.kilogram,
gstRate: 0,
),
Product(
id: 'p072',
name: 'Potato 1kg',
barcode: '8901234500738',
sku: 'VEG-POT-1000',
category: ProductCategory.vegetables,
price: 30,
stock: 70,
emoji: '🥔',
unit: UnitOfMeasure.kilogram,
gstRate: 0,
),
Product(
id: 'p073',
name: 'Carrot 500g',
barcode: '8901234500745',
sku: 'VEG-CAR-0500',
category: ProductCategory.vegetables,
price: 32,
stock: 8,
emoji: '🥕',
gstRate: 0,
),
];
static List<Customer> customers() => [
Customer(
id: 'c001',
name: 'Abhishek',
mobile: '9876543210',
email: 'abhishek@example.com',
gender: Gender.male,
dateOfBirth: DateTime(1994, 3, 18),
loyaltyPoints: 320,
lifetimeSpend: 24500,
visitCount: 41,
createdAt: DateTime(2024, 1, 12),
lastVisitAt: DateTime.now().subtract(const Duration(days: 3)),
),
Customer(
id: 'c002',
name: 'Priya Raman',
mobile: '9812345678',
email: 'priya.r@example.com',
gender: Gender.female,
dateOfBirth: DateTime(1990, 7, 2),
loyaltyPoints: 1180,
lifetimeSpend: 68200,
visitCount: 96,
createdAt: DateTime(2023, 6, 4),
lastVisitAt: DateTime.now().subtract(const Duration(days: 1)),
),
Customer(
id: 'c003',
name: 'Karthik S',
mobile: '9900112233',
gender: Gender.male,
loyaltyPoints: 45,
lifetimeSpend: 3200,
visitCount: 7,
createdAt: DateTime(2025, 2, 20),
lastVisitAt: DateTime.now().subtract(const Duration(days: 11)),
),
Customer(
id: 'c004',
name: 'Meena Lakshmi',
mobile: '9445566778',
email: 'meena.l@example.com',
gender: Gender.female,
dateOfBirth: DateTime(1986, 11, 30),
loyaltyPoints: 2640,
lifetimeSpend: 172000,
visitCount: 210,
createdAt: DateTime(2022, 9, 15),
lastVisitAt: DateTime.now().subtract(const Duration(hours: 20)),
),
];
}

View File

@@ -0,0 +1,96 @@
import 'package:uuid/uuid.dart';
import '../../core/utils/extensions.dart';
import '../../domain/entities/customer.dart';
import '../../domain/repositories/customer_repository.dart';
import '../datasources/local_store.dart';
class CustomerRepositoryImpl implements CustomerRepository {
CustomerRepositoryImpl(this._store);
final LocalStore _store;
static const _uuid = Uuid();
String _digits(String v) => v.replaceAll(RegExp(r'\D'), '');
@override
Future<Customer?> findByMobile(String mobile) async {
final needle = _digits(mobile);
return _store.customers
.firstWhereOrNull((c) => _digits(c.mobile) == needle);
}
@override
Future<Customer?> findById(String id) async => _store.customerById(id);
@override
Future<Customer> create(Customer customer) async {
final existing = await findByMobile(customer.mobile);
if (existing != null) {
throw StateError('A customer with this mobile number already exists.');
}
final created = Customer(
id: _uuid.v4(),
name: customer.name.trim(),
mobile: _digits(customer.mobile),
email: customer.email?.trim().isEmpty ?? true
? null
: customer.email!.trim(),
gender: customer.gender,
dateOfBirth: customer.dateOfBirth,
loyaltyPoints: 0,
lifetimeSpend: 0,
visitCount: 0,
createdAt: DateTime.now(),
);
_store.putCustomer(created);
return created;
}
@override
Future<Customer> update(Customer customer) async {
_store.putCustomer(customer);
return customer;
}
@override
Future<Customer> recordSale({
required String customerId,
required double amount,
required int pointsEarned,
required int pointsRedeemed,
}) async {
final current = _store.customerById(customerId);
if (current == null) {
throw StateError('Customer $customerId not found.');
}
final updated = current.copyWith(
loyaltyPoints:
(current.loyaltyPoints - pointsRedeemed + pointsEarned)
.clamp(0, 1 << 31),
lifetimeSpend: (current.lifetimeSpend + amount).asMoney,
visitCount: current.visitCount + 1,
lastVisitAt: DateTime.now(),
);
_store.putCustomer(updated);
return updated;
}
@override
Future<List<Customer>> search(String query) async {
final q = query.trim().toLowerCase();
if (q.isEmpty) return recent();
return _store.customers
.where((c) =>
c.name.toLowerCase().contains(q) || _digits(c.mobile).contains(q))
.toList();
}
@override
Future<List<Customer>> recent({int limit = 20}) async {
final list = _store.customers.toList()
..sort((a, b) => (b.lastVisitAt ?? DateTime(2000))
.compareTo(a.lastVisitAt ?? DateTime(2000)));
return list.take(limit).toList();
}
}

View File

@@ -0,0 +1,68 @@
import '../../core/utils/extensions.dart';
import '../../domain/entities/product.dart';
import '../../domain/repositories/product_repository.dart';
import '../datasources/local_store.dart';
class ProductRepositoryImpl implements ProductRepository {
ProductRepositoryImpl(this._store);
final LocalStore _store;
@override
Future<List<Product>> getAll() async =>
_store.products.where((p) => p.isActive).toList();
@override
Future<List<Product>> getByCategory(ProductCategory category) async =>
_store.products
.where((p) => p.isActive && p.category == category)
.toList();
@override
Future<Product?> findByBarcode(String barcode) async {
final needle = barcode.trim();
return _store.products.firstWhereOrNull(
(p) => p.barcode == needle && p.isActive,
);
}
@override
Future<Product?> findById(String id) async => _store.productById(id);
@override
Future<List<Product>> search(String query) async {
final q = query.trim();
if (q.isEmpty) return getAll();
final results = _store.products.where((p) => p.isActive && p.matches(q));
// Rank exact barcode and SKU hits above fuzzy name matches so the top
// result is the one the cashier almost certainly meant.
final ranked = results.toList()
..sort((a, b) => _score(b, q).compareTo(_score(a, q)));
return ranked;
}
int _score(Product p, String q) {
final lq = q.toLowerCase();
if (p.barcode == q) return 100;
if (p.sku.toLowerCase() == lq) return 90;
if (p.name.toLowerCase().startsWith(lq)) return 70;
if (p.name.toLowerCase().contains(lq)) return 50;
if (p.brand?.toLowerCase().contains(lq) ?? false) return 30;
return 10;
}
@override
Future<void> decrementStock(Map<String, double> quantities) async {
quantities.forEach((id, qty) {
final p = _store.productById(id);
if (p == null) return;
final next = (p.stock - qty).clamp(0, double.infinity).toDouble();
_store.putProduct(p.copyWith(stock: next));
});
}
@override
Future<void> upsert(Product product) async => _store.putProduct(product);
}

View File

@@ -0,0 +1,159 @@
import 'package:uuid/uuid.dart';
import '../../core/utils/formatters.dart';
import '../../domain/entities/shift_report.dart';
import '../../domain/entities/sync_event.dart';
import '../../domain/repositories/sync_repository.dart';
import '../datasources/local_store.dart';
import '../datasources/remote_catalogue_source.dart';
class SyncRepositoryImpl implements SyncRepository {
SyncRepositoryImpl(this._store, this._catalogue, this._reports);
final LocalStore _store;
final RemoteCatalogueSource _catalogue;
final RemoteReportSink _reports;
static const _uuid = Uuid();
@override
bool get hasCatalogue => _store.hasCatalogue;
@override
DateTime? get lastImportAt => _store.lastImportAt;
@override
String? get catalogueRevision => _store.catalogueRevision;
@override
List<SyncEvent> get events => _store.events;
@override
bool get hasUnsyncedEvents => _store.hasUnsyncedEvents;
@override
Future<SyncEvent> importCatalogue({
void Function(double progress, String stage)? onProgress,
}) async {
final event = SyncEvent(
id: _uuid.v4(),
type: SyncEventType.catalogueImport,
status: SyncStatus.syncing,
createdAt: DateTime.now(),
summary: 'Catalogue import started',
);
_store.addEvent(event);
try {
final snapshot = await _catalogue.fetch(onProgress: onProgress);
_store.importCatalogue(
products: snapshot.products,
customers: snapshot.customers,
revision: snapshot.revision,
at: snapshot.fetchedAt,
);
final done = event.copyWith(
status: SyncStatus.synced,
syncedAt: DateTime.now(),
attempts: 1,
);
final settled = SyncEvent(
id: done.id,
type: done.type,
status: done.status,
createdAt: done.createdAt,
summary: '${snapshot.products.length} products, '
'${snapshot.customers.length} customers · ${snapshot.revision}',
payload: {
'products': snapshot.products.length,
'customers': snapshot.customers.length,
'revision': snapshot.revision,
},
syncedAt: done.syncedAt,
attempts: 1,
);
_store.updateEvent(settled);
return settled;
} catch (e) {
final failed = event.copyWith(
status: SyncStatus.failed,
error: e.toString(),
attempts: 1,
);
_store.updateEvent(failed);
return failed;
}
}
@override
ShiftReport buildShiftReport({
required DateTime businessDate,
required String terminalId,
required String cashierName,
}) {
return ShiftReport.fromTransactions(
transactions: _store.transactions,
businessDate: businessDate,
terminalId: terminalId,
cashierName: cashierName,
);
}
@override
Future<SyncEvent> pushShiftReport(ShiftReport report) async {
// Queued first, so the data is durable before the network is touched.
final queued = SyncEvent(
id: _uuid.v4(),
type: SyncEventType.shiftReport,
status: SyncStatus.pending,
createdAt: DateTime.now(),
summary: '${report.billCount} bills · '
'${Formatters.money(report.grossSales)} · '
'${Formatters.date(report.businessDate)}',
payload: report.toPayload(),
);
_store.addEvent(queued);
return _attempt(queued);
}
@override
Future<SyncEvent> retry(String eventId) async {
final matches = _store.events.where((e) => e.id == eventId).toList();
if (matches.isEmpty) {
throw StateError('No queued event with id $eventId');
}
final event = matches.first;
if (event.type == SyncEventType.catalogueImport) {
return importCatalogue();
}
return _attempt(event);
}
/// Sends one event, leaving it queued if the push fails.
Future<SyncEvent> _attempt(SyncEvent event) async {
_store.updateEvent(event.copyWith(status: SyncStatus.syncing));
try {
await _reports.push(event.payload);
final done = event.copyWith(
status: SyncStatus.synced,
syncedAt: DateTime.now(),
attempts: event.attempts + 1,
clearError: true,
);
_store.updateEvent(done);
return done.copyWith();
} catch (e) {
final failed = event.copyWith(
status: SyncStatus.failed,
error: e.toString(),
attempts: event.attempts + 1,
);
_store.updateEvent(failed);
return failed;
}
}
}

View File

@@ -0,0 +1,49 @@
import '../../core/utils/extensions.dart';
import '../../domain/entities/transaction.dart';
import '../../domain/repositories/transaction_repository.dart';
import '../datasources/local_store.dart';
class TransactionRepositoryImpl implements TransactionRepository {
TransactionRepositoryImpl(this._store);
final LocalStore _store;
@override
Future<SaleTransaction> save(SaleTransaction transaction) async {
_store.addTransaction(transaction);
return transaction;
}
@override
Future<List<SaleTransaction>> history({int limit = 50}) async =>
_store.transactions.take(limit).toList();
@override
Future<SaleTransaction?> findByInvoice(String invoiceNumber) async =>
_store.transactions
.firstWhereOrNull((t) => t.invoiceNumber == invoiceNumber);
@override
Future<int> nextInvoiceSequence() async => _store.nextInvoiceSequence();
@override
Future<void> park(ParkedBill bill) async => _store.addParked(bill);
@override
Future<List<ParkedBill>> parkedBills() async => _store.parked;
@override
Future<void> removeParked(String id) async => _store.removeParked(id);
@override
Future<double> salesTotalForDay(DateTime day) async {
return _store.transactions
.where((t) =>
t.status == TransactionStatus.completed &&
t.createdAt.year == day.year &&
t.createdAt.month == day.month &&
t.createdAt.day == day.day)
.fold(0.0, (sum, t) => sum + t.total)
.asMoney;
}
}

View File

@@ -0,0 +1,238 @@
import 'package:equatable/equatable.dart';
import '../../core/constants/app_constants.dart';
import '../../core/utils/extensions.dart';
import 'customer.dart';
import 'product.dart';
/// How a discount value should be interpreted.
enum DiscountType { none, percentage, flat }
/// A discount applied to a single line or to the whole bill.
class Discount extends Equatable {
const Discount({this.type = DiscountType.none, this.value = 0, this.reason});
final DiscountType type;
final double value;
final String? reason;
static const Discount none = Discount();
bool get isActive => type != DiscountType.none && value > 0;
/// Resolves the discount to rupees against [base], never exceeding it.
double amountOn(double base) {
if (!isActive || base <= 0) return 0;
final raw = switch (type) {
DiscountType.percentage => base * (value / 100),
DiscountType.flat => value,
DiscountType.none => 0.0,
};
return raw.clamp(0, base).toDouble().asMoney;
}
String get label => switch (type) {
DiscountType.percentage => '${value.toStringAsFixed(0)}% off',
DiscountType.flat => 'Flat ${AppConstants.currencySymbol}$value off',
DiscountType.none => 'No discount',
};
@override
List<Object?> get props => [type, value, reason];
}
/// One product line inside the cart.
class CartLine extends Equatable {
const CartLine({
required this.product,
required this.quantity,
this.discount = Discount.none,
this.addedAt,
});
final Product product;
final double quantity;
final Discount discount;
final DateTime? addedAt;
String get id => product.id;
/// Line value before discount, GST inclusive.
double get grossAmount => (product.price * quantity).asMoney;
double get discountAmount => discount.amountOn(grossAmount);
/// Payable for this line after discount, GST inclusive.
double get payable => (grossAmount - discountAmount).asMoney;
/// Taxable value inside [payable].
double get taxableValue => (payable / (1 + product.gstRate)).asMoney;
/// GST rupees inside [payable].
double get taxAmount => (payable - taxableValue).asMoney;
double get cgst => (taxAmount / 2).asMoney;
double get sgst => (taxAmount / 2).asMoney;
double get mrpSavings => product.hasDiscount
? (product.savings * quantity).asMoney
: 0;
bool get exceedsStock => quantity > product.stock;
CartLine copyWith({double? quantity, Discount? discount}) => CartLine(
product: product,
quantity: quantity ?? this.quantity,
discount: discount ?? this.discount,
addedAt: addedAt,
);
@override
List<Object?> get props => [product.id, quantity, discount];
}
/// The live bill. Immutable — every mutation returns a new instance, which
/// keeps the Riverpod notifier predictable and makes undo trivial.
class Cart extends Equatable {
const Cart({
this.lines = const [],
this.customer,
this.billDiscount = Discount.none,
this.pointsRedeemed = 0,
this.note,
});
final List<CartLine> lines;
final Customer? customer;
final Discount billDiscount;
final int pointsRedeemed;
final String? note;
static const Cart empty = Cart();
bool get isEmpty => lines.isEmpty;
bool get isNotEmpty => lines.isNotEmpty;
bool get isWalkIn => customer == null;
int get lineCount => lines.length;
double get totalQuantity =>
lines.fold(0.0, (sum, l) => sum + l.quantity);
/// Sum of line values before any bill-level discount, GST inclusive.
double get subtotal =>
lines.fold(0.0, (sum, l) => sum + l.payable).asMoney;
/// Discounts applied at the individual line level.
double get lineDiscountTotal =>
lines.fold(0.0, (sum, l) => sum + l.discountAmount).asMoney;
/// Automatic discount earned through the customer's membership tier.
Discount get membershipDiscount {
final rate = customer?.tier.discountRate ?? 0;
if (rate <= 0) return Discount.none;
return Discount(
type: DiscountType.percentage,
value: rate * 100,
reason: '${customer!.tier.label} member',
);
}
double get membershipDiscountAmount =>
membershipDiscount.amountOn(subtotal);
double get manualBillDiscountAmount => billDiscount.amountOn(subtotal);
/// All bill-level reductions combined.
double get billDiscountTotal =>
(membershipDiscountAmount + manualBillDiscountAmount)
.clamp(0, subtotal)
.toDouble()
.asMoney;
double get loyaltyRedemptionValue =>
(pointsRedeemed * AppConstants.loyaltyPointValue).asMoney;
/// Payable after every discount, GST inclusive, before round-off.
double get netAmount {
final v = subtotal - billDiscountTotal - loyaltyRedemptionValue;
return v.clamp(0, double.infinity).toDouble().asMoney;
}
/// Proportion of the bill remaining after bill-level reductions. Used to
/// spread those reductions fairly across lines when apportioning GST.
double get _billFactor => subtotal <= 0 ? 1 : netAmount / subtotal;
/// GST payable across the bill, after apportioning bill-level discounts.
double get taxAmount =>
lines.fold(0.0, (sum, l) => sum + l.taxAmount * _billFactor).asMoney;
double get cgst => (taxAmount / 2).asMoney;
double get sgst => (taxAmount / 2).asMoney;
/// Taxable value across the bill.
double get taxableAmount => (netAmount - taxAmount).asMoney;
/// GST broken out per slab — required on a compliant tax invoice.
Map<double, double> get taxBreakdown {
final map = <double, double>{};
for (final line in lines) {
final rate = line.product.gstRate;
map[rate] = ((map[rate] ?? 0) + line.taxAmount * _billFactor).asMoney;
}
return map;
}
double get grandTotal => netAmount.roundedToRupee;
/// The paise adjustment shown as "Round Off" on the bill.
double get roundOff => (grandTotal - netAmount).asMoney;
double get mrpSavingsTotal =>
lines.fold(0.0, (sum, l) => sum + l.mrpSavings).asMoney;
/// Everything the shopper saved on this bill.
double get totalSavings =>
(mrpSavingsTotal + lineDiscountTotal + billDiscountTotal).asMoney;
/// Points this sale will earn. Walk-in customers earn nothing.
int get pointsEarned {
if (customer == null) return 0;
return (grandTotal / AppConstants.loyaltyRupeesPerPoint).floor();
}
int get maxRedeemablePoints {
final c = customer;
if (c == null) return 0;
final byBalance = c.loyaltyPoints;
final byBill =
(subtotal - billDiscountTotal) ~/ AppConstants.loyaltyPointValue;
return byBalance < byBill ? byBalance : byBill;
}
CartLine? lineFor(String productId) =>
lines.firstWhereOrNull((l) => l.product.id == productId);
bool contains(String productId) => lineFor(productId) != null;
Cart copyWith({
List<CartLine>? lines,
Customer? customer,
bool clearCustomer = false,
Discount? billDiscount,
int? pointsRedeemed,
String? note,
}) {
return Cart(
lines: lines ?? this.lines,
customer: clearCustomer ? null : (customer ?? this.customer),
billDiscount: billDiscount ?? this.billDiscount,
pointsRedeemed: pointsRedeemed ?? this.pointsRedeemed,
note: note ?? this.note,
);
}
@override
List<Object?> get props =>
[lines, customer, billDiscount, pointsRedeemed, note];
}

View File

@@ -0,0 +1,123 @@
import 'package:equatable/equatable.dart';
import '../../core/constants/app_constants.dart';
enum Gender {
male('Male'),
female('Female'),
other('Other'),
unspecified('Prefer not to say');
const Gender(this.label);
final String label;
}
/// Loyalty tier, derived from lifetime spend.
enum MembershipTier {
bronze('Bronze', 0, 0.0),
silver('Silver', 10000, 0.02),
gold('Gold', 50000, 0.05),
platinum('Platinum', 150000, 0.08);
const MembershipTier(this.label, this.threshold, this.discountRate);
final String label;
/// Lifetime spend in rupees required to reach this tier.
final double threshold;
/// Automatic bill discount granted to members of this tier.
final double discountRate;
static MembershipTier forSpend(double lifetimeSpend) {
return MembershipTier.values.lastWhere(
(t) => lifetimeSpend >= t.threshold,
orElse: () => MembershipTier.bronze,
);
}
MembershipTier? get next {
final i = index;
return i < MembershipTier.values.length - 1
? MembershipTier.values[i + 1]
: null;
}
}
/// A registered shopper. A `null` customer on a sale means walk-in.
class Customer extends Equatable {
const Customer({
required this.id,
required this.name,
required this.mobile,
this.email,
this.gender = Gender.unspecified,
this.dateOfBirth,
this.loyaltyPoints = 0,
this.lifetimeSpend = 0,
this.visitCount = 0,
this.createdAt,
this.lastVisitAt,
});
final String id;
final String name;
final String mobile;
final String? email;
final Gender gender;
final DateTime? dateOfBirth;
final int loyaltyPoints;
final double lifetimeSpend;
final int visitCount;
final DateTime? createdAt;
final DateTime? lastVisitAt;
MembershipTier get tier => MembershipTier.forSpend(lifetimeSpend);
/// Cash value of the points currently held.
double get redeemableValue =>
loyaltyPoints * AppConstants.loyaltyPointValue;
/// Rupees of additional spend needed to reach the next tier.
double? get spendToNextTier {
final next = tier.next;
if (next == null) return null;
return (next.threshold - lifetimeSpend).clamp(0, double.infinity);
}
bool get isBirthdayToday {
final dob = dateOfBirth;
if (dob == null) return false;
final now = DateTime.now();
return dob.month == now.month && dob.day == now.day;
}
Customer copyWith({
String? name,
String? email,
Gender? gender,
DateTime? dateOfBirth,
int? loyaltyPoints,
double? lifetimeSpend,
int? visitCount,
DateTime? lastVisitAt,
}) {
return Customer(
id: id,
name: name ?? this.name,
mobile: mobile,
email: email ?? this.email,
gender: gender ?? this.gender,
dateOfBirth: dateOfBirth ?? this.dateOfBirth,
loyaltyPoints: loyaltyPoints ?? this.loyaltyPoints,
lifetimeSpend: lifetimeSpend ?? this.lifetimeSpend,
visitCount: visitCount ?? this.visitCount,
createdAt: createdAt,
lastVisitAt: lastVisitAt ?? this.lastVisitAt,
);
}
@override
List<Object?> get props => [id, name, mobile, loyaltyPoints, lifetimeSpend];
}

View File

@@ -0,0 +1,134 @@
import 'package:equatable/equatable.dart';
import '../../core/constants/app_constants.dart';
/// Merchandise categories shown as filter chips on the POS dashboard.
enum ProductCategory {
dairy('Dairy', '🥛'),
grocery('Grocery', '🛒'),
fruits('Fruits', '🍎'),
vegetables('Vegetables', '🥦'),
beverages('Beverages', '🥤'),
snacks('Snacks', '🍪'),
personalCare('Personal Care', '🧴'),
household('Household', '🏠');
const ProductCategory(this.label, this.emoji);
final String label;
final String emoji;
}
/// Unit of measure — drives whether fractional quantities are permitted.
enum UnitOfMeasure {
piece('pc'),
kilogram('kg'),
gram('g'),
litre('L'),
millilitre('ml'),
pack('pack');
const UnitOfMeasure(this.symbol);
final String symbol;
bool get allowsFractional =>
this == UnitOfMeasure.kilogram || this == UnitOfMeasure.litre;
}
/// A sellable item in the catalogue.
class Product extends Equatable {
const Product({
required this.id,
required this.name,
required this.barcode,
required this.sku,
required this.category,
required this.price,
required this.stock,
this.mrp,
this.emoji = '📦',
this.imageUrl,
this.unit = UnitOfMeasure.piece,
this.gstRate = AppConstants.defaultGstRate,
this.brand,
this.isActive = true,
});
final String id;
final String name;
final String barcode;
final String sku;
final ProductCategory category;
/// Selling price per [unit], inclusive of GST (Indian retail convention).
final double price;
/// Printed maximum retail price, used to display savings.
final double? mrp;
final double stock;
final String emoji;
final String? imageUrl;
final UnitOfMeasure unit;
final double gstRate;
final String? brand;
final bool isActive;
bool get isOutOfStock => stock <= 0;
bool get isLowStock =>
stock > 0 && stock <= AppConstants.lowStockThreshold;
bool get hasDiscount => mrp != null && mrp! > price;
double get savings => hasDiscount ? (mrp! - price) : 0;
double get discountPercent =>
hasDiscount ? ((mrp! - price) / mrp!) * 100 : 0;
/// Price stripped of embedded GST — the taxable value.
double get netPrice => price / (1 + gstRate);
/// GST rupees embedded inside [price].
double get taxPerUnit => price - netPrice;
/// Fuzzy match used by the search bar across name, barcode, SKU and brand.
bool matches(String query) {
final q = query.trim().toLowerCase();
if (q.isEmpty) return true;
return name.toLowerCase().contains(q) ||
barcode.toLowerCase().contains(q) ||
sku.toLowerCase().contains(q) ||
(brand?.toLowerCase().contains(q) ?? false) ||
category.label.toLowerCase().contains(q);
}
Product copyWith({
String? name,
double? price,
double? mrp,
double? stock,
ProductCategory? category,
bool? isActive,
}) {
return Product(
id: id,
name: name ?? this.name,
barcode: barcode,
sku: sku,
category: category ?? this.category,
price: price ?? this.price,
mrp: mrp ?? this.mrp,
stock: stock ?? this.stock,
emoji: emoji,
imageUrl: imageUrl,
unit: unit,
gstRate: gstRate,
brand: brand,
isActive: isActive ?? this.isActive,
);
}
@override
List<Object?> get props => [id, name, barcode, sku, price, stock, isActive];
}

View File

@@ -0,0 +1,152 @@
import 'package:equatable/equatable.dart';
import '../../core/utils/extensions.dart';
import 'transaction.dart';
/// Everything the back office needs from a day at this terminal.
///
/// Computed from the locally stored transactions, so it can be produced with
/// no connection and pushed whenever one is available.
class ShiftReport extends Equatable {
const ShiftReport({
required this.businessDate,
required this.terminalId,
required this.cashierName,
required this.billCount,
required this.itemCount,
required this.grossSales,
required this.taxCollected,
required this.discountGiven,
required this.roundOff,
required this.paymentBreakdown,
required this.loyaltyPointsIssued,
required this.loyaltyPointsRedeemed,
this.firstBillAt,
this.lastBillAt,
});
final DateTime businessDate;
final String terminalId;
final String cashierName;
final int billCount;
/// Total units sold across every bill.
final double itemCount;
final double grossSales;
final double taxCollected;
final double discountGiven;
final double roundOff;
final Map<PaymentMethod, double> paymentBreakdown;
final int loyaltyPointsIssued;
final int loyaltyPointsRedeemed;
final DateTime? firstBillAt;
final DateTime? lastBillAt;
/// A zeroed report for a day with no trading. Not a const — [DateTime]
/// cannot appear in a constant expression.
factory ShiftReport.blank({
required DateTime businessDate,
required String terminalId,
required String cashierName,
}) =>
ShiftReport(
businessDate: businessDate,
terminalId: terminalId,
cashierName: cashierName,
billCount: 0,
itemCount: 0,
grossSales: 0,
taxCollected: 0,
discountGiven: 0,
roundOff: 0,
paymentBreakdown: const {},
loyaltyPointsIssued: 0,
loyaltyPointsRedeemed: 0,
);
bool get isEmpty => billCount == 0;
double get averageBasket =>
billCount == 0 ? 0 : (grossSales / billCount).asMoney;
double get netOfTax => (grossSales - taxCollected).asMoney;
/// Builds the report from the day's transactions.
factory ShiftReport.fromTransactions({
required List<SaleTransaction> transactions,
required DateTime businessDate,
required String terminalId,
required String cashierName,
}) {
final completed = transactions
.where((t) =>
t.status == TransactionStatus.completed &&
t.createdAt.year == businessDate.year &&
t.createdAt.month == businessDate.month &&
t.createdAt.day == businessDate.day)
.toList()
..sort((a, b) => a.createdAt.compareTo(b.createdAt));
final byMethod = <PaymentMethod, double>{};
for (final t in completed) {
for (final p in t.payments) {
byMethod[p.method] = ((byMethod[p.method] ?? 0) + p.amount).asMoney;
}
}
return ShiftReport(
businessDate: businessDate,
terminalId: terminalId,
cashierName: cashierName,
billCount: completed.length,
itemCount:
completed.fold(0.0, (s, t) => s + t.cart.totalQuantity),
grossSales: completed.fold(0.0, (s, t) => s + t.total).asMoney,
taxCollected:
completed.fold(0.0, (s, t) => s + t.cart.taxAmount).asMoney,
discountGiven: completed
.fold(0.0,
(s, t) => s + t.cart.billDiscountTotal + t.cart.lineDiscountTotal)
.asMoney,
roundOff: completed.fold(0.0, (s, t) => s + t.cart.roundOff).asMoney,
paymentBreakdown: byMethod,
loyaltyPointsIssued:
completed.fold(0, (s, t) => s + t.pointsEarned),
loyaltyPointsRedeemed:
completed.fold(0, (s, t) => s + t.pointsRedeemed),
firstBillAt: completed.isEmpty ? null : completed.first.createdAt,
lastBillAt: completed.isEmpty ? null : completed.last.createdAt,
);
}
/// The JSON body that would be sent to the back office.
Map<String, Object?> toPayload() => {
'business_date': businessDate.toIso8601String().substring(0, 10),
'terminal_id': terminalId,
'cashier': cashierName,
'bill_count': billCount,
'item_count': itemCount,
'gross_sales': grossSales,
'net_of_tax': netOfTax,
'tax_collected': taxCollected,
'discount_given': discountGiven,
'round_off': roundOff,
'average_basket': averageBasket,
'loyalty_points_issued': loyaltyPointsIssued,
'loyalty_points_redeemed': loyaltyPointsRedeemed,
'first_bill_at': firstBillAt?.toIso8601String(),
'last_bill_at': lastBillAt?.toIso8601String(),
'payments': {
for (final e in paymentBreakdown.entries) e.key.name: e.value,
},
};
@override
List<Object?> get props =>
[businessDate, terminalId, billCount, grossSales];
}

View File

@@ -0,0 +1,63 @@
import 'package:equatable/equatable.dart';
/// What a staff member is allowed to do.
enum StaffRole {
admin('Admin', 'Full access to every module'),
manager('Manager', 'Sales, inventory and reports'),
cashier('Cashier', 'Billing and customers only');
const StaffRole(this.label, this.description);
final String label;
final String description;
bool get canVoidSale => this != StaffRole.cashier;
bool get canEditPricing => this == StaffRole.admin;
bool get canViewReports => this != StaffRole.cashier;
}
/// A person who signs in at the terminal.
class StaffUser extends Equatable {
const StaffUser({
required this.id,
required this.name,
required this.role,
required this.pin,
});
final String id;
final String name;
final StaffRole role;
/// Four-digit quick-unlock code. Never rendered.
final String pin;
@override
List<Object?> get props => [id, name, role];
}
/// The registered outlet this terminal belongs to.
class StoreAccount extends Equatable {
const StoreAccount({
required this.id,
required this.name,
required this.email,
required this.address,
required this.gstin,
required this.phone,
required this.staff,
this.plan = 'Business',
});
final String id;
final String name;
final String email;
final String address;
final String gstin;
final String phone;
final List<StaffUser> staff;
final String plan;
@override
List<Object?> get props => [id, email];
}

View File

@@ -0,0 +1,85 @@
import 'package:equatable/equatable.dart';
/// The two moments this terminal talks to the server.
enum SyncEventType {
catalogueImport('Catalogue Import', 'Pulled products from the server'),
shiftReport('Shift Report', 'Pushed the day\'s takings to the server');
const SyncEventType(this.label, this.description);
final String label;
final String description;
bool get isInbound => this == SyncEventType.catalogueImport;
}
enum SyncStatus {
/// Held locally, not yet sent. Nothing is ever discarded in this state.
pending('Pending'),
syncing('Syncing'),
synced('Synced'),
failed('Failed');
const SyncStatus(this.label);
final String label;
bool get isTerminal => this == SyncStatus.synced;
bool get needsAttention => this == SyncStatus.failed || this == SyncStatus.pending;
}
/// A durable record of one sync attempt.
///
/// Events are never deleted on failure — a failed push stays queued so the
/// day's takings survive a dropped connection.
class SyncEvent extends Equatable {
const SyncEvent({
required this.id,
required this.type,
required this.status,
required this.createdAt,
required this.summary,
this.payload = const {},
this.syncedAt,
this.error,
this.attempts = 0,
});
final String id;
final SyncEventType type;
final SyncStatus status;
final DateTime createdAt;
/// One-line description shown in the events log.
final String summary;
/// What would be transmitted. Kept so a retry needs no recomputation.
final Map<String, Object?> payload;
final DateTime? syncedAt;
final String? error;
final int attempts;
SyncEvent copyWith({
SyncStatus? status,
DateTime? syncedAt,
String? error,
bool clearError = false,
int? attempts,
}) {
return SyncEvent(
id: id,
type: type,
status: status ?? this.status,
createdAt: createdAt,
summary: summary,
payload: payload,
syncedAt: syncedAt ?? this.syncedAt,
error: clearError ? null : (error ?? this.error),
attempts: attempts ?? this.attempts,
);
}
@override
List<Object?> get props => [id, status, attempts, syncedAt];
}

View File

@@ -0,0 +1,133 @@
import 'package:equatable/equatable.dart';
import '../../core/utils/extensions.dart';
import 'cart.dart';
import 'customer.dart';
enum PaymentMethod {
cash('Cash', '💵', true),
card('Card', '💳', false),
upi('UPI', '📱', false),
wallet('Wallet', '👛', false),
giftCard('Gift Card', '🎁', false),
loyalty('Loyalty Points', '', false);
const PaymentMethod(this.label, this.emoji, this.needsChange);
final String label;
final String emoji;
/// Only cash tenders can be over-paid and produce change.
final bool needsChange;
/// Non-cash tenders normally capture a reference number.
bool get needsReference =>
this == PaymentMethod.card ||
this == PaymentMethod.upi ||
this == PaymentMethod.giftCard;
}
/// A single tender against a bill. A split payment holds several of these.
class PaymentSplit extends Equatable {
const PaymentSplit({
required this.method,
required this.amount,
this.tendered,
this.reference,
});
final PaymentMethod method;
/// Amount settled by this tender.
final double amount;
/// Cash handed over — may exceed [amount].
final double? tendered;
/// Card approval code, UPI txn id, gift card number.
final String? reference;
double get change {
if (!method.needsChange || tendered == null) return 0;
final diff = tendered! - amount;
return diff > 0 ? diff.asMoney : 0;
}
@override
List<Object?> get props => [method, amount, tendered, reference];
}
enum TransactionStatus { completed, parked, voided, refunded }
/// An immutable record of a finished sale.
class SaleTransaction extends Equatable {
const SaleTransaction({
required this.id,
required this.invoiceNumber,
required this.cart,
required this.payments,
required this.createdAt,
required this.cashierName,
this.status = TransactionStatus.completed,
this.terminalId = 'TERM-01',
});
final String id;
final String invoiceNumber;
final Cart cart;
final List<PaymentSplit> payments;
final DateTime createdAt;
final String cashierName;
final TransactionStatus status;
final String terminalId;
Customer? get customer => cart.customer;
double get total => cart.grandTotal;
double get amountPaid =>
payments.fold(0.0, (sum, p) => sum + p.amount).asMoney;
double get amountTendered => payments
.fold(0.0, (sum, p) => sum + (p.tendered ?? p.amount))
.asMoney;
double get changeDue =>
payments.fold(0.0, (sum, p) => sum + p.change).asMoney;
double get balanceDue => (total - amountPaid).clamp(0, double.infinity);
bool get isFullySettled => balanceDue <= 0.001;
bool get isSplit => payments.length > 1;
int get pointsEarned => cart.pointsEarned;
int get pointsRedeemed => cart.pointsRedeemed;
String get paymentSummary =>
payments.map((p) => p.method.label).toSet().join(' + ');
@override
List<Object?> get props => [id, invoiceNumber, createdAt, status];
}
/// A bill set aside so the cashier can serve the next shopper.
class ParkedBill extends Equatable {
const ParkedBill({
required this.id,
required this.cart,
required this.parkedAt,
this.label,
});
final String id;
final Cart cart;
final DateTime parkedAt;
final String? label;
String get displayLabel =>
label ?? cart.customer?.name ?? 'Walk-in #${id.substring(0, 4)}';
@override
List<Object?> get props => [id, parkedAt];
}

View File

@@ -0,0 +1,24 @@
import '../entities/customer.dart';
abstract class CustomerRepository {
/// Primary lookup on the Existing Customer screen.
Future<Customer?> findByMobile(String mobile);
Future<Customer?> findById(String id);
Future<Customer> create(Customer customer);
Future<Customer> update(Customer customer);
/// Applies loyalty and lifetime-spend changes once a sale completes.
Future<Customer> recordSale({
required String customerId,
required double amount,
required int pointsEarned,
required int pointsRedeemed,
});
Future<List<Customer>> search(String query);
Future<List<Customer>> recent({int limit = 20});
}

View File

@@ -0,0 +1,22 @@
import '../entities/product.dart';
/// Contract for catalogue access. Implemented in the data layer so the
/// presentation layer never depends on Hive, HTTP or any other detail.
abstract class ProductRepository {
Future<List<Product>> getAll();
Future<List<Product>> getByCategory(ProductCategory category);
/// Exact barcode lookup — the hot path for scanner billing.
Future<Product?> findByBarcode(String barcode);
Future<Product?> findById(String id);
/// Fuzzy search across name, barcode, SKU, brand and category.
Future<List<Product>> search(String query);
/// Decrements stock after a completed sale.
Future<void> decrementStock(Map<String, double> quantitiesByProductId);
Future<void> upsert(Product product);
}

View File

@@ -0,0 +1,38 @@
import '../entities/shift_report.dart';
import '../entities/sync_event.dart';
/// The terminal's two network touchpoints, plus the durable event log.
abstract class SyncRepository {
/// True once products have been pulled onto this terminal.
bool get hasCatalogue;
DateTime? get lastImportAt;
String? get catalogueRevision;
/// Pulls the catalogue and writes it locally.
///
/// Records a [SyncEventType.catalogueImport] event whether or not it
/// succeeds, so the log reflects every attempt.
Future<SyncEvent> importCatalogue({
void Function(double progress, String stage)? onProgress,
});
/// Builds the day's report from locally stored sales.
ShiftReport buildShiftReport({
required DateTime businessDate,
required String terminalId,
required String cashierName,
});
/// Queues the report and attempts to push it.
///
/// On failure the event is kept in [SyncStatus.failed] so nothing is lost.
Future<SyncEvent> pushShiftReport(ShiftReport report);
/// Retries a previously failed or pending push.
Future<SyncEvent> retry(String eventId);
List<SyncEvent> get events;
bool get hasUnsyncedEvents;
}

View File

@@ -0,0 +1,20 @@
import '../entities/transaction.dart';
abstract class TransactionRepository {
Future<SaleTransaction> save(SaleTransaction transaction);
Future<List<SaleTransaction>> history({int limit = 50});
Future<SaleTransaction?> findByInvoice(String invoiceNumber);
/// Next invoice sequence for the current month.
Future<int> nextInvoiceSequence();
Future<void> park(ParkedBill bill);
Future<List<ParkedBill>> parkedBills();
Future<void> removeParked(String id);
Future<double> salesTotalForDay(DateTime day);
}

View File

@@ -0,0 +1,139 @@
import 'package:uuid/uuid.dart';
import '../../core/constants/app_constants.dart';
import '../../core/utils/formatters.dart';
import '../entities/cart.dart';
import '../entities/customer.dart';
import '../entities/transaction.dart';
import '../repositories/customer_repository.dart';
import '../repositories/product_repository.dart';
import '../repositories/transaction_repository.dart';
/// Raised when a sale cannot be completed. Carries a cashier-readable message.
class CheckoutFailure implements Exception {
const CheckoutFailure(this.message);
final String message;
@override
String toString() => message;
}
/// Result of a successful checkout.
class CheckoutResult {
const CheckoutResult({required this.transaction, this.updatedCustomer});
final SaleTransaction transaction;
final Customer? updatedCustomer;
}
/// Completes a sale end to end.
///
/// Validates tenders, persists the transaction, decrements stock and applies
/// loyalty movement. Everything the cashier's Complete Sale button needs lives
/// here rather than in the UI, so the flow is unit-testable in isolation.
class CheckoutSale {
const CheckoutSale({
required ProductRepository productRepository,
required CustomerRepository customerRepository,
required TransactionRepository transactionRepository,
}) : _products = productRepository,
_customers = customerRepository,
_transactions = transactionRepository;
final ProductRepository _products;
final CustomerRepository _customers;
final TransactionRepository _transactions;
static const _uuid = Uuid();
Future<CheckoutResult> call({
required Cart cart,
required List<PaymentSplit> payments,
required String cashierName,
}) async {
_validate(cart, payments);
final now = DateTime.now();
final sequence = await _transactions.nextInvoiceSequence();
final transaction = SaleTransaction(
id: _uuid.v4(),
invoiceNumber: Formatters.invoiceNumber(sequence, now),
cart: cart,
payments: payments,
createdAt: now,
cashierName: cashierName,
);
await _transactions.save(transaction);
await _products.decrementStock({
for (final line in cart.lines) line.product.id: line.quantity,
});
Customer? updatedCustomer;
final customer = cart.customer;
if (customer != null) {
updatedCustomer = await _customers.recordSale(
customerId: customer.id,
amount: cart.grandTotal,
pointsEarned: cart.pointsEarned,
pointsRedeemed: cart.pointsRedeemed,
);
}
return CheckoutResult(
transaction: transaction,
updatedCustomer: updatedCustomer,
);
}
void _validate(Cart cart, List<PaymentSplit> payments) {
if (cart.isEmpty) {
throw const CheckoutFailure('Add at least one item before charging.');
}
if (payments.isEmpty) {
throw const CheckoutFailure('Select a payment method.');
}
for (final line in cart.lines) {
if (line.quantity <= 0) {
throw CheckoutFailure('${line.product.name} has an invalid quantity.');
}
if (line.exceedsStock) {
throw CheckoutFailure(
'Only ${line.product.stock.toStringAsFixed(0)} '
'${line.product.unit.symbol} of ${line.product.name} in stock.',
);
}
}
if (cart.pointsRedeemed > 0) {
final available = cart.customer?.loyaltyPoints ?? 0;
if (cart.pointsRedeemed > available) {
throw const CheckoutFailure('Not enough loyalty points to redeem.');
}
}
final paid = payments.fold(0.0, (sum, p) => sum + p.amount);
final shortfall = cart.grandTotal - paid;
if (shortfall > 0.01) {
throw CheckoutFailure(
'${AppConstants.currencySymbol}${shortfall.toStringAsFixed(2)} '
'still due on this bill.',
);
}
for (final p in payments) {
if (p.amount <= 0) {
throw CheckoutFailure('${p.method.label} amount must be positive.');
}
if (p.method.needsChange &&
p.tendered != null &&
p.tendered! < p.amount) {
throw const CheckoutFailure('Cash tendered is less than the amount due.');
}
}
}
}

37
lib/main.dart Normal file
View File

@@ -0,0 +1,37 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'app/app.dart';
import 'core/services/sound_service.dart';
import 'data/datasources/local_store.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await _configureChrome();
await LocalStore.instance.init();
await SoundService.instance.preload();
runApp(const ProviderScope(child: NearlePosApp()));
}
/// Locks the terminal into landscape and hides the system bars.
///
/// Both calls are Android/iOS only. On desktop the window manager owns sizing
/// and chrome, so we skip them — invoking them there is at best a no-op and can
/// raise a MissingPluginException on some engine builds.
Future<void> _configureChrome() async {
final isMobile = defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
if (kIsWeb || !isMobile) return;
await SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
}

View File

@@ -0,0 +1,115 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/constants/app_constants.dart';
import '../../../domain/entities/store_account.dart';
/// Sign-in state for the terminal.
sealed class AuthState {
const AuthState();
bool get isAuthenticated => this is Authenticated;
}
class Unauthenticated extends AuthState {
const Unauthenticated();
}
class Authenticating extends AuthState {
const Authenticating();
}
class Authenticated extends AuthState {
const Authenticated({required this.store, required this.user});
final StoreAccount store;
final StaffUser user;
}
class AuthFailure extends AuthState {
const AuthFailure(this.message);
final String message;
}
/// Credentials that ship with the demo build.
class DemoCredentials {
const DemoCredentials._();
static const String email = 'admin@nearle.in';
static const String password = 'nearle123';
}
const _demoStore = StoreAccount(
id: 'store-001',
name: AppConstants.storeName,
email: DemoCredentials.email,
address: AppConstants.storeAddress,
gstin: AppConstants.storeGstin,
phone: AppConstants.storePhone,
staff: [
StaffUser(id: 'u1', name: 'Suriya', role: StaffRole.admin, pin: '1234'),
StaffUser(id: 'u2', name: 'Divya', role: StaffRole.manager, pin: '2345'),
StaffUser(id: 'u3', name: 'Rahul', role: StaffRole.cashier, pin: '3456'),
],
);
/// Validates store credentials and holds the signed-in session.
///
/// Backed by a hardcoded account for now; swapping in a real identity provider
/// means changing only [signIn].
class AuthController extends StateNotifier<AuthState> {
AuthController() : super(const Unauthenticated());
Future<bool> signIn({
required String email,
required String password,
}) async {
state = const Authenticating();
// Stand-in for the network round trip.
await Future<void>.delayed(const Duration(milliseconds: 600));
final normalised = email.trim().toLowerCase();
if (normalised != DemoCredentials.email) {
state = const AuthFailure('No store is registered against that email.');
return false;
}
if (password != DemoCredentials.password) {
state = const AuthFailure('Incorrect password. Please try again.');
return false;
}
state = Authenticated(store: _demoStore, user: _demoStore.staff.first);
return true;
}
/// Switches the active operator without signing the store out.
void switchUser(StaffUser user) {
final current = state;
if (current is! Authenticated) return;
state = Authenticated(store: current.store, user: user);
}
void signOut() => state = const Unauthenticated();
void clearError() {
if (state is AuthFailure) state = const Unauthenticated();
}
}
final authControllerProvider =
StateNotifierProvider<AuthController, AuthState>((ref) => AuthController());
/// The signed-in store, or null before sign-in.
final currentStoreProvider = Provider<StoreAccount?>((ref) {
final s = ref.watch(authControllerProvider);
return s is Authenticated ? s.store : null;
});
/// The active operator, or null before sign-in.
final currentUserProvider = Provider<StaffUser?>((ref) {
final s = ref.watch(authControllerProvider);
return s is Authenticated ? s.user : null;
});

View File

@@ -0,0 +1,549 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../app/providers.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/validators.dart';
import '../../../core/widgets/primary_button.dart';
import '../providers/auth_controller.dart';
/// Store sign-in. The terminal shows this until a valid account is entered.
class LoginScreen extends ConsumerStatefulWidget {
const LoginScreen({super.key});
@override
ConsumerState<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends ConsumerState<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _email = TextEditingController(text: DemoCredentials.email);
final _password = TextEditingController(text: DemoCredentials.password);
bool _obscure = true;
bool _rememberTerminal = true;
@override
void dispose() {
_email.dispose();
_password.dispose();
super.dispose();
}
Future<void> _submit() async {
FocusScope.of(context).unfocus();
if (!(_formKey.currentState?.validate() ?? false)) return;
final ok = await ref.read(authControllerProvider.notifier).signIn(
email: _email.text,
password: _password.text,
);
if (ok && mounted) context.go(AppRoutes.welcome);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
body: LayoutBuilder(
builder: (context, constraints) {
// Below this there isn't room for the brand panel beside the form.
final showBrandPanel = constraints.maxWidth >= 1000;
return Row(
children: [
if (showBrandPanel)
const Expanded(flex: 5, child: _BrandPanel()),
Expanded(
flex: 4,
child: _FormPanel(
formKey: _formKey,
email: _email,
password: _password,
obscure: _obscure,
rememberTerminal: _rememberTerminal,
showCompactLogo: !showBrandPanel,
onToggleObscure: () => setState(() => _obscure = !_obscure),
onToggleRemember: (v) =>
setState(() => _rememberTerminal = v ?? true),
onSubmit: _submit,
),
),
],
);
},
),
);
}
}
class _BrandPanel extends StatelessWidget {
const _BrandPanel();
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(gradient: AppColors.primaryGradient),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.giant),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 42,
height: 42,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(11),
),
alignment: Alignment.center,
child: const Text(
'N',
style: TextStyle(
color: AppColors.primary,
fontSize: 23,
fontWeight: FontWeight.w800,
),
),
),
const SizedBox(width: AppSpacing.md),
const Flexible(
child: Text(
'Nearle POS',
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w700,
letterSpacing: -0.4,
),
),
),
],
),
const SizedBox(height: AppSpacing.giant),
const Text(
'Billing that keeps up\nwith your counter.',
style: TextStyle(
color: Colors.white,
fontSize: 34,
height: 1.25,
fontWeight: FontWeight.w700,
letterSpacing: -1,
),
),
const SizedBox(height: AppSpacing.lg),
Text(
'Scanner-first billing, GST-ready invoices and loyalty '
'built in — for supermarkets, pharmacies and retail.',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.78),
fontSize: 15,
height: 1.6,
),
),
const SizedBox(height: AppSpacing.giant),
const _Feature(
icon: Icons.qr_code_scanner_rounded,
title: 'Scan and go',
body: 'No dialogs between items. Barcode to bill instantly.',
),
const _Feature(
icon: Icons.receipt_long_rounded,
title: 'GST compliant',
body: 'Per-slab tax split into CGST and SGST on every bill.',
),
const _Feature(
icon: Icons.stars_rounded,
title: 'Loyalty that runs itself',
body: 'Tiers and points applied without cashier input.',
),
],
),
),
),
),
).animate().fadeIn(duration: 300.ms);
}
}
class _Feature extends StatelessWidget {
const _Feature({
required this.icon,
required this.title,
required this.body,
});
final IconData icon;
final String title;
final String body;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.xl),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.16),
borderRadius: AppRadius.brSm,
),
child: Icon(icon, color: Colors.white, size: 19),
),
const SizedBox(width: AppSpacing.lg),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
body,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.72),
fontSize: 13,
height: 1.5,
),
),
],
),
),
],
),
);
}
}
class _FormPanel extends ConsumerWidget {
const _FormPanel({
required this.formKey,
required this.email,
required this.password,
required this.obscure,
required this.rememberTerminal,
required this.showCompactLogo,
required this.onToggleObscure,
required this.onToggleRemember,
required this.onSubmit,
});
final GlobalKey<FormState> formKey;
final TextEditingController email;
final TextEditingController password;
final bool obscure;
final bool rememberTerminal;
final bool showCompactLogo;
final VoidCallback onToggleObscure;
final ValueChanged<bool?> onToggleRemember;
final VoidCallback onSubmit;
@override
Widget build(BuildContext context, WidgetRef ref) {
final auth = ref.watch(authControllerProvider);
final session = ref.watch(cashierSessionProvider);
final busy = auth is Authenticating;
return SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: Form(
key: formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (showCompactLogo) ...[
Center(
child: Container(
width: 52,
height: 52,
decoration: BoxDecoration(
gradient: AppColors.primaryGradient,
borderRadius: BorderRadius.circular(14),
),
alignment: Alignment.center,
child: const Text(
'N',
style: TextStyle(
color: Colors.white,
fontSize: 26,
fontWeight: FontWeight.w800,
),
),
),
),
const SizedBox(height: AppSpacing.xxl),
],
Text(
'Sign in to your store',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: AppSpacing.xs),
const Text(
'Use the credentials issued when your outlet was '
'registered.',
style: TextStyle(
fontSize: 13.5,
color: AppColors.textSecondary,
height: 1.5,
),
),
const SizedBox(height: AppSpacing.xxxl),
const _Label('Store email'),
TextFormField(
controller: email,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
enabled: !busy,
validator: (v) => (v ?? '').trim().isEmpty
? 'Store email is required'
: Validators.emailOptional(v),
decoration: const InputDecoration(
hintText: 'store@example.in',
prefixIcon: Icon(Icons.storefront_outlined),
),
),
const SizedBox(height: AppSpacing.lg),
const _Label('Password'),
TextFormField(
controller: password,
obscureText: obscure,
enabled: !busy,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => onSubmit(),
validator: (v) => (v ?? '').isEmpty
? 'Password is required'
: ((v ?? '').length < 6
? 'Password looks too short'
: null),
decoration: InputDecoration(
hintText: 'Enter your password',
prefixIcon: const Icon(Icons.lock_outline_rounded),
suffixIcon: IconButton(
onPressed: onToggleObscure,
icon: Icon(
obscure
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
size: 20,
),
tooltip: obscure ? 'Show password' : 'Hide password',
),
),
),
const SizedBox(height: AppSpacing.sm),
// Wrap, not Row — on a narrow tablet these would collide.
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
InkWell(
onTap: busy
? null
: () => onToggleRemember(!rememberTerminal),
borderRadius: AppRadius.brXs,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 22,
height: 22,
child: Checkbox(
value: rememberTerminal,
onChanged: busy ? null : onToggleRemember,
visualDensity: VisualDensity.compact,
),
),
const SizedBox(width: AppSpacing.sm),
const Text(
'Remember this terminal',
style: TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
),
),
],
),
),
),
TextButton(
onPressed: busy ? null : () {},
child: const Text('Forgot password?'),
),
],
),
if (auth is AuthFailure) ...[
const SizedBox(height: AppSpacing.sm),
Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brSm,
),
child: Row(
children: [
const Icon(Icons.error_outline_rounded,
color: AppColors.danger, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
auth.message,
style: const TextStyle(
color: AppColors.danger,
fontSize: 13,
),
),
),
],
),
).animate().shake(duration: 320.ms, hz: 3),
],
const SizedBox(height: AppSpacing.xl),
PrimaryButton(
label: 'Sign in',
icon: Icons.login_rounded,
large: true,
busy: busy,
onPressed: onSubmit,
),
const SizedBox(height: AppSpacing.xl),
_DemoHint(
onFill: busy
? null
: () {
email.text = DemoCredentials.email;
password.text = DemoCredentials.password;
},
),
const SizedBox(height: AppSpacing.xxl),
Center(
child: Text(
'Terminal ${session.terminalId}',
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
),
),
),
],
),
),
),
),
),
);
}
}
class _Label extends StatelessWidget {
const _Label(this.text);
final String text;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.sm),
child: Text(
text,
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
);
}
}
class _DemoHint extends StatelessWidget {
const _DemoHint({this.onFill});
final VoidCallback? onFill;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.primaryBorder),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.info_outline_rounded,
size: 17, color: AppColors.primary),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Demo account',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: AppColors.primary,
),
),
const SizedBox(height: 2),
SelectableText(
'${DemoCredentials.email} · ${DemoCredentials.password}',
style: const TextStyle(
fontSize: 12,
color: AppColors.textSecondary,
),
),
],
),
),
TextButton(
onPressed: onFill,
style: TextButton.styleFrom(
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm),
),
child: const Text('Fill', style: TextStyle(fontSize: 12.5)),
),
],
),
);
}
}

View File

@@ -0,0 +1,71 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../domain/entities/customer.dart';
/// Outcome of the mobile-number lookup on the Existing Customer screen.
sealed class CustomerLookupState {
const CustomerLookupState();
}
class LookupIdle extends CustomerLookupState {
const LookupIdle();
}
class LookupSearching extends CustomerLookupState {
const LookupSearching();
}
class LookupFound extends CustomerLookupState {
const LookupFound(this.customer);
final Customer customer;
}
class LookupNotFound extends CustomerLookupState {
const LookupNotFound(this.mobile);
final String mobile;
}
class LookupError extends CustomerLookupState {
const LookupError(this.message);
final String message;
}
class CustomerLookupController extends StateNotifier<CustomerLookupState> {
CustomerLookupController(this._ref) : super(const LookupIdle());
final Ref _ref;
Future<void> search(String mobile) async {
final digits = mobile.replaceAll(RegExp(r'\D'), '');
if (digits.length != 10) {
state = const LookupIdle();
return;
}
state = const LookupSearching();
try {
final customer =
await _ref.read(customerRepositoryProvider).findByMobile(digits);
state = customer != null
? LookupFound(customer)
: LookupNotFound(digits);
} catch (e) {
state = LookupError(e.toString());
}
}
void reset() => state = const LookupIdle();
}
final customerLookupProvider =
StateNotifierProvider<CustomerLookupController, CustomerLookupState>(
(ref) => CustomerLookupController(ref),
);
final recentCustomersProvider = FutureProvider<List<Customer>>(
(ref) => ref.watch(customerRepositoryProvider).recent(limit: 6),
);

View File

@@ -0,0 +1,321 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../app/providers.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/utils/validators.dart';
import '../../../core/widgets/glass_card.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/customer.dart';
import '../../pos/providers/cart_controller.dart';
import '../providers/customer_providers.dart';
/// Screen 2 — registers a shopper and drops straight into billing.
class CustomerRegistrationScreen extends ConsumerStatefulWidget {
const CustomerRegistrationScreen({super.key, this.prefillMobile});
final String? prefillMobile;
@override
ConsumerState<CustomerRegistrationScreen> createState() =>
_CustomerRegistrationScreenState();
}
class _CustomerRegistrationScreenState
extends ConsumerState<CustomerRegistrationScreen> {
final _formKey = GlobalKey<FormState>();
late final TextEditingController _mobile;
final _name = TextEditingController();
final _email = TextEditingController();
Gender _gender = Gender.unspecified;
DateTime? _dob;
bool _saving = false;
String? _serverError;
@override
void initState() {
super.initState();
_mobile = TextEditingController(text: widget.prefillMobile ?? '');
}
@override
void dispose() {
_mobile.dispose();
_name.dispose();
_email.dispose();
super.dispose();
}
Future<void> _save() async {
setState(() => _serverError = null);
if (!(_formKey.currentState?.validate() ?? false)) return;
setState(() => _saving = true);
try {
final customer = await ref.read(customerRepositoryProvider).create(
Customer(
id: '',
name: _name.text,
mobile: _mobile.text,
email: _email.text,
gender: _gender,
dateOfBirth: _dob,
),
);
ref.read(cartControllerProvider.notifier).attachCustomer(customer);
ref.invalidate(recentCustomersProvider);
if (!mounted) return;
context.go(AppRoutes.pos);
} catch (e) {
if (!mounted) return;
setState(() {
_saving = false;
_serverError = e is StateError ? e.message : 'Could not save customer.';
});
}
}
Future<void> _pickDob() async {
final now = DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: _dob ?? DateTime(now.year - 25),
firstDate: DateTime(now.year - 100),
lastDate: now,
helpText: 'Date of birth',
);
if (picked != null) setState(() => _dob = picked);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: const Text('New Customer'),
leading: IconButton(
icon: const Icon(Icons.arrow_back_rounded),
onPressed: () => context.pop(),
),
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 640),
child: GlassCard(
padding: const EdgeInsets.all(AppSpacing.xxxl),
radius: AppRadius.xl,
shadows: AppColors.shadowMd,
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Register a shopper',
style: context.text.headlineSmall),
const SizedBox(height: AppSpacing.xs),
Text(
'Only the mobile number and name are required.',
style: context.text.bodySmall,
),
const SizedBox(height: AppSpacing.xxl),
_Field(
label: 'Mobile Number',
required: true,
child: TextFormField(
controller: _mobile,
autofocus: true,
keyboardType: TextInputType.phone,
maxLength: 10,
validator: Validators.mobile,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
decoration: const InputDecoration(
hintText: '10-digit mobile number',
prefixText: '+91 ',
counterText: '',
prefixIcon: Icon(Icons.phone_outlined),
),
),
),
_Field(
label: 'Customer Name',
required: true,
child: TextFormField(
controller: _name,
textCapitalization: TextCapitalization.words,
validator: Validators.name,
decoration: const InputDecoration(
hintText: 'Full name',
prefixIcon: Icon(Icons.person_outline_rounded),
),
),
),
_Field(
label: 'Email',
child: TextFormField(
controller: _email,
keyboardType: TextInputType.emailAddress,
validator: Validators.emailOptional,
decoration: const InputDecoration(
hintText: 'name@example.com',
prefixIcon: Icon(Icons.mail_outline_rounded),
),
),
),
_Field(
label: 'Gender',
child: Wrap(
spacing: AppSpacing.sm,
children: Gender.values
.map((g) => ChoiceChip(
label: Text(g.label),
selected: _gender == g,
onSelected: (_) =>
setState(() => _gender = g),
labelStyle: TextStyle(
color: _gender == g
? Colors.white
: AppColors.textSecondary,
fontWeight: FontWeight.w600,
),
))
.toList(),
),
),
_Field(
label: 'Date of Birth',
child: InkWell(
onTap: _pickDob,
borderRadius: AppRadius.brMd,
child: InputDecorator(
decoration: const InputDecoration(
prefixIcon: Icon(Icons.cake_outlined),
),
child: Text(
_dob == null
? 'Select a date (optional)'
: Formatters.date(_dob!),
style: TextStyle(
color: _dob == null
? AppColors.textTertiary
: AppColors.textPrimary,
fontSize: 15,
),
),
),
),
),
if (_serverError != null) ...[
const SizedBox(height: AppSpacing.sm),
Container(
width: double.infinity,
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brSm,
),
child: Row(children: [
const Icon(Icons.error_outline_rounded,
color: AppColors.danger, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
_serverError!,
style: const TextStyle(
color: AppColors.danger,
fontSize: 13.5,
),
),
),
]),
),
],
const SizedBox(height: AppSpacing.xxl),
Row(children: [
Expanded(
child: PrimaryButton(
label: 'Cancel',
tone: ButtonTone.neutral,
onPressed:
_saving ? null : () => context.pop(),
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
flex: 2,
child: PrimaryButton(
label: 'Save & Continue',
icon: Icons.check_rounded,
busy: _saving,
onPressed: _save,
),
),
]),
],
),
),
),
),
),
),
);
}
}
class _Field extends StatelessWidget {
const _Field({
required this.label,
required this.child,
this.required = false,
});
final String label;
final Widget child;
final bool required;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.lg),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Text(label,
style: context.text.labelMedium
?.copyWith(color: AppColors.textSecondary)),
if (required)
const Text(' *',
style: TextStyle(color: AppColors.danger, fontSize: 13)),
if (!required)
Text(' optional',
style: context.text.labelSmall
?.copyWith(color: AppColors.textTertiary)),
]),
const SizedBox(height: AppSpacing.sm),
child,
],
),
);
}
}

View File

@@ -0,0 +1,504 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/glass_card.dart';
import '../../../core/widgets/numeric_keypad.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../core/widgets/status_pill.dart';
import '../../../domain/entities/customer.dart';
import '../../pos/providers/cart_controller.dart';
import '../providers/customer_providers.dart';
/// Screen 3 — mobile lookup that auto-searches on the tenth digit.
class ExistingCustomerScreen extends ConsumerStatefulWidget {
const ExistingCustomerScreen({super.key});
@override
ConsumerState<ExistingCustomerScreen> createState() =>
_ExistingCustomerScreenState();
}
class _ExistingCustomerScreenState
extends ConsumerState<ExistingCustomerScreen> {
String _digits = '';
void _append(String d) {
if (_digits.length >= AppConstants.mobileNumberLength) return;
setState(() => _digits += d);
if (_digits.length == AppConstants.mobileNumberLength) _search();
}
void _backspace() {
if (_digits.isEmpty) return;
setState(() => _digits = _digits.substring(0, _digits.length - 1));
ref.read(customerLookupProvider.notifier).reset();
}
void _clear() {
setState(() => _digits = '');
ref.read(customerLookupProvider.notifier).reset();
}
void _search() => ref.read(customerLookupProvider.notifier).search(_digits);
void _continueWith(Customer customer) {
ref.read(cartControllerProvider.notifier).attachCustomer(customer);
context.go(AppRoutes.pos);
}
@override
Widget build(BuildContext context) {
final lookup = ref.watch(customerLookupProvider);
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: const Text('Find Customer'),
leading: IconButton(
icon: const Icon(Icons.arrow_back_rounded),
onPressed: () => context.pop(),
),
actions: [
TextButton.icon(
onPressed: () {
ref.read(cartControllerProvider.notifier).attachCustomer(null);
context.go(AppRoutes.pos);
},
icon: const Icon(Icons.directions_walk_rounded,
color: Colors.white, size: 18),
label: const Text('Continue as Walk-in',
style: TextStyle(color: Colors.white)),
),
const SizedBox(width: AppSpacing.lg),
],
),
body: Padding(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: context.isCompact
? SingleChildScrollView(
child: Column(children: [
_entryPanel(),
const SizedBox(height: AppSpacing.xxl),
// Bound the height: the panel uses Expanded/Spacer
// internally, which a scroll view cannot supply.
SizedBox(height: 480, child: _resultPanel(lookup)),
]),
)
: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(flex: 4, child: _entryPanel()),
const SizedBox(width: AppSpacing.xxl),
Expanded(flex: 5, child: _resultPanel(lookup)),
],
),
),
);
}
Widget _entryPanel() {
return GlassCard(
padding: const EdgeInsets.all(AppSpacing.xxl),
radius: AppRadius.xl,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Mobile number', style: context.text.labelMedium),
const SizedBox(height: AppSpacing.md),
_display(),
const SizedBox(height: AppSpacing.xxl),
Center(
child: NumericKeypad(
onKey: _append,
onBackspace: _backspace,
onClear: _clear,
onSubmit:
_digits.length == AppConstants.mobileNumberLength
? _search
: null,
submitLabel: 'Search',
),
),
],
),
);
}
/// Ten slots so the cashier can see progress at a glance.
Widget _display() {
return Container(
height: 72,
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brLg,
border: Border.all(color: AppColors.primaryBorder),
),
child: Row(children: [
const Text('+91',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
)),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(
AppConstants.mobileNumberLength,
(i) {
final filled = i < _digits.length;
return AnimatedContainer(
duration: AppMotion.fast,
width: 22,
alignment: Alignment.center,
child: Text(
filled ? _digits[i] : '',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
color: filled
? AppColors.textPrimary
: AppColors.textTertiary.withValues(alpha: 0.5),
),
),
);
},
),
),
),
if (_digits.isNotEmpty)
IconButton(
onPressed: _clear,
icon: const Icon(Icons.close_rounded, size: 20),
color: AppColors.textTertiary,
tooltip: 'Clear',
),
]),
);
}
Widget _resultPanel(CustomerLookupState state) {
return GlassCard(
padding: const EdgeInsets.all(AppSpacing.xxl),
radius: AppRadius.xl,
child: switch (state) {
LookupIdle() => _idle(),
LookupSearching() => const Center(
child: CircularProgressIndicator(color: AppColors.primary),
),
LookupFound(:final customer) => _found(customer),
LookupNotFound(:final mobile) => _notFound(mobile),
LookupError(:final message) => EmptyState(
title: 'Something went wrong',
message: message,
emoji: '⚠️',
),
},
);
}
Widget _idle() {
final recent = ref.watch(recentCustomersProvider);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Recent customers', style: context.text.titleMedium),
const SizedBox(height: AppSpacing.xs),
Text('Tap to select, or key in a mobile number.',
style: context.text.bodySmall),
const SizedBox(height: AppSpacing.lg),
Expanded(
child: recent.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => EmptyState(
title: 'Could not load customers',
message: '$e',
emoji: '⚠️',
compact: true,
),
data: (customers) => customers.isEmpty
? const EmptyState(
title: 'No customers yet',
message: 'Register the first one from the welcome screen.',
emoji: '👤',
compact: true,
)
: ListView.separated(
itemCount: customers.length,
separatorBuilder: (_, __) =>
const SizedBox(height: AppSpacing.sm),
itemBuilder: (_, i) => _RecentTile(
customer: customers[i],
onTap: () => _continueWith(customers[i]),
),
),
),
),
],
);
}
Widget _found(Customer c) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(children: [
CircleAvatar(
radius: 30,
backgroundColor: AppColors.primarySurface,
child: Text(
Formatters.initials(c.name),
style: const TextStyle(
color: AppColors.primary,
fontSize: 22,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: AppSpacing.lg),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Flexible(
child: Text(c.name,
style: context.text.headlineSmall,
overflow: TextOverflow.ellipsis),
),
const SizedBox(width: AppSpacing.sm),
StatusPill.tier(c.tier),
]),
const SizedBox(height: 2),
Text('+91 ${Formatters.mobile(c.mobile)}',
style: context.text.bodyMedium
?.copyWith(color: AppColors.textSecondary)),
],
),
),
]),
if (c.isBirthdayToday) ...[
const SizedBox(height: AppSpacing.lg),
Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.warningSurface,
borderRadius: AppRadius.brSm,
),
child: const Row(children: [
Text('🎂', style: TextStyle(fontSize: 18)),
SizedBox(width: AppSpacing.sm),
Text("It's their birthday today — wish them!",
style: TextStyle(
color: AppColors.warning,
fontWeight: FontWeight.w600,
)),
]),
),
],
const SizedBox(height: AppSpacing.xxl),
Row(children: [
Expanded(
child: _Stat(
label: 'Loyalty Points',
value: '${c.loyaltyPoints}',
caption: 'Worth ${Formatters.money(c.redeemableValue)}',
icon: Icons.stars_rounded,
color: AppColors.tierGold,
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: _Stat(
label: 'Lifetime Spend',
value: Formatters.moneyCompact(c.lifetimeSpend),
caption: '${c.visitCount} visits',
icon: Icons.receipt_long_rounded,
color: AppColors.primary,
),
),
]),
if (c.tier.discountRate > 0) ...[
const SizedBox(height: AppSpacing.md),
Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.successSurface,
borderRadius: AppRadius.brSm,
),
child: Row(children: [
const Icon(Icons.local_offer_rounded,
color: AppColors.success, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
'${c.tier.label} members get '
'${Formatters.percent(c.tier.discountRate)} off '
'automatically on every bill.',
style: const TextStyle(
color: AppColors.success,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
]),
),
],
const Spacer(),
PrimaryButton(
label: 'Continue to Billing',
icon: Icons.point_of_sale_rounded,
large: true,
onPressed: () => _continueWith(c),
),
],
).animate().fadeIn(duration: 200.ms);
}
Widget _notFound(String mobile) {
return Column(
children: [
Expanded(
child: EmptyState(
title: 'No customer found',
message: 'Nobody is registered against '
'+91 ${Formatters.mobile(mobile)}.',
emoji: '🔍',
),
),
PrimaryButton(
label: 'Register Customer',
icon: Icons.person_add_alt_1_rounded,
onPressed: () => context.push(
'${AppRoutes.registerCustomer}?mobile=$mobile',
),
),
const SizedBox(height: AppSpacing.md),
PrimaryButton(
label: 'Continue as Walk-in',
icon: Icons.directions_walk_rounded,
tone: ButtonTone.neutral,
onPressed: () {
ref.read(cartControllerProvider.notifier).attachCustomer(null);
context.go(AppRoutes.pos);
},
),
],
).animate().fadeIn(duration: 200.ms);
}
}
class _RecentTile extends StatelessWidget {
const _RecentTile({required this.customer, required this.onTap});
final Customer customer;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brMd,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Row(children: [
CircleAvatar(
radius: 18,
backgroundColor: AppColors.primarySurface,
child: Text(
Formatters.initials(customer.name),
style: const TextStyle(
color: AppColors.primary,
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(customer.name,
style: context.text.titleSmall,
overflow: TextOverflow.ellipsis),
Text(Formatters.maskedMobile(customer.mobile),
style: context.text.bodySmall),
],
),
),
StatusPill.tier(customer.tier, dense: true),
const SizedBox(width: AppSpacing.sm),
const Icon(Icons.chevron_right_rounded,
color: AppColors.textTertiary),
]),
),
),
);
}
}
class _Stat extends StatelessWidget {
const _Stat({
required this.label,
required this.value,
required this.caption,
required this.icon,
required this.color,
});
final String label;
final String value;
final String caption;
final IconData icon;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
border: Border.all(color: AppColors.border),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: AppSpacing.xs),
Text(label,
style: context.text.labelSmall
?.copyWith(color: AppColors.textSecondary)),
]),
const SizedBox(height: AppSpacing.sm),
Text(value,
style: context.text.headlineSmall?.copyWith(color: color)),
Text(caption, style: context.text.bodySmall),
],
),
);
}
}

View File

@@ -0,0 +1,209 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/status_pill.dart';
import '../../../domain/entities/customer.dart';
import '../widgets/module_widgets.dart';
/// Full customer book, independent of the six shown during billing.
final allCustomersProvider = FutureProvider<List<Customer>>(
(ref) => ref.watch(customerRepositoryProvider).recent(limit: 200),
);
class CustomersView extends ConsumerStatefulWidget {
const CustomersView({super.key});
@override
ConsumerState<CustomersView> createState() => _CustomersViewState();
}
class _CustomersViewState extends ConsumerState<CustomersView> {
String _query = '';
MembershipTier? _tier;
Color _tierColor(MembershipTier t) => switch (t) {
MembershipTier.bronze => AppColors.tierBronze,
MembershipTier.silver => AppColors.tierSilver,
MembershipTier.gold => AppColors.tierGold,
MembershipTier.platinum => AppColors.tierPlatinum,
};
@override
Widget build(BuildContext context) {
final all = ref.watch(allCustomersProvider).value ?? const <Customer>[];
final filtered = all.where((c) {
final q = _query.trim().toLowerCase();
final matchesQuery = q.isEmpty ||
c.name.toLowerCase().contains(q) ||
c.mobile.contains(q);
return matchesQuery && (_tier == null || c.tier == _tier);
}).toList();
final lifetime = all.fold<double>(0, (s, c) => s + c.lifetimeSpend);
final points = all.fold<int>(0, (s, c) => s + c.loyaltyPoints);
return ModulePage(
children: [
Wrap(
spacing: AppSpacing.lg,
runSpacing: AppSpacing.lg,
children: [
StatTile(
label: 'Total Customers',
value: '${all.length}',
icon: Icons.people_alt_rounded,
caption: 'registered',
),
StatTile(
label: 'Lifetime Value',
value: Formatters.moneyCompact(lifetime),
icon: Icons.payments_rounded,
color: AppColors.success,
caption: 'all customers',
),
StatTile(
label: 'Points Outstanding',
value: '$points',
icon: Icons.stars_rounded,
color: AppColors.tierGold,
caption: 'worth ${Formatters.money(points * 0.25)}',
),
StatTile(
label: 'Avg Spend',
value: Formatters.money(all.isEmpty ? 0 : lifetime / all.length),
icon: Icons.trending_up_rounded,
color: AppColors.info,
caption: 'per customer',
),
],
),
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Tier distribution',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final t in MembershipTier.values)
ProgressRow(
label: '${t.label} · '
'${(t.discountRate * 100).toStringAsFixed(0)}% off',
value: '${all.where((c) => c.tier == t).length}',
fraction: all.isEmpty
? 0
: all.where((c) => c.tier == t).length / all.length,
color: _tierColor(t),
),
],
),
),
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Customer book',
subtitle: '${filtered.length} shown',
action: FilledButton.icon(
onPressed: () {},
icon: const Icon(Icons.person_add_alt_1_rounded, size: 17),
label: const Text('Add customer'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
minimumSize: const Size(0, 40),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
onChanged: (v) => setState(() => _query = v),
decoration: const InputDecoration(
hintText: 'Search by name or mobile number…',
prefixIcon: Icon(Icons.search_rounded),
isDense: true,
),
),
const SizedBox(height: AppSpacing.md),
Wrap(
spacing: AppSpacing.sm,
runSpacing: AppSpacing.sm,
children: [
ChoiceChip(
label: const Text('All tiers'),
selected: _tier == null,
onSelected: (_) => setState(() => _tier = null),
labelStyle: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: _tier == null
? Colors.white
: AppColors.textSecondary,
),
),
for (final t in MembershipTier.values)
ChoiceChip(
label: Text(t.label),
selected: _tier == t,
onSelected: (_) =>
setState(() => _tier = _tier == t ? null : t),
labelStyle: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: _tier == t
? Colors.white
: AppColors.textSecondary,
),
),
],
),
const SizedBox(height: AppSpacing.lg),
ResponsiveTable(
columns: const [
TableCol('Customer', flex: 4),
TableCol('Mobile', flex: 3, priority: 1),
TableCol('Tier', flex: 2),
TableCol('Points', flex: 2, numeric: true, priority: 1),
TableCol('Lifetime', flex: 2, numeric: true),
TableCol('Visits', flex: 2, numeric: true, priority: 1),
],
rows: filtered
.map((c) => [
Row(
mainAxisSize: MainAxisSize.min,
children: [
CircleAvatar(
radius: 14,
backgroundColor: AppColors.primarySurface,
child: Text(
Formatters.initials(c.name),
style: const TextStyle(
fontSize: 10.5,
fontWeight: FontWeight.w700,
color: AppColors.primary,
),
),
),
const SizedBox(width: AppSpacing.sm),
Flexible(child: Cell(c.name, bold: true)),
],
),
Cell(Formatters.mobile(c.mobile), mono: true),
StatusPill.tier(c.tier, dense: true),
Cell('${c.loyaltyPoints}', mono: true),
Cell(Formatters.moneyCompact(c.lifetimeSpend),
mono: true, bold: true),
Cell('${c.visitCount}', mono: true),
])
.toList(),
),
],
),
),
],
);
}
}

View File

@@ -0,0 +1,287 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/sync_event.dart';
import '../../../domain/entities/transaction.dart';
import '../../sync/providers/sync_controller.dart';
import '../widgets/module_widgets.dart';
/// The terminal's outbound half: what today produced, and what has been sent.
class EventsView extends ConsumerWidget {
const EventsView({super.key});
static Color statusColor(SyncStatus s) => switch (s) {
SyncStatus.synced => AppColors.success,
SyncStatus.failed => AppColors.danger,
SyncStatus.syncing => AppColors.info,
SyncStatus.pending => AppColors.warning,
};
@override
Widget build(BuildContext context, WidgetRef ref) {
final report = ref.watch(shiftReportProvider);
final events = ref.watch(syncEventsProvider);
final pushing = ref.watch(reportPushProvider);
return ModulePage(
children: [
Wrap(
spacing: AppSpacing.lg,
runSpacing: AppSpacing.lg,
children: [
StatTile(
label: 'Bills Today',
value: '${report.billCount}',
icon: Icons.receipt_long_rounded,
caption: report.firstBillAt == null
? 'no sales yet'
: '${Formatters.time(report.firstBillAt!)} '
'${Formatters.time(report.lastBillAt!)}',
),
StatTile(
label: 'Items Sold',
value: report.itemCount.toStringAsFixed(0),
icon: Icons.shopping_basket_rounded,
color: AppColors.info,
caption: 'units across all bills',
),
StatTile(
label: "Today's Sales",
value: Formatters.money(report.grossSales),
icon: Icons.payments_rounded,
color: AppColors.success,
caption: 'gross takings',
),
StatTile(
label: 'Average Basket',
value: Formatters.money(report.averageBasket),
icon: Icons.trending_up_rounded,
color: AppColors.tierGold,
caption: 'per bill',
),
],
),
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Shift report',
subtitle: '${Formatters.date(report.businessDate)} · '
'${report.cashierName} · ${report.terminalId}',
action: TagChip(
report.isEmpty ? 'Nothing to send' : 'Ready to push',
color: report.isEmpty ? AppColors.textSecondary : AppColors.warning,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
_row('Bills', '${report.billCount}'),
_row('Items sold', report.itemCount.toStringAsFixed(0)),
_row('Gross sales', Formatters.money(report.grossSales)),
_row('Net of tax', Formatters.money(report.netOfTax)),
_row('GST collected', Formatters.money(report.taxCollected)),
_row('Discount given', Formatters.money(report.discountGiven)),
_row('Round off', Formatters.money(report.roundOff)),
_row('Points issued', '${report.loyaltyPointsIssued}'),
_row('Points redeemed', '${report.loyaltyPointsRedeemed}'),
if (report.paymentBreakdown.isNotEmpty) ...[
const Divider(height: AppSpacing.xxl),
const Align(
alignment: Alignment.centerLeft,
child: Text(
'By payment method',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
),
const SizedBox(height: AppSpacing.sm),
for (final e in report.paymentBreakdown.entries)
ProgressRow(
label: '${e.key.emoji} ${e.key.label}',
value: Formatters.money(e.value),
fraction: report.grossSales <= 0
? 0
: e.value / report.grossSales,
color: _methodColor(e.key),
),
],
const SizedBox(height: AppSpacing.xl),
PrimaryButton(
label: 'Push report to server',
icon: Icons.cloud_upload_rounded,
large: true,
busy: pushing,
onPressed: report.isEmpty
? null
: () async {
final event = await ref
.read(reportPushProvider.notifier)
.pushToday();
if (!context.mounted) return;
final ok = event.status == SyncStatus.synced;
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(
backgroundColor:
ok ? AppColors.success : AppColors.danger,
content: Text(
ok
? 'Shift report sent.'
: 'Push failed — the report is still saved '
'on this terminal.',
),
));
},
),
const SizedBox(height: AppSpacing.md),
const Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.shield_outlined,
size: 15, color: AppColors.textTertiary),
SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
'A failed push never discards data. The report stays '
'queued below and can be retried at any time.',
style: TextStyle(
fontSize: 12,
color: AppColors.textTertiary,
height: 1.5,
),
),
),
],
),
],
),
),
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Event log',
subtitle: '${events.length} recorded · '
'${events.where((e) => e.status != SyncStatus.synced).length} '
'outstanding',
child: events.isEmpty
? const Padding(
padding: EdgeInsets.symmetric(vertical: AppSpacing.lg),
child: Text(
'No sync activity yet. Importing the catalogue or pushing '
'a report will appear here.',
style: TextStyle(color: AppColors.textTertiary),
),
)
: ResponsiveTable(
columns: const [
TableCol('Event', flex: 3),
TableCol('Detail', flex: 5, priority: 1),
TableCol('Time', flex: 2, numeric: true, priority: 1),
TableCol('Status', flex: 2, numeric: true),
],
rows: events
.map((e) => [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
e.type.isInbound
? Icons.cloud_download_rounded
: Icons.cloud_upload_rounded,
size: 15,
color: AppColors.textSecondary,
),
const SizedBox(width: AppSpacing.sm),
Flexible(child: Cell(e.type.label, bold: true)),
],
),
Cell(
e.error ?? e.summary,
color: e.error != null
? AppColors.danger
: AppColors.textSecondary,
),
Cell(Formatters.time(e.createdAt),
color: AppColors.textTertiary),
e.status == SyncStatus.failed
? _RetryButton(eventId: e.id)
: TagChip(
e.status.label,
color: statusColor(e.status),
),
])
.toList(),
),
),
],
);
}
static Color _methodColor(PaymentMethod m) => switch (m) {
PaymentMethod.cash => AppColors.success,
PaymentMethod.card => AppColors.info,
PaymentMethod.upi => AppColors.primary,
PaymentMethod.wallet => AppColors.warning,
PaymentMethod.giftCard => AppColors.tierGold,
PaymentMethod.loyalty => AppColors.tierSilver,
};
Widget _row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs + 2),
child: Row(
children: [
Expanded(
child: Text(
label,
style: const TextStyle(
fontSize: 13.5,
color: AppColors.textSecondary,
),
),
),
const SizedBox(width: AppSpacing.md),
Text(
value,
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
],
),
);
}
class _RetryButton extends ConsumerWidget {
const _RetryButton({required this.eventId});
final String eventId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final busy = ref.watch(reportPushProvider);
return TextButton.icon(
onPressed: busy
? null
: () => ref.read(reportPushProvider.notifier).retry(eventId),
icon: const Icon(Icons.refresh_rounded, size: 15),
label: const Text('Retry', style: TextStyle(fontSize: 12.5)),
style: TextButton.styleFrom(
foregroundColor: AppColors.danger,
minimumSize: const Size(0, 30),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm),
),
);
}
}

View File

@@ -0,0 +1,338 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/product.dart';
import '../../pos/providers/catalog_providers.dart';
import '../../pos/providers/navigation_provider.dart';
import '../../sync/providers/sync_controller.dart';
import '../widgets/module_widgets.dart';
/// Pulls the catalogue onto the terminal.
///
/// This is the first thing a cashier does at the start of a session — until it
/// succeeds there is nothing to bill. Once imported, everything runs locally.
class ProductImportView extends ConsumerWidget {
const ProductImportView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(catalogueImportProvider);
final ready = ref.watch(catalogueReadyProvider);
final lastImport = ref.watch(lastImportAtProvider);
final products = ref.watch(allProductsProvider).value ?? const <Product>[];
final revision = ref.watch(syncRepositoryProvider).catalogueRevision;
return ModulePage(
children: [
if (!ready) _NotImportedBanner(state: state),
if (ready) ...[
Wrap(
spacing: AppSpacing.lg,
runSpacing: AppSpacing.lg,
children: [
StatTile(
label: 'Products Loaded',
value: '${products.length}',
icon: Icons.inventory_2_rounded,
color: AppColors.success,
caption: 'available offline',
),
StatTile(
label: 'Catalogue Revision',
value: revision ?? '',
icon: Icons.tag_rounded,
color: AppColors.info,
caption: 'server version',
),
StatTile(
label: 'Last Imported',
value: lastImport == null
? ''
: Formatters.time(lastImport),
icon: Icons.schedule_rounded,
caption: lastImport == null
? 'never'
: Formatters.date(lastImport),
),
StatTile(
label: 'Stock Value',
value: Formatters.moneyCompact(
products.fold<double>(0, (s, p) => s + p.price * p.stock),
),
icon: Icons.savings_rounded,
color: AppColors.tierGold,
caption: 'at selling price',
),
],
),
const SizedBox(height: AppSpacing.lg),
],
PanelCard(
title: ready ? 'Re-import catalogue' : 'Import catalogue',
subtitle: ready
? 'Pulls the latest prices and products. Stock already sold on '
'this terminal is preserved.'
: 'Connect once to load products, then bill offline all day.',
child: _ImportPanel(state: state, ready: ready),
),
if (ready) ...[
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Imported products',
subtitle: '${products.length} items on this terminal',
child: ResponsiveTable(
columns: const [
TableCol('Product', flex: 4),
TableCol('SKU', flex: 3, priority: 1),
TableCol('Category', flex: 2, priority: 1),
TableCol('Price', flex: 2, numeric: true),
TableCol('Stock', flex: 2, numeric: true),
],
rows: products
.map((p) => [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(p.emoji,
style: const TextStyle(fontSize: 17)),
const SizedBox(width: AppSpacing.sm),
Flexible(child: Cell(p.name, bold: true)),
],
),
Cell(p.sku, color: AppColors.textTertiary),
TagChip(p.category.label,
color: AppColors.textSecondary),
Cell(Formatters.money(p.price), mono: true, bold: true),
TagChip(
p.isOutOfStock
? 'Out'
: '${p.stock.toStringAsFixed(0)} ${p.unit.symbol}',
color: p.isOutOfStock
? AppColors.danger
: (p.isLowStock
? AppColors.warning
: AppColors.success),
),
])
.toList(),
),
),
],
],
);
}
}
class _NotImportedBanner extends StatelessWidget {
const _NotImportedBanner({required this.state});
final ImportState state;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(bottom: AppSpacing.lg),
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.warningSurface,
borderRadius: AppRadius.brLg,
border: Border.all(color: AppColors.warning.withValues(alpha: 0.35)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.cloud_download_outlined,
color: AppColors.warning, size: 22),
const SizedBox(width: AppSpacing.md),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'No catalogue on this terminal',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
SizedBox(height: 2),
Text(
'Billing is disabled until products are imported. This is '
'the only step that needs a connection at the start of a '
'shift.',
style: TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
height: 1.5,
),
),
],
),
),
],
),
);
}
}
class _ImportPanel extends ConsumerWidget {
const _ImportPanel({required this.state, required this.ready});
final ImportState state;
final bool ready;
@override
Widget build(BuildContext context, WidgetRef ref) {
final running = state is ImportRunning;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (state is ImportRunning) ...[
Text(
(state as ImportRunning).stage,
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w500,
color: AppColors.textSecondary,
),
),
const SizedBox(height: AppSpacing.sm),
ClipRRect(
borderRadius: AppRadius.brPill,
child: LinearProgressIndicator(
value: (state as ImportRunning).progress,
minHeight: 8,
backgroundColor: AppColors.divider,
valueColor:
const AlwaysStoppedAnimation<Color>(AppColors.primary),
),
),
const SizedBox(height: AppSpacing.lg),
],
if (state is ImportFailed) ...[
Container(
padding: const EdgeInsets.all(AppSpacing.md),
margin: const EdgeInsets.only(bottom: AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brSm,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.wifi_off_rounded,
color: AppColors.danger, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
(state as ImportFailed).message,
style: const TextStyle(
color: AppColors.danger,
fontSize: 13,
height: 1.45,
),
),
),
],
),
),
],
if (state is ImportDone) ...[
Container(
padding: const EdgeInsets.all(AppSpacing.md),
margin: const EdgeInsets.only(bottom: AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.successSurface,
borderRadius: AppRadius.brSm,
),
child: Row(
children: [
const Icon(Icons.check_circle_outline_rounded,
color: AppColors.success, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
(state as ImportDone).event.summary,
style: const TextStyle(
color: AppColors.success,
fontSize: 13,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
],
// Wrap so the buttons stack rather than overflow on a narrow panel.
Wrap(
spacing: AppSpacing.md,
runSpacing: AppSpacing.md,
children: [
SizedBox(
width: 240,
child: PrimaryButton(
label: ready ? 'Re-import now' : 'Import catalogue',
icon: Icons.cloud_download_rounded,
large: true,
busy: running,
onPressed: running
? null
: () => ref.read(catalogueImportProvider.notifier).run(),
),
),
if (ready && !running)
SizedBox(
width: 200,
child: PrimaryButton(
label: 'Start billing',
icon: Icons.point_of_sale_rounded,
large: true,
tone: ButtonTone.ghost,
onPressed: () => ref
.read(activeModuleProvider.notifier)
.state = PosModule.pos,
),
),
],
),
const SizedBox(height: AppSpacing.lg),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.info_outline_rounded,
size: 15, color: AppColors.textTertiary),
const SizedBox(width: AppSpacing.sm),
const Expanded(
child: Text(
'After this import the terminal works entirely offline. '
'Sales, customers and parked bills are held locally and are '
'only sent when you push the shift report at sign-out.',
style: TextStyle(
fontSize: 12,
color: AppColors.textTertiary,
height: 1.5,
),
),
),
],
),
],
);
}
}

View File

@@ -0,0 +1,202 @@
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../widgets/module_widgets.dart';
/// Discount rules and campaigns.
class PromosView extends StatefulWidget {
const PromosView({super.key});
@override
State<PromosView> createState() => _PromosViewState();
}
class _PromosViewState extends State<PromosView> {
final Set<String> _enabled = {'WEEKEND10', 'DAIRY5', 'FESTIVE'};
static const _campaigns = [
(
'WEEKEND10',
'Weekend Saver',
'10% off bills above ₹500',
'SatSun',
412,
AppColors.primary,
),
(
'DAIRY5',
'Dairy Days',
'5% off all dairy products',
'Ends 31 Aug',
286,
AppColors.info,
),
(
'FESTIVE',
'Festive Bonus',
'Double loyalty points',
'Ends 15 Sep',
178,
AppColors.tierGold,
),
(
'NEWCUST',
'First Purchase',
'₹50 off the first bill',
'Always on',
94,
AppColors.success,
),
];
@override
Widget build(BuildContext context) {
return ModulePage(
children: [
Wrap(
spacing: AppSpacing.lg,
runSpacing: AppSpacing.lg,
children: [
StatTile(
label: 'Active Campaigns',
value: '${_enabled.length}',
icon: Icons.campaign_rounded,
caption: 'of ${_campaigns.length} configured',
),
StatTile(
label: 'Redemptions',
value: '970',
icon: Icons.confirmation_number_rounded,
color: AppColors.info,
caption: 'this month',
),
StatTile(
label: 'Discount Given',
value: '₹48,240',
icon: Icons.local_offer_rounded,
color: AppColors.warning,
caption: '2.6% of sales',
),
StatTile(
label: 'Incremental Sales',
value: '₹2.14L',
icon: Icons.trending_up_rounded,
color: AppColors.success,
delta: '+18%',
caption: 'attributed',
),
],
),
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Campaigns',
subtitle: 'Toggle a rule to apply it at the till immediately',
action: FilledButton.icon(
onPressed: () {},
icon: const Icon(Icons.add_rounded, size: 18),
label: const Text('New campaign'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
minimumSize: const Size(0, 40),
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final c in _campaigns)
Container(
margin: const EdgeInsets.only(bottom: AppSpacing.sm),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
border: Border.all(color: AppColors.border),
),
// Wrap prevents collision when the panel is narrow.
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppSpacing.md,
runSpacing: AppSpacing.sm,
children: [
SizedBox(
width: 320,
child: Row(
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: c.$6.withValues(alpha: 0.12),
borderRadius: AppRadius.brSm,
),
child: Icon(Icons.sell_rounded,
size: 18, color: c.$6),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
c.$2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
Text(
c.$3,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5,
color: AppColors.textSecondary,
),
),
],
),
),
],
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
TagChip(c.$1, color: c.$6),
const SizedBox(width: AppSpacing.sm),
TagChip(c.$4, color: AppColors.textSecondary),
const SizedBox(width: AppSpacing.sm),
Text(
'${c.$5} used',
style: const TextStyle(
fontSize: 12,
color: AppColors.textTertiary,
),
),
const SizedBox(width: AppSpacing.sm),
Switch(
value: _enabled.contains(c.$1),
onChanged: (v) => setState(() {
if (v) {
_enabled.add(c.$1);
} else {
_enabled.remove(c.$1);
}
}),
),
],
),
],
),
),
],
),
),
],
);
}
}

View File

@@ -0,0 +1,322 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/store_account.dart';
import '../../../domain/entities/sync_event.dart';
import '../../auth/providers/auth_controller.dart';
import '../../sync/providers/sync_controller.dart';
import '../widgets/module_widgets.dart';
/// Terminal and store configuration.
class SettingsView extends ConsumerStatefulWidget {
const SettingsView({super.key});
@override
ConsumerState<SettingsView> createState() => _SettingsViewState();
}
class _SettingsViewState extends ConsumerState<SettingsView> {
bool _scannerSound = true;
bool _autoPrint = true;
bool _openDrawer = true;
bool _roundOff = true;
bool _autoLoyalty = true;
bool _offline = false;
@override
Widget build(BuildContext context) {
final store = ref.watch(currentStoreProvider);
final user = ref.watch(currentUserProvider);
return ModulePage(
children: [
LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= 1040;
final left = Column(
children: [
_storeCard(store),
const SizedBox(height: AppSpacing.lg),
_taxCard(),
const SizedBox(height: AppSpacing.lg),
_loyaltyCard(),
],
);
final right = Column(
children: [
_hardwareCard(),
const SizedBox(height: AppSpacing.lg),
_connectivityCard(),
const SizedBox(height: AppSpacing.lg),
_staffCard(store, user),
const SizedBox(height: AppSpacing.lg),
_aboutCard(),
],
);
if (!wide) {
return Column(
children: [left, const SizedBox(height: AppSpacing.lg), right],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: left),
const SizedBox(width: AppSpacing.lg),
Expanded(child: right),
],
);
},
),
],
);
}
Widget _storeCard(StoreAccount? store) => PanelCard(
title: 'Store details',
subtitle: 'Printed on every invoice',
action: TextButton(onPressed: () {}, child: const Text('Edit')),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_row('Store name', store?.name ?? AppConstants.storeName),
_row('Address', store?.address ?? AppConstants.storeAddress),
_row('GSTIN', store?.gstin ?? AppConstants.storeGstin, mono: true),
_row('Phone', store?.phone ?? AppConstants.storePhone, mono: true),
_row('Plan', store?.plan ?? 'Business'),
],
),
);
Widget _taxCard() => PanelCard(
title: 'Tax & pricing',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_row(
'Default GST slab',
Formatters.percent(AppConstants.defaultGstRate),
),
_row('Prices include tax', 'Yes'),
_toggle(
'Round bills to nearest rupee',
'Shows the adjustment as a Round Off line',
_roundOff,
(v) => setState(() => _roundOff = v),
),
],
),
);
Widget _loyaltyCard() => PanelCard(
title: 'Loyalty programme',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_row(
'Earn rate',
'1 point per '
'${Formatters.money(AppConstants.loyaltyRupeesPerPoint)}',
),
_row(
'Point value',
Formatters.money(AppConstants.loyaltyPointValue),
),
_toggle(
'Apply tier discount automatically',
'Silver 2%, Gold 5%, Platinum 8%',
_autoLoyalty,
(v) => setState(() => _autoLoyalty = v),
),
],
),
);
Widget _hardwareCard() => PanelCard(
title: 'Hardware & peripherals',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_toggle(
'Scanner beep',
'Audible confirmation on every scan',
_scannerSound,
(v) => setState(() => _scannerSound = v),
),
_toggle(
'Print receipt automatically',
'Sends to the default roll printer with no dialog',
_autoPrint,
(v) => setState(() => _autoPrint = v),
),
_toggle(
'Open cash drawer on cash sales',
'Sends the ESC/POS kick pulse',
_openDrawer,
(v) => setState(() => _openDrawer = v),
),
const Divider(height: AppSpacing.xxl),
_row('Receipt printer', 'EPSON TM-T82 (default)'),
_row('Barcode scanner', 'Keyboard wedge · detected'),
_row('Cash drawer', 'Connected via printer'),
],
),
);
Widget _staffCard(StoreAccount? store, StaffUser? current) => PanelCard(
title: 'Users & roles',
action: TextButton(onPressed: () {}, child: const Text('Manage')),
child: ResponsiveTable(
stackBelow: 360,
columns: const [
TableCol('Name', flex: 3),
TableCol('Role', flex: 3),
TableCol('', flex: 2, numeric: true),
],
rows: (store?.staff ?? const <StaffUser>[])
.map((s) => [
Cell(s.name, bold: true),
Cell(s.role.label, color: AppColors.textSecondary),
s.id == current?.id
? const TagChip('Signed in',
color: AppColors.success)
: const SizedBox.shrink(),
])
.toList(),
),
);
Widget _connectivityCard() {
final ready = ref.watch(catalogueReadyProvider);
final lastImport = ref.watch(lastImportAtProvider);
final outstanding = ref
.watch(syncEventsProvider)
.where((e) => e.status != SyncStatus.synced)
.length;
return PanelCard(
title: 'Connectivity & sync',
subtitle: 'This terminal only needs a connection to import the '
'catalogue and to push the shift report.',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_row('Catalogue', ready ? 'Loaded' : 'Not imported'),
_row(
'Last import',
lastImport == null ? 'Never' : Formatters.dateTime(lastImport),
),
_row('Outstanding pushes', '$outstanding'),
_toggle(
'Simulate offline',
'Forces import and push to fail, so you can confirm nothing is '
'lost when the network drops',
_offline,
(v) {
setState(() => _offline = v);
ref.read(remoteCatalogueProvider).simulateOffline = v;
ref.read(remoteReportSinkProvider).simulateOffline = v;
},
),
],
),
);
}
Widget _aboutCard() => PanelCard(
title: 'About',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_row('Application', '${AppConstants.appName} 1.0.0'),
_row('Terminal', 'TERM-01'),
_row('Data store', 'Local — offline first'),
const SizedBox(height: AppSpacing.md),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.sync_rounded, size: 17),
label: const Text('Check for updates'),
),
),
],
),
);
Widget _row(String label, String value, {bool mono = false}) => Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.sm),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 148,
child: Text(
label,
style: const TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
),
),
),
Expanded(
child: Text(
value,
textAlign: TextAlign.right,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
fontFamily: mono ? 'monospace' : null,
),
),
),
],
),
);
Widget _toggle(
String title,
String subtitle,
bool value,
ValueChanged<bool> onChanged,
) =>
Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w500,
),
),
Text(
subtitle,
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
height: 1.4,
),
),
],
),
),
const SizedBox(width: AppSpacing.md),
Switch(value: value, onChanged: onChanged),
],
),
);
}

View File

@@ -0,0 +1,580 @@
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
/// Scrollable page body shared by every module screen.
///
/// Always scrolls vertically, so no module can overflow no matter how short
/// the viewport gets.
class ModulePage extends StatelessWidget {
const ModulePage({
super.key,
required this.children,
this.padding = AppSpacing.xxl,
});
final List<Widget> children;
final double padding;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
padding: EdgeInsets.all(padding),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
}
}
/// KPI card. Designed to sit inside a [Wrap] so it reflows instead of
/// overflowing when the window narrows.
class StatTile extends StatelessWidget {
const StatTile({
super.key,
required this.label,
required this.value,
required this.icon,
this.color = AppColors.primary,
this.delta,
this.deltaPositive = true,
this.caption,
this.width = 232,
});
final String label;
final String value;
final IconData icon;
final Color color;
final String? delta;
final bool deltaPositive;
final String? caption;
final double width;
@override
Widget build(BuildContext context) {
return Container(
width: width,
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brLg,
border: Border.all(color: AppColors.border),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: AppRadius.brSm,
),
child: Icon(icon, size: 17, color: color),
),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
label,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w500,
color: AppColors.textSecondary,
),
),
),
],
),
const SizedBox(height: AppSpacing.md),
FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(value, style: AppTypography.money(24)),
),
if (delta != null || caption != null) ...[
const SizedBox(height: AppSpacing.xs),
Row(
children: [
if (delta != null) ...[
Icon(
deltaPositive
? Icons.trending_up_rounded
: Icons.trending_down_rounded,
size: 14,
color:
deltaPositive ? AppColors.success : AppColors.danger,
),
const SizedBox(width: 3),
Text(
delta!,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color:
deltaPositive ? AppColors.success : AppColors.danger,
),
),
const SizedBox(width: AppSpacing.xs),
],
if (caption != null)
Expanded(
child: Text(
caption!,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
),
),
),
],
),
],
],
),
);
}
}
/// Titled container for a block of module content.
class PanelCard extends StatelessWidget {
const PanelCard({
super.key,
required this.title,
required this.child,
this.subtitle,
this.action,
this.padding = AppSpacing.lg,
});
final String title;
final Widget child;
final String? subtitle;
final Widget? action;
final double padding;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brLg,
border: Border.all(color: AppColors.border),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.fromLTRB(padding, padding, padding, AppSpacing.md),
// Wrap so a long title plus an action never collide.
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppSpacing.md,
runSpacing: AppSpacing.sm,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
style: const TextStyle(
fontSize: 15.5,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
if (subtitle != null)
Text(
subtitle!,
style: const TextStyle(
fontSize: 12.5,
color: AppColors.textTertiary,
),
),
],
),
if (action != null) action!,
],
),
),
const Divider(height: 1),
Padding(padding: EdgeInsets.all(padding), child: child),
],
),
);
}
}
/// One column of a [ResponsiveTable].
class TableCol {
const TableCol(
this.label, {
this.flex = 2,
this.numeric = false,
this.priority = 0,
});
final String label;
final int flex;
final bool numeric;
/// Higher numbers are dropped first as the table narrows.
final int priority;
}
/// Table that degrades into stacked cards rather than overflowing.
///
/// Above [stackBelow] it renders as aligned columns; below, each row becomes a
/// label/value card. Low-priority columns are hidden at intermediate widths.
class ResponsiveTable extends StatelessWidget {
const ResponsiveTable({
super.key,
required this.columns,
required this.rows,
this.stackBelow = 620,
this.hideSecondaryBelow = 900,
this.onRowTap,
});
final List<TableCol> columns;
/// Each row must supply exactly one cell per column.
final List<List<Widget>> rows;
final double stackBelow;
final double hideSecondaryBelow;
final void Function(int index)? onRowTap;
@override
Widget build(BuildContext context) {
if (rows.isEmpty) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: AppSpacing.xxl),
child: Center(
child: Text(
'Nothing to show yet.',
style: TextStyle(color: AppColors.textTertiary),
),
),
);
}
return LayoutBuilder(
builder: (context, constraints) {
final w = constraints.maxWidth;
if (w < stackBelow) return _stacked();
final visible = <int>[
for (var i = 0; i < columns.length; i++)
if (w >= hideSecondaryBelow || columns[i].priority == 0) i,
];
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.sm),
child: Row(
children: [
for (final i in visible)
Expanded(
flex: columns[i].flex,
child: Text(
columns[i].label.toUpperCase(),
textAlign:
columns[i].numeric ? TextAlign.right : TextAlign.left,
overflow: TextOverflow.ellipsis,
style: AppTypography.sectionLabel(),
),
),
],
),
),
const Divider(height: 1),
for (var r = 0; r < rows.length; r++)
InkWell(
onTap: onRowTap == null ? null : () => onRowTap!(r),
borderRadius: AppRadius.brXs,
child: Container(
padding:
const EdgeInsets.symmetric(vertical: AppSpacing.md),
decoration: const BoxDecoration(
border:
Border(bottom: BorderSide(color: AppColors.divider)),
),
child: Row(
children: [
for (final i in visible)
Expanded(
flex: columns[i].flex,
child: Align(
alignment: columns[i].numeric
? Alignment.centerRight
: Alignment.centerLeft,
child: rows[r][i],
),
),
],
),
),
),
],
);
},
);
}
Widget _stacked() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
for (var r = 0; r < rows.length; r++)
Container(
margin: const EdgeInsets.only(bottom: AppSpacing.sm),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.border),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (var c = 0; c < columns.length; c++)
Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 104,
child: Text(
columns[c].label,
style: const TextStyle(
fontSize: 12,
color: AppColors.textTertiary,
),
),
),
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: rows[r][c],
),
),
],
),
),
],
),
),
],
);
}
}
/// Plain text cell.
class Cell extends StatelessWidget {
const Cell(
this.text, {
super.key,
this.bold = false,
this.color,
this.mono = false,
});
final String text;
final bool bold;
final Color? color;
final bool mono;
@override
Widget build(BuildContext context) {
return Text(
text,
overflow: TextOverflow.ellipsis,
style: mono
? AppTypography.money(13.5,
weight: bold ? FontWeight.w700 : FontWeight.w500, color: color)
: TextStyle(
fontSize: 13.5,
fontWeight: bold ? FontWeight.w600 : FontWeight.w400,
color: color ?? AppColors.textPrimary,
),
);
}
}
/// Small coloured status label.
class TagChip extends StatelessWidget {
const TagChip(this.label, {super.key, this.color = AppColors.primary});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm, vertical: 3),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: AppRadius.brPill,
),
child: Text(
label,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: color,
),
),
);
}
}
/// Lightweight bar chart painted in code, so no charting dependency is needed.
class MiniBarChart extends StatelessWidget {
const MiniBarChart({
super.key,
required this.values,
required this.labels,
this.height = 180,
this.color = AppColors.primary,
});
final List<double> values;
final List<String> labels;
final double height;
final Color color;
@override
Widget build(BuildContext context) {
if (values.isEmpty) return SizedBox(height: height);
final max = values.reduce((a, b) => a > b ? a : b);
return SizedBox(
height: height,
child: LayoutBuilder(
builder: (context, constraints) {
// Labels are dropped rather than squeezed when space is tight.
final showLabels = constraints.maxWidth / values.length >= 28;
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
for (var i = 0; i < values.length; i++)
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Expanded(
child: FractionallySizedBox(
alignment: Alignment.bottomCenter,
heightFactor:
max <= 0 ? 0 : (values[i] / max).clamp(0.03, 1),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
color,
color.withValues(alpha: 0.45),
],
),
borderRadius: const BorderRadius.vertical(
top: Radius.circular(5),
),
),
),
),
),
if (showLabels) ...[
const SizedBox(height: AppSpacing.sm),
Text(
labels[i],
maxLines: 1,
overflow: TextOverflow.clip,
style: const TextStyle(
fontSize: 10.5,
color: AppColors.textTertiary,
),
),
],
],
),
),
),
],
);
},
),
);
}
}
/// Horizontal proportion bar used for breakdowns.
class ProgressRow extends StatelessWidget {
const ProgressRow({
super.key,
required this.label,
required this.value,
required this.fraction,
this.color = AppColors.primary,
});
final String label;
final String value;
final double fraction;
final Color color;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.sm),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
label,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13),
),
),
const SizedBox(width: AppSpacing.sm),
Text(value, style: AppTypography.money(13)),
],
),
const SizedBox(height: AppSpacing.sm),
ClipRRect(
borderRadius: AppRadius.brPill,
child: LinearProgressIndicator(
value: fraction.clamp(0, 1),
minHeight: 6,
backgroundColor: AppColors.divider,
valueColor: AlwaysStoppedAnimation(color),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,187 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/utils/extensions.dart';
import '../../../domain/entities/transaction.dart';
import '../../../domain/usecases/checkout_sale.dart';
import '../../pos/providers/cart_controller.dart';
import '../../pos/providers/catalog_providers.dart';
/// UI state for the payment screen.
class PaymentState {
const PaymentState({
this.splits = const [],
this.activeMethod = PaymentMethod.cash,
this.cashTendered = 0,
this.reference = '',
this.isProcessing = false,
this.error,
this.result,
});
final List<PaymentSplit> splits;
final PaymentMethod activeMethod;
final double cashTendered;
final String reference;
final bool isProcessing;
final String? error;
final CheckoutResult? result;
double get settled =>
splits.fold(0.0, (sum, s) => sum + s.amount).asMoney;
bool get isComplete => result != null;
PaymentState copyWith({
List<PaymentSplit>? splits,
PaymentMethod? activeMethod,
double? cashTendered,
String? reference,
bool? isProcessing,
String? error,
bool clearError = false,
CheckoutResult? result,
}) {
return PaymentState(
splits: splits ?? this.splits,
activeMethod: activeMethod ?? this.activeMethod,
cashTendered: cashTendered ?? this.cashTendered,
reference: reference ?? this.reference,
isProcessing: isProcessing ?? this.isProcessing,
error: clearError ? null : (error ?? this.error),
result: result ?? this.result,
);
}
}
class PaymentController extends StateNotifier<PaymentState> {
PaymentController(this._ref) : super(const PaymentState());
final Ref _ref;
double get _billTotal => _ref.read(cartControllerProvider).grandTotal;
/// Amount still outstanding after the tenders recorded so far.
double get balanceDue =>
(_billTotal - state.settled).clamp(0, double.infinity);
double get changeDue {
if (!state.activeMethod.needsChange) return 0;
final diff = state.cashTendered - balanceDue;
return diff > 0 ? diff.asMoney : 0;
}
bool get canConfirm {
if (state.activeMethod.needsChange) {
return state.cashTendered >= balanceDue && balanceDue > 0;
}
return balanceDue > 0;
}
void selectMethod(PaymentMethod method) {
state = state.copyWith(
activeMethod: method,
cashTendered: 0,
reference: '',
clearError: true,
);
}
void setCashTendered(double amount) =>
state = state.copyWith(cashTendered: amount, clearError: true);
/// Adds to the tendered amount — powers the quick-cash denomination chips.
void addCash(double amount) => setCashTendered(state.cashTendered + amount);
/// Fills the exact balance, the most common cash case.
void tenderExact() => setCashTendered(balanceDue);
void setReference(String value) =>
state = state.copyWith(reference: value, clearError: true);
/// Records the active tender. For a split payment, call this once per part.
void addSplit({double? amount}) {
final value = (amount ?? balanceDue).clamp(0, balanceDue).toDouble();
if (value <= 0) return;
final split = PaymentSplit(
method: state.activeMethod,
amount: value.asMoney,
tendered: state.activeMethod.needsChange
? (state.cashTendered > 0 ? state.cashTendered : value)
: null,
reference: state.reference.trim().isEmpty ? null : state.reference.trim(),
);
state = state.copyWith(
splits: [...state.splits, split],
cashTendered: 0,
reference: '',
clearError: true,
);
}
void removeSplit(int index) {
final next = [...state.splits]..removeAt(index);
state = state.copyWith(splits: next);
}
void clearSplits() => state = state.copyWith(splits: const []);
/// Finalises the sale. On success the caller navigates to the receipt.
Future<CheckoutResult?> confirm() async {
if (state.isProcessing) return null;
// A single-tender sale needn't be staged first — fold it in automatically.
var splits = state.splits;
if (splits.isEmpty || balanceDue > 0.01) {
addSplit();
splits = state.splits;
}
state = state.copyWith(isProcessing: true, clearError: true);
try {
final cart = _ref.read(cartControllerProvider);
final session = _ref.read(cashierSessionProvider);
final result = await _ref.read(checkoutSaleProvider)(
cart: cart,
payments: splits,
cashierName: session.name,
);
state = state.copyWith(isProcessing: false, result: result);
// Fire and forget — printing must never block the next sale.
final receipts = _ref.read(receiptServiceProvider);
unawaited(receipts.printDirect(result.transaction));
unawaited(receipts.openCashDrawer());
unawaited(_ref.read(soundServiceProvider).saleComplete());
// Stock changed, so the grid must refresh.
_ref.invalidate(allProductsProvider);
_ref.invalidate(visibleProductsProvider);
return result;
} on CheckoutFailure catch (e) {
state = state.copyWith(isProcessing: false, error: e.message);
return null;
} catch (e) {
state = state.copyWith(
isProcessing: false,
error: 'Could not complete the sale. $e',
);
return null;
}
}
void reset() => state = const PaymentState();
}
final paymentControllerProvider =
StateNotifierProvider.autoDispose<PaymentController, PaymentState>(
(ref) => PaymentController(ref),
);

View File

@@ -0,0 +1,511 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/glass_card.dart';
import '../../../core/widgets/numeric_keypad.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/transaction.dart';
import '../../pos/providers/cart_controller.dart';
import '../providers/payment_controller.dart';
class PaymentScreen extends ConsumerStatefulWidget {
const PaymentScreen({super.key});
@override
ConsumerState<PaymentScreen> createState() => _PaymentScreenState();
}
class _PaymentScreenState extends ConsumerState<PaymentScreen> {
String _cashBuffer = '';
void _syncCash() {
final value = double.tryParse(_cashBuffer) ?? 0;
ref.read(paymentControllerProvider.notifier).setCashTendered(value);
}
void _appendCash(String d) {
if (d == '.' && _cashBuffer.contains('.')) return;
if (_cashBuffer.length >= 8) return;
setState(() => _cashBuffer += d);
_syncCash();
}
void _backspaceCash() {
if (_cashBuffer.isEmpty) return;
setState(() => _cashBuffer = _cashBuffer.substring(0, _cashBuffer.length - 1));
_syncCash();
}
void _setCash(double value) {
setState(() => _cashBuffer = value.toStringAsFixed(0));
_syncCash();
}
Future<void> _confirm() async {
final result = await ref.read(paymentControllerProvider.notifier).confirm();
if (result == null || !mounted) return;
// Sale is banked — clear the terminal and show the receipt.
ref.read(cartControllerProvider.notifier).reset();
context.go(AppRoutes.receipt, extra: result.transaction);
}
@override
Widget build(BuildContext context) {
final cart = ref.watch(cartControllerProvider);
final state = ref.watch(paymentControllerProvider);
final controller = ref.read(paymentControllerProvider.notifier);
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: const Text('Payment'),
leading: IconButton(
icon: const Icon(Icons.arrow_back_rounded),
onPressed: () => context.pop(),
),
),
body: Padding(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: context.isCompact
? SingleChildScrollView(
child: Column(children: [
_amountCard(controller, state),
const SizedBox(height: AppSpacing.lg),
_methodsCard(controller, state),
const SizedBox(height: AppSpacing.lg),
_tenderCard(controller, state),
]),
)
: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
flex: 4,
child: Column(children: [
_amountCard(controller, state),
const SizedBox(height: AppSpacing.lg),
Expanded(child: _methodsCard(controller, state)),
]),
),
const SizedBox(width: AppSpacing.lg),
Expanded(flex: 5, child: _tenderCard(controller, state)),
],
),
),
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(
AppSpacing.xxl,
0,
AppSpacing.xxl,
AppSpacing.xxl,
),
child: Column(mainAxisSize: MainAxisSize.min, children: [
if (state.error != null) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.all(AppSpacing.md),
margin: const EdgeInsets.only(bottom: AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brSm,
),
child: Row(children: [
const Icon(Icons.error_outline_rounded,
color: AppColors.danger, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(state.error!,
style: const TextStyle(color: AppColors.danger)),
),
]),
).animate().shake(duration: 300.ms, hz: 3),
],
PrimaryButton(
label: 'Complete Sale',
icon: Icons.check_circle_outline_rounded,
large: true,
tone: ButtonTone.success,
busy: state.isProcessing,
onPressed: cart.isEmpty ? null : _confirm,
trailing: Text(
Formatters.money(cart.grandTotal),
style: AppTypography.money(21, color: Colors.white),
),
),
]),
),
),
);
}
// ------------------------------------------------------------- Sections
Widget _amountCard(PaymentController controller, PaymentState state) {
final cart = ref.watch(cartControllerProvider);
return GlassCard(
padding: const EdgeInsets.all(AppSpacing.xxl),
radius: AppRadius.xl,
tinted: true,
child: Column(children: [
Text('Amount due', style: context.text.labelMedium),
const SizedBox(height: AppSpacing.xs),
Text(
Formatters.money(controller.balanceDue),
style: AppTypography.money(40, color: AppColors.primary),
),
const SizedBox(height: AppSpacing.md),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
_mini('Items', '${cart.lineCount}'),
_dot(),
_mini('Bill total', Formatters.money(cart.grandTotal)),
if (state.settled > 0) ...[
_dot(),
_mini('Settled', Formatters.money(state.settled)),
],
]),
]),
);
}
Widget _methodsCard(PaymentController controller, PaymentState state) {
return GlassCard(
padding: const EdgeInsets.all(AppSpacing.xl),
radius: AppRadius.xl,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Payment method', style: context.text.titleMedium),
const SizedBox(height: AppSpacing.lg),
Wrap(
spacing: AppSpacing.md,
runSpacing: AppSpacing.md,
children: PaymentMethod.values
.where((m) => m != PaymentMethod.loyalty)
.map((m) => _MethodTile(
method: m,
selected: state.activeMethod == m,
onTap: () {
setState(() => _cashBuffer = '');
controller.selectMethod(m);
},
))
.toList(),
),
if (state.splits.isNotEmpty) ...[
const SizedBox(height: AppSpacing.xl),
const Divider(),
const SizedBox(height: AppSpacing.md),
Row(children: [
Text('Split tenders', style: context.text.titleSmall),
const Spacer(),
TextButton(
onPressed: controller.clearSplits,
style: TextButton.styleFrom(
foregroundColor: AppColors.danger),
child: const Text('Clear all'),
),
]),
const SizedBox(height: AppSpacing.sm),
...state.splits.asMap().entries.map((e) => Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.sm),
child: Row(children: [
Text(e.value.method.emoji,
style: const TextStyle(fontSize: 16)),
const SizedBox(width: AppSpacing.sm),
Expanded(child: Text(e.value.method.label)),
Text(Formatters.money(e.value.amount),
style: AppTypography.money(14.5)),
IconButton(
onPressed: () => controller.removeSplit(e.key),
icon: const Icon(Icons.close_rounded, size: 17),
color: AppColors.textTertiary,
constraints:
const BoxConstraints(minWidth: 30, minHeight: 30),
padding: EdgeInsets.zero,
),
]),
)),
],
],
),
);
}
Widget _tenderCard(PaymentController controller, PaymentState state) {
final isCash = state.activeMethod.needsChange;
return GlassCard(
padding: const EdgeInsets.all(AppSpacing.xl),
radius: AppRadius.xl,
child: isCash
? _cashTender(controller, state)
: _referenceTender(controller, state),
);
}
Widget _cashTender(PaymentController controller, PaymentState state) {
final change = controller.changeDue;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Cash received', style: context.text.titleMedium),
const SizedBox(height: AppSpacing.md),
Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
vertical: AppSpacing.lg,
),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brLg,
border: Border.all(color: AppColors.border),
),
child: Row(children: [
const Text('',
style: TextStyle(fontSize: 24, color: AppColors.textTertiary)),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
_cashBuffer.isEmpty ? '0' : _cashBuffer,
style: AppTypography.money(30),
),
),
]),
),
const SizedBox(height: AppSpacing.md),
Wrap(
spacing: AppSpacing.sm,
runSpacing: AppSpacing.sm,
children: [
ActionChip(
avatar: const Icon(Icons.done_all_rounded, size: 15),
label: const Text('Exact'),
onPressed: () => _setCash(controller.balanceDue),
),
...[50, 100, 200, 500, 2000].map(
(note) => ActionChip(
label: Text('$note'),
onPressed: () => _setCash(
(double.tryParse(_cashBuffer) ?? 0) + note,
),
),
),
],
),
const SizedBox(height: AppSpacing.lg),
AnimatedContainer(
duration: AppMotion.normal,
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: change > 0
? AppColors.successSurface
: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
),
child: Row(children: [
Icon(
change > 0
? Icons.currency_exchange_rounded
: Icons.info_outline_rounded,
size: 19,
color: change > 0 ? AppColors.success : AppColors.textTertiary,
),
const SizedBox(width: AppSpacing.md),
Text(
'Change to return',
style: TextStyle(
fontWeight: FontWeight.w600,
color: change > 0
? AppColors.success
: AppColors.textSecondary,
),
),
const Spacer(),
Text(
Formatters.money(change),
style: AppTypography.money(
22,
color: change > 0 ? AppColors.success : AppColors.textTertiary,
),
),
]),
),
const SizedBox(height: AppSpacing.lg),
Center(
child: NumericKeypad(
allowDecimal: true,
maxWidth: 330,
onKey: _appendCash,
onBackspace: _backspaceCash,
),
),
const SizedBox(height: AppSpacing.md),
OutlinedButton.icon(
onPressed: controller.balanceDue > 0
? () {
controller.addSplit(
amount: (double.tryParse(_cashBuffer) ?? 0)
.clamp(0, controller.balanceDue)
.toDouble(),
);
setState(() => _cashBuffer = '');
}
: null,
icon: const Icon(Icons.call_split_rounded, size: 17),
label: const Text('Add as split payment'),
),
],
);
}
Widget _referenceTender(PaymentController controller, PaymentState state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(children: [
Text(state.activeMethod.emoji, style: const TextStyle(fontSize: 22)),
const SizedBox(width: AppSpacing.sm),
Text('${state.activeMethod.label} payment',
style: context.text.titleMedium),
]),
const SizedBox(height: AppSpacing.xxl),
Center(
child: Column(children: [
Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brXl,
),
alignment: Alignment.center,
child: Text(state.activeMethod.emoji,
style: const TextStyle(fontSize: 52)),
),
const SizedBox(height: AppSpacing.lg),
Text(
'Charge ${Formatters.money(controller.balanceDue)} '
'on the ${state.activeMethod.label.toLowerCase()} terminal',
textAlign: TextAlign.center,
style: context.text.bodyMedium,
),
]),
),
const SizedBox(height: AppSpacing.xxl),
if (state.activeMethod.needsReference)
TextField(
onChanged: controller.setReference,
decoration: InputDecoration(
labelText: switch (state.activeMethod) {
PaymentMethod.card => 'Approval code',
PaymentMethod.upi => 'UPI transaction ID',
PaymentMethod.giftCard => 'Gift card number',
_ => 'Reference',
},
prefixIcon: const Icon(Icons.tag_rounded),
),
),
const SizedBox(height: AppSpacing.xxxl),
OutlinedButton.icon(
onPressed: controller.balanceDue > 0
? () => controller.addSplit()
: null,
icon: const Icon(Icons.call_split_rounded, size: 17),
label: const Text('Add as split payment'),
),
],
);
}
Widget _mini(String label, String value) => Column(children: [
Text(label,
style: const TextStyle(
fontSize: 11,
color: AppColors.textSecondary,
)),
Text(value,
style: AppTypography.money(14, weight: FontWeight.w600)),
]);
Widget _dot() => Container(
width: 3,
height: 3,
margin: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
decoration: const BoxDecoration(
color: AppColors.textTertiary,
shape: BoxShape.circle,
),
);
}
class _MethodTile extends StatelessWidget {
const _MethodTile({
required this.method,
required this.selected,
required this.onTap,
});
final PaymentMethod method;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: selected ? AppColors.primary : AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brMd,
child: AnimatedContainer(
duration: AppMotion.fast,
width: 118,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.lg,
),
decoration: BoxDecoration(
borderRadius: AppRadius.brMd,
border: Border.all(
color: selected ? AppColors.primary : AppColors.border,
),
),
child: Column(children: [
Text(method.emoji, style: const TextStyle(fontSize: 24)),
const SizedBox(height: AppSpacing.sm),
Text(
method.label,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: selected ? Colors.white : AppColors.textPrimary,
),
),
]),
),
),
);
}
}

View File

@@ -0,0 +1,307 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart';
import '../../../app/providers.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/services/sound_service.dart';
import '../../../domain/entities/cart.dart';
import '../../../domain/entities/customer.dart';
import '../../../domain/entities/product.dart';
import '../../../domain/entities/transaction.dart';
import '../../../domain/repositories/product_repository.dart';
import '../../../domain/repositories/transaction_repository.dart';
/// Transient feedback for the scan toast — never a blocking dialog.
enum ScanOutcome { added, incremented, notFound, outOfStock }
class ScanFeedback {
const ScanFeedback({
required this.outcome,
required this.stamp,
this.product,
this.message,
});
final ScanOutcome outcome;
final DateTime stamp;
final Product? product;
final String? message;
bool get isSuccess =>
outcome == ScanOutcome.added || outcome == ScanOutcome.incremented;
}
/// Owns the live bill.
///
/// All mutations funnel through here so that scanner input, product taps and
/// keyboard shortcuts share one code path and one set of guarantees.
class CartController extends StateNotifier<Cart> {
CartController({
required ProductRepository products,
required TransactionRepository transactions,
required SoundService sound,
required this.onFeedback,
}) : _products = products,
_transactions = transactions,
_sound = sound,
super(Cart.empty);
final ProductRepository _products;
final TransactionRepository _transactions;
final SoundService _sound;
final void Function(ScanFeedback) onFeedback;
static const _uuid = Uuid();
/// Snapshots for undo — capped so memory can't grow unbounded on a terminal
/// that runs for days.
final List<Cart> _undoStack = [];
static const int _maxUndo = 25;
bool get canUndo => _undoStack.isNotEmpty;
void _push() {
_undoStack.add(state);
if (_undoStack.length > _maxUndo) _undoStack.removeAt(0);
}
void undo() {
if (_undoStack.isEmpty) return;
state = _undoStack.removeLast();
}
// ------------------------------------------------------------ Line items
/// Adds a product, merging into the existing line when already present.
void addProduct(Product product, {double quantity = 1}) {
if (product.isOutOfStock) {
_sound.scanError();
onFeedback(ScanFeedback(
outcome: ScanOutcome.outOfStock,
stamp: DateTime.now(),
product: product,
message: '${product.name} is out of stock',
));
return;
}
_push();
final existing = state.lineFor(product.id);
final requested = (existing?.quantity ?? 0) + quantity;
if (requested > product.stock) {
_undoStack.removeLast();
_sound.scanError();
onFeedback(ScanFeedback(
outcome: ScanOutcome.outOfStock,
stamp: DateTime.now(),
product: product,
message: 'Only ${product.stock.toStringAsFixed(0)} '
'${product.unit.symbol} left',
));
return;
}
if (existing == null) {
state = state.copyWith(lines: [
...state.lines,
CartLine(
product: product,
quantity: quantity,
addedAt: DateTime.now(),
),
]);
} else {
state = state.copyWith(
lines: _replace(existing.copyWith(quantity: requested)),
);
}
_clampRedemption();
_sound.scanSuccess();
onFeedback(ScanFeedback(
outcome: existing == null ? ScanOutcome.added : ScanOutcome.incremented,
stamp: DateTime.now(),
product: product,
));
}
/// Scanner entry point. Resolves the barcode and adds it with no dialogs.
Future<void> scanBarcode(String code) async {
final product = await _products.findByBarcode(code);
if (product == null) {
_sound.scanError();
onFeedback(ScanFeedback(
outcome: ScanOutcome.notFound,
stamp: DateTime.now(),
message: 'No product for barcode $code',
));
return;
}
addProduct(product);
}
void setQuantity(String productId, double quantity) {
final line = state.lineFor(productId);
if (line == null) return;
if (quantity <= 0) {
removeLine(productId);
return;
}
final capped = quantity
.clamp(0, AppConstants.maxCartQuantityPerLine.toDouble())
.toDouble();
if (capped > line.product.stock) {
_sound.scanError();
onFeedback(ScanFeedback(
outcome: ScanOutcome.outOfStock,
stamp: DateTime.now(),
product: line.product,
message: 'Only ${line.product.stock.toStringAsFixed(0)} in stock',
));
return;
}
_push();
state = state.copyWith(lines: _replace(line.copyWith(quantity: capped)));
_clampRedemption();
}
void increment(String productId, {double by = 1}) {
final line = state.lineFor(productId);
if (line == null) return;
setQuantity(productId, line.quantity + by);
}
void decrement(String productId, {double by = 1}) {
final line = state.lineFor(productId);
if (line == null) return;
setQuantity(productId, line.quantity - by);
}
void removeLine(String productId) {
if (!state.contains(productId)) return;
_push();
state = state.copyWith(
lines: state.lines.where((l) => l.product.id != productId).toList(),
);
_clampRedemption();
}
void applyLineDiscount(String productId, Discount discount) {
final line = state.lineFor(productId);
if (line == null) return;
_push();
state = state.copyWith(lines: _replace(line.copyWith(discount: discount)));
_clampRedemption();
}
// ------------------------------------------------------------ Bill level
void applyBillDiscount(Discount discount) {
_push();
state = state.copyWith(billDiscount: discount);
_clampRedemption();
}
void clearBillDiscount() => applyBillDiscount(Discount.none);
void attachCustomer(Customer? customer) {
_push();
state = customer == null
? state.copyWith(clearCustomer: true, pointsRedeemed: 0)
: state.copyWith(customer: customer);
_clampRedemption();
}
void redeemPoints(int points) {
final max = state.maxRedeemablePoints;
_push();
state = state.copyWith(pointsRedeemed: points.clamp(0, max));
}
void redeemAllPoints() => redeemPoints(state.maxRedeemablePoints);
void clearRedemption() => redeemPoints(0);
void setNote(String? note) => state = state.copyWith(note: note);
/// Keeps redemption legal after the bill shrinks below the redeemed value.
void _clampRedemption() {
if (state.pointsRedeemed == 0) return;
final max = state.maxRedeemablePoints;
if (state.pointsRedeemed > max) {
state = state.copyWith(pointsRedeemed: max);
}
}
// --------------------------------------------------------------- Session
void clear() {
_push();
state = Cart.empty;
}
/// Starts a brand new sale, dropping undo history and the customer.
void reset() {
_undoStack.clear();
state = Cart.empty;
}
/// Keeps the customer attached for a follow-up bill.
void resetKeepingCustomer() {
_undoStack.clear();
state = Cart(customer: state.customer);
}
// ---------------------------------------------------------- Parked bills
Future<void> park({String? label}) async {
if (state.isEmpty) return;
await _transactions.park(ParkedBill(
id: _uuid.v4(),
cart: state,
parkedAt: DateTime.now(),
label: label,
));
reset();
}
Future<void> resume(ParkedBill bill) async {
await _transactions.removeParked(bill.id);
_undoStack.clear();
state = bill.cart;
}
List<CartLine> _replace(CartLine updated) => [
for (final l in state.lines)
if (l.product.id == updated.product.id) updated else l,
];
}
// ----------------------------------------------------------------- Providers
final scanFeedbackProvider = StateProvider<ScanFeedback?>((ref) => null);
final cartControllerProvider =
StateNotifierProvider<CartController, Cart>((ref) {
return CartController(
products: ref.watch(productRepositoryProvider),
transactions: ref.watch(transactionRepositoryProvider),
sound: ref.watch(soundServiceProvider),
onFeedback: (feedback) =>
ref.read(scanFeedbackProvider.notifier).state = feedback,
);
});
/// Convenience selectors — each rebuilds only the widget that needs it.
final cartTotalProvider =
Provider<double>((ref) => ref.watch(cartControllerProvider).grandTotal);
final cartItemCountProvider =
Provider<int>((ref) => ref.watch(cartControllerProvider).lineCount);
final parkedBillsProvider = FutureProvider<List<ParkedBill>>(
(ref) => ref.watch(transactionRepositoryProvider).parkedBills(),
);

View File

@@ -0,0 +1,44 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../domain/entities/product.dart';
/// `null` means the "All" chip is selected.
final selectedCategoryProvider =
StateProvider<ProductCategory?>((ref) => null);
final searchQueryProvider = StateProvider<String>((ref) => '');
final allProductsProvider = FutureProvider<List<Product>>(
(ref) => ref.watch(productRepositoryProvider).getAll(),
);
/// The grid's data source: category filter and search applied together.
final visibleProductsProvider = FutureProvider<List<Product>>((ref) async {
final repo = ref.watch(productRepositoryProvider);
final query = ref.watch(searchQueryProvider);
final category = ref.watch(selectedCategoryProvider);
final base = query.trim().isEmpty
? await repo.getAll()
: await repo.search(query);
if (category == null) return base;
return base.where((p) => p.category == category).toList();
});
/// Counts per category for the chip badges.
final categoryCountsProvider =
FutureProvider<Map<ProductCategory, int>>((ref) async {
final products = await ref.watch(allProductsProvider.future);
final map = <ProductCategory, int>{};
for (final p in products) {
map[p.category] = (map[p.category] ?? 0) + 1;
}
return map;
});
final lowStockProductsProvider = FutureProvider<List<Product>>((ref) async {
final products = await ref.watch(allProductsProvider.future);
return products.where((p) => p.isLowStock || p.isOutOfStock).toList();
});

View File

@@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
/// The modules a cashier needs. Deliberately excludes analytics — this
/// terminal is for billing, not back-office reporting.
enum PosModule {
pos('Point of Sale', 'POS', Icons.point_of_sale_rounded, NavSection.billing),
customers('Customers', 'Customers', Icons.people_alt_rounded,
NavSection.billing),
productImport('Product Import', 'Product Import',
Icons.cloud_download_rounded, NavSection.catalogue),
promos('Promotions', 'Promo', Icons.sell_rounded, NavSection.catalogue),
events('Events', 'Events', Icons.sync_rounded, NavSection.session),
settings('Settings', 'Settings', Icons.settings_rounded, NavSection.session);
const PosModule(this.title, this.label, this.icon, this.section);
/// Long form, shown in the page header.
final String title;
/// Short form, shown in the sidebar.
final String label;
final IconData icon;
final NavSection section;
}
/// Groups the navigation into labelled blocks.
enum NavSection {
billing('Billing'),
catalogue('Catalogue'),
session('Session');
const NavSection(this.label);
final String label;
List<PosModule> get modules =>
PosModule.values.where((m) => m.section == this).toList();
}
final activeModuleProvider = StateProvider<PosModule>((ref) => PosModule.pos);

View File

@@ -0,0 +1,171 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/services/barcode_service.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_layout.dart';
import '../../modules/screens/customers_view.dart';
import '../../modules/screens/events_view.dart';
import '../../modules/screens/product_import_view.dart';
import '../../modules/screens/promos_view.dart';
import '../../modules/screens/settings_view.dart';
import '../../sync/providers/sync_controller.dart';
import '../providers/cart_controller.dart';
import '../providers/navigation_provider.dart';
import '../widgets/app_sidebar.dart';
import '../widgets/billing_panel.dart';
import '../widgets/cart_fab.dart';
import '../widgets/page_header.dart';
import 'pos_view.dart';
/// Application shell.
///
/// Owns the sidebar, page header and the body for whichever module is active.
/// Keeping one shell means navigation never rebuilds the chrome, and the
/// scanner stays live across modules.
///
/// Layout collapses in a fixed order as width shrinks:
///
/// * `>= 1300` sidebar with labels, docked bill
/// * `11201300` sidebar as an icon rail, docked bill
/// * `9201120` icon rail, bill becomes a bottom sheet
/// * `< 920` sidebar goes off-canvas behind a menu button
class PosDashboardScreen extends ConsumerStatefulWidget {
const PosDashboardScreen({super.key});
@override
ConsumerState<PosDashboardScreen> createState() => _PosDashboardScreenState();
}
class _PosDashboardScreenState extends ConsumerState<PosDashboardScreen> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final FocusNode _searchFocus = FocusNode();
late final BarcodeService _barcode;
@override
void initState() {
super.initState();
// The scanner behaves like a keyboard, so listen globally rather than
// depending on any one field holding focus. A scan from another module
// jumps back to billing, which is what a cashier expects.
_barcode = BarcodeService(
onScan: (code) {
// Without an imported catalogue there is nothing to resolve against.
if (!ref.read(catalogueReadyProvider)) return;
ref.read(activeModuleProvider.notifier).state = PosModule.pos;
ref.read(cartControllerProvider.notifier).scanBarcode(code);
},
)..attach();
}
@override
void dispose() {
_barcode.dispose();
_searchFocus.dispose();
super.dispose();
}
void _openBillingSheet() {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => FractionallySizedBox(
heightFactor: 0.92,
child: ClipRRect(
borderRadius: const BorderRadius.vertical(
top: Radius.circular(AppRadius.xxl),
),
child: const BillingPanel(inSheet: true),
),
),
);
}
Widget _body(PosModule module, PosLayout layout) => switch (module) {
PosModule.pos => PosView(layout: layout, searchFocus: _searchFocus),
PosModule.customers => const CustomersView(),
PosModule.productImport => const ProductImportView(),
PosModule.promos => const PromosView(),
PosModule.events => const EventsView(),
PosModule.settings => const SettingsView(),
};
@override
Widget build(BuildContext context) {
final layout = PosLayout.of(context);
final module = ref.watch(activeModuleProvider);
final ready = ref.watch(catalogueReadyProvider);
final isPos = module == PosModule.pos && ready;
// Only the terminal itself needs the bill docked beside it.
final showDockedBill = isPos && !layout.billingIsSheet;
final showCartFab = isPos && layout.billingIsSheet;
return Scaffold(
key: _scaffoldKey,
backgroundColor: AppColors.background,
drawer: layout.sidebarIsDrawer
? Drawer(
width: PosLayout.expandedWidth,
backgroundColor: AppColors.surface,
child: AppSidebar(
mode: SidebarMode.expanded,
onDestinationTap: () => Navigator.of(context).maybePop(),
),
)
: null,
floatingActionButton:
showCartFab ? CartFab(onTap: _openBillingSheet) : null,
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.f2):
_searchFocus.requestFocus,
const SingleActivator(LogicalKeyboardKey.f8): () =>
ref.read(cartControllerProvider.notifier).undo(),
const SingleActivator(LogicalKeyboardKey.escape):
_searchFocus.unfocus,
},
child: Focus(
autofocus: true,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!layout.sidebarIsDrawer) AppSidebar(mode: layout.sidebar),
Expanded(
child: Column(
children: [
PageHeader(
layout: layout,
onMenuTap: () => _scaffoldKey.currentState?.openDrawer(),
),
Expanded(
child: AnimatedSwitcher(
duration: AppMotion.fast,
child: KeyedSubtree(
key: ValueKey(module),
child: _body(module, layout),
),
),
),
],
),
),
if (showDockedBill) ...[
const VerticalDivider(width: 1),
SizedBox(
width: layout.billingWidth,
child: const BillingPanel(),
),
],
],
),
),
),
);
}
}

View File

@@ -0,0 +1,197 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_layout.dart';
import '../../../core/widgets/primary_button.dart';
import '../../sync/providers/sync_controller.dart';
import '../providers/navigation_provider.dart';
import '../widgets/category_chips.dart';
import '../widgets/customer_bar.dart';
import '../widgets/product_grid.dart';
import '../widgets/scan_toast.dart';
import '../widgets/search_field.dart';
/// Catalogue half of the terminal.
///
/// Gated on the catalogue import: with no products loaded there is nothing to
/// sell, so the cashier is sent to the import step instead of a broken grid.
class PosView extends ConsumerWidget {
const PosView({super.key, required this.layout, required this.searchFocus});
final PosLayout layout;
final FocusNode searchFocus;
@override
Widget build(BuildContext context, WidgetRef ref) {
if (!ref.watch(catalogueReadyProvider)) {
return const _CatalogueRequired();
}
final pad = layout.contentPadding;
// Keep the last grid row clear of the floating bill button.
final bottomInset = layout.billingIsSheet
? AppSizes.buttonHeightLarge + AppSpacing.xxxl
: AppSpacing.xxl;
return Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const CustomerBar(),
const Divider(height: 1),
Padding(
padding:
EdgeInsets.fromLTRB(pad, AppSpacing.lg, pad, AppSpacing.md),
child: PosSearchField(focusNode: searchFocus),
),
CategoryChips(horizontalPadding: pad),
const SizedBox(height: AppSpacing.md),
Expanded(
child: ProductGrid(
horizontalPadding: pad,
tileExtent: layout.gridTileExtent,
bottomPadding: bottomInset,
),
),
],
),
Positioned(
left: 0,
right: 0,
bottom: bottomInset,
child: const Align(
alignment: Alignment.bottomCenter,
child: ScanToast(),
),
),
],
);
}
}
/// Shown until the catalogue has been pulled onto this terminal.
class _CatalogueRequired extends ConsumerWidget {
const _CatalogueRequired();
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(catalogueImportProvider);
final running = state is ImportRunning;
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 460),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 96,
height: 96,
decoration: const BoxDecoration(
color: AppColors.primarySurface,
shape: BoxShape.circle,
),
child: const Icon(Icons.cloud_download_outlined,
size: 42, color: AppColors.primary),
),
const SizedBox(height: AppSpacing.xxl),
Text(
'Import products to start billing',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: AppSpacing.sm),
const Text(
'This terminal has no catalogue yet. Pull the current products '
'once at the start of your shift — after that everything runs '
'offline.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
color: AppColors.textSecondary,
height: 1.6,
),
),
const SizedBox(height: AppSpacing.xxl),
if (running) ...[
Text(
state.stage,
style: const TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
),
),
const SizedBox(height: AppSpacing.sm),
ClipRRect(
borderRadius: AppRadius.brPill,
child: LinearProgressIndicator(
value: state.progress,
minHeight: 8,
backgroundColor: AppColors.divider,
valueColor: const AlwaysStoppedAnimation<Color>(
AppColors.primary),
),
),
const SizedBox(height: AppSpacing.lg),
],
if (state is ImportFailed) ...[
Container(
padding: const EdgeInsets.all(AppSpacing.md),
margin: const EdgeInsets.only(bottom: AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brSm,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.wifi_off_rounded,
color: AppColors.danger, size: 18),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
state.message,
style: const TextStyle(
color: AppColors.danger,
fontSize: 13,
height: 1.45,
),
),
),
],
),
),
],
PrimaryButton(
label: 'Import catalogue now',
icon: Icons.cloud_download_rounded,
large: true,
busy: running,
onPressed: running
? null
: () => ref.read(catalogueImportProvider.notifier).run(),
),
const SizedBox(height: AppSpacing.md),
TextButton.icon(
onPressed: () => ref
.read(activeModuleProvider.notifier)
.state = PosModule.productImport,
icon: const Icon(Icons.open_in_new_rounded, size: 16),
label: const Text('Open Product Import'),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,485 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_layout.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/sync_event.dart';
import '../../auth/providers/auth_controller.dart';
import '../../sync/widgets/sign_out_dialog.dart';
import '../providers/cart_controller.dart';
import '../../sync/providers/sync_controller.dart';
import '../providers/navigation_provider.dart';
/// Left navigation rail.
///
/// Renders in three widths: full labels on desktop, icons only on tablet
/// landscape, and off-canvas below that. The same widget serves all three so
/// the active state and badges never drift apart.
class AppSidebar extends ConsumerWidget {
const AppSidebar({
super.key,
required this.mode,
this.onDestinationTap,
});
final SidebarMode mode;
/// Lets the drawer close itself after a tap.
final VoidCallback? onDestinationTap;
@override
Widget build(BuildContext context, WidgetRef ref) {
// The drawer presentation uses the expanded layout at full width.
final expanded = mode != SidebarMode.rail;
final width = mode == SidebarMode.rail
? PosLayout.railWidth
: PosLayout.expandedWidth;
return AnimatedContainer(
duration: AppMotion.normal,
curve: AppMotion.emphasized,
width: width,
decoration: const BoxDecoration(
color: AppColors.surface,
border: Border(right: BorderSide(color: AppColors.border)),
),
child: SafeArea(
right: false,
child: Column(
children: [
_Brand(expanded: expanded),
const Divider(height: 1),
_Profile(expanded: expanded),
const Divider(height: 1),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.md),
child: Column(
children: [
for (final section in NavSection.values)
_Section(
section: section,
expanded: expanded,
onDestinationTap: onDestinationTap,
),
],
),
),
),
const Divider(height: 1),
_LogoutTile(expanded: expanded),
],
),
),
);
}
}
class _Brand extends StatelessWidget {
const _Brand({required this.expanded});
final bool expanded;
@override
Widget build(BuildContext context) {
return Container(
height: AppSizes.headerHeight,
padding: EdgeInsets.symmetric(
horizontal: expanded ? AppSpacing.xl : AppSpacing.md,
),
alignment: expanded ? Alignment.centerLeft : Alignment.center,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(
gradient: AppColors.primaryGradient,
borderRadius: BorderRadius.circular(10),
),
alignment: Alignment.center,
child: const Text(
'N',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
),
if (expanded) ...[
const SizedBox(width: AppSpacing.md),
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Nearle',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
letterSpacing: -0.3,
color: AppColors.textPrimary,
height: 1.1,
),
),
Text(
'POS',
style: AppTypography.sectionLabel()
.copyWith(color: AppColors.primary),
),
],
),
),
],
],
),
);
}
}
class _Profile extends ConsumerWidget {
const _Profile({required this.expanded});
final bool expanded;
@override
Widget build(BuildContext context, WidgetRef ref) {
final user = ref.watch(currentUserProvider);
final name = user?.name ?? ref.watch(cashierSessionProvider).name;
final role = user?.role.label ?? ref.watch(cashierSessionProvider).role;
return Padding(
padding: EdgeInsets.symmetric(
horizontal: expanded ? AppSpacing.lg : AppSpacing.sm,
vertical: AppSpacing.md,
),
child: Row(
mainAxisAlignment:
expanded ? MainAxisAlignment.start : MainAxisAlignment.center,
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.primaryBorder),
),
alignment: Alignment.center,
child: Text(
Formatters.initials(name),
style: const TextStyle(
color: AppColors.primary,
fontSize: 13,
fontWeight: FontWeight.w700,
),
),
),
if (expanded) ...[
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
height: 1.2,
),
),
Text(
role,
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
height: 1.3,
),
),
],
),
),
],
],
),
);
}
}
class _Section extends ConsumerWidget {
const _Section({
required this.section,
required this.expanded,
this.onDestinationTap,
});
final NavSection section;
final bool expanded;
final VoidCallback? onDestinationTap;
@override
Widget build(BuildContext context, WidgetRef ref) {
final active = ref.watch(activeModuleProvider);
final cartCount = ref.watch(cartItemCountProvider);
final ready = ref.watch(catalogueReadyProvider);
final outstanding = ref
.watch(syncEventsProvider)
.where((e) => e.status != SyncStatus.synced)
.length;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (expanded)
Padding(
padding: const EdgeInsets.fromLTRB(
AppSpacing.xl,
AppSpacing.lg,
AppSpacing.xl,
AppSpacing.sm,
),
child: Text(section.label.toUpperCase(),
style: AppTypography.sectionLabel()),
)
else
const Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
vertical: AppSpacing.md,
),
child: Divider(height: 1),
),
for (final module in section.modules)
_NavTile(
module: module,
expanded: expanded,
selected: active == module,
badge: switch (module) {
PosModule.pos => cartCount > 0 ? cartCount : null,
PosModule.productImport => ready ? null : 1,
PosModule.events => outstanding > 0 ? outstanding : null,
_ => null,
},
badgeColor: switch (module) {
PosModule.productImport => AppColors.danger,
PosModule.events => AppColors.warning,
_ => AppColors.primary,
},
onTap: () {
ref.read(activeModuleProvider.notifier).state = module;
onDestinationTap?.call();
},
),
],
);
}
}
class _NavTile extends StatefulWidget {
const _NavTile({
required this.module,
required this.expanded,
required this.selected,
required this.onTap,
this.badge,
this.badgeColor,
});
final PosModule module;
final bool expanded;
final bool selected;
final VoidCallback onTap;
final int? badge;
final Color? badgeColor;
@override
State<_NavTile> createState() => _NavTileState();
}
class _NavTileState extends State<_NavTile> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final selected = widget.selected;
final fg = selected
? AppColors.primary
: (_hovered ? AppColors.textPrimary : AppColors.textSecondary);
final tile = AnimatedContainer(
duration: AppMotion.fast,
height: AppSizes.navItemHeight,
padding: EdgeInsets.symmetric(
horizontal: widget.expanded ? AppSpacing.md : 0,
),
decoration: BoxDecoration(
color: selected
? AppColors.primarySurface
: (_hovered ? AppColors.surfaceAlt : Colors.transparent),
borderRadius: AppRadius.brSm,
),
child: Row(
mainAxisAlignment: widget.expanded
? MainAxisAlignment.start
: MainAxisAlignment.center,
children: [
Stack(
clipBehavior: Clip.none,
children: [
Icon(widget.module.icon, size: 20, color: fg),
// In rail mode the label is gone, so the badge rides the icon.
if (widget.badge != null && !widget.expanded)
Positioned(
top: -5,
right: -8,
child: _Badge(
value: widget.badge!,
color: widget.badgeColor ?? AppColors.primary,
),
),
],
),
if (widget.expanded) ...[
const SizedBox(width: AppSpacing.md),
Expanded(
child: Text(
widget.module.label,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: selected ? FontWeight.w600 : FontWeight.w500,
color: fg,
),
),
),
if (widget.badge != null)
_Badge(
value: widget.badge!,
color: widget.badgeColor ?? AppColors.primary,
),
],
],
),
);
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: widget.expanded ? AppSpacing.md : AppSpacing.lg,
vertical: 2,
),
child: Stack(
children: [
Material(
color: Colors.transparent,
child: InkWell(
onTap: widget.onTap,
borderRadius: AppRadius.brSm,
child: widget.expanded
? tile
: Tooltip(message: widget.module.title, child: tile),
),
),
// Accent bar marking the active destination.
if (selected)
Positioned(
left: 0,
top: 10,
bottom: 10,
child: Container(
width: 3,
decoration: const BoxDecoration(
color: AppColors.primary,
borderRadius: AppRadius.brPill,
),
),
),
],
),
),
);
}
}
class _Badge extends StatelessWidget {
const _Badge({required this.value, required this.color});
final int value;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(minWidth: 19),
height: 19,
padding: const EdgeInsets.symmetric(horizontal: 5),
decoration: BoxDecoration(color: color, borderRadius: AppRadius.brPill),
alignment: Alignment.center,
child: Text(
value > 99 ? '99+' : '$value',
style: const TextStyle(
color: Colors.white,
fontSize: 10.5,
fontWeight: FontWeight.w700,
),
),
);
}
}
class _LogoutTile extends ConsumerWidget {
const _LogoutTile({required this.expanded});
final bool expanded;
@override
Widget build(BuildContext context, WidgetRef ref) {
return Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () => showSignOutDialog(context, ref),
borderRadius: AppRadius.brSm,
child: Container(
height: AppSizes.navItemHeight,
padding: EdgeInsets.symmetric(
horizontal: expanded ? AppSpacing.md : 0,
),
alignment: expanded ? Alignment.centerLeft : Alignment.center,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.logout_rounded,
size: 19, color: AppColors.danger),
if (expanded) ...[
const SizedBox(width: AppSpacing.md),
const Text(
'Logout',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.danger,
),
),
],
],
),
),
),
),
);
}
}

View File

@@ -0,0 +1,368 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/cart.dart';
import '../providers/cart_controller.dart';
import 'cart_line_tile.dart';
import 'discount_sheet.dart';
/// Always-visible bill on the right of the dashboard.
class BillingPanel extends ConsumerWidget {
const BillingPanel({super.key, this.inSheet = false});
final bool inSheet;
@override
Widget build(BuildContext context, WidgetRef ref) {
final cart = ref.watch(cartControllerProvider);
final controller = ref.read(cartControllerProvider.notifier);
return Container(
color: AppColors.surface,
child: Column(children: [
_Header(cart: cart, inSheet: inSheet),
const Divider(height: 1),
Expanded(
child: cart.isEmpty
? const EmptyState(
title: 'Cart is empty',
message: 'Scan a barcode or tap a product to begin.',
emoji: '🛒',
compact: true,
)
: ListView.separated(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.md,
),
itemCount: cart.lines.length,
separatorBuilder: (_, __) =>
const SizedBox(height: AppSpacing.sm),
itemBuilder: (_, i) {
// Newest line first mirrors what the cashier just scanned.
final line = cart.lines[cart.lines.length - 1 - i];
return CartLineTile(
key: ValueKey(line.product.id),
line: line,
onIncrement: () => controller.increment(line.product.id),
onDecrement: () => controller.decrement(line.product.id),
onRemove: () => controller.removeLine(line.product.id),
onDiscount: () =>
showLineDiscountSheet(context, ref, line),
);
},
),
),
if (cart.isNotEmpty) _Summary(cart: cart),
_Actions(cart: cart),
]),
);
}
}
class _Header extends ConsumerWidget {
const _Header({required this.cart, required this.inSheet});
final Cart cart;
final bool inSheet;
@override
Widget build(BuildContext context, WidgetRef ref) {
final controller = ref.read(cartControllerProvider.notifier);
return Padding(
padding: const EdgeInsets.fromLTRB(
AppSpacing.xl,
AppSpacing.lg,
AppSpacing.md,
AppSpacing.lg,
),
child: Row(children: [
Text('Cart', style: context.text.headlineSmall),
const SizedBox(width: AppSpacing.sm),
if (cart.isNotEmpty)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brPill,
),
child: Text(
'${cart.lineCount}',
style: const TextStyle(
color: AppColors.primary,
fontWeight: FontWeight.w800,
fontSize: 13,
),
),
),
const Spacer(),
if (controller.canUndo)
IconButton(
tooltip: 'Undo (F8)',
onPressed: controller.undo,
icon: const Icon(Icons.undo_rounded, size: 19),
color: AppColors.textSecondary,
),
if (cart.isNotEmpty) ...[
TextButton.icon(
onPressed: () async {
await controller.park();
ref.invalidate(parkedBillsProvider);
if (context.mounted) context.showSnack('Bill parked');
},
icon: const Icon(Icons.pause_circle_outline_rounded, size: 17),
label: const Text('Park'),
style: TextButton.styleFrom(foregroundColor: AppColors.warning),
),
TextButton(
onPressed: controller.clear,
style: TextButton.styleFrom(foregroundColor: AppColors.danger),
child: const Text('Clear'),
),
],
if (inSheet)
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close_rounded),
),
]),
);
}
}
class _Summary extends ConsumerWidget {
const _Summary({required this.cart});
final Cart cart;
@override
Widget build(BuildContext context, WidgetRef ref) {
final controller = ref.read(cartControllerProvider.notifier);
return Container(
padding: const EdgeInsets.fromLTRB(
AppSpacing.xl,
AppSpacing.lg,
AppSpacing.xl,
AppSpacing.md,
),
decoration: const BoxDecoration(
border: Border(top: BorderSide(color: AppColors.divider)),
),
child: Column(children: [
if (cart.pointsEarned > 0)
Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: AppSpacing.md),
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.sm + 2,
),
decoration: BoxDecoration(
color: AppColors.successSurface,
borderRadius: AppRadius.brSm,
),
child: Row(children: [
const Icon(Icons.stars_rounded,
size: 16, color: AppColors.success),
const SizedBox(width: AppSpacing.sm),
Text(
'This sale earns +${cart.pointsEarned} pts',
style: const TextStyle(
color: AppColors.success,
fontWeight: FontWeight.w700,
fontSize: 13,
),
),
]),
),
_Row(label: 'Subtotal', value: Formatters.money(cart.subtotal)),
if (cart.membershipDiscountAmount > 0)
_Row(
label: '${cart.customer!.tier.label} discount',
value: '-${Formatters.money(cart.membershipDiscountAmount)}',
valueColor: AppColors.success,
),
_Row(
label: 'GST',
value: Formatters.money(cart.taxAmount),
hint: cart.taxBreakdown.keys.isEmpty
? null
: cart.taxBreakdown.keys
.map((r) => '${(r * 100).toStringAsFixed(0)}%')
.join(', '),
),
InkWell(
onTap: () => showBillDiscountSheet(context, ref),
borderRadius: AppRadius.brXs,
child: _Row(
label: 'Discount',
value: cart.manualBillDiscountAmount > 0
? '-${Formatters.money(cart.manualBillDiscountAmount)}'
: '-${Formatters.money(0)}',
valueColor: cart.manualBillDiscountAmount > 0
? AppColors.success
: null,
trailingIcon: Icons.edit_outlined,
),
),
if (cart.maxRedeemablePoints > 0 || cart.pointsRedeemed > 0)
InkWell(
onTap: () => cart.pointsRedeemed > 0
? controller.clearRedemption()
: controller.redeemAllPoints(),
borderRadius: AppRadius.brXs,
child: _Row(
label: cart.pointsRedeemed > 0
? 'Points redeemed (${cart.pointsRedeemed})'
: 'Redeem ${cart.maxRedeemablePoints} points',
value: cart.pointsRedeemed > 0
? '-${Formatters.money(cart.loyaltyRedemptionValue)}'
: 'Apply',
valueColor: AppColors.primary,
trailingIcon: cart.pointsRedeemed > 0
? Icons.close_rounded
: Icons.add_rounded,
),
),
if (cart.roundOff != 0)
_Row(
label: 'Round Off',
value: '${cart.roundOff >= 0 ? '+' : ''}'
'${Formatters.money(cart.roundOff)}',
),
const Padding(
padding: EdgeInsets.symmetric(vertical: AppSpacing.md),
child: Divider(height: 1),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Total', style: context.text.titleLarge),
Text(
Formatters.money(cart.grandTotal),
style: AppTypography.money(26, color: AppColors.primary),
),
],
),
if (cart.totalSavings > 0)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.xs),
child: Align(
alignment: Alignment.centerRight,
child: Text(
'You saved ${Formatters.money(cart.totalSavings)}',
style: const TextStyle(
color: AppColors.success,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
),
),
]),
);
}
}
class _Row extends StatelessWidget {
const _Row({
required this.label,
required this.value,
this.valueColor,
this.hint,
this.trailingIcon,
});
final String label;
final String value;
final Color? valueColor;
final String? hint;
final IconData? trailingIcon;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs + 2),
child: Row(children: [
Text(label,
style: const TextStyle(
fontSize: 14,
color: AppColors.textSecondary,
)),
if (hint != null) ...[
const SizedBox(width: AppSpacing.xs),
Text('($hint)',
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
)),
],
const Spacer(),
Text(
value,
style: AppTypography.money(
14.5,
weight: FontWeight.w600,
color: valueColor ?? AppColors.textPrimary,
),
),
if (trailingIcon != null) ...[
const SizedBox(width: AppSpacing.xs),
Icon(trailingIcon, size: 14, color: AppColors.textTertiary),
],
]),
);
}
}
class _Actions extends ConsumerWidget {
const _Actions({required this.cart});
final Cart cart;
@override
Widget build(BuildContext context, WidgetRef ref) {
final enabled = cart.isNotEmpty;
return Container(
padding: const EdgeInsets.fromLTRB(
AppSpacing.xl,
AppSpacing.sm,
AppSpacing.xl,
AppSpacing.xl,
),
child: PrimaryButton(
label: 'CHARGE',
large: true,
onPressed: enabled ? () => context.push(AppRoutes.payment) : null,
trailing: enabled
? Text(
Formatters.money(cart.grandTotal),
style: AppTypography.money(21, color: Colors.white),
)
: null,
),
);
}
}

View File

@@ -0,0 +1,83 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/formatters.dart';
import '../providers/cart_controller.dart';
/// Floating bill summary shown when the billing panel is collapsed into a
/// sheet. Gives the cashier the running total without opening anything.
class CartFab extends ConsumerWidget {
const CartFab({super.key, required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context, WidgetRef ref) {
final cart = ref.watch(cartControllerProvider);
if (cart.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
child: Material(
color: AppColors.primary,
borderRadius: AppRadius.brLg,
elevation: 0,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brLg,
child: Container(
height: AppSizes.buttonHeightLarge,
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xl),
decoration: BoxDecoration(
borderRadius: AppRadius.brLg,
boxShadow: AppColors.shadowLg,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 28,
height: 28,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.22),
borderRadius: AppRadius.brXs,
),
alignment: Alignment.center,
child: Text(
'${cart.lineCount}',
style: const TextStyle(
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: AppSpacing.md),
const Text(
'View bill',
style: TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: AppSpacing.xl),
Text(
Formatters.money(cart.grandTotal),
style: AppTypography.money(19, color: Colors.white),
),
const SizedBox(width: AppSpacing.sm),
const Icon(Icons.keyboard_arrow_up_rounded,
color: Colors.white, size: 20),
],
),
),
),
),
).animate().fadeIn(duration: 180.ms).slideY(begin: 0.3, end: 0);
}
}

View File

@@ -0,0 +1,241 @@
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/cart.dart';
/// One row of the bill, with inline quantity stepper.
class CartLineTile extends StatelessWidget {
const CartLineTile({
super.key,
required this.line,
required this.onIncrement,
required this.onDecrement,
required this.onRemove,
this.onDiscount,
});
final CartLine line;
final VoidCallback onIncrement;
final VoidCallback onDecrement;
final VoidCallback onRemove;
final VoidCallback? onDiscount;
@override
Widget build(BuildContext context) {
final p = line.product;
return Dismissible(
key: ValueKey('dismiss_${p.id}'),
direction: DismissDirection.endToStart,
onDismissed: (_) => onRemove(),
background: Container(
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: AppSpacing.xl),
decoration: BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brMd,
),
child: const Icon(Icons.delete_outline_rounded,
color: AppColors.danger),
),
child: Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
border: Border.all(
color: line.exceedsStock ? AppColors.danger : AppColors.border,
),
),
child: Column(children: [
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Container(
width: 42,
height: 42,
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.border),
),
alignment: Alignment.center,
child: Text(p.emoji, style: const TextStyle(fontSize: 21)),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
p.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Row(children: [
Text(
Formatters.money(p.price),
style: AppTypography.money(13.5,
weight: FontWeight.w600,
color: AppColors.textSecondary),
),
Text(' / ${p.unit.symbol}',
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
)),
if (line.discount.isActive) ...[
const SizedBox(width: AppSpacing.sm),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 5, vertical: 1),
decoration: BoxDecoration(
color: AppColors.successSurface,
borderRadius: BorderRadius.circular(4),
),
child: Text(
line.discount.label,
style: const TextStyle(
fontSize: 10,
color: AppColors.success,
fontWeight: FontWeight.w700,
),
),
),
],
]),
],
),
),
IconButton(
onPressed: onRemove,
icon: const Icon(Icons.close_rounded, size: 18),
color: AppColors.textTertiary,
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
padding: EdgeInsets.zero,
tooltip: 'Remove',
),
]),
const SizedBox(height: AppSpacing.sm),
Row(children: [
_Stepper(
quantity: line.quantity,
unit: p.unit.symbol,
onIncrement: onIncrement,
onDecrement: onDecrement,
),
if (onDiscount != null) ...[
const SizedBox(width: AppSpacing.sm),
IconButton(
onPressed: onDiscount,
icon: const Icon(Icons.local_offer_outlined, size: 17),
color: AppColors.textSecondary,
constraints: const BoxConstraints(minWidth: 34, minHeight: 34),
padding: EdgeInsets.zero,
tooltip: 'Line discount',
),
],
const Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (line.discountAmount > 0)
Text(
Formatters.money(line.grossAmount),
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
decoration: TextDecoration.lineThrough,
),
),
Text(
Formatters.money(line.payable),
style: AppTypography.money(16),
),
],
),
]),
if (line.exceedsStock)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.sm),
child: Row(children: [
const Icon(Icons.error_outline_rounded,
size: 14, color: AppColors.danger),
const SizedBox(width: AppSpacing.xs),
Text(
'Only ${p.stock.toStringAsFixed(0)} ${p.unit.symbol} '
'available',
style: const TextStyle(
fontSize: 11.5,
color: AppColors.danger,
fontWeight: FontWeight.w600,
),
),
]),
),
]),
),
);
}
}
class _Stepper extends StatelessWidget {
const _Stepper({
required this.quantity,
required this.unit,
required this.onIncrement,
required this.onDecrement,
});
final double quantity;
final String unit;
final VoidCallback onIncrement;
final VoidCallback onDecrement;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.border),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
_btn(Icons.remove_rounded, onDecrement),
Container(
constraints: const BoxConstraints(minWidth: 42),
alignment: Alignment.center,
child: Text(
quantity % 1 == 0
? quantity.toStringAsFixed(0)
: quantity.toStringAsFixed(2),
style: AppTypography.money(15.5),
),
),
_btn(Icons.add_rounded, onIncrement),
]),
);
}
Widget _btn(IconData icon, VoidCallback onTap) => Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brSm,
child: SizedBox(
width: 34,
height: 34,
child: Icon(icon, size: 17, color: AppColors.primary),
),
),
);
}

View File

@@ -0,0 +1,117 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../domain/entities/product.dart';
import '../providers/catalog_providers.dart';
class CategoryChips extends ConsumerWidget {
const CategoryChips({super.key, this.horizontalPadding = AppSpacing.xxl});
/// Matched to the surrounding content gutter by the dashboard layout.
final double horizontalPadding;
@override
Widget build(BuildContext context, WidgetRef ref) {
final selected = ref.watch(selectedCategoryProvider);
final counts = ref.watch(categoryCountsProvider).value ?? const {};
return SizedBox(
height: 52,
child: ListView(
scrollDirection: Axis.horizontal,
padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
children: [
_Chip(
label: 'All',
selected: selected == null,
onTap: () =>
ref.read(selectedCategoryProvider.notifier).state = null,
),
for (final category in ProductCategory.values)
_Chip(
label: category.label,
emoji: category.emoji,
count: counts[category],
selected: selected == category,
onTap: () => ref.read(selectedCategoryProvider.notifier).state =
selected == category ? null : category,
),
],
),
);
}
}
class _Chip extends StatelessWidget {
const _Chip({
required this.label,
required this.selected,
required this.onTap,
this.emoji,
this.count,
});
final String label;
final bool selected;
final VoidCallback onTap;
final String? emoji;
final int? count;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: AppSpacing.md),
child: Material(
color: selected ? AppColors.primary : AppColors.surface,
borderRadius: AppRadius.brPill,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brPill,
child: AnimatedContainer(
duration: AppMotion.fast,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
vertical: AppSpacing.md,
),
decoration: BoxDecoration(
borderRadius: AppRadius.brPill,
border: Border.all(
color: selected ? AppColors.primary : AppColors.border,
),
boxShadow: selected ? AppColors.shadowSm : null,
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
if (emoji != null) ...[
Text(emoji!, style: const TextStyle(fontSize: 15)),
const SizedBox(width: AppSpacing.sm),
],
Text(
label,
style: TextStyle(
color: selected ? Colors.white : AppColors.textPrimary,
fontWeight: FontWeight.w600,
fontSize: 14.5,
),
),
if (count != null) ...[
const SizedBox(width: AppSpacing.sm),
Text(
'$count',
style: TextStyle(
color: selected
? Colors.white.withValues(alpha: 0.75)
: AppColors.textTertiary,
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
],
]),
),
),
),
);
}
}

View File

@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/status_pill.dart';
import '../providers/cart_controller.dart';
/// Strip above the product grid showing who the sale belongs to.
class CustomerBar extends ConsumerWidget {
const CustomerBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final customer = ref.watch(
cartControllerProvider.select((cart) => cart.customer),
);
return Container(
height: AppSizes.customerBarHeight,
color: AppColors.surface,
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl),
child: Row(children: [
CircleAvatar(
radius: 20,
backgroundColor: customer == null
? AppColors.border
: AppColors.primarySurface,
child: customer == null
? const Icon(Icons.directions_walk_rounded,
size: 20, color: AppColors.textSecondary)
: Text(
Formatters.initials(customer.name),
style: const TextStyle(
color: AppColors.primary,
fontSize: 14,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: AppSpacing.md),
Flexible(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(mainAxisSize: MainAxisSize.min, children: [
Flexible(
child: Text(
customer?.name ?? 'Walk-in Customer',
style: context.text.titleMedium,
overflow: TextOverflow.ellipsis,
),
),
if (customer != null) ...[
const SizedBox(width: AppSpacing.sm),
StatusPill.tier(customer.tier, dense: true),
],
]),
if (customer != null)
Text(
'${Formatters.mobile(customer.mobile)} · '
'${customer.loyaltyPoints} pts',
style: context.text.bodySmall,
)
else
Text('No loyalty tracking for this sale',
style: context.text.bodySmall),
],
),
),
const Spacer(),
if (customer != null)
TextButton.icon(
onPressed: () =>
ref.read(cartControllerProvider.notifier).attachCustomer(null),
icon: const Icon(Icons.person_off_outlined, size: 17),
label: const Text('Detach'),
style: TextButton.styleFrom(
foregroundColor: AppColors.textSecondary),
),
const SizedBox(width: AppSpacing.sm),
OutlinedButton.icon(
onPressed: () => context.push(AppRoutes.existingCustomer),
icon: const Icon(Icons.sync_alt_rounded, size: 17),
label: Text(customer == null ? 'Add Customer' : 'Change'),
style: OutlinedButton.styleFrom(
minimumSize: const Size(0, 44),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
),
),
]),
);
}
}

View File

@@ -0,0 +1,213 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/cart.dart';
import '../providers/cart_controller.dart';
Future<void> showLineDiscountSheet(
BuildContext context,
WidgetRef ref,
CartLine line,
) {
return _show(
context: context,
title: line.product.name,
subtitle: 'Line value ${Formatters.money(line.grossAmount)}',
current: line.discount,
onApply: (d) => ref
.read(cartControllerProvider.notifier)
.applyLineDiscount(line.product.id, d),
);
}
Future<void> showBillDiscountSheet(BuildContext context, WidgetRef ref) {
final cart = ref.read(cartControllerProvider);
return _show(
context: context,
title: 'Bill discount',
subtitle: 'Subtotal ${Formatters.money(cart.subtotal)}',
current: cart.billDiscount,
onApply: (d) =>
ref.read(cartControllerProvider.notifier).applyBillDiscount(d),
);
}
Future<void> _show({
required BuildContext context,
required String title,
required String subtitle,
required Discount current,
required ValueChanged<Discount> onApply,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => _DiscountSheet(
title: title,
subtitle: subtitle,
current: current,
onApply: onApply,
),
);
}
class _DiscountSheet extends StatefulWidget {
const _DiscountSheet({
required this.title,
required this.subtitle,
required this.current,
required this.onApply,
});
final String title;
final String subtitle;
final Discount current;
final ValueChanged<Discount> onApply;
@override
State<_DiscountSheet> createState() => _DiscountSheetState();
}
class _DiscountSheetState extends State<_DiscountSheet> {
late DiscountType _type =
widget.current.type == DiscountType.none
? DiscountType.percentage
: widget.current.type;
late final TextEditingController _value = TextEditingController(
text: widget.current.isActive
? widget.current.value.toStringAsFixed(0)
: '',
);
@override
void dispose() {
_value.dispose();
super.dispose();
}
void _apply() {
final v = double.tryParse(_value.text.trim()) ?? 0;
widget.onApply(
v <= 0 ? Discount.none : Discount(type: _type, value: v),
);
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: Container(
padding: const EdgeInsets.all(AppSpacing.xxl),
decoration: const BoxDecoration(
color: AppColors.surface,
borderRadius:
BorderRadius.vertical(top: Radius.circular(AppRadius.xxl)),
),
child: Column(mainAxisSize: MainAxisSize.min, children: [
Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColors.border,
borderRadius: AppRadius.brPill,
),
),
const SizedBox(height: AppSpacing.xl),
Text(widget.title,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700)),
const SizedBox(height: 2),
Text(widget.subtitle,
style: const TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
)),
const SizedBox(height: AppSpacing.xxl),
SegmentedButton<DiscountType>(
segments: const [
ButtonSegment(
value: DiscountType.percentage,
label: Text('Percentage'),
icon: Icon(Icons.percent_rounded, size: 17),
),
ButtonSegment(
value: DiscountType.flat,
label: Text('Flat amount'),
icon: Icon(Icons.currency_rupee_rounded, size: 17),
),
],
selected: {_type},
onSelectionChanged: (s) => setState(() => _type = s.first),
),
const SizedBox(height: AppSpacing.xl),
TextField(
controller: _value,
autofocus: true,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
],
style: const TextStyle(fontSize: 24, fontWeight: FontWeight.w700),
textAlign: TextAlign.center,
decoration: InputDecoration(
hintText: '0',
prefixText: _type == DiscountType.flat ? '' : null,
suffixText: _type == DiscountType.percentage ? '%' : null,
),
onSubmitted: (_) => _apply(),
),
const SizedBox(height: AppSpacing.lg),
Wrap(
spacing: AppSpacing.sm,
children: (_type == DiscountType.percentage
? const [5, 10, 15, 20, 25]
: const [10, 20, 50, 100, 200])
.map((v) => ActionChip(
label: Text(_type == DiscountType.percentage
? '$v%'
: '$v'),
onPressed: () =>
setState(() => _value.text = v.toString()),
))
.toList(),
),
const SizedBox(height: AppSpacing.xxl),
Row(children: [
Expanded(
child: PrimaryButton(
label: 'Remove',
tone: ButtonTone.neutral,
onPressed: () {
widget.onApply(Discount.none);
Navigator.of(context).pop();
},
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
flex: 2,
child: PrimaryButton(
label: 'Apply discount',
icon: Icons.check_rounded,
onPressed: _apply,
),
),
]),
]),
),
);
}
}

View File

@@ -0,0 +1,324 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../app/providers.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_layout.dart';
import '../../../core/utils/formatters.dart';
import '../providers/cart_controller.dart';
import '../providers/navigation_provider.dart';
/// White page header: breadcrumb, title, and the terminal's quick actions.
///
/// Replaces the old purple app bar now that branding lives in the sidebar.
class PageHeader extends ConsumerWidget {
const PageHeader({
super.key,
required this.layout,
this.onMenuTap,
});
final PosLayout layout;
final VoidCallback? onMenuTap;
@override
Widget build(BuildContext context, WidgetRef ref) {
final module = ref.watch(activeModuleProvider);
final now = ref.watch(clockProvider).value ?? DateTime.now();
final compact = layout.sidebarIsDrawer;
return Container(
constraints: const BoxConstraints(minHeight: AppSizes.headerHeight),
padding: EdgeInsets.symmetric(
horizontal: layout.contentPadding,
vertical: AppSpacing.md,
),
decoration: const BoxDecoration(
color: AppColors.surface,
border: Border(bottom: BorderSide(color: AppColors.border)),
),
child: Row(
children: [
if (compact) ...[
IconButton(
onPressed: onMenuTap,
icon: const Icon(Icons.menu_rounded),
tooltip: 'Menu',
color: AppColors.textPrimary,
),
const SizedBox(width: AppSpacing.xs),
],
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
module.title,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 19,
fontWeight: FontWeight.w600,
letterSpacing: -0.4,
color: AppColors.textPrimary,
height: 1.2,
),
),
if (!compact) _Breadcrumb(module: module),
],
),
),
const Spacer(),
if (!compact) ...[
const _LivePill(),
const SizedBox(width: AppSpacing.lg),
Text(
Formatters.time(now),
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w500,
color: AppColors.textSecondary,
fontFeatures: [FontFeature.tabularFigures()],
),
),
const SizedBox(width: AppSpacing.lg),
Container(width: 1, height: 26, color: AppColors.border),
const SizedBox(width: AppSpacing.lg),
],
_ParkedBillsButton(compact: compact),
const SizedBox(width: AppSpacing.sm),
_NewSaleButton(compact: compact),
],
),
);
}
}
class _Breadcrumb extends StatelessWidget {
const _Breadcrumb({required this.module});
final PosModule module;
@override
Widget build(BuildContext context) {
const style = TextStyle(fontSize: 12, color: AppColors.textTertiary);
return Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Home', style: style),
const Padding(
padding: EdgeInsets.symmetric(horizontal: AppSpacing.xs + 2),
child: Icon(Icons.chevron_right_rounded,
size: 13, color: AppColors.textTertiary),
),
Text(module.section.label, style: style),
const Padding(
padding: EdgeInsets.symmetric(horizontal: AppSpacing.xs + 2),
child: Icon(Icons.chevron_right_rounded,
size: 13, color: AppColors.textTertiary),
),
Text(
module.label,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppColors.primary,
),
),
],
);
}
}
class _LivePill extends StatefulWidget {
const _LivePill();
@override
State<_LivePill> createState() => _LivePillState();
}
class _LivePillState extends State<_LivePill>
with SingleTickerProviderStateMixin {
late final AnimationController _c = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1400),
)..repeat(reverse: true);
@override
void dispose() {
_c.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.xs + 2,
),
decoration: BoxDecoration(
color: AppColors.successSurface,
borderRadius: AppRadius.brPill,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
FadeTransition(
opacity: _c,
child: Container(
width: 7,
height: 7,
decoration: const BoxDecoration(
color: AppColors.success,
shape: BoxShape.circle,
),
),
),
const SizedBox(width: AppSpacing.xs + 2),
const Text(
'LIVE',
style: TextStyle(
color: AppColors.success,
fontSize: 10.5,
fontWeight: FontWeight.w700,
letterSpacing: 0.8,
),
),
],
),
);
}
}
class _ParkedBillsButton extends ConsumerWidget {
const _ParkedBillsButton({required this.compact});
final bool compact;
@override
Widget build(BuildContext context, WidgetRef ref) {
final parked = ref.watch(parkedBillsProvider).value ?? const [];
if (compact) {
return IconButton(
tooltip: 'Parked bills',
onPressed: () => _openParked(context, ref),
icon: Badge(
isLabelVisible: parked.isNotEmpty,
label: Text('${parked.length}'),
backgroundColor: AppColors.warning,
child: const Icon(Icons.pause_circle_outline_rounded),
),
);
}
return OutlinedButton.icon(
onPressed: () => _openParked(context, ref),
icon: const Icon(Icons.pause_circle_outline_rounded, size: 17),
label: Text(
parked.isEmpty ? 'Parked' : 'Parked (${parked.length})',
),
style: OutlinedButton.styleFrom(
minimumSize: const Size(0, 42),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
foregroundColor: AppColors.textSecondary,
),
);
}
void _openParked(BuildContext context, WidgetRef ref) {
final parked = ref.read(parkedBillsProvider).value ?? const [];
if (parked.isEmpty) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(const SnackBar(content: Text('No parked bills.')));
return;
}
showDialog<void>(
context: context,
builder: (_) => AlertDialog(
title: const Text('Parked bills'),
content: SizedBox(
width: 380,
child: ListView.separated(
shrinkWrap: true,
itemCount: parked.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (_, i) {
final bill = parked[i];
return ListTile(
leading: const Icon(Icons.receipt_long_rounded,
color: AppColors.primary),
title: Text(bill.displayLabel),
subtitle: Text(
'${bill.cart.lineCount} items · '
'${Formatters.money(bill.cart.grandTotal)} · '
'${Formatters.time(bill.parkedAt)}',
),
onTap: () async {
await ref
.read(cartControllerProvider.notifier)
.resume(bill);
ref.invalidate(parkedBillsProvider);
if (context.mounted) Navigator.of(context).pop();
},
);
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
);
}
}
class _NewSaleButton extends ConsumerWidget {
const _NewSaleButton({required this.compact});
final bool compact;
@override
Widget build(BuildContext context, WidgetRef ref) {
void start() {
ref.read(cartControllerProvider.notifier).reset();
context.go(AppRoutes.welcome);
}
if (compact) {
return IconButton.filled(
tooltip: 'New sale',
onPressed: start,
icon: const Icon(Icons.add_rounded),
style: IconButton.styleFrom(backgroundColor: AppColors.primary),
);
}
return FilledButton.icon(
onPressed: start,
icon: const Icon(Icons.add_rounded, size: 18),
label: const Text('New Sale'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
minimumSize: const Size(0, 42),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
shape: const RoundedRectangleBorder(borderRadius: AppRadius.brSm),
),
);
}
}

View File

@@ -0,0 +1,217 @@
import 'package:flutter/material.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/product.dart';
/// Tapping anywhere on the card bills the item — no confirm step.
class ProductCard extends StatefulWidget {
const ProductCard({
super.key,
required this.product,
required this.onTap,
this.inCartQuantity = 0,
});
final Product product;
final VoidCallback onTap;
final double inCartQuantity;
@override
State<ProductCard> createState() => _ProductCardState();
}
class _ProductCardState extends State<ProductCard> {
bool _hovered = false;
bool _pressed = false;
@override
Widget build(BuildContext context) {
final p = widget.product;
final disabled = p.isOutOfStock;
final inCart = widget.inCartQuantity > 0;
return MouseRegion(
cursor: disabled ? SystemMouseCursors.forbidden : SystemMouseCursors.click,
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTapDown: (_) => setState(() => _pressed = true),
onTapUp: (_) => setState(() => _pressed = false),
onTapCancel: () => setState(() => _pressed = false),
onTap: disabled ? null : widget.onTap,
child: AnimatedScale(
scale: _pressed ? 0.96 : 1,
duration: AppMotion.instant,
child: AnimatedContainer(
duration: AppMotion.fast,
decoration: BoxDecoration(
color: disabled ? AppColors.surfaceAlt : AppColors.surface,
borderRadius: AppRadius.brLg,
border: Border.all(
color: inCart
? AppColors.primary
: (_hovered ? AppColors.primaryBorder : AppColors.border),
width: inCart ? 1.8 : 1,
),
boxShadow: _hovered && !disabled
? AppColors.shadowMd
: AppColors.shadowSm,
),
child: Stack(children: [
Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Opacity(
opacity: disabled ? 0.4 : 1,
child: Text(p.emoji,
style: const TextStyle(fontSize: 40)),
),
const SizedBox(height: AppSpacing.sm),
Text(
p.name,
maxLines: 2,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
height: 1.25,
color: disabled
? AppColors.textTertiary
: AppColors.textPrimary,
),
),
const SizedBox(height: AppSpacing.xs + 2),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
Formatters.money(p.price),
style: AppTypography.money(17,
color: disabled
? AppColors.textTertiary
: AppColors.primary),
),
if (p.hasDiscount) ...[
const SizedBox(width: AppSpacing.xs + 2),
Padding(
padding: const EdgeInsets.only(bottom: 1.5),
child: Text(
Formatters.money(p.mrp!),
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
decoration: TextDecoration.lineThrough,
),
),
),
],
],
),
const SizedBox(height: AppSpacing.xs),
Text(
disabled
? 'Out of stock'
: '${p.stock.toStringAsFixed(0)} in stock',
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w500,
color: disabled
? AppColors.danger
: (p.isLowStock
? AppColors.warning
: AppColors.textTertiary),
),
),
],
),
),
if (p.hasDiscount && !disabled)
Positioned(
top: AppSpacing.sm,
left: AppSpacing.sm,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: AppColors.success,
borderRadius: BorderRadius.circular(5),
),
child: Text(
'${p.discountPercent.toStringAsFixed(0)}%',
style: const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.w800,
),
),
),
),
if (p.isLowStock && !disabled)
const Positioned(
top: AppSpacing.sm,
right: AppSpacing.sm,
child: Icon(Icons.warning_amber_rounded,
size: 15, color: AppColors.warning),
),
// Quantity badge once the item is on the bill.
if (inCart)
Positioned(
top: AppSpacing.sm,
right: AppSpacing.sm,
child: Container(
constraints: const BoxConstraints(minWidth: 24),
height: 24,
padding: const EdgeInsets.symmetric(horizontal: 6),
decoration: const BoxDecoration(
color: AppColors.primary,
shape: BoxShape.rectangle,
borderRadius: AppRadius.brPill,
),
alignment: Alignment.center,
child: Text(
widget.inCartQuantity % 1 == 0
? widget.inCartQuantity.toStringAsFixed(0)
: widget.inCartQuantity.toStringAsFixed(2),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w800,
),
),
),
),
// Hover-only add affordance keeps the resting card clean.
if (_hovered && !disabled && !inCart)
Positioned(
bottom: AppSpacing.sm,
right: AppSpacing.sm,
child: Container(
width: 28,
height: 28,
decoration: const BoxDecoration(
color: AppColors.primary,
shape: BoxShape.circle,
),
child: const Icon(Icons.add_rounded,
size: 18, color: Colors.white),
),
),
]),
),
),
),
);
}
}

View File

@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/empty_state.dart';
import '../providers/cart_controller.dart';
import '../providers/catalog_providers.dart';
import 'product_card.dart';
/// Responsive grid that fills the available width with cards of a stable
/// minimum size, rather than a fixed column count.
class ProductGrid extends ConsumerWidget {
const ProductGrid({
super.key,
this.horizontalPadding = AppSpacing.xxl,
this.tileExtent = 186,
this.bottomPadding = AppSpacing.xxl,
});
/// Content gutter, supplied by the dashboard layout.
final double horizontalPadding;
/// Maximum card width; the grid fits as many columns as will fit.
final double tileExtent;
/// Extra space so the floating bill button never covers the last row.
final double bottomPadding;
@override
Widget build(BuildContext context, WidgetRef ref) {
final products = ref.watch(visibleProductsProvider);
final cart = ref.watch(cartControllerProvider);
return products.when(
loading: () => const Center(
child: CircularProgressIndicator(color: AppColors.primary),
),
error: (e, _) => EmptyState(
title: 'Could not load products',
message: '$e',
emoji: '⚠️',
),
data: (items) {
if (items.isEmpty) {
return const EmptyState(
title: 'No products match',
message: 'Try a different search term or category.',
emoji: '🔎',
);
}
return GridView.builder(
padding: EdgeInsets.fromLTRB(
horizontalPadding,
0,
horizontalPadding,
bottomPadding,
),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: tileExtent,
mainAxisSpacing: AppSpacing.md,
crossAxisSpacing: AppSpacing.md,
childAspectRatio: AppSizes.productCardAspect,
),
itemCount: items.length,
itemBuilder: (context, i) {
final product = items[i];
return ProductCard(
key: ValueKey(product.id),
product: product,
inCartQuantity: cart.lineFor(product.id)?.quantity ?? 0,
onTap: () => ref
.read(cartControllerProvider.notifier)
.addProduct(product),
);
},
);
},
);
}
}

View File

@@ -0,0 +1,121 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../providers/cart_controller.dart';
/// Brief floating confirmation after a scan.
///
/// Deliberately not a dialog: the cashier must never have to dismiss anything
/// between items.
class ScanToast extends ConsumerStatefulWidget {
const ScanToast({super.key});
@override
ConsumerState<ScanToast> createState() => _ScanToastState();
}
class _ScanToastState extends ConsumerState<ScanToast> {
Timer? _timer;
ScanFeedback? _visible;
void _show(ScanFeedback feedback) {
_timer?.cancel();
setState(() => _visible = feedback);
_timer = Timer(
const Duration(milliseconds: 1600),
() {
if (mounted) setState(() => _visible = null);
},
);
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
ref.listen<ScanFeedback?>(scanFeedbackProvider, (prev, next) {
if (next != null) _show(next);
});
final feedback = _visible;
if (feedback == null) return const SizedBox.shrink();
final success = feedback.isSuccess;
final color = success ? AppColors.success : AppColors.danger;
final product = feedback.product;
final message = feedback.message ??
switch (feedback.outcome) {
ScanOutcome.added => 'Added to bill',
ScanOutcome.incremented => 'Quantity updated',
ScanOutcome.notFound => 'Product not found',
ScanOutcome.outOfStock => 'Out of stock',
};
return Container(
margin: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl),
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
vertical: AppSpacing.md,
),
decoration: BoxDecoration(
color: AppColors.textPrimary,
borderRadius: AppRadius.brPill,
boxShadow: AppColors.shadowLg,
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Container(
width: 26,
height: 26,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
child: Icon(
success ? Icons.check_rounded : Icons.priority_high_rounded,
size: 17,
color: Colors.white,
),
),
const SizedBox(width: AppSpacing.md),
if (product != null) ...[
Text(product.emoji, style: const TextStyle(fontSize: 17)),
const SizedBox(width: AppSpacing.sm),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 220),
child: Text(
product.name,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 14.5,
),
),
),
const SizedBox(width: AppSpacing.sm),
Container(width: 1, height: 16, color: Colors.white24),
const SizedBox(width: AppSpacing.sm),
],
Text(
message,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.85),
fontSize: 13.5,
),
),
]),
)
.animate(key: ValueKey(feedback.stamp))
.fadeIn(duration: 140.ms)
.slideY(begin: 0.4, end: 0, curve: Curves.easeOutBack)
.then(delay: 1200.ms)
.fadeOut(duration: 250.ms);
}
}

View File

@@ -0,0 +1,103 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/validators.dart';
import '../providers/cart_controller.dart';
import '../providers/catalog_providers.dart';
/// Doubles as the barcode input.
///
/// If the submitted text looks like a barcode we bill it immediately and clear
/// the field; otherwise it stays as a live search term.
class PosSearchField extends ConsumerStatefulWidget {
const PosSearchField({super.key, this.focusNode});
final FocusNode? focusNode;
@override
ConsumerState<PosSearchField> createState() => _PosSearchFieldState();
}
class _PosSearchFieldState extends ConsumerState<PosSearchField> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _submit(String value) {
final text = value.trim();
if (text.isEmpty) return;
if (Validators.isLikelyBarcode(text)) {
ref.read(cartControllerProvider.notifier).scanBarcode(text);
_controller.clear();
ref.read(searchQueryProvider.notifier).state = '';
}
}
@override
Widget build(BuildContext context) {
final query = ref.watch(searchQueryProvider);
return TextField(
controller: _controller,
focusNode: widget.focusNode,
autofocus: true,
textInputAction: TextInputAction.search,
style: const TextStyle(fontSize: 16),
onChanged: (v) => ref.read(searchQueryProvider.notifier).state = v,
onSubmitted: _submit,
decoration: InputDecoration(
hintText: 'Search product, scan barcode or enter SKU…',
prefixIcon: const Padding(
padding: EdgeInsets.only(left: AppSpacing.md, right: AppSpacing.sm),
child: Icon(Icons.search_rounded, color: AppColors.textTertiary),
),
prefixIconConstraints: const BoxConstraints(minWidth: 0),
contentPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.lg + 2,
),
suffixIcon: Row(mainAxisSize: MainAxisSize.min, children: [
if (query.isNotEmpty)
IconButton(
tooltip: 'Clear',
icon: const Icon(Icons.close_rounded, size: 20),
color: AppColors.textTertiary,
onPressed: () {
_controller.clear();
ref.read(searchQueryProvider.notifier).state = '';
},
),
Container(
margin: const EdgeInsets.only(right: AppSpacing.sm),
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.sm,
),
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brSm,
),
child: const Row(mainAxisSize: MainAxisSize.min, children: [
Icon(Icons.qr_code_scanner_rounded,
size: 18, color: AppColors.primary),
SizedBox(width: AppSpacing.xs + 2),
Text('Scanner ready',
style: TextStyle(
color: AppColors.primary,
fontSize: 12,
fontWeight: FontWeight.w600,
)),
]),
),
]),
),
);
}
}

View File

@@ -0,0 +1,250 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../app/providers.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/glass_card.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/transaction.dart';
import '../../pos/providers/cart_controller.dart';
import '../widgets/receipt_preview.dart';
/// Confirmation screen. Counts down and starts the next sale on its own so an
/// unattended terminal never sits on a finished bill.
class ReceiptScreen extends ConsumerStatefulWidget {
const ReceiptScreen({super.key, required this.transaction});
final SaleTransaction transaction;
@override
ConsumerState<ReceiptScreen> createState() => _ReceiptScreenState();
}
class _ReceiptScreenState extends ConsumerState<ReceiptScreen> {
late int _seconds = AppConstants.postSaleResetDelay.inSeconds + 5;
Timer? _timer;
@override
void initState() {
super.initState();
_timer = Timer.periodic(const Duration(seconds: 1), (t) {
if (!mounted) return;
setState(() => _seconds--);
if (_seconds <= 0) _newSale();
});
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _cancelAutoReturn() {
_timer?.cancel();
if (mounted) setState(() => _seconds = -1);
}
void _newSale() {
_timer?.cancel();
ref.read(cartControllerProvider.notifier).reset();
if (mounted) context.go(AppRoutes.welcome);
}
void _continueBilling() {
_timer?.cancel();
ref.read(cartControllerProvider.notifier).reset();
if (mounted) context.go(AppRoutes.pos);
}
@override
Widget build(BuildContext context) {
final txn = widget.transaction;
return Scaffold(
backgroundColor: AppColors.background,
body: SafeArea(
child: Listener(
onPointerDown: (_) => _cancelAutoReturn(),
child: Padding(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: context.isCompact
? SingleChildScrollView(
child: Column(children: [
_summary(txn),
const SizedBox(height: AppSpacing.lg),
SizedBox(
height: 480,
child: ReceiptPreview(transaction: txn),
),
]),
)
: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(flex: 5, child: _summary(txn)),
const SizedBox(width: AppSpacing.xxl),
Expanded(
flex: 4,
child: ReceiptPreview(transaction: txn),
),
],
),
),
),
),
);
}
Widget _summary(SaleTransaction txn) {
return GlassCard(
padding: const EdgeInsets.all(AppSpacing.xxxl),
radius: AppRadius.xxl,
shadows: AppColors.shadowMd,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: Container(
width: 84,
height: 84,
decoration: const BoxDecoration(
color: AppColors.successSurface,
shape: BoxShape.circle,
),
child: const Icon(Icons.check_rounded,
size: 44, color: AppColors.success),
)
.animate()
.scale(
duration: 340.ms,
curve: Curves.easeOutBack,
begin: const Offset(0.5, 0.5),
)
.fadeIn(),
),
const SizedBox(height: AppSpacing.xl),
Text('Sale complete',
textAlign: TextAlign.center,
style: context.text.headlineMedium),
const SizedBox(height: AppSpacing.xs),
Text(
'${txn.invoiceNumber} · ${Formatters.dateTime(txn.createdAt)}',
textAlign: TextAlign.center,
style: context.text.bodySmall,
),
const SizedBox(height: AppSpacing.xxl),
Container(
padding: const EdgeInsets.all(AppSpacing.xl),
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brLg,
),
child: Column(children: [
Text('Amount paid', style: context.text.labelMedium),
Text(
Formatters.money(txn.total),
style: AppTypography.money(36, color: AppColors.primary),
),
const SizedBox(height: AppSpacing.md),
const Divider(),
const SizedBox(height: AppSpacing.md),
_row('Paid via', txn.paymentSummary),
if (txn.changeDue > 0)
_row('Change returned', Formatters.money(txn.changeDue),
highlight: AppColors.success),
_row('Items', '${txn.cart.lineCount}'),
if (txn.customer != null) ...[
_row('Customer', txn.customer!.name),
_row('Points earned', '+${txn.pointsEarned}',
highlight: AppColors.success),
if (txn.pointsRedeemed > 0)
_row('Points redeemed', '-${txn.pointsRedeemed}'),
],
if (txn.cart.totalSavings > 0)
_row(
'Customer saved',
Formatters.money(txn.cart.totalSavings),
highlight: AppColors.success,
),
]),
),
const SizedBox(height: AppSpacing.xxl),
Row(children: [
Expanded(
child: PrimaryButton(
label: 'Reprint',
icon: Icons.print_outlined,
tone: ButtonTone.neutral,
onPressed: () {
_cancelAutoReturn();
ref.read(receiptServiceProvider).printWithDialog(txn);
},
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: PrimaryButton(
label: 'Share',
icon: Icons.ios_share_rounded,
tone: ButtonTone.neutral,
onPressed: () {
_cancelAutoReturn();
ref.read(receiptServiceProvider).share(txn);
},
),
),
]),
const SizedBox(height: AppSpacing.md),
PrimaryButton(
label: _seconds > 0
? 'New Sale ($_seconds)'
: 'New Sale',
icon: Icons.add_shopping_cart_rounded,
large: true,
onPressed: _newSale,
),
const SizedBox(height: AppSpacing.sm),
TextButton(
onPressed: _continueBilling,
child: const Text('Back to billing screen'),
),
],
),
);
}
Widget _row(String label, String value, {Color? highlight}) => Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label,
style: const TextStyle(
fontSize: 13.5,
color: AppColors.textSecondary,
)),
Text(
value,
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
color: highlight ?? AppColors.textPrimary,
),
),
],
),
);
}

View File

@@ -0,0 +1,289 @@
import 'package:flutter/material.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/transaction.dart';
/// Paper-like preview of what the thermal printer produced.
class ReceiptPreview extends StatelessWidget {
const ReceiptPreview({super.key, required this.transaction});
final SaleTransaction transaction;
@override
Widget build(BuildContext context) {
final txn = transaction;
final cart = txn.cart;
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brLg,
boxShadow: AppColors.shadowMd,
),
child: Column(children: [
const _Perforation(top: true),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xxl,
vertical: AppSpacing.xl,
),
child: DefaultTextStyle(
style: AppTypography.mono(11.5, color: AppColors.textPrimary),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: Column(children: [
Text(
AppConstants.storeName.toUpperCase(),
style: AppTypography.mono(15)
.copyWith(fontWeight: FontWeight.w700),
),
const SizedBox(height: 3),
Text(AppConstants.storeAddress,
textAlign: TextAlign.center,
style: AppTypography.mono(9.5)),
Text('GSTIN: ${AppConstants.storeGstin}',
style: AppTypography.mono(9.5)),
const SizedBox(height: AppSpacing.sm),
Text('TAX INVOICE',
style: AppTypography.mono(11.5)
.copyWith(fontWeight: FontWeight.w700)),
]),
),
const _Dashes(),
_row('Invoice', txn.invoiceNumber),
_row('Date', Formatters.receiptStamp(txn.createdAt)),
_row('Cashier', txn.cashierName),
_row('Customer', txn.customer?.name ?? 'Walk-in'),
const _Dashes(),
Row(children: [
Expanded(flex: 5, child: _bold('Item')),
Expanded(
flex: 2,
child: _bold('Qty', align: TextAlign.center),
),
Expanded(
flex: 3,
child: _bold('Amount', align: TextAlign.right),
),
]),
const SizedBox(height: AppSpacing.xs),
...cart.lines.map((line) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2.5),
child: Row(children: [
Expanded(flex: 5, child: Text(line.product.name)),
Expanded(
flex: 2,
child: Text(
line.quantity % 1 == 0
? line.quantity.toStringAsFixed(0)
: line.quantity.toStringAsFixed(2),
textAlign: TextAlign.center,
),
),
Expanded(
flex: 3,
child: Text(
line.payable.toStringAsFixed(2),
textAlign: TextAlign.right,
),
),
]),
)),
const _Dashes(),
_row('Subtotal', cart.subtotal.toStringAsFixed(2)),
if (cart.billDiscountTotal > 0)
_row('Discount',
'-${cart.billDiscountTotal.toStringAsFixed(2)}'),
if (cart.loyaltyRedemptionValue > 0)
_row('Points redeemed',
'-${cart.loyaltyRedemptionValue.toStringAsFixed(2)}'),
_row('CGST', cart.cgst.toStringAsFixed(2)),
_row('SGST', cart.sgst.toStringAsFixed(2)),
if (cart.roundOff != 0)
_row('Round off', cart.roundOff.toStringAsFixed(2)),
const _Dashes(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('TOTAL',
style: AppTypography.mono(15).copyWith(
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
)),
Text(
Formatters.money(txn.total),
style: AppTypography.mono(15).copyWith(
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
],
),
const _Dashes(),
...txn.payments.map((p) =>
_row(p.method.label, p.amount.toStringAsFixed(2))),
if (txn.changeDue > 0)
_row('Change', txn.changeDue.toStringAsFixed(2)),
if (txn.customer != null) ...[
const _Dashes(),
_row('Points earned', '+${txn.pointsEarned}'),
_row('Membership', txn.customer!.tier.label),
],
const SizedBox(height: AppSpacing.lg),
Center(
child: Column(children: [
_FakeBarcode(value: txn.invoiceNumber),
const SizedBox(height: AppSpacing.sm),
Text('Thank you for shopping with us!',
style: AppTypography.mono(11)
.copyWith(fontWeight: FontWeight.w700)),
const SizedBox(height: 2),
Text('Powered by Nearle POS',
style: AppTypography.mono(9)),
]),
),
],
),
),
),
),
const _Perforation(top: false),
]),
);
}
Widget _row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 1.5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [Text(label), Text(value)],
),
);
Widget _bold(String text, {TextAlign align = TextAlign.left}) => Text(
text,
textAlign: align,
style: AppTypography.mono(11.5).copyWith(
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
),
);
}
class _Dashes extends StatelessWidget {
const _Dashes();
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: AppSpacing.sm),
child: Text(
'- - - - - - - - - - - - - - - - - - - - - - - - - -',
maxLines: 1,
overflow: TextOverflow.clip,
style: TextStyle(color: AppColors.textTertiary, fontSize: 10),
),
);
}
}
/// Zig-zag torn-paper edge.
class _Perforation extends StatelessWidget {
const _Perforation({required this.top});
final bool top;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 10,
child: CustomPaint(
size: const Size(double.infinity, 10),
painter: _PerforationPainter(top: top),
),
);
}
}
class _PerforationPainter extends CustomPainter {
const _PerforationPainter({required this.top});
final bool top;
@override
void paint(Canvas canvas, Size size) {
const tooth = 12.0;
final path = Path();
if (top) {
path.moveTo(0, size.height);
for (var x = 0.0; x < size.width; x += tooth) {
path.lineTo(x + tooth / 2, 0);
path.lineTo(x + tooth, size.height);
}
path.lineTo(size.width, size.height);
} else {
path.moveTo(0, 0);
for (var x = 0.0; x < size.width; x += tooth) {
path.lineTo(x + tooth / 2, size.height);
path.lineTo(x + tooth, 0);
}
path.lineTo(size.width, 0);
}
path.close();
canvas.drawPath(path, Paint()..color = AppColors.surface);
}
@override
bool shouldRepaint(covariant _PerforationPainter oldDelegate) =>
oldDelegate.top != top;
}
/// Decorative Code-128-style bar rendering for the preview only.
class _FakeBarcode extends StatelessWidget {
const _FakeBarcode({required this.value});
final String value;
@override
Widget build(BuildContext context) {
final bars = value.codeUnits;
return Column(children: [
SizedBox(
height: 38,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (var i = 0; i < bars.length * 2; i++)
Container(
width: (bars[i ~/ 2] % 3 == 0) ? 3 : 1.5,
margin: const EdgeInsets.symmetric(horizontal: 0.7),
color: i.isEven
? AppColors.textPrimary
: Colors.transparent,
),
],
),
),
const SizedBox(height: 3),
Text(value, style: AppTypography.mono(9)),
]);
}
}

View File

@@ -0,0 +1,156 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../domain/entities/shift_report.dart';
import '../../../domain/entities/sync_event.dart';
import '../../auth/providers/auth_controller.dart';
import '../../pos/providers/catalog_providers.dart';
/// Progress of a catalogue pull.
sealed class ImportState {
const ImportState();
}
class ImportIdle extends ImportState {
const ImportIdle();
}
class ImportRunning extends ImportState {
const ImportRunning(this.progress, this.stage);
final double progress;
final String stage;
}
class ImportDone extends ImportState {
const ImportDone(this.event);
final SyncEvent event;
}
class ImportFailed extends ImportState {
const ImportFailed(this.message);
final String message;
}
/// Bumped after every successful import so catalogue providers refetch.
final catalogueVersionProvider = StateProvider<int>((ref) => 0);
/// Whether the terminal has products to sell. The POS is gated on this.
final catalogueReadyProvider = Provider<bool>((ref) {
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).hasCatalogue;
});
final lastImportAtProvider = Provider<DateTime?>((ref) {
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).lastImportAt;
});
class CatalogueImportController extends StateNotifier<ImportState> {
CatalogueImportController(this._ref) : super(const ImportIdle());
final Ref _ref;
Future<bool> run() async {
if (state is ImportRunning) return false;
state = const ImportRunning(0, 'Starting…');
final event = await _ref.read(syncRepositoryProvider).importCatalogue(
onProgress: (progress, stage) {
if (mounted) state = ImportRunning(progress, stage);
},
);
if (event.status == SyncStatus.synced) {
// Force every catalogue-backed provider to refetch.
_ref.read(catalogueVersionProvider.notifier).state++;
_ref.invalidate(allProductsProvider);
_ref.invalidate(visibleProductsProvider);
_ref.invalidate(categoryCountsProvider);
_ref.invalidate(lowStockProductsProvider);
state = ImportDone(event);
return true;
}
state = ImportFailed(event.error ?? 'Import failed.');
return false;
}
void reset() => state = const ImportIdle();
}
final catalogueImportProvider =
StateNotifierProvider<CatalogueImportController, ImportState>(
(ref) => CatalogueImportController(ref),
);
// ------------------------------------------------------------------ Events
/// Bumped whenever the event log changes.
final syncVersionProvider = StateProvider<int>((ref) => 0);
final syncEventsProvider = Provider<List<SyncEvent>>((ref) {
ref.watch(syncVersionProvider);
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).events;
});
final hasUnsyncedProvider = Provider<bool>((ref) {
ref.watch(syncVersionProvider);
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).hasUnsyncedEvents;
});
/// Today's takings, recomputed from local sales on every change.
final shiftReportProvider = Provider<ShiftReport>((ref) {
ref.watch(syncVersionProvider);
final session = ref.watch(cashierSessionProvider);
final user = ref.watch(currentUserProvider);
return ref.watch(syncRepositoryProvider).buildShiftReport(
businessDate: DateTime.now(),
terminalId: session.terminalId,
cashierName: user?.name ?? session.name,
);
});
/// Drives the push button and the sign-out dialog.
class ReportPushController extends StateNotifier<bool> {
ReportPushController(this._ref) : super(false);
final Ref _ref;
/// Pushes today's report. Returns the resulting event so the caller can
/// tell the cashier whether it landed.
Future<SyncEvent> pushToday() async {
state = true;
try {
final report = _ref.read(shiftReportProvider);
final event =
await _ref.read(syncRepositoryProvider).pushShiftReport(report);
_ref.read(syncVersionProvider.notifier).state++;
return event;
} finally {
if (mounted) state = false;
}
}
Future<SyncEvent> retry(String eventId) async {
state = true;
try {
final event = await _ref.read(syncRepositoryProvider).retry(eventId);
_ref.read(syncVersionProvider.notifier).state++;
return event;
} finally {
if (mounted) state = false;
}
}
}
final reportPushProvider =
StateNotifierProvider<ReportPushController, bool>(
(ref) => ReportPushController(ref),
);

View File

@@ -0,0 +1,233 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/sync_event.dart';
import '../../auth/providers/auth_controller.dart';
import '../../pos/providers/cart_controller.dart';
import '../providers/sync_controller.dart';
/// End-of-shift flow.
///
/// The day's takings are pushed here — the second and last moment this
/// terminal needs a connection. Signing out without pushing is allowed, but
/// the report stays queued locally rather than being discarded.
Future<void> showSignOutDialog(BuildContext context, WidgetRef ref) {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => const _SignOutDialog(),
);
}
class _SignOutDialog extends ConsumerStatefulWidget {
const _SignOutDialog();
@override
ConsumerState<_SignOutDialog> createState() => _SignOutDialogState();
}
class _SignOutDialogState extends ConsumerState<_SignOutDialog> {
SyncEvent? _result;
void _finish() {
ref.read(cartControllerProvider.notifier).reset();
ref.read(authControllerProvider.notifier).signOut();
Navigator.of(context).pop();
context.go(AppRoutes.login);
}
Future<void> _pushThenFinish() async {
final event = await ref.read(reportPushProvider.notifier).pushToday();
if (!mounted) return;
setState(() => _result = event);
if (event.status == SyncStatus.synced) {
await Future<void>.delayed(const Duration(milliseconds: 700));
if (mounted) _finish();
}
}
@override
Widget build(BuildContext context) {
final report = ref.watch(shiftReportProvider);
final cart = ref.watch(cartControllerProvider);
final pushing = ref.watch(reportPushProvider);
final failed = _result?.status == SyncStatus.failed;
return AlertDialog(
title: const Text('End shift'),
contentPadding: const EdgeInsets.fromLTRB(
AppSpacing.xxl,
AppSpacing.lg,
AppSpacing.xxl,
AppSpacing.sm,
),
content: SizedBox(
width: 420,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (cart.isNotEmpty)
_Banner(
icon: Icons.warning_amber_rounded,
color: AppColors.warning,
background: AppColors.warningSurface,
message: 'The current bill has ${cart.lineCount} item(s) '
'and will be cleared. Park it first if you need it.',
),
if (report.isEmpty)
const _Banner(
icon: Icons.info_outline_rounded,
color: AppColors.textSecondary,
background: AppColors.surfaceAlt,
message: 'No sales were recorded today, so there is nothing '
'to push.',
)
else ...[
const Text(
"Today's takings",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
const SizedBox(height: AppSpacing.sm),
_row('Bills', '${report.billCount}'),
_row('Items sold', report.itemCount.toStringAsFixed(0)),
_row('Gross sales', Formatters.money(report.grossSales)),
_row('GST collected', Formatters.money(report.taxCollected)),
_row('Average basket',
Formatters.money(report.averageBasket)),
],
if (failed) ...[
const SizedBox(height: AppSpacing.md),
_Banner(
icon: Icons.wifi_off_rounded,
color: AppColors.danger,
background: AppColors.dangerSurface,
message: _result?.error ??
'The push failed. The report is still saved on this '
'terminal and can be retried from Events.',
),
],
],
),
),
),
actionsPadding: const EdgeInsets.fromLTRB(
AppSpacing.xxl,
0,
AppSpacing.xxl,
AppSpacing.lg,
),
actions: [
// Wrap keeps three actions from overflowing a narrow dialog.
Wrap(
alignment: WrapAlignment.end,
spacing: AppSpacing.sm,
runSpacing: AppSpacing.sm,
children: [
TextButton(
onPressed: pushing ? null : () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
TextButton(
onPressed: pushing ? null : _finish,
style: TextButton.styleFrom(
foregroundColor: AppColors.textSecondary,
),
child: Text(
report.isEmpty ? 'Sign out' : 'Sign out without pushing',
),
),
if (!report.isEmpty)
SizedBox(
width: 190,
child: PrimaryButton(
label: failed ? 'Retry push' : 'Push & sign out',
icon: Icons.cloud_upload_rounded,
busy: pushing,
onPressed: _pushThenFinish,
),
),
],
),
],
);
}
Widget _row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
children: [
Expanded(
child: Text(
label,
style: const TextStyle(
fontSize: 13.5,
color: AppColors.textSecondary,
),
),
),
Text(
value,
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
),
),
],
),
);
}
class _Banner extends StatelessWidget {
const _Banner({
required this.icon,
required this.color,
required this.background,
required this.message,
});
final IconData icon;
final Color color;
final Color background;
final String message;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(bottom: AppSpacing.md),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: background,
borderRadius: AppRadius.brSm,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: color),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
message,
style: TextStyle(fontSize: 12.5, color: color, height: 1.45),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,337 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../app/providers.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/extensions.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/glass_card.dart';
import '../../pos/providers/cart_controller.dart';
import '../widgets/welcome_illustration.dart';
/// Screen 1 — the terminal's resting state between sales.
class WelcomeScreen extends ConsumerWidget {
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final session = ref.watch(cashierSessionProvider);
final clock = ref.watch(clockProvider).value ?? DateTime.now();
return Scaffold(
body: Container(
decoration: const BoxDecoration(gradient: AppColors.primaryGradient),
child: SafeArea(
child: Column(
children: [
_TopBar(cashier: session.name, now: clock),
Expanded(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.xxl),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 920),
child: GlassCard(
blur: 18,
padding: EdgeInsets.all(
context.responsive(
compact: AppSpacing.xxl,
expanded: AppSpacing.giant,
),
),
radius: AppRadius.xxl,
shadows: AppColors.shadowLg,
child: context.isCompact
? const _StackedLayout()
: const _SideBySideLayout(),
),
),
).animate().fadeIn(duration: 350.ms).slideY(
begin: 0.04,
end: 0,
curve: Curves.easeOutCubic,
),
),
),
const _BottomHint(),
],
),
),
),
);
}
}
class _SideBySideLayout extends StatelessWidget {
const _SideBySideLayout();
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Expanded(flex: 4, child: WelcomeIllustration(size: 260)),
SizedBox(width: AppSpacing.giant),
Expanded(flex: 5, child: _WelcomeContent()),
],
);
}
}
class _StackedLayout extends StatelessWidget {
const _StackedLayout();
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: const [
WelcomeIllustration(size: 150),
SizedBox(height: AppSpacing.xxl),
_WelcomeContent(),
],
);
}
}
class _WelcomeContent extends ConsumerWidget {
const _WelcomeContent();
@override
Widget build(BuildContext context, WidgetRef ref) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Welcome to',
style: context.text.titleMedium?.copyWith(
color: AppColors.textSecondary,
letterSpacing: 1.4,
),
),
const SizedBox(height: AppSpacing.xs),
Text(
'Nearle POS',
style: context.text.displaySmall?.copyWith(
color: AppColors.primary,
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: AppSpacing.md),
Text(
'Start a new sale by identifying the shopper, '
'or skip straight to billing.',
style: context.text.bodyMedium
?.copyWith(color: AppColors.textSecondary),
),
const SizedBox(height: AppSpacing.xxxl),
_WelcomeAction(
icon: Icons.person_add_alt_1_rounded,
title: 'New Customer',
subtitle: 'Register and start earning loyalty points',
onTap: () => context.push(AppRoutes.registerCustomer),
primary: true,
),
const SizedBox(height: AppSpacing.md),
_WelcomeAction(
icon: Icons.badge_outlined,
title: 'Existing Customer',
subtitle: 'Look up by mobile number',
onTap: () => context.push(AppRoutes.existingCustomer),
),
const SizedBox(height: AppSpacing.md),
_WelcomeAction(
icon: Icons.directions_walk_rounded,
title: 'Skip Customer',
subtitle: 'Walk-in sale, no loyalty tracking',
onTap: () {
ref.read(cartControllerProvider.notifier).reset();
context.go(AppRoutes.pos);
},
),
],
);
}
}
/// A tall, unmistakable target — the cashier taps this hundreds of times a day.
class _WelcomeAction extends StatefulWidget {
const _WelcomeAction({
required this.icon,
required this.title,
required this.subtitle,
required this.onTap,
this.primary = false,
});
final IconData icon;
final String title;
final String subtitle;
final VoidCallback onTap;
final bool primary;
@override
State<_WelcomeAction> createState() => _WelcomeActionState();
}
class _WelcomeActionState extends State<_WelcomeAction> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final bg = widget.primary
? AppColors.primary
: (_hovered ? AppColors.primarySurface : AppColors.surface);
final fg =
widget.primary ? AppColors.textOnPrimary : AppColors.textPrimary;
final sub = widget.primary
? AppColors.textOnPrimary.withValues(alpha: 0.78)
: AppColors.textSecondary;
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: AnimatedContainer(
duration: AppMotion.fast,
transform: Matrix4.translationValues(0, _hovered ? -2 : 0, 0),
child: Material(
color: bg,
borderRadius: AppRadius.brLg,
child: InkWell(
onTap: widget.onTap,
borderRadius: AppRadius.brLg,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
vertical: AppSpacing.lg,
),
decoration: BoxDecoration(
borderRadius: AppRadius.brLg,
border: Border.all(
color: widget.primary
? Colors.transparent
: AppColors.border,
),
boxShadow: widget.primary && _hovered
? AppColors.shadowMd
: null,
),
child: Row(
children: [
Container(
width: 46,
height: 46,
decoration: BoxDecoration(
color: widget.primary
? Colors.white.withValues(alpha: 0.18)
: AppColors.primarySurface,
borderRadius: AppRadius.brMd,
),
child: Icon(
widget.icon,
color: widget.primary
? AppColors.textOnPrimary
: AppColors.primary,
size: 22,
),
),
const SizedBox(width: AppSpacing.lg),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.title,
style: context.text.titleMedium?.copyWith(color: fg),
),
const SizedBox(height: 2),
Text(
widget.subtitle,
style: context.text.bodySmall?.copyWith(color: sub),
),
],
),
),
Icon(Icons.arrow_forward_rounded, color: sub, size: 20),
],
),
),
),
),
),
);
}
}
class _TopBar extends StatelessWidget {
const _TopBar({required this.cashier, required this.now});
final String cashier;
final DateTime now;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xxl,
vertical: AppSpacing.lg,
),
child: Row(
children: [
const Icon(Icons.storefront_rounded,
color: Colors.white, size: 26),
const SizedBox(width: AppSpacing.md),
Text(
AppConstants.storeName,
style: context.text.titleLarge?.copyWith(color: Colors.white),
),
const Spacer(),
Text(
'${Formatters.date(now)} ${Formatters.time(now)}',
style: context.text.bodyMedium
?.copyWith(color: Colors.white.withValues(alpha: 0.85)),
),
const SizedBox(width: AppSpacing.xxl),
CircleAvatar(
radius: 16,
backgroundColor: Colors.white.withValues(alpha: 0.2),
child: Text(
Formatters.initials(cashier),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: AppSpacing.sm),
Text(cashier,
style: context.text.bodyMedium?.copyWith(color: Colors.white)),
],
),
);
}
}
class _BottomHint extends StatelessWidget {
const _BottomHint();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.xl),
child: Text(
'Scan a barcode at any time to begin a walk-in sale',
style: context.text.bodySmall
?.copyWith(color: Colors.white.withValues(alpha: 0.7)),
),
);
}
}

View File

@@ -0,0 +1,156 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../../../core/theme/app_colors.dart';
/// Vector shopping-cart illustration drawn in code.
///
/// Painting it avoids shipping a raster asset and keeps it crisp on 4K desktop
/// displays as well as tablet screens.
class WelcomeIllustration extends StatelessWidget {
const WelcomeIllustration({super.key, this.size = 240});
final double size;
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: CustomPaint(painter: _CartPainter()),
)
.animate(onPlay: (c) => c.repeat(reverse: true))
.moveY(begin: 0, end: -8, duration: 2400.ms, curve: Curves.easeInOut);
}
}
class _CartPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final w = size.width;
final h = size.height;
final unit = w / 100;
// Soft backdrop disc.
canvas.drawCircle(
Offset(w * 0.5, h * 0.5),
w * 0.46,
Paint()..color = AppColors.primarySurface,
);
// Decorative arc.
canvas.drawArc(
Rect.fromCircle(center: Offset(w * 0.5, h * 0.5), radius: w * 0.46),
-1.1,
2.0,
false,
Paint()
..color = AppColors.primaryBorder
..style = PaintingStyle.stroke
..strokeWidth = unit * 1.6
..strokeCap = StrokeCap.round,
);
final stroke = Paint()
..color = AppColors.primary
..style = PaintingStyle.stroke
..strokeWidth = unit * 3
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round;
final fill = Paint()..color = AppColors.primary.withValues(alpha: 0.16);
// Cart basket.
final basket = Path()
..moveTo(w * 0.30, h * 0.36)
..lineTo(w * 0.78, h * 0.36)
..lineTo(w * 0.70, h * 0.60)
..lineTo(w * 0.37, h * 0.60)
..close();
canvas.drawPath(basket, fill);
canvas.drawPath(basket, stroke);
// Handle running to the push bar.
canvas.drawPath(
Path()
..moveTo(w * 0.16, h * 0.26)
..lineTo(w * 0.24, h * 0.26)
..lineTo(w * 0.30, h * 0.36),
stroke,
);
// Basket ribs.
for (var i = 1; i <= 2; i++) {
final t = i / 3;
canvas.drawLine(
Offset(w * (0.30 + 0.48 * t), h * 0.36),
Offset(w * (0.37 + 0.33 * t), h * 0.60),
stroke..strokeWidth = unit * 1.6,
);
}
stroke.strokeWidth = unit * 3;
// Wheels.
for (final dx in [0.44, 0.66]) {
canvas.drawCircle(
Offset(w * dx, h * 0.70),
unit * 5,
Paint()..color = AppColors.surface,
);
canvas.drawCircle(Offset(w * dx, h * 0.70), unit * 5, stroke);
}
// Groceries poking out of the basket.
_item(canvas, Offset(w * 0.42, h * 0.30), unit * 5.5,
AppColors.tierGold.withValues(alpha: 0.9));
_item(canvas, Offset(w * 0.55, h * 0.27), unit * 6.5,
AppColors.success.withValues(alpha: 0.85));
_item(canvas, Offset(w * 0.67, h * 0.31), unit * 5,
AppColors.danger.withValues(alpha: 0.75));
// Receipt tape drifting away from the terminal.
final receipt = Path()
..moveTo(w * 0.80, h * 0.20)
..lineTo(w * 0.94, h * 0.20)
..lineTo(w * 0.94, h * 0.44)
..lineTo(w * 0.905, h * 0.40)
..lineTo(w * 0.87, h * 0.44)
..lineTo(w * 0.835, h * 0.40)
..lineTo(w * 0.80, h * 0.44)
..close();
canvas.drawPath(receipt, Paint()..color = AppColors.surface);
canvas.drawPath(
receipt,
Paint()
..color = AppColors.primaryLight
..style = PaintingStyle.stroke
..strokeWidth = unit * 1.4
..strokeJoin = StrokeJoin.round,
);
// Receipt lines.
final line = Paint()
..color = AppColors.primaryBorder
..strokeWidth = unit * 1.2
..strokeCap = StrokeCap.round;
for (var i = 0; i < 3; i++) {
final y = h * (0.25 + i * 0.05);
canvas.drawLine(Offset(w * 0.835, y), Offset(w * 0.905, y), line);
}
}
void _item(Canvas canvas, Offset center, double radius, Color color) {
canvas.drawCircle(center, radius, Paint()..color = color);
canvas.drawCircle(
center,
radius,
Paint()
..color = Colors.white.withValues(alpha: 0.5)
..style = PaintingStyle.stroke
..strokeWidth = 1.5,
);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}