Fix billing data integrity, sale atomicity and stock safety
Bills were persisted correctly but read back wrong. The read path rebuilt a cart from its lines alone, dropping bill-level discounts and loyalty, so every figure derived from a stored bill was overstated: the upload payload, the day archive and the shift report. A discounted 529 bill read back as 620. Money and data integrity - order_dao: restore bill_discount and points_redeemed when rebuilding a cart; keep the reconstruction tier-less so the membership discount is not applied twice. Trust the recorded total and points via SaleTransaction.storedTotal. - checkout_sale + order_dao.commitSale: write the bill, its stock movement and the loyalty update in one transaction. Previously a failure part-way through left a persisted bill the cashier believed had failed, inviting a duplicate. - checkout_sale: re-check every line against live stock. A parked bill resumed after its stock was sold passed validation and oversold. - catalogue_dao: allocate the invoice sequence in one transaction; the previous read-modify-write could hand two sales the same number and fail UNIQUE. - local_store: replay unsynced sales after a catalogue import, so a mid-shift re-import cannot restore stock that has already been sold. - payment_controller: stamp the signed-in operator on the bill instead of the hardcoded seed session, and pass the terminal id through. - cart: reconcile per-slab GST against the bill total so the parts sum to the whole on a tax invoice. Sync and reporting - sync_repository: drain unsynced bills in a loop rather than silently capping at one page; stop on rejection so rejected rows cannot loop forever. - sync_log_dao (new): persist the sync history to the sync_log table, which the schema already defined but nothing used. It was in memory, so the only record that bills had been uploaded died at restart. - Scope shift reports by cashier. day_archive is re-keyed to (business_date, cashier_name) so a till stays settleable after its bills are uploaded and deleted. Schema v4 with a migration that carries v3 rows across. Input and UI - barcode_service: consume machine-paced keystrokes so a scan cannot also land in the focused field, and raise the bar to 60ms/char while a text field has focus so typing a mobile number is not read as a scan. Clock and focus check injected so the behaviour is testable. - primary_button: make the label flexible; label plus trailing total overflowed the Charge button by up to 131px. - app_router: redirect instead of null-casting when the receipt route is entered without its transaction. - customer_repository: reduce the search query to digits so a punctuated mobile number matches. Cleanup - Remove TransactionRepository.save, CustomerRepository.recordSale and OrderDao.insertOrder, all superseded by commitSale. - dart fix across the tree; 251 analyzer issues down to 3 info-level. Tests: 23 passing / 15 failing -> 90 passing. Fixed the two defects that broke the existing suite (containsAll type argument, reset() needing a catalogue) and deleted the leftover template test. Added coverage for the order round trip, the day archive after a real sync, stock safety, checkout atomicity, the v3->v4 migration, scanner-versus-human input, and an app-level smoke test that renders every module. Note: bills already uploaded with a discount went up overstated. This stops it happening again but does not correct historical server data. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/product.dart';
|
||||
import '../../domain/entities/sync_event.dart';
|
||||
import '../local/app_database.dart';
|
||||
import '../local/catalogue_dao.dart';
|
||||
import '../local/order_dao.dart';
|
||||
import '../local/sync_log_dao.dart';
|
||||
|
||||
/// Terminal-side storage facade.
|
||||
///
|
||||
@@ -17,9 +19,11 @@ class LocalStore {
|
||||
|
||||
late CatalogueDao catalogue;
|
||||
late OrderDao orders;
|
||||
late SyncLogDao syncLog;
|
||||
|
||||
final Map<String, Product> _products = {};
|
||||
final Map<String, Customer> _customers = {};
|
||||
final List<SyncEvent> _syncEvents = [];
|
||||
|
||||
DateTime? _lastImportAt;
|
||||
String? _catalogueRevision;
|
||||
@@ -39,6 +43,7 @@ class LocalStore {
|
||||
|
||||
catalogue = CatalogueDao(AppDatabase.instance.db);
|
||||
orders = OrderDao(AppDatabase.instance.db);
|
||||
syncLog = SyncLogDao(AppDatabase.instance.db);
|
||||
|
||||
await hydrate();
|
||||
_ready = true;
|
||||
@@ -63,6 +68,20 @@ class LocalStore {
|
||||
: DateTime.fromMillisecondsSinceEpoch(int.parse(stamp));
|
||||
_catalogueRevision = await catalogue.meta(MetaKeys.catalogueRevision);
|
||||
_unsyncedOrders = await orders.unsyncedCount();
|
||||
|
||||
_syncEvents
|
||||
..clear()
|
||||
..addAll(await syncLog.recent());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Sync log
|
||||
/// Newest first. Backed by the table, so it survives a restart.
|
||||
List<SyncEvent> get syncEvents => List.unmodifiable(_syncEvents);
|
||||
|
||||
Future<void> appendSyncEvent(SyncEvent event) async {
|
||||
await syncLog.insert(event);
|
||||
await syncLog.trim();
|
||||
_syncEvents.insert(0, event);
|
||||
}
|
||||
|
||||
/// Test helper: wipes every table and reloads.
|
||||
@@ -102,6 +121,15 @@ class LocalStore {
|
||||
required DateTime at,
|
||||
}) async {
|
||||
await catalogue.replaceCatalogue(products: products, customers: customers);
|
||||
|
||||
// The server's stock figure predates any sale this terminal has made but
|
||||
// not yet uploaded, so those units would reappear on the shelf. Replay them
|
||||
// before anyone can bill against the inflated count.
|
||||
final committed = await orders.unsyncedStockCommitments();
|
||||
if (committed.isNotEmpty) {
|
||||
await catalogue.decrementStock(committed);
|
||||
}
|
||||
|
||||
await catalogue.setMeta(
|
||||
MetaKeys.lastImportAt,
|
||||
'${at.millisecondsSinceEpoch}',
|
||||
@@ -131,6 +159,12 @@ class LocalStore {
|
||||
|
||||
Future<void> applyStockMovement(Map<String, double> quantities) async {
|
||||
await catalogue.decrementStock(quantities);
|
||||
cacheStockMovement(quantities);
|
||||
}
|
||||
|
||||
/// Mirrors a stock decrement already written to disk into the memory cache.
|
||||
/// Used after a sale is committed as part of a larger transaction.
|
||||
void cacheStockMovement(Map<String, double> quantities) {
|
||||
quantities.forEach((id, qty) {
|
||||
final p = _products[id];
|
||||
if (p == null) return;
|
||||
@@ -149,6 +183,9 @@ class LocalStore {
|
||||
_customers[c.id] = c;
|
||||
}
|
||||
|
||||
/// Mirrors a customer already written to disk into the memory cache.
|
||||
void cacheCustomer(Customer c) => _customers[c.id] = c;
|
||||
|
||||
// ----------------------------------------------------------------- Orders
|
||||
/// Refreshes the cached unsynced tally after a write or a sync.
|
||||
Future<int> refreshUnsyncedCount() async {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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.
|
||||
@@ -14,7 +13,7 @@ class AppDatabase {
|
||||
static final AppDatabase instance = AppDatabase._();
|
||||
|
||||
static const String _fileName = 'nearle_pos.db';
|
||||
static const int _version = 3;
|
||||
static const int _version = 4;
|
||||
|
||||
Database? _db;
|
||||
|
||||
@@ -70,6 +69,7 @@ class AppDatabase {
|
||||
'ALTER TABLE ${Tables.products} ADD COLUMN hsn_code TEXT',
|
||||
);
|
||||
}
|
||||
if (from < 4) await _upgradeToV4(db, from: from);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -238,18 +238,7 @@ class AppDatabase {
|
||||
''');
|
||||
|
||||
// -------------------------------------------------------------- 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
|
||||
)
|
||||
''');
|
||||
await db.execute(_createSyncLog);
|
||||
|
||||
// ------------------------------------------------------------- archive
|
||||
await db.execute(_createDayArchive);
|
||||
@@ -264,14 +253,61 @@ class AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Running totals per business day.
|
||||
/// Moves the schema to v4.
|
||||
///
|
||||
/// Adds the payload column the sync log needs to be usable at all, and re-keys
|
||||
/// the day archive by cashier so a shift report can be scoped to whoever is
|
||||
/// settling their till. Existing archived rows predate per-cashier attribution,
|
||||
/// so they are folded under an empty name rather than guessed at.
|
||||
Future<void> _upgradeToV4(Database db, {required int from}) async {
|
||||
// A v1 database had no sync_log payload column; v2+ did not either.
|
||||
await db.execute(
|
||||
'ALTER TABLE ${Tables.syncLog} ADD COLUMN payload_json TEXT',
|
||||
);
|
||||
|
||||
await db.execute('ALTER TABLE ${Tables.dayArchive} RENAME TO _day_archive_v3');
|
||||
await db.execute(_createDayArchive);
|
||||
await db.execute('''
|
||||
INSERT INTO ${Tables.dayArchive} (
|
||||
business_date, cashier_name, bill_count, item_count, gross_sales,
|
||||
tax_collected, discount_given, round_off, points_issued,
|
||||
points_redeemed, payments_json, first_bill_at, last_bill_at,
|
||||
synced_bills
|
||||
)
|
||||
SELECT
|
||||
business_date, '', bill_count, item_count, gross_sales,
|
||||
tax_collected, discount_given, round_off, points_issued,
|
||||
points_redeemed, payments_json, first_bill_at, last_bill_at,
|
||||
synced_bills
|
||||
FROM _day_archive_v3
|
||||
''');
|
||||
await db.execute('DROP TABLE _day_archive_v3');
|
||||
}
|
||||
|
||||
const String _createSyncLog = '''
|
||||
CREATE TABLE sync_log (
|
||||
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,
|
||||
payload_json TEXT
|
||||
)
|
||||
''';
|
||||
|
||||
/// Running totals per business day and cashier.
|
||||
///
|
||||
/// Synced orders are deleted from the terminal, so their figures are folded in
|
||||
/// here first — otherwise "Bills Today" would collapse to zero the moment a
|
||||
/// mid-shift sync ran.
|
||||
/// mid-shift sync ran. Keyed by cashier as well as date, because once the
|
||||
/// orders are gone this row is the only thing left to settle a till against.
|
||||
const String _createDayArchive = '''
|
||||
CREATE TABLE day_archive (
|
||||
business_date TEXT PRIMARY KEY,
|
||||
business_date TEXT NOT NULL,
|
||||
cashier_name TEXT NOT NULL DEFAULT '',
|
||||
bill_count INTEGER NOT NULL DEFAULT 0,
|
||||
item_count REAL NOT NULL DEFAULT 0,
|
||||
gross_sales REAL NOT NULL DEFAULT 0,
|
||||
@@ -283,7 +319,8 @@ const String _createDayArchive = '''
|
||||
payments_json TEXT NOT NULL DEFAULT '{}',
|
||||
first_bill_at INTEGER,
|
||||
last_bill_at INTEGER,
|
||||
synced_bills INTEGER NOT NULL DEFAULT 0
|
||||
synced_bills INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (business_date, cashier_name)
|
||||
)
|
||||
''';
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ class CatalogueDao {
|
||||
|
||||
static DateTime? _date(Object? millis) => millis == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(millis! as int);
|
||||
: DateTime.fromMillisecondsSinceEpoch(millis as int);
|
||||
|
||||
// -------------------------------------------------------------- Products
|
||||
Future<List<Product>> allProducts() async {
|
||||
@@ -248,10 +248,30 @@ class CatalogueDao {
|
||||
}
|
||||
|
||||
/// Monotonic invoice counter held in the meta table.
|
||||
///
|
||||
/// Read and write happen in one transaction. Done as separate awaits, two
|
||||
/// checkouts could interleave, take the same number, and the second insert
|
||||
/// would then fail the UNIQUE constraint on `invoice_number` — after the
|
||||
/// sequence had already been consumed.
|
||||
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;
|
||||
return _db.transaction<int>((txn) async {
|
||||
final rows = await txn.query(
|
||||
Tables.meta,
|
||||
where: 'key = ?',
|
||||
whereArgs: [MetaKeys.invoiceSequence],
|
||||
limit: 1,
|
||||
);
|
||||
final current = rows.isEmpty
|
||||
? 0
|
||||
: int.tryParse(rows.first['value']! as String) ?? 0;
|
||||
final next = current + 1;
|
||||
|
||||
await txn.insert(
|
||||
Tables.meta,
|
||||
{'key': MetaKeys.invoiceSequence, 'value': '$next'},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,76 +28,127 @@ class OrderDao {
|
||||
'${dt.day.toString().padLeft(2, '0')}';
|
||||
|
||||
// ----------------------------------------------------------------- Write
|
||||
/// Writes the bill and its lines atomically.
|
||||
Future<void> insertOrder(SaleTransaction t) async {
|
||||
final cart = t.cart;
|
||||
|
||||
/// Commits an entire sale in one transaction.
|
||||
///
|
||||
/// The bill, the stock it consumed and the shopper's loyalty movement have to
|
||||
/// land together or not at all. Applied as three separate writes, a failure
|
||||
/// part-way through left a persisted bill with unapplied loyalty while the
|
||||
/// cashier saw an error and rang the sale again — a duplicate bill and a
|
||||
/// double stock decrement.
|
||||
Future<void> commitSale({
|
||||
required SaleTransaction transaction,
|
||||
required Map<String, double> stockMovements,
|
||||
Map<String, Object?>? customerRow,
|
||||
}) async {
|
||||
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,
|
||||
);
|
||||
await _insertOrder(txn, transaction);
|
||||
|
||||
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,
|
||||
});
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
stockMovements.forEach((id, qty) {
|
||||
batch.rawUpdate(
|
||||
'UPDATE ${Tables.products} '
|
||||
'SET stock = MAX(0, stock - ?), updated_at = ? WHERE id = ?',
|
||||
[qty, now, id],
|
||||
);
|
||||
});
|
||||
if (customerRow != null) {
|
||||
batch.insert(
|
||||
Tables.customers,
|
||||
customerRow,
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
await batch.commit(noResult: true);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _insertOrder(DatabaseExecutor txn, SaleTransaction t) async {
|
||||
final cart = t.cart;
|
||||
|
||||
// A replace of the order row does not reliably cascade to its lines, so
|
||||
// clear them first — otherwise re-saving a bill doubles its items.
|
||||
await txn.delete(Tables.orderItems, where: 'order_id = ?', whereArgs: [t.id]);
|
||||
|
||||
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': t.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)]);
|
||||
/// Bills for a day, optionally narrowed to one operator.
|
||||
///
|
||||
/// A shift report that is settled against a till has to cover exactly the
|
||||
/// bills that cashier rang, not everything the terminal did that day.
|
||||
Future<List<SaleTransaction>> forBusinessDate(
|
||||
DateTime day, {
|
||||
String? cashierName,
|
||||
}) =>
|
||||
_query(
|
||||
where: cashierName == null
|
||||
? 'business_date = ?'
|
||||
: 'business_date = ? AND cashier_name = ?',
|
||||
whereArgs: [
|
||||
businessDateOf(day),
|
||||
if (cashierName != null) cashierName,
|
||||
],
|
||||
);
|
||||
|
||||
/// The end-of-day upload set.
|
||||
Future<List<SaleTransaction>> unsynced({int limit = 500}) => _query(
|
||||
@@ -124,6 +175,25 @@ class OrderDao {
|
||||
return r.first['c']! as int;
|
||||
}
|
||||
|
||||
/// Stock already consumed by bills that have not yet reached the server.
|
||||
///
|
||||
/// A re-import overwrites stock with the server's figure, which does not know
|
||||
/// about these sales. Replaying them keeps the shelf count honest when the
|
||||
/// catalogue is pulled again mid-shift.
|
||||
Future<Map<String, double>> unsyncedStockCommitments() async {
|
||||
final rows = await _db.rawQuery(
|
||||
'SELECT i.product_id AS pid, SUM(i.quantity) AS q '
|
||||
'FROM ${Tables.orderItems} i '
|
||||
'JOIN ${Tables.orders} o ON o.id = i.order_id '
|
||||
'WHERE o.sync_status = ? GROUP BY i.product_id',
|
||||
[pending],
|
||||
);
|
||||
return {
|
||||
for (final r in rows)
|
||||
r['pid']! as String: (r['q']! as num).toDouble(),
|
||||
};
|
||||
}
|
||||
|
||||
Future<double> salesTotalForDay(DateTime day) async {
|
||||
final r = await _db.rawQuery(
|
||||
'SELECT COALESCE(SUM(total), 0) AS t FROM ${Tables.orders} '
|
||||
@@ -182,19 +252,23 @@ class OrderDao {
|
||||
if (orders.isEmpty) return;
|
||||
|
||||
await _db.transaction((txn) async {
|
||||
final byDate = <String, List<SaleTransaction>>{};
|
||||
// Grouped by cashier as well as day: the archive is what a till is
|
||||
// settled against once the bills themselves are gone.
|
||||
final byDate = <({String date, String cashier}), List<SaleTransaction>>{};
|
||||
for (final o in orders) {
|
||||
byDate.putIfAbsent(businessDateOf(o.createdAt), () => []).add(o);
|
||||
final key = (date: businessDateOf(o.createdAt), cashier: o.cashierName);
|
||||
byDate.putIfAbsent(key, () => []).add(o);
|
||||
}
|
||||
|
||||
for (final entry in byDate.entries) {
|
||||
final date = entry.key;
|
||||
final date = entry.key.date;
|
||||
final cashier = entry.key.cashier;
|
||||
final batchOrders = entry.value;
|
||||
|
||||
final prior = await txn.query(
|
||||
Tables.dayArchive,
|
||||
where: 'business_date = ?',
|
||||
whereArgs: [date],
|
||||
where: 'business_date = ? AND cashier_name = ?',
|
||||
whereArgs: [date, cashier],
|
||||
limit: 1,
|
||||
);
|
||||
final existing = prior.isEmpty ? null : prior.first;
|
||||
@@ -221,6 +295,7 @@ class OrderDao {
|
||||
Tables.dayArchive,
|
||||
{
|
||||
'business_date': date,
|
||||
'cashier_name': cashier,
|
||||
'bill_count':
|
||||
((existing?['bill_count'] as int?) ?? 0) + batchOrders.length,
|
||||
'item_count': ((existing?['item_count'] as num?)?.toDouble() ?? 0) +
|
||||
@@ -267,16 +342,24 @@ class OrderDao {
|
||||
});
|
||||
}
|
||||
|
||||
/// Archived figures for a business day, or null if nothing has synced yet.
|
||||
Future<Map<String, Object?>?> dayArchive(DateTime day) async {
|
||||
final rows = await _db.query(
|
||||
Tables.dayArchive,
|
||||
where: 'business_date = ?',
|
||||
whereArgs: [businessDateOf(day)],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
/// Archived figures for a business day, one row per cashier.
|
||||
///
|
||||
/// Empty when nothing has synced yet. Pass [cashierName] to scope it to a
|
||||
/// single operator; omit it for the whole terminal.
|
||||
Future<List<Map<String, Object?>>> dayArchive(
|
||||
DateTime day, {
|
||||
String? cashierName,
|
||||
}) =>
|
||||
_db.query(
|
||||
Tables.dayArchive,
|
||||
where: cashierName == null
|
||||
? 'business_date = ?'
|
||||
: 'business_date = ? AND cashier_name = ?',
|
||||
whereArgs: [
|
||||
businessDateOf(day),
|
||||
if (cashierName != null) cashierName,
|
||||
],
|
||||
);
|
||||
|
||||
/// Records a failed attempt. The rows stay at `sync_status = 0`.
|
||||
Future<void> markFailed(List<String> orderIds, String error) async {
|
||||
@@ -316,7 +399,7 @@ class OrderDao {
|
||||
cart: _cartFromJson(
|
||||
jsonDecode(r['cart_json']! as String) as Map<String, Object?>,
|
||||
),
|
||||
))
|
||||
),)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -389,6 +472,9 @@ class OrderDao {
|
||||
}).toList();
|
||||
|
||||
final customerId = o['customer_id'] as String?;
|
||||
// Rebuilt with no lifetime spend on purpose: the tier discount this shopper
|
||||
// earned is already included in the recorded `bill_discount`, so giving the
|
||||
// reconstruction a tier would apply it a second time.
|
||||
final customer = customerId == null
|
||||
? null
|
||||
: Customer(
|
||||
@@ -404,18 +490,37 @@ class OrderDao {
|
||||
amount: (p['amount']! as num).toDouble(),
|
||||
tendered: (p['tendered'] as num?)?.toDouble(),
|
||||
reference: p['reference'] as String?,
|
||||
))
|
||||
),)
|
||||
.toList();
|
||||
|
||||
// Bill-level reductions live on the order row, not on the lines, so they
|
||||
// have to be put back explicitly. Without this the rebuilt cart bills at
|
||||
// the undiscounted subtotal and every downstream figure — the upload
|
||||
// payload, the day archive, the shift report — is overstated.
|
||||
final billDiscount = (o['bill_discount']! as num).toDouble();
|
||||
|
||||
return SaleTransaction(
|
||||
id: o['id']! as String,
|
||||
invoiceNumber: o['invoice_number']! as String,
|
||||
cart: Cart(lines: lines, customer: customer),
|
||||
cart: Cart(
|
||||
lines: lines,
|
||||
customer: customer,
|
||||
billDiscount: billDiscount > 0
|
||||
? Discount(
|
||||
type: DiscountType.flat,
|
||||
value: billDiscount,
|
||||
reason: 'Bill discount',
|
||||
)
|
||||
: Discount.none,
|
||||
pointsRedeemed: (o['points_redeemed'] as int?) ?? 0,
|
||||
),
|
||||
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),
|
||||
storedTotal: (o['total']! as num).toDouble(),
|
||||
storedPointsEarned: (o['points_earned'] as int?) ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
75
lib/data/local/sync_log_dao.dart
Normal file
75
lib/data/local/sync_log_dao.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
|
||||
import '../../domain/entities/sync_event.dart';
|
||||
import 'app_database.dart';
|
||||
|
||||
/// Persists the history of this terminal's conversations with the server.
|
||||
///
|
||||
/// Held on disk rather than in memory because it is the only record of a sync
|
||||
/// that survives the bills themselves: once the server accepts an order the row
|
||||
/// is deleted from the terminal, so without this the evidence that it ever went
|
||||
/// up disappears at the next restart.
|
||||
class SyncLogDao {
|
||||
const SyncLogDao(this._db);
|
||||
|
||||
final Database _db;
|
||||
|
||||
Future<void> insert(SyncEvent e) async {
|
||||
await _db.insert(
|
||||
Tables.syncLog,
|
||||
{
|
||||
'id': e.id,
|
||||
'type': e.type.name,
|
||||
'status': e.status.name,
|
||||
'created_at': e.createdAt.millisecondsSinceEpoch,
|
||||
'synced_at': e.syncedAt?.millisecondsSinceEpoch,
|
||||
'summary': e.summary,
|
||||
'error': e.error,
|
||||
'attempts': e.attempts,
|
||||
'payload_json': e.payload.isEmpty ? null : jsonEncode(e.payload),
|
||||
},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
/// Newest first, which is the order the events log renders.
|
||||
Future<List<SyncEvent>> recent({int limit = 200}) async {
|
||||
final rows = await _db.query(
|
||||
Tables.syncLog,
|
||||
orderBy: 'created_at DESC',
|
||||
limit: limit,
|
||||
);
|
||||
return rows.map(_fromRow).toList();
|
||||
}
|
||||
|
||||
/// Keeps the log from growing without bound on a terminal that runs for
|
||||
/// months. Only ever trims the oldest entries.
|
||||
Future<void> trim({int keep = 500}) async {
|
||||
await _db.rawDelete(
|
||||
'DELETE FROM ${Tables.syncLog} WHERE id NOT IN ('
|
||||
'SELECT id FROM ${Tables.syncLog} ORDER BY created_at DESC LIMIT ?)',
|
||||
[keep],
|
||||
);
|
||||
}
|
||||
|
||||
SyncEvent _fromRow(Map<String, Object?> r) {
|
||||
final payload = r['payload_json'] as String?;
|
||||
return SyncEvent(
|
||||
id: r['id']! as String,
|
||||
type: SyncEventType.values.byName(r['type']! as String),
|
||||
status: SyncStatus.values.byName(r['status']! as String),
|
||||
createdAt: DateTime.fromMillisecondsSinceEpoch(r['created_at']! as int),
|
||||
summary: r['summary']! as String,
|
||||
payload: payload == null
|
||||
? const {}
|
||||
: (jsonDecode(payload) as Map).cast<String, Object?>(),
|
||||
syncedAt: r['synced_at'] == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(r['synced_at']! as int),
|
||||
error: r['error'] as String?,
|
||||
attempts: (r['attempts'] as int?) ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,44 +53,26 @@ class CustomerRepositoryImpl implements CustomerRepository {
|
||||
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(),
|
||||
);
|
||||
await _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();
|
||||
|
||||
// Stored numbers are digits only, so the query has to be reduced the same
|
||||
// way — otherwise a cashier typing "98765 43210" or "98-76" matches nothing.
|
||||
final digits = _digits(q);
|
||||
|
||||
return _store.customers.where((c) {
|
||||
if (c.name.toLowerCase().contains(q)) return true;
|
||||
return digits.isNotEmpty && _digits(c.mobile).contains(digits);
|
||||
}).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)));
|
||||
.compareTo(a.lastVisitAt ?? DateTime(2000)),);
|
||||
return list.take(limit).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,9 +20,8 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
|
||||
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 = [];
|
||||
/// Human-readable history of sync attempts, backed by the `sync_log` table.
|
||||
/// Order sync state itself lives on the order rows.
|
||||
|
||||
@override
|
||||
bool get hasCatalogue => _store.hasCatalogue;
|
||||
@@ -34,9 +33,9 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
String? get catalogueRevision => _store.catalogueRevision;
|
||||
|
||||
@override
|
||||
List<SyncEvent> get events => List.unmodifiable(_events.reversed);
|
||||
List<SyncEvent> get events => _store.syncEvents;
|
||||
|
||||
void _log(SyncEvent e) => _events.add(e);
|
||||
Future<void> _log(SyncEvent e) => _store.appendSyncEvent(e);
|
||||
|
||||
// ------------------------------------------------------- Morning: import
|
||||
@override
|
||||
@@ -71,7 +70,7 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
},
|
||||
attempts: 1,
|
||||
);
|
||||
_log(event);
|
||||
await _log(event);
|
||||
return event;
|
||||
} catch (e) {
|
||||
final event = SyncEvent(
|
||||
@@ -83,7 +82,7 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
error: e.toString(),
|
||||
attempts: 1,
|
||||
);
|
||||
_log(event);
|
||||
await _log(event);
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -99,39 +98,45 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
Future<ShiftReport> todayReport({
|
||||
required String terminalId,
|
||||
required String cashierName,
|
||||
bool scopeToCashier = false,
|
||||
}) async {
|
||||
final today = DateTime.now();
|
||||
final scope = scopeToCashier ? cashierName : null;
|
||||
|
||||
// Bills still held locally.
|
||||
final live = ShiftReport.fromTransactions(
|
||||
transactions: await _store.orders.forBusinessDate(today),
|
||||
var report = ShiftReport.fromTransactions(
|
||||
transactions:
|
||||
await _store.orders.forBusinessDate(today, cashierName: scope),
|
||||
businessDate: today,
|
||||
terminalId: terminalId,
|
||||
cashierName: cashierName,
|
||||
);
|
||||
|
||||
// Bills already uploaded and deleted survive only as archived totals.
|
||||
final row = await _store.orders.dayArchive(today);
|
||||
if (row == null) return live;
|
||||
// Bills already uploaded and deleted survive only as archived totals, one
|
||||
// row per cashier. Unscoped, every operator's row folds into the total.
|
||||
final rows = await _store.orders.dayArchive(today, cashierName: scope);
|
||||
|
||||
final payments = (jsonDecode(row['payments_json']! as String)
|
||||
as Map<String, Object?>)
|
||||
.map(
|
||||
(k, v) => MapEntry(
|
||||
PaymentMethod.values.byName(k),
|
||||
(v! as num).toDouble(),
|
||||
),
|
||||
);
|
||||
for (final row in rows) {
|
||||
final payments = (jsonDecode(row['payments_json']! as String)
|
||||
as Map<String, Object?>)
|
||||
.map(
|
||||
(k, v) => MapEntry(
|
||||
PaymentMethod.values.byName(k),
|
||||
(v! as num).toDouble(),
|
||||
),
|
||||
);
|
||||
|
||||
final archived = ShiftReport.fromArchive(
|
||||
row: row,
|
||||
payments: payments,
|
||||
businessDate: today,
|
||||
terminalId: terminalId,
|
||||
cashierName: cashierName,
|
||||
);
|
||||
report = ShiftReport.fromArchive(
|
||||
row: row,
|
||||
payments: payments,
|
||||
businessDate: today,
|
||||
terminalId: terminalId,
|
||||
cashierName: cashierName,
|
||||
) +
|
||||
report;
|
||||
}
|
||||
|
||||
return archived + live;
|
||||
return report;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -150,7 +155,7 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
: DateTime.fromMillisecondsSinceEpoch(r['synced_at']! as int),
|
||||
attempts: (r['sync_attempts'] as int?) ?? 0,
|
||||
error: r['sync_error'] as String?,
|
||||
))
|
||||
),)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -161,71 +166,99 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
}) async {
|
||||
onProgress?.call(0.05, 'Collecting unsynced bills…');
|
||||
|
||||
final pending = await _store.orders.unsynced();
|
||||
if (pending.isEmpty) {
|
||||
final started = DateTime.now();
|
||||
final total = await _store.orders.unsyncedCount();
|
||||
|
||||
if (total == 0) {
|
||||
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();
|
||||
var attempted = 0;
|
||||
var uploaded = 0;
|
||||
final syncedInvoices = <String>[];
|
||||
|
||||
onProgress?.call(0.35, 'Uploading ${pending.length} bills…');
|
||||
// `unsynced()` returns a bounded page. Draining it in a loop means a day
|
||||
// with more bills than one page still uploads completely, instead of
|
||||
// reporting success with the remainder silently left behind.
|
||||
while (true) {
|
||||
final batch = await _store.orders.unsynced();
|
||||
if (batch.isEmpty) break;
|
||||
|
||||
try {
|
||||
final accepted = await _orderSink.pushOrders(
|
||||
pending.map(_orderToPayload).toList(),
|
||||
final ids = batch.map((o) => o.id).toList();
|
||||
attempted += batch.length;
|
||||
|
||||
onProgress?.call(
|
||||
(attempted / total).clamp(0.05, 0.9),
|
||||
'Uploading $attempted of $total bills…',
|
||||
);
|
||||
|
||||
onProgress?.call(0.85, 'Clearing uploaded bills from this terminal…');
|
||||
try {
|
||||
final accepted = await _orderSink.pushOrders(
|
||||
batch.map(_orderToPayload).toList(),
|
||||
);
|
||||
|
||||
// Only what the server confirmed is archived and removed. Anything it
|
||||
// did not acknowledge stays on disk.
|
||||
final acceptedOrders =
|
||||
pending.where((o) => accepted.contains(o.id)).toList();
|
||||
await _store.orders.archiveAndDelete(acceptedOrders);
|
||||
await _store.refreshUnsyncedCount();
|
||||
// Only what the server confirmed is archived and removed. Anything it
|
||||
// did not acknowledge stays on disk.
|
||||
final acceptedOrders =
|
||||
batch.where((o) => accepted.contains(o.id)).toList();
|
||||
await _store.orders.archiveAndDelete(acceptedOrders);
|
||||
await _store.refreshUnsyncedCount();
|
||||
|
||||
final rejected = ids.where((id) => !accepted.contains(id)).toList();
|
||||
if (rejected.isNotEmpty) {
|
||||
await _store.orders.markFailed(rejected, 'Rejected by server');
|
||||
uploaded += acceptedOrders.length;
|
||||
syncedInvoices.addAll(acceptedOrders.map((o) => o.invoiceNumber));
|
||||
|
||||
final rejected = ids.where((id) => !accepted.contains(id)).toList();
|
||||
if (rejected.isNotEmpty) {
|
||||
await _store.orders.markFailed(rejected, 'Rejected by server');
|
||||
// Rejected rows stay pending, so the next page would return the same
|
||||
// bills forever. Stop and let the cashier retry.
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
// Transport failed: record the attempt but leave every row at 0.
|
||||
await _store.orders.markFailed(ids, e.toString());
|
||||
await _store.refreshUnsyncedCount();
|
||||
|
||||
final remaining = await _store.orders.unsyncedCount();
|
||||
final pendingValue =
|
||||
batch.fold<double>(0, (s, o) => s + o.total);
|
||||
|
||||
await _log(SyncEvent(
|
||||
id: _uuid.v4(),
|
||||
type: SyncEventType.shiftReport,
|
||||
status: SyncStatus.failed,
|
||||
createdAt: started,
|
||||
summary: '$remaining bills still pending '
|
||||
'(${Formatters.money(pendingValue)})',
|
||||
error: e.toString(),
|
||||
attempts: 1,
|
||||
),);
|
||||
|
||||
return SyncOutcome(
|
||||
attempted: attempted,
|
||||
uploaded: uploaded,
|
||||
error: e.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
onProgress?.call(1, 'Done');
|
||||
|
||||
_log(SyncEvent(
|
||||
id: _uuid.v4(),
|
||||
type: SyncEventType.shiftReport,
|
||||
status: SyncStatus.synced,
|
||||
createdAt: started,
|
||||
syncedAt: DateTime.now(),
|
||||
summary: '${accepted.length} of ${pending.length} bills uploaded',
|
||||
attempts: 1,
|
||||
));
|
||||
|
||||
return SyncOutcome(attempted: pending.length, uploaded: accepted.length);
|
||||
} catch (e) {
|
||||
// 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(),
|
||||
);
|
||||
}
|
||||
|
||||
onProgress?.call(1, 'Done');
|
||||
|
||||
// Synced bills are deleted from the terminal, so this log line is the only
|
||||
// remaining record on the device that they went up.
|
||||
await _log(SyncEvent(
|
||||
id: _uuid.v4(),
|
||||
type: SyncEventType.shiftReport,
|
||||
status: SyncStatus.synced,
|
||||
createdAt: started,
|
||||
syncedAt: DateTime.now(),
|
||||
summary: '$uploaded of $attempted bills uploaded',
|
||||
payload: {'invoices': syncedInvoices},
|
||||
attempts: 1,
|
||||
),);
|
||||
|
||||
return SyncOutcome(attempted: attempted, uploaded: uploaded);
|
||||
}
|
||||
|
||||
/// The JSON body sent per order.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/transaction.dart';
|
||||
import '../../domain/repositories/transaction_repository.dart';
|
||||
import '../datasources/local_store.dart';
|
||||
import '../local/catalogue_dao.dart';
|
||||
|
||||
/// All bill persistence goes straight to SQLite.
|
||||
class TransactionRepositoryImpl implements TransactionRepository {
|
||||
@@ -9,11 +11,23 @@ class TransactionRepositoryImpl implements TransactionRepository {
|
||||
final LocalStore _store;
|
||||
|
||||
@override
|
||||
Future<SaleTransaction> save(SaleTransaction transaction) async {
|
||||
// Written with sync_status = 0; the end-of-day upload picks it up.
|
||||
await _store.orders.insertOrder(transaction);
|
||||
Future<void> commitSale({
|
||||
required SaleTransaction transaction,
|
||||
required Map<String, double> stockMovements,
|
||||
Customer? updatedCustomer,
|
||||
}) async {
|
||||
await _store.orders.commitSale(
|
||||
transaction: transaction,
|
||||
stockMovements: stockMovements,
|
||||
customerRow: updatedCustomer == null
|
||||
? null
|
||||
: CatalogueDao.customerToRow(updatedCustomer),
|
||||
);
|
||||
|
||||
// Disk is committed; bring the read caches in line with it.
|
||||
_store.cacheStockMovement(stockMovements);
|
||||
if (updatedCustomer != null) _store.cacheCustomer(updatedCustomer);
|
||||
await _store.refreshUnsyncedCount();
|
||||
return transaction;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
Reference in New Issue
Block a user