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:
@@ -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