added local db

This commit is contained in:
2026-07-29 13:06:39 +05:30
parent d72522e737
commit d9886880cc
38 changed files with 2895 additions and 2261 deletions

View File

@@ -1,136 +1,172 @@
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';
import '../local/app_database.dart';
import '../local/catalogue_dao.dart';
import '../local/order_dao.dart';
/// On-terminal storage.
/// Terminal-side storage facade.
///
/// 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.
/// SQLite is the source of truth. The catalogue is additionally held in memory
/// because barcode resolution happens on every scan and the product grid reads
/// it constantly — but every write goes to disk first, so nothing depends on
/// the process staying alive.
class LocalStore {
LocalStore._();
static final LocalStore instance = LocalStore._();
late CatalogueDao catalogue;
late OrderDao orders;
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;
int _unsyncedOrders = 0;
/// Nothing to seed — the catalogue arrives via import.
Future<void> init() async {}
bool _ready = false;
/// Test helper. Clears everything and optionally loads the demo catalogue
/// so fixtures don't have to run an import first.
bool get isReady => _ready;
/// Opens the database and loads the catalogue into memory.
Future<void> init({String? databasePath, bool inMemory = false}) async {
if (inMemory) {
await AppDatabase.instance.openInMemory();
} else {
await AppDatabase.instance.open(overridePath: databasePath);
}
catalogue = CatalogueDao(AppDatabase.instance.db);
orders = OrderDao(AppDatabase.instance.db);
await hydrate();
_ready = true;
}
/// Re-reads cached state from disk. Called on start and after an import.
Future<void> hydrate() async {
_products
..clear()
..addEntries(
(await catalogue.allProducts()).map((p) => MapEntry(p.id, p)),
);
_customers
..clear()
..addEntries(
(await catalogue.allCustomers()).map((c) => MapEntry(c.id, c)),
);
final stamp = await catalogue.meta(MetaKeys.lastImportAt);
_lastImportAt = stamp == null
? null
: DateTime.fromMillisecondsSinceEpoch(int.parse(stamp));
_catalogueRevision = await catalogue.meta(MetaKeys.catalogueRevision);
_unsyncedOrders = await orders.unsyncedCount();
}
/// Test helper: wipes every table and reloads.
Future<void> reset({bool withCatalogue = false}) async {
_products.clear();
_customers.clear();
_transactions.clear();
_parked.clear();
_events.clear();
_invoiceSequence = 0;
_lastImportAt = null;
_catalogueRevision = null;
if (!_ready) await init(inMemory: true);
await AppDatabase.instance.clear();
if (withCatalogue) {
importCatalogue(
products: SeedData.products(),
customers: SeedData.customers(),
revision: 'seed',
at: DateTime.now(),
// Imported here rather than at the top of the file so the seed data is
// only pulled in by tests and the simulated remote source.
await catalogue.replaceCatalogue(
products: _seedProducts(),
customers: _seedCustomers(),
);
await catalogue.setMeta(
MetaKeys.lastImportAt,
'${DateTime.now().millisecondsSinceEpoch}',
);
await catalogue.setMeta(MetaKeys.catalogueRevision, 'seed');
}
await hydrate();
}
// -------------------------------------------------------------- Catalogue
/// True once a catalogue has been pulled. The POS refuses to bill until so.
/// True once products exist on this terminal. Billing is gated on it.
bool get hasCatalogue => _products.isNotEmpty;
DateTime? get lastImportAt => _lastImportAt;
String? get catalogueRevision => _catalogueRevision;
int get unsyncedOrders => _unsyncedOrders;
/// 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({
Future<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;
}) async {
await catalogue.replaceCatalogue(products: products, customers: customers);
await catalogue.setMeta(
MetaKeys.lastImportAt,
'${at.millisecondsSinceEpoch}',
);
await catalogue.setMeta(MetaKeys.catalogueRevision, revision);
await hydrate();
}
// --------------------------------------------------------------- Products
List<Product> get products => _products.values.toList(growable: false);
void putProduct(Product p) => _products[p.id] = p;
Product? productById(String id) => _products[id];
Product? productByBarcode(String barcode) {
final needle = barcode.trim();
for (final p in _products.values) {
if (p.barcode == needle && p.isActive) return p;
}
return null;
}
/// Write-through: disk first, then the cache.
Future<void> putProduct(Product p) async {
await catalogue.upsertProduct(p);
_products[p.id] = p;
}
Future<void> applyStockMovement(Map<String, double> quantities) async {
await catalogue.decrementStock(quantities);
quantities.forEach((id, qty) {
final p = _products[id];
if (p == null) return;
_products[id] =
p.copyWith(stock: (p.stock - qty).clamp(0, double.infinity));
});
}
// -------------------------------------------------------------- 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;
Future<void> putCustomer(Customer c) async {
await catalogue.upsertCustomer(c);
_customers[c.id] = c;
}
bool get hasUnsyncedEvents =>
_events.any((e) => e.status != SyncStatus.synced);
// ----------------------------------------------------------------- Orders
/// Refreshes the cached unsynced tally after a write or a sync.
Future<int> refreshUnsyncedCount() async {
_unsyncedOrders = await orders.unsyncedCount();
return _unsyncedOrders;
}
// ------------------------------------------------------------- Seed data
// Kept behind these hooks so production code never reaches for them.
static List<Product> Function() _seedProducts = () => const [];
static List<Customer> Function() _seedCustomers = () => const [];
/// Lets the simulated remote source and tests supply demo rows.
static void registerSeed({
required List<Product> Function() products,
required List<Customer> Function() customers,
}) {
_seedProducts = products;
_seedCustomers = customers;
}
}

View File

@@ -1,5 +1,6 @@
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import 'local_store.dart';
import 'seed_data.dart';
/// What one catalogue pull returns.
@@ -35,7 +36,12 @@ class CatalogueSyncException implements Exception {
/// The real implementation would issue an HTTP request; the contract is the
/// same, so only this class changes.
class RemoteCatalogueSource {
RemoteCatalogueSource();
RemoteCatalogueSource() {
LocalStore.registerSeed(
products: SeedData.products,
customers: SeedData.customers,
);
}
/// Flipped from Settings to exercise the offline path.
bool simulateOffline = false;
@@ -75,24 +81,28 @@ class RemoteCatalogueSource {
}
}
/// Stands in for the back-office reporting API.
class RemoteReportSink {
RemoteReportSink();
/// Stands in for the back-office order intake API.
class RemoteOrderSink {
RemoteOrderSink();
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));
/// Uploads a batch of orders and returns the ids the server accepted.
///
/// Throws on transport failure so the caller leaves every row at
/// `sync_status = 0` rather than marking anything sent.
Future<List<String>> pushOrders(List<Map<String, Object?>> orders) async {
await Future<void>.delayed(
Duration(milliseconds: 400 + orders.length * 60),
);
if (simulateOffline) {
throw const CatalogueSyncException(
'Could not reach the reporting server. '
'The report is still saved on this terminal.',
'Could not reach the order server. Every bill is still stored on '
'this terminal and will upload on the next attempt.',
);
}
return 'ACK-${DateTime.now().millisecondsSinceEpoch % 1000000}';
return orders.map((o) => o['id']! as String).toList();
}
}

View File

@@ -0,0 +1,263 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
/// SQLite database for the terminal.
///
/// This is the source of truth for everything the cashier produces. Orders are
/// written here the moment a sale completes, so a crash, a power cut or a
/// closed app cannot lose a bill that has not yet reached the server.
class AppDatabase {
AppDatabase._();
static final AppDatabase instance = AppDatabase._();
static const String _fileName = 'nearle_pos.db';
static const int _version = 1;
Database? _db;
Database get db {
final database = _db;
if (database == null) {
throw StateError('AppDatabase.open() must be called before use.');
}
return database;
}
bool get isOpen => _db != null;
/// Opens the database, creating the schema on first run.
///
/// Desktop needs the FFI factory installed first; Android and iOS use the
/// platform implementation that ships with sqflite.
Future<void> open({String? overridePath}) async {
if (_db != null) return;
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
}
final path = overridePath ??
p.join(await databaseFactory.getDatabasesPath(), _fileName);
_db = await databaseFactory.openDatabase(
path,
options: OpenDatabaseOptions(
version: _version,
onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
onCreate: (db, version) async => _createSchema(db),
onUpgrade: (db, from, to) async {
// Single version so far; migrations land here as the schema grows.
},
),
);
}
/// In-memory database for tests.
Future<void> openInMemory() async {
if (_db != null) await close();
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
_db = await databaseFactory.openDatabase(
inMemoryDatabasePath,
options: OpenDatabaseOptions(
version: _version,
onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
onCreate: (db, version) async => _createSchema(db),
),
);
}
Future<void> close() async {
await _db?.close();
_db = null;
}
/// Drops every row without touching the schema. Used by tests.
Future<void> clear() async {
final batch = db.batch();
for (final t in const [
Tables.orderItems,
Tables.orders,
Tables.products,
Tables.customers,
Tables.parkedBills,
Tables.syncLog,
Tables.meta,
]) {
batch.delete(t);
}
await batch.commit(noResult: true);
}
Future<void> _createSchema(Database db) async {
// ------------------------------------------------------------ products
await db.execute('''
CREATE TABLE ${Tables.products} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
barcode TEXT NOT NULL,
sku TEXT NOT NULL,
category TEXT NOT NULL,
price REAL NOT NULL,
mrp REAL,
stock REAL NOT NULL DEFAULT 0,
emoji TEXT,
image_url TEXT,
unit TEXT NOT NULL DEFAULT 'piece',
gst_rate REAL NOT NULL DEFAULT 0.18,
brand TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
updated_at INTEGER NOT NULL
)
''');
// Barcode lookup is the hot path during scanning.
await db.execute(
'CREATE UNIQUE INDEX idx_products_barcode ON ${Tables.products}(barcode)',
);
await db.execute(
'CREATE INDEX idx_products_category ON ${Tables.products}(category)',
);
// ----------------------------------------------------------- customers
await db.execute('''
CREATE TABLE ${Tables.customers} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
mobile TEXT NOT NULL,
email TEXT,
gender TEXT NOT NULL DEFAULT 'unspecified',
date_of_birth INTEGER,
loyalty_points INTEGER NOT NULL DEFAULT 0,
lifetime_spend REAL NOT NULL DEFAULT 0,
visit_count INTEGER NOT NULL DEFAULT 0,
created_at INTEGER,
last_visit_at INTEGER
)
''');
await db.execute(
'CREATE UNIQUE INDEX idx_customers_mobile ON ${Tables.customers}(mobile)',
);
// -------------------------------------------------------------- orders
await db.execute('''
CREATE TABLE ${Tables.orders} (
id TEXT PRIMARY KEY,
invoice_number TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
business_date TEXT NOT NULL,
cashier_name TEXT NOT NULL,
terminal_id TEXT NOT NULL,
customer_id TEXT,
customer_mobile TEXT,
customer_name TEXT,
subtotal REAL NOT NULL,
line_discount REAL NOT NULL DEFAULT 0,
bill_discount REAL NOT NULL DEFAULT 0,
loyalty_value REAL NOT NULL DEFAULT 0,
taxable_amount REAL NOT NULL DEFAULT 0,
tax_amount REAL NOT NULL DEFAULT 0,
round_off REAL NOT NULL DEFAULT 0,
total REAL NOT NULL,
points_earned INTEGER NOT NULL DEFAULT 0,
points_redeemed INTEGER NOT NULL DEFAULT 0,
payments_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'completed',
-- 0 = held on this terminal, 1 = accepted by the server
sync_status INTEGER NOT NULL DEFAULT 0,
synced_at INTEGER,
sync_attempts INTEGER NOT NULL DEFAULT 0,
sync_error TEXT
)
''');
// The end-of-day upload selects on this, so it must be indexed.
await db.execute(
'CREATE INDEX idx_orders_sync ON ${Tables.orders}(sync_status)',
);
await db.execute(
'CREATE INDEX idx_orders_date ON ${Tables.orders}(business_date)',
);
// --------------------------------------------------------- order items
await db.execute('''
CREATE TABLE ${Tables.orderItems} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id TEXT NOT NULL,
product_id TEXT NOT NULL,
name TEXT NOT NULL,
barcode TEXT NOT NULL,
sku TEXT NOT NULL,
unit TEXT NOT NULL,
unit_price REAL NOT NULL,
quantity REAL NOT NULL,
discount REAL NOT NULL DEFAULT 0,
gst_rate REAL NOT NULL DEFAULT 0,
tax_amount REAL NOT NULL DEFAULT 0,
line_total REAL NOT NULL,
FOREIGN KEY (order_id) REFERENCES ${Tables.orders}(id)
ON DELETE CASCADE
)
''');
await db.execute(
'CREATE INDEX idx_items_order ON ${Tables.orderItems}(order_id)',
);
// --------------------------------------------------------- parked bills
await db.execute('''
CREATE TABLE ${Tables.parkedBills} (
id TEXT PRIMARY KEY,
label TEXT,
parked_at INTEGER NOT NULL,
cart_json TEXT NOT NULL
)
''');
// -------------------------------------------------------------- syncLog
await db.execute('''
CREATE TABLE ${Tables.syncLog} (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
status TEXT NOT NULL,
created_at INTEGER NOT NULL,
synced_at INTEGER,
summary TEXT NOT NULL,
error TEXT,
attempts INTEGER NOT NULL DEFAULT 0
)
''');
// ----------------------------------------------------------------- meta
await db.execute('''
CREATE TABLE ${Tables.meta} (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
''');
}
}
class Tables {
const Tables._();
static const String products = 'products';
static const String customers = 'customers';
static const String orders = 'orders';
static const String orderItems = 'order_items';
static const String parkedBills = 'parked_bills';
static const String syncLog = 'sync_log';
static const String meta = 'app_meta';
}
class MetaKeys {
const MetaKeys._();
static const String lastImportAt = 'last_import_at';
static const String catalogueRevision = 'catalogue_revision';
static const String invoiceSequence = 'invoice_sequence';
}

View File

@@ -0,0 +1,248 @@
import 'package:sqflite/sqflite.dart';
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import 'app_database.dart';
/// Reads and writes the imported catalogue.
class CatalogueDao {
const CatalogueDao(this._db);
final Database _db;
// --------------------------------------------------------------- Mapping
static Map<String, Object?> productToRow(Product p) => {
'id': p.id,
'name': p.name,
'barcode': p.barcode,
'sku': p.sku,
'category': p.category.name,
'price': p.price,
'mrp': p.mrp,
'stock': p.stock,
'emoji': p.emoji,
'image_url': p.imageUrl,
'unit': p.unit.name,
'gst_rate': p.gstRate,
'brand': p.brand,
'is_active': p.isActive ? 1 : 0,
'updated_at': DateTime.now().millisecondsSinceEpoch,
};
static Product productFromRow(Map<String, Object?> r) => Product(
id: r['id']! as String,
name: r['name']! as String,
barcode: r['barcode']! as String,
sku: r['sku']! as String,
category: ProductCategory.values.byName(r['category']! as String),
price: (r['price']! as num).toDouble(),
mrp: (r['mrp'] as num?)?.toDouble(),
stock: (r['stock']! as num).toDouble(),
emoji: (r['emoji'] as String?) ?? '📦',
imageUrl: r['image_url'] as String?,
unit: UnitOfMeasure.values.byName((r['unit'] as String?) ?? 'piece'),
gstRate: (r['gst_rate']! as num).toDouble(),
brand: r['brand'] as String?,
isActive: (r['is_active']! as int) == 1,
);
static Map<String, Object?> customerToRow(Customer c) => {
'id': c.id,
'name': c.name,
'mobile': c.mobile,
'email': c.email,
'gender': c.gender.name,
'date_of_birth': c.dateOfBirth?.millisecondsSinceEpoch,
'loyalty_points': c.loyaltyPoints,
'lifetime_spend': c.lifetimeSpend,
'visit_count': c.visitCount,
'created_at': c.createdAt?.millisecondsSinceEpoch,
'last_visit_at': c.lastVisitAt?.millisecondsSinceEpoch,
};
static Customer customerFromRow(Map<String, Object?> r) => Customer(
id: r['id']! as String,
name: r['name']! as String,
mobile: r['mobile']! as String,
email: r['email'] as String?,
gender: Gender.values.byName((r['gender'] as String?) ?? 'unspecified'),
dateOfBirth: _date(r['date_of_birth']),
loyaltyPoints: (r['loyalty_points'] as int?) ?? 0,
lifetimeSpend: (r['lifetime_spend'] as num?)?.toDouble() ?? 0,
visitCount: (r['visit_count'] as int?) ?? 0,
createdAt: _date(r['created_at']),
lastVisitAt: _date(r['last_visit_at']),
);
static DateTime? _date(Object? millis) => millis == null
? null
: DateTime.fromMillisecondsSinceEpoch(millis! as int);
// -------------------------------------------------------------- Products
Future<List<Product>> allProducts() async {
final rows = await _db.query(
Tables.products,
where: 'is_active = 1',
orderBy: 'category, name',
);
return rows.map(productFromRow).toList();
}
Future<Product?> productByBarcode(String barcode) async {
final rows = await _db.query(
Tables.products,
where: 'barcode = ? AND is_active = 1',
whereArgs: [barcode.trim()],
limit: 1,
);
return rows.isEmpty ? null : productFromRow(rows.first);
}
Future<Product?> productById(String id) async {
final rows = await _db.query(
Tables.products,
where: 'id = ?',
whereArgs: [id],
limit: 1,
);
return rows.isEmpty ? null : productFromRow(rows.first);
}
Future<int> productCount() async {
final r = await _db.rawQuery(
'SELECT COUNT(*) AS c FROM ${Tables.products} WHERE is_active = 1',
);
return (r.first['c']! as int);
}
Future<void> upsertProduct(Product p) async {
await _db.insert(
Tables.products,
productToRow(p),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
/// Writes the pulled catalogue in one transaction.
///
/// Stock already decremented by local sales is preserved for products that
/// survive the import, so re-importing mid-shift cannot resurrect sold units.
Future<void> replaceCatalogue({
required List<Product> products,
required List<Customer> customers,
}) async {
await _db.transaction((txn) async {
final existing = await txn.query(
Tables.products,
columns: ['id', 'stock'],
);
final heldStock = {
for (final r in existing) r['id']! as String: (r['stock']! as num).toDouble(),
};
final batch = txn.batch();
for (final p in products) {
final held = heldStock[p.id];
batch.insert(
Tables.products,
productToRow(held == null ? p : p.copyWith(stock: held)),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// Locally registered customers must survive a server pull, so this
// ignores rows that already exist rather than replacing them.
for (final c in customers) {
batch.insert(
Tables.customers,
customerToRow(c),
conflictAlgorithm: ConflictAlgorithm.ignore,
);
}
await batch.commit(noResult: true);
});
}
/// Applies stock movement after a sale, clamped at zero.
Future<void> decrementStock(Map<String, double> quantities) async {
if (quantities.isEmpty) return;
await _db.transaction((txn) async {
final batch = txn.batch();
quantities.forEach((id, qty) {
batch.rawUpdate(
'UPDATE ${Tables.products} '
'SET stock = MAX(0, stock - ?), updated_at = ? WHERE id = ?',
[qty, DateTime.now().millisecondsSinceEpoch, id],
);
});
await batch.commit(noResult: true);
});
}
// ------------------------------------------------------------- Customers
Future<List<Customer>> allCustomers({int limit = 500}) async {
final rows = await _db.query(
Tables.customers,
orderBy: 'last_visit_at DESC',
limit: limit,
);
return rows.map(customerFromRow).toList();
}
Future<Customer?> customerByMobile(String mobile) async {
final digits = mobile.replaceAll(RegExp(r'\D'), '');
final rows = await _db.query(
Tables.customers,
where: 'mobile = ?',
whereArgs: [digits],
limit: 1,
);
return rows.isEmpty ? null : customerFromRow(rows.first);
}
Future<Customer?> customerById(String id) async {
final rows = await _db.query(
Tables.customers,
where: 'id = ?',
whereArgs: [id],
limit: 1,
);
return rows.isEmpty ? null : customerFromRow(rows.first);
}
Future<void> upsertCustomer(Customer c) async {
await _db.insert(
Tables.customers,
customerToRow(c),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// ------------------------------------------------------------------ Meta
Future<String?> meta(String key) async {
final rows = await _db.query(
Tables.meta,
where: 'key = ?',
whereArgs: [key],
limit: 1,
);
return rows.isEmpty ? null : rows.first['value'] as String?;
}
Future<void> setMeta(String key, String value) async {
await _db.insert(
Tables.meta,
{'key': key, 'value': value},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
/// Monotonic invoice counter held in the meta table.
Future<int> nextInvoiceSequence() async {
final current = int.tryParse(await meta(MetaKeys.invoiceSequence) ?? '0') ?? 0;
final next = current + 1;
await setMeta(MetaKeys.invoiceSequence, '$next');
return next;
}
}

View File

@@ -0,0 +1,367 @@
import 'dart:convert';
import 'package:sqflite/sqflite.dart';
import '../../domain/entities/cart.dart';
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import '../../domain/entities/transaction.dart';
import 'app_database.dart';
import 'catalogue_dao.dart';
/// Persists bills.
///
/// Every completed sale lands here with `sync_status = 0`. The end-of-day
/// upload selects those rows, sends them, and flips the accepted ones to 1.
/// Nothing is ever deleted as part of syncing.
class OrderDao {
const OrderDao(this._db);
final Database _db;
static const int pending = 0;
static const int synced = 1;
static String businessDateOf(DateTime dt) =>
'${dt.year.toString().padLeft(4, '0')}-'
'${dt.month.toString().padLeft(2, '0')}-'
'${dt.day.toString().padLeft(2, '0')}';
// ----------------------------------------------------------------- Write
/// Writes the bill and its lines atomically.
Future<void> insertOrder(SaleTransaction t) async {
final cart = t.cart;
await _db.transaction((txn) async {
await txn.insert(
Tables.orders,
{
'id': t.id,
'invoice_number': t.invoiceNumber,
'created_at': t.createdAt.millisecondsSinceEpoch,
'business_date': businessDateOf(t.createdAt),
'cashier_name': t.cashierName,
'terminal_id': t.terminalId,
'customer_id': cart.customer?.id,
'customer_mobile': cart.customer?.mobile,
'customer_name': cart.customer?.name,
'subtotal': cart.subtotal,
'line_discount': cart.lineDiscountTotal,
'bill_discount': cart.billDiscountTotal,
'loyalty_value': cart.loyaltyRedemptionValue,
'taxable_amount': cart.taxableAmount,
'tax_amount': cart.taxAmount,
'round_off': cart.roundOff,
'total': t.total,
'points_earned': cart.pointsEarned,
'points_redeemed': cart.pointsRedeemed,
'payments_json': jsonEncode([
for (final p in t.payments)
{
'method': p.method.name,
'amount': p.amount,
'tendered': p.tendered,
'reference': p.reference,
},
]),
'status': t.status.name,
'sync_status': pending,
'sync_attempts': 0,
},
conflictAlgorithm: ConflictAlgorithm.replace,
);
final batch = txn.batch();
for (final line in cart.lines) {
batch.insert(Tables.orderItems, {
'order_id': t.id,
'product_id': line.product.id,
'name': line.product.name,
'barcode': line.product.barcode,
'sku': line.product.sku,
'unit': line.product.unit.name,
'unit_price': line.product.price,
'quantity': line.quantity,
'discount': line.discountAmount,
'gst_rate': line.product.gstRate,
'tax_amount': line.taxAmount,
'line_total': line.payable,
});
}
await batch.commit(noResult: true);
});
}
// ------------------------------------------------------------------ Read
Future<List<SaleTransaction>> recent({int limit = 100}) =>
_query(orderBy: 'created_at DESC', limit: limit);
Future<List<SaleTransaction>> forBusinessDate(DateTime day) =>
_query(where: 'business_date = ?', whereArgs: [businessDateOf(day)]);
/// The end-of-day upload set.
Future<List<SaleTransaction>> unsynced({int limit = 500}) => _query(
where: 'sync_status = ?',
whereArgs: [pending],
orderBy: 'created_at ASC',
limit: limit,
);
Future<SaleTransaction?> byInvoice(String invoiceNumber) async {
final rows = await _query(
where: 'invoice_number = ?',
whereArgs: [invoiceNumber],
limit: 1,
);
return rows.isEmpty ? null : rows.first;
}
Future<int> unsyncedCount() async {
final r = await _db.rawQuery(
'SELECT COUNT(*) AS c FROM ${Tables.orders} WHERE sync_status = ?',
[pending],
);
return r.first['c']! as int;
}
Future<double> salesTotalForDay(DateTime day) async {
final r = await _db.rawQuery(
'SELECT COALESCE(SUM(total), 0) AS t FROM ${Tables.orders} '
"WHERE business_date = ? AND status = 'completed'",
[businessDateOf(day)],
);
return (r.first['t']! as num).toDouble();
}
/// Sync state of an order, for display in the events log.
Future<Map<String, Object?>?> syncRow(String orderId) async {
final rows = await _db.query(
Tables.orders,
columns: [
'id',
'invoice_number',
'total',
'created_at',
'sync_status',
'synced_at',
'sync_attempts',
'sync_error',
],
where: 'id = ?',
whereArgs: [orderId],
limit: 1,
);
return rows.isEmpty ? null : rows.first;
}
Future<List<Map<String, Object?>>> syncRows({int limit = 200}) => _db.query(
Tables.orders,
columns: [
'id',
'invoice_number',
'total',
'created_at',
'sync_status',
'synced_at',
'sync_attempts',
'sync_error',
],
orderBy: 'created_at DESC',
limit: limit,
);
// ----------------------------------------------------------------- Sync
/// Flips accepted orders to `sync_status = 1`.
Future<void> markSynced(List<String> orderIds) async {
if (orderIds.isEmpty) return;
final now = DateTime.now().millisecondsSinceEpoch;
final placeholders = List.filled(orderIds.length, '?').join(',');
await _db.rawUpdate(
'UPDATE ${Tables.orders} SET sync_status = ?, synced_at = ?, '
'sync_error = NULL WHERE id IN ($placeholders)',
[synced, now, ...orderIds],
);
}
/// Records a failed attempt. The rows stay at `sync_status = 0`.
Future<void> markFailed(List<String> orderIds, String error) async {
if (orderIds.isEmpty) return;
final placeholders = List.filled(orderIds.length, '?').join(',');
await _db.rawUpdate(
'UPDATE ${Tables.orders} SET sync_attempts = sync_attempts + 1, '
'sync_error = ? WHERE id IN ($placeholders)',
[error, ...orderIds],
);
}
// ---------------------------------------------------------- Parked bills
Future<void> park(ParkedBill bill) async {
await _db.insert(
Tables.parkedBills,
{
'id': bill.id,
'label': bill.label,
'parked_at': bill.parkedAt.millisecondsSinceEpoch,
'cart_json': jsonEncode(_cartToJson(bill.cart)),
},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<ParkedBill>> parkedBills() async {
final rows =
await _db.query(Tables.parkedBills, orderBy: 'parked_at DESC');
return rows
.map((r) => ParkedBill(
id: r['id']! as String,
label: r['label'] as String?,
parkedAt:
DateTime.fromMillisecondsSinceEpoch(r['parked_at']! as int),
cart: _cartFromJson(
jsonDecode(r['cart_json']! as String) as Map<String, Object?>,
),
))
.toList();
}
Future<void> removeParked(String id) async {
await _db.delete(Tables.parkedBills, where: 'id = ?', whereArgs: [id]);
}
// -------------------------------------------------------------- Internals
Future<List<SaleTransaction>> _query({
String? where,
List<Object?>? whereArgs,
String orderBy = 'created_at DESC',
int? limit,
}) async {
final orders = await _db.query(
Tables.orders,
where: where,
whereArgs: whereArgs,
orderBy: orderBy,
limit: limit,
);
if (orders.isEmpty) return const [];
final ids = orders.map((o) => o['id']! as String).toList();
final placeholders = List.filled(ids.length, '?').join(',');
final items = await _db.query(
Tables.orderItems,
where: 'order_id IN ($placeholders)',
whereArgs: ids,
);
final byOrder = <String, List<Map<String, Object?>>>{};
for (final i in items) {
byOrder.putIfAbsent(i['order_id']! as String, () => []).add(i);
}
return orders
.map((o) => _transactionFromRows(o, byOrder[o['id']] ?? const []))
.toList();
}
SaleTransaction _transactionFromRows(
Map<String, Object?> o,
List<Map<String, Object?>> items,
) {
// Lines are rebuilt from the snapshot taken at sale time, not from the
// current catalogue, so a reprint always shows what was actually charged.
final lines = items.map((i) {
final product = Product(
id: i['product_id']! as String,
name: i['name']! as String,
barcode: i['barcode']! as String,
sku: i['sku']! as String,
category: ProductCategory.grocery,
price: (i['unit_price']! as num).toDouble(),
stock: 0,
unit: UnitOfMeasure.values.byName(i['unit']! as String),
gstRate: (i['gst_rate']! as num).toDouble(),
);
return CartLine(
product: product,
quantity: (i['quantity']! as num).toDouble(),
discount: (i['discount']! as num) > 0
? Discount(
type: DiscountType.flat,
value: (i['discount']! as num).toDouble(),
)
: Discount.none,
);
}).toList();
final customerId = o['customer_id'] as String?;
final customer = customerId == null
? null
: Customer(
id: customerId,
name: (o['customer_name'] as String?) ?? 'Customer',
mobile: (o['customer_mobile'] as String?) ?? '',
);
final payments = (jsonDecode(o['payments_json']! as String) as List)
.cast<Map<String, Object?>>()
.map((p) => PaymentSplit(
method: PaymentMethod.values.byName(p['method']! as String),
amount: (p['amount']! as num).toDouble(),
tendered: (p['tendered'] as num?)?.toDouble(),
reference: p['reference'] as String?,
))
.toList();
return SaleTransaction(
id: o['id']! as String,
invoiceNumber: o['invoice_number']! as String,
cart: Cart(lines: lines, customer: customer),
payments: payments,
createdAt: DateTime.fromMillisecondsSinceEpoch(o['created_at']! as int),
cashierName: o['cashier_name']! as String,
terminalId: o['terminal_id']! as String,
status: TransactionStatus.values.byName(o['status']! as String),
);
}
Map<String, Object?> _cartToJson(Cart cart) => {
'customer': cart.customer == null
? null
: CatalogueDao.customerToRow(cart.customer!),
'points_redeemed': cart.pointsRedeemed,
'note': cart.note,
'lines': [
for (final l in cart.lines)
{
'product': CatalogueDao.productToRow(l.product),
'quantity': l.quantity,
'discount_type': l.discount.type.name,
'discount_value': l.discount.value,
},
],
};
Cart _cartFromJson(Map<String, Object?> j) {
final customerRow = j['customer'] as Map<String, Object?>?;
return Cart(
customer: customerRow == null
? null
: CatalogueDao.customerFromRow(customerRow),
pointsRedeemed: (j['points_redeemed'] as int?) ?? 0,
note: j['note'] as String?,
lines: (j['lines'] as List).cast<Map<String, Object?>>().map((l) {
return CartLine(
product: CatalogueDao.productFromRow(
l['product']! as Map<String, Object?>,
),
quantity: (l['quantity']! as num).toDouble(),
discount: Discount(
type: DiscountType.values.byName(l['discount_type']! as String),
value: (l['discount_value']! as num).toDouble(),
),
);
}).toList(),
);
}
}

View File

@@ -43,13 +43,13 @@ class CustomerRepositoryImpl implements CustomerRepository {
visitCount: 0,
createdAt: DateTime.now(),
);
_store.putCustomer(created);
await _store.putCustomer(created);
return created;
}
@override
Future<Customer> update(Customer customer) async {
_store.putCustomer(customer);
await _store.putCustomer(customer);
return customer;
}
@@ -72,7 +72,7 @@ class CustomerRepositoryImpl implements CustomerRepository {
visitCount: current.visitCount + 1,
lastVisitAt: DateTime.now(),
);
_store.putCustomer(updated);
await _store.putCustomer(updated);
return updated;
}

View File

@@ -1,8 +1,9 @@
import '../../core/utils/extensions.dart';
import '../../domain/entities/product.dart';
import '../../domain/repositories/product_repository.dart';
import '../datasources/local_store.dart';
/// Reads come from the in-memory catalogue for speed; writes go through the
/// store, which persists to SQLite before touching the cache.
class ProductRepositoryImpl implements ProductRepository {
ProductRepositoryImpl(this._store);
@@ -19,12 +20,8 @@ class ProductRepositoryImpl implements ProductRepository {
.toList();
@override
Future<Product?> findByBarcode(String barcode) async {
final needle = barcode.trim();
return _store.products.firstWhereOrNull(
(p) => p.barcode == needle && p.isActive,
);
}
Future<Product?> findByBarcode(String barcode) async =>
_store.productByBarcode(barcode);
@override
Future<Product?> findById(String id) async => _store.productById(id);
@@ -34,15 +31,13 @@ class ProductRepositoryImpl implements ProductRepository {
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()
final ranked = _store.products.where((p) => p.isActive && p.matches(q)).toList()
..sort((a, b) => _score(b, q).compareTo(_score(a, q)));
return ranked;
}
/// Exact barcode and SKU hits rank above fuzzy name matches, so the top
/// result is the one the cashier almost certainly meant.
int _score(Product p, String q) {
final lq = q.toLowerCase();
if (p.barcode == q) return 100;
@@ -54,15 +49,9 @@ class ProductRepositoryImpl implements ProductRepository {
}
@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));
});
}
Future<void> decrementStock(Map<String, double> quantities) =>
_store.applyStockMovement(quantities);
@override
Future<void> upsert(Product product) async => _store.putProduct(product);
Future<void> upsert(Product product) => _store.putProduct(product);
}

View File

@@ -3,19 +3,25 @@ import 'package:uuid/uuid.dart';
import '../../core/utils/formatters.dart';
import '../../domain/entities/shift_report.dart';
import '../../domain/entities/sync_event.dart';
import '../../domain/entities/transaction.dart';
import '../../domain/repositories/sync_repository.dart';
import '../datasources/local_store.dart';
import '../datasources/remote_catalogue_source.dart';
import '../local/order_dao.dart';
class SyncRepositoryImpl implements SyncRepository {
SyncRepositoryImpl(this._store, this._catalogue, this._reports);
SyncRepositoryImpl(this._store, this._catalogue, this._orderSink);
final LocalStore _store;
final RemoteCatalogueSource _catalogue;
final RemoteReportSink _reports;
final RemoteOrderSink _orderSink;
static const _uuid = Uuid();
/// In-session event log. Order sync state itself lives on the order rows,
/// so this is only a human-readable history of attempts.
final List<SyncEvent> _events = [];
@override
bool get hasCatalogue => _store.hasCatalogue;
@@ -26,134 +32,216 @@ class SyncRepositoryImpl implements SyncRepository {
String? get catalogueRevision => _store.catalogueRevision;
@override
List<SyncEvent> get events => _store.events;
List<SyncEvent> get events => List.unmodifiable(_events.reversed);
@override
bool get hasUnsyncedEvents => _store.hasUnsyncedEvents;
void _log(SyncEvent e) => _events.add(e);
// ------------------------------------------------------- Morning: import
@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);
final id = _uuid.v4();
final started = DateTime.now();
try {
final snapshot = await _catalogue.fetch(onProgress: onProgress);
_store.importCatalogue(
await _store.importCatalogue(
products: snapshot.products,
customers: snapshot.customers,
revision: snapshot.revision,
at: snapshot.fetchedAt,
);
final done = event.copyWith(
final event = SyncEvent(
id: id,
type: SyncEventType.catalogueImport,
status: SyncStatus.synced,
createdAt: started,
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}',
summary: '${snapshot.products.length} products saved to SQLite '
'· ${snapshot.revision}',
payload: {
'products': snapshot.products.length,
'customers': snapshot.customers.length,
'revision': snapshot.revision,
},
syncedAt: done.syncedAt,
attempts: 1,
);
_store.updateEvent(settled);
return settled;
_log(event);
return event;
} catch (e) {
final failed = event.copyWith(
final event = SyncEvent(
id: id,
type: SyncEventType.catalogueImport,
status: SyncStatus.failed,
createdAt: started,
summary: 'Catalogue import failed',
error: e.toString(),
attempts: 1,
);
_store.updateEvent(failed);
return failed;
_log(event);
return event;
}
}
// --------------------------------------------------- Business hours: read
@override
ShiftReport buildShiftReport({
required DateTime businessDate,
Future<int> unsyncedCount() => _store.orders.unsyncedCount();
@override
Future<List<SaleTransaction>> unsyncedOrders() => _store.orders.unsynced();
@override
Future<ShiftReport> todayReport({
required String terminalId,
required String cashierName,
}) {
}) async {
final today = DateTime.now();
final orders = await _store.orders.forBusinessDate(today);
return ShiftReport.fromTransactions(
transactions: _store.transactions,
businessDate: businessDate,
transactions: orders,
businessDate: today,
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);
Future<List<OrderSyncRow>> orderSyncRows({int limit = 200}) async {
final rows = await _store.orders.syncRows(limit: limit);
return rows
.map((r) => OrderSyncRow(
orderId: r['id']! as String,
invoiceNumber: r['invoice_number']! as String,
total: (r['total']! as num).toDouble(),
createdAt:
DateTime.fromMillisecondsSinceEpoch(r['created_at']! as int),
isSynced: (r['sync_status']! as int) == OrderDao.synced,
syncedAt: r['synced_at'] == null
? null
: DateTime.fromMillisecondsSinceEpoch(r['synced_at']! as int),
attempts: (r['sync_attempts'] as int?) ?? 0,
error: r['sync_error'] as String?,
))
.toList();
}
// ------------------------------------------------------ End of day: sync
@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);
}
Future<SyncOutcome> syncOrders({
void Function(double progress, String stage)? onProgress,
}) async {
onProgress?.call(0.05, 'Collecting unsynced bills…');
/// Sends one event, leaving it queued if the push fails.
Future<SyncEvent> _attempt(SyncEvent event) async {
_store.updateEvent(event.copyWith(status: SyncStatus.syncing));
final pending = await _store.orders.unsynced();
if (pending.isEmpty) {
onProgress?.call(1, 'Nothing to upload');
return const SyncOutcome(attempted: 0, uploaded: 0);
}
final started = DateTime.now();
final ids = pending.map((o) => o.id).toList();
onProgress?.call(0.35, 'Uploading ${pending.length} bills…');
try {
await _reports.push(event.payload);
final done = event.copyWith(
final accepted = await _orderSink.pushOrders(
pending.map(_orderToPayload).toList(),
);
onProgress?.call(0.85, 'Marking bills as synced…');
// Only what the server confirmed is flipped to 1.
await _store.orders.markSynced(accepted);
await _store.refreshUnsyncedCount();
final rejected = ids.where((id) => !accepted.contains(id)).toList();
if (rejected.isNotEmpty) {
await _store.orders.markFailed(rejected, 'Rejected by server');
}
onProgress?.call(1, 'Done');
_log(SyncEvent(
id: _uuid.v4(),
type: SyncEventType.shiftReport,
status: SyncStatus.synced,
createdAt: started,
syncedAt: DateTime.now(),
attempts: event.attempts + 1,
clearError: true,
);
_store.updateEvent(done);
return done.copyWith();
summary: '${accepted.length} of ${pending.length} bills uploaded',
attempts: 1,
));
return SyncOutcome(attempted: pending.length, uploaded: accepted.length);
} catch (e) {
final failed = event.copyWith(
// Transport failed: record the attempt but leave every row at 0.
await _store.orders.markFailed(ids, e.toString());
await _store.refreshUnsyncedCount();
_log(SyncEvent(
id: _uuid.v4(),
type: SyncEventType.shiftReport,
status: SyncStatus.failed,
createdAt: started,
summary: '${pending.length} bills still pending '
'(${Formatters.money(pending.fold<double>(0, (s, o) => s + o.total))})',
error: e.toString(),
attempts: 1,
));
return SyncOutcome(
attempted: pending.length,
uploaded: 0,
error: e.toString(),
attempts: event.attempts + 1,
);
_store.updateEvent(failed);
return failed;
}
}
/// The JSON body sent per order.
Map<String, Object?> _orderToPayload(SaleTransaction t) => {
'id': t.id,
'invoice_number': t.invoiceNumber,
'created_at': t.createdAt.toIso8601String(),
'terminal_id': t.terminalId,
'cashier': t.cashierName,
'customer': t.customer == null
? null
: {
'id': t.customer!.id,
'mobile': t.customer!.mobile,
'name': t.customer!.name,
},
'subtotal': t.cart.subtotal,
'discount': t.cart.billDiscountTotal + t.cart.lineDiscountTotal,
'tax': t.cart.taxAmount,
'round_off': t.cart.roundOff,
'total': t.total,
'points_earned': t.pointsEarned,
'points_redeemed': t.pointsRedeemed,
'payments': [
for (final p in t.payments)
{
'method': p.method.name,
'amount': p.amount,
'reference': p.reference,
},
],
'items': [
for (final l in t.cart.lines)
{
'product_id': l.product.id,
'barcode': l.product.barcode,
'name': l.product.name,
'quantity': l.quantity,
'unit_price': l.product.price,
'discount': l.discountAmount,
'gst_rate': l.product.gstRate,
'tax': l.taxAmount,
'line_total': l.payable,
},
],
};
}

View File

@@ -1,8 +1,8 @@
import '../../core/utils/extensions.dart';
import '../../domain/entities/transaction.dart';
import '../../domain/repositories/transaction_repository.dart';
import '../datasources/local_store.dart';
/// All bill persistence goes straight to SQLite.
class TransactionRepositoryImpl implements TransactionRepository {
TransactionRepositoryImpl(this._store);
@@ -10,40 +10,33 @@ class TransactionRepositoryImpl implements TransactionRepository {
@override
Future<SaleTransaction> save(SaleTransaction transaction) async {
_store.addTransaction(transaction);
// Written with sync_status = 0; the end-of-day upload picks it up.
await _store.orders.insertOrder(transaction);
await _store.refreshUnsyncedCount();
return transaction;
}
@override
Future<List<SaleTransaction>> history({int limit = 50}) async =>
_store.transactions.take(limit).toList();
Future<List<SaleTransaction>> history({int limit = 50}) =>
_store.orders.recent(limit: limit);
@override
Future<SaleTransaction?> findByInvoice(String invoiceNumber) async =>
_store.transactions
.firstWhereOrNull((t) => t.invoiceNumber == invoiceNumber);
Future<SaleTransaction?> findByInvoice(String invoiceNumber) =>
_store.orders.byInvoice(invoiceNumber);
@override
Future<int> nextInvoiceSequence() async => _store.nextInvoiceSequence();
Future<int> nextInvoiceSequence() => _store.catalogue.nextInvoiceSequence();
@override
Future<void> park(ParkedBill bill) async => _store.addParked(bill);
Future<void> park(ParkedBill bill) => _store.orders.park(bill);
@override
Future<List<ParkedBill>> parkedBills() async => _store.parked;
Future<List<ParkedBill>> parkedBills() => _store.orders.parkedBills();
@override
Future<void> removeParked(String id) async => _store.removeParked(id);
Future<void> removeParked(String id) => _store.orders.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;
}
Future<double> salesTotalForDay(DateTime day) =>
_store.orders.salesTotalForDay(day);
}