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:
Suriya
2026-07-31 18:34:10 +05:30
parent 9891a69a5f
commit af3933092f
62 changed files with 2035 additions and 561 deletions

View File

@@ -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)
)
''';

View File

@@ -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;
});
}
}

View File

@@ -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,
);
}

View 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,
);
}
}