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

@@ -0,0 +1,169 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/core/services/barcode_service.dart';
/// The scanner is a keyboard, so the only thing separating a scan from the
/// cashier typing is timing. These drive the handler with a controlled clock
/// rather than real delays, so the boundary is exact.
void main() {
late List<String> scans;
late int manualKeys;
late DateTime now;
late bool editingText;
setUp(() {
scans = [];
manualKeys = 0;
now = DateTime(2026, 7, 31, 10);
editingText = false;
});
BarcodeService build() => BarcodeService(
onScan: scans.add,
onManualKey: () => manualKeys++,
clock: () => now,
isEditingText: () => editingText,
);
KeyEvent char(String c) => KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyA,
logicalKey: LogicalKeyboardKey.keyA,
character: c,
timeStamp: Duration.zero,
);
KeyEvent enterKey() => const KeyDownEvent(
physicalKey: PhysicalKeyboardKey.enter,
logicalKey: LogicalKeyboardKey.enter,
timeStamp: Duration.zero,
);
/// Feeds [text] with a fixed gap between keystrokes, returning which
/// keystrokes the service swallowed.
List<bool> type(
BarcodeService service,
String text, {
required int gapMs,
}) {
return [
for (final c in text.split('')) ...[
() {
now = now.add(Duration(milliseconds: gapMs));
return service.handleKey(char(c));
}(),
],
];
}
group('scanner input', () {
test('a fast burst terminated by Enter is billed as a scan', () {
final service = build();
type(service, '8901234500011', gapMs: 5);
now = now.add(const Duration(milliseconds: 5));
final enterConsumed = service.handleKey(enterKey());
expect(scans, ['8901234500011']);
expect(enterConsumed, isTrue,
reason: 'the scanner terminator must not reach the focused field',);
expect(manualKeys, 0);
});
test('the burst is swallowed so it cannot also land in a text field', () {
final service = build();
final consumed = type(service, '8901234500011', gapMs: 5);
// The first keystroke cannot be judged yet — nothing has arrived to
// measure a gap against — so exactly one character escapes. Everything
// after it is recognised as machine-paced and consumed.
expect(consumed.first, isFalse);
expect(consumed.skip(1), everyElement(isTrue));
});
test('a scanner that sends no Enter still flushes on idle', () async {
final service = build();
type(service, '8901234500011', gapMs: 5);
expect(scans, isEmpty, reason: 'nothing has flushed yet');
await Future<void>.delayed(const Duration(milliseconds: 300));
expect(scans, ['8901234500011']);
});
});
group('human input', () {
test('typing at human speed is never treated as a scan', () {
final service = build();
final consumed = type(service, '9876543210', gapMs: 200);
now = now.add(const Duration(milliseconds: 200));
final enterConsumed = service.handleKey(enterKey());
expect(scans, isEmpty);
expect(consumed, everyElement(isFalse),
reason: 'hand-typed characters must reach the field',);
expect(enterConsumed, isFalse,
reason: 'swallowing Enter would break form submission',);
});
test('a fast typist in a text field does not trigger a phantom scan', () {
editingText = true;
final service = build();
// ~100ms per character is a quick typist and used to clear the bar.
type(service, '9876543210', gapMs: 100);
now = now.add(const Duration(milliseconds: 100));
final enterConsumed = service.handleKey(enterKey());
expect(scans, isEmpty,
reason: 'entering a mobile number must not jump to billing',);
expect(enterConsumed, isFalse);
});
test('the same speed does count as a scan when no field has focus', () {
editingText = false;
final service = build();
type(service, '9876543210', gapMs: 100);
now = now.add(const Duration(milliseconds: 100));
service.handleKey(enterKey());
expect(scans, ['9876543210']);
});
test('a pause mid-burst starts a new entry', () {
final service = build();
type(service, '890123', gapMs: 5);
now = now.add(const Duration(milliseconds: 500)); // cashier hesitates
type(service, '4500011', gapMs: 5);
now = now.add(const Duration(milliseconds: 5));
service.handleKey(enterKey());
expect(scans, ['4500011'],
reason: 'only the characters after the pause form the code',);
});
});
group('rejected input', () {
test('a buffer shorter than a barcode is reported as manual input', () {
final service = build();
type(service, 'abc', gapMs: 5);
now = now.add(const Duration(milliseconds: 5));
final enterConsumed = service.handleKey(enterKey());
expect(scans, isEmpty);
expect(manualKeys, 1);
expect(enterConsumed, isFalse);
});
test('non-alphanumeric characters are ignored entirely', () {
final service = build();
now = now.add(const Duration(milliseconds: 5));
expect(service.handleKey(char(r'$')), isFalse);
expect(scans, isEmpty);
});
});
}

View File

@@ -15,7 +15,7 @@ const _item = Product(
gstRate: 0.18,
);
Customer _silver() => Customer(
Customer _silver() => const Customer(
id: 'cust-1',
name: 'Silver Shopper',
mobile: '9876543210',
@@ -169,10 +169,10 @@ void main() {
const cart = Cart(lines: [
CartLine(product: _item, quantity: 1),
CartLine(product: zeroRated, quantity: 1),
]);
],);
final breakdown = cart.taxBreakdown;
expect(breakdown.keys, containsAll<double>([0.18, 0.0]));
expect(breakdown.keys, containsAll([0.18, 0.0]));
expect(breakdown[0.0], 0);
expect(breakdown[0.18]!, greaterThan(0));
});

View File

@@ -1,5 +1,6 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/data/datasources/local_store.dart';
import 'package:nearle_pos/data/datasources/seed_data.dart';
import 'package:nearle_pos/data/repositories/customer_repository_impl.dart';
import 'package:nearle_pos/data/repositories/product_repository_impl.dart';
import 'package:nearle_pos/data/repositories/transaction_repository_impl.dart';
@@ -15,10 +16,19 @@ void main() {
late TransactionRepositoryImpl transactions;
late CheckoutSale checkout;
setUpAll(() {
// The store only reaches for demo rows through these hooks, so the seed has
// to be registered before any test asks for a catalogue.
LocalStore.registerSeed(
products: SeedData.products,
customers: SeedData.customers,
);
});
setUp(() async {
store = LocalStore.instance;
// Fresh seed for every test so stock and invoice sequence never leak.
await store.reset();
await store.reset(withCatalogue: true);
products = ProductRepositoryImpl(store);
customers = CustomerRepositoryImpl(store);

View File

@@ -0,0 +1,204 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/data/local/app_database.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
/// A terminal already in the field is running the v3 schema. Upgrading it must
/// carry the day's archived takings across rather than dropping them, so this
/// builds a genuine v3 database and opens it with the current code.
void main() {
late Directory dir;
late String dbPath;
setUpAll(sqfliteFfiInit);
setUp(() async {
dir = await Directory.systemTemp.createTemp('nearle_migration');
dbPath = '${dir.path}/nearle_pos.db';
databaseFactory = databaseFactoryFfi;
});
tearDown(() async {
await AppDatabase.instance.close();
if (dir.existsSync()) dir.deleteSync(recursive: true);
});
/// The schema exactly as v3 shipped it.
Future<void> createV3Database() async {
final db = await databaseFactory.openDatabase(
dbPath,
options: OpenDatabaseOptions(
version: 3,
onCreate: (db, _) async {
await db.execute('''
CREATE TABLE 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, hsn_code TEXT, brand TEXT,
is_active INTEGER NOT NULL DEFAULT 1, updated_at INTEGER NOT NULL)
''');
await db.execute('''
CREATE TABLE 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 TABLE 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',
sync_status INTEGER NOT NULL DEFAULT 0, synced_at INTEGER,
sync_attempts INTEGER NOT NULL DEFAULT 0, sync_error TEXT)
''');
await db.execute('''
CREATE TABLE order_items (
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 orders(id) ON DELETE CASCADE)
''');
await db.execute('''
CREATE TABLE parked_bills (
id TEXT PRIMARY KEY, label TEXT, parked_at INTEGER NOT NULL,
cart_json TEXT NOT NULL)
''');
// v3 sync_log: no payload column.
await db.execute('''
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)
''');
// v3 day_archive: keyed by date alone, no cashier.
await db.execute('''
CREATE TABLE day_archive (
business_date TEXT PRIMARY KEY,
bill_count INTEGER NOT NULL DEFAULT 0,
item_count REAL NOT NULL DEFAULT 0,
gross_sales REAL NOT NULL DEFAULT 0,
tax_collected REAL NOT NULL DEFAULT 0,
discount_given REAL NOT NULL DEFAULT 0,
round_off REAL NOT NULL DEFAULT 0,
points_issued INTEGER NOT NULL DEFAULT 0,
points_redeemed INTEGER NOT NULL DEFAULT 0,
payments_json TEXT NOT NULL DEFAULT '{}',
first_bill_at INTEGER, last_bill_at INTEGER,
synced_bills INTEGER NOT NULL DEFAULT 0)
''');
await db.execute(
'CREATE TABLE app_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)',
);
},
),
);
await db.insert('day_archive', {
'business_date': '2026-07-30',
'bill_count': 12,
'item_count': 40.0,
'gross_sales': 8450.0,
'tax_collected': 620.5,
'discount_given': 130.0,
'round_off': 1.5,
'points_issued': 84,
'points_redeemed': 20,
'payments_json': '{"cash":5000.0,"upi":3450.0}',
'first_bill_at': 1000,
'last_bill_at': 2000,
'synced_bills': 12,
});
await db.insert('app_meta', {'key': 'invoice_sequence', 'value': '12'});
await db.close();
}
test('a v3 terminal upgrades without losing its archived takings', () async {
await createV3Database();
await AppDatabase.instance.open(overridePath: dbPath);
final db = AppDatabase.instance.db;
expect(await db.getVersion(), 4);
final rows = await db.query('day_archive');
expect(rows, hasLength(1));
final row = rows.single;
expect(row['business_date'], '2026-07-30');
expect(row['cashier_name'], '',
reason: 'rows from before per-cashier attribution get an empty name',);
expect(row['bill_count'], 12);
expect(row['gross_sales'], 8450.0);
expect(row['tax_collected'], 620.5);
expect(row['payments_json'], '{"cash":5000.0,"upi":3450.0}');
expect(row['synced_bills'], 12);
// Unrelated state must be untouched by the migration.
final meta = await db.query('app_meta', where: "key = 'invoice_sequence'");
expect(meta.single['value'], '12');
});
test('the upgraded sync log accepts a payload', () async {
await createV3Database();
await AppDatabase.instance.open(overridePath: dbPath);
final db = AppDatabase.instance.db;
await db.insert('sync_log', {
'id': 'e1',
'type': 'shiftReport',
'status': 'synced',
'created_at': 1,
'summary': '3 bills uploaded',
'attempts': 1,
'payload_json': '{"invoices":["INV-1"]}',
});
final row = (await db.query('sync_log')).single;
expect(row['payload_json'], '{"invoices":["INV-1"]}');
});
test('the day archive now holds one row per cashier', () async {
await createV3Database();
await AppDatabase.instance.open(overridePath: dbPath);
final db = AppDatabase.instance.db;
for (final cashier in ['Divya', 'Rahul']) {
await db.insert('day_archive', {
'business_date': '2026-07-31',
'cashier_name': cashier,
'bill_count': 1,
'gross_sales': 100.0,
'payments_json': '{}',
});
}
final rows = await db.query(
'day_archive',
where: 'business_date = ?',
whereArgs: ['2026-07-31'],
);
expect(rows, hasLength(2),
reason: 'two cashiers on the same day must not collide',);
});
}

View File

@@ -0,0 +1,463 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/data/datasources/local_store.dart';
import 'package:nearle_pos/data/datasources/remote_catalogue_source.dart';
import 'package:nearle_pos/data/datasources/seed_data.dart';
import 'package:nearle_pos/data/repositories/customer_repository_impl.dart';
import 'package:nearle_pos/data/repositories/product_repository_impl.dart';
import 'package:nearle_pos/data/repositories/sync_repository_impl.dart';
import 'package:nearle_pos/data/repositories/transaction_repository_impl.dart';
import 'package:nearle_pos/domain/entities/cart.dart';
import 'package:nearle_pos/domain/entities/customer.dart';
import 'package:nearle_pos/domain/entities/shift_report.dart';
import 'package:nearle_pos/domain/entities/sync_event.dart';
import 'package:nearle_pos/domain/entities/transaction.dart';
import 'package:nearle_pos/domain/usecases/checkout_sale.dart';
/// Guards the boundary between a live bill and a stored one.
///
/// Every figure a shop is paid on survives a write to SQLite and a read back
/// out of it. These are regressions: the read path used to rebuild a bill from
/// its lines alone, silently dropping bill-level discounts and loyalty.
void main() {
late LocalStore store;
late ProductRepositoryImpl products;
late CustomerRepositoryImpl customers;
late TransactionRepositoryImpl transactions;
late CheckoutSale checkout;
setUpAll(() {
LocalStore.registerSeed(
products: SeedData.products,
customers: SeedData.customers,
);
});
setUp(() async {
store = LocalStore.instance;
await store.reset(withCatalogue: true);
products = ProductRepositoryImpl(store);
customers = CustomerRepositoryImpl(store);
transactions = TransactionRepositoryImpl(store);
checkout = CheckoutSale(
productRepository: products,
customerRepository: customers,
transactionRepository: transactions,
);
});
/// A Gold member (5% tier discount) holding 400 points.
Future<Customer> goldMember() async {
final created = await customers.create(const Customer(
id: 'ignored',
name: 'Gold Shopper',
mobile: '9000000001',
),);
return customers.update(
created.copyWith(loyaltyPoints: 400, lifetimeSpend: 60000),
);
}
group('order round trip', () {
test('bill discount, loyalty and total survive a write and read back',
() async {
final milk = (await products.findByBarcode('8901234500011'))!;
final member = await goldMember();
// 10 x 62.00 = 620 subtotal, less 5% tier (31) and a flat 50 = 81,
// less 40 points at 0.25 = 10. Payable 529.
final cart = Cart(
lines: [CartLine(product: milk, quantity: 10)],
customer: member,
billDiscount: const Discount(type: DiscountType.flat, value: 50),
pointsRedeemed: 40,
);
expect(cart.grandTotal, 529);
expect(cart.billDiscountTotal, 81);
final result = await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 529, tendered: 529),
],
cashierName: 'Divya',
);
final stored = (await transactions.history()).single;
expect(stored.total, result.transaction.total,
reason: 'the figure charged must not move in storage',);
expect(stored.total, 529);
expect(stored.cart.billDiscountTotal, 81);
expect(stored.cart.loyaltyRedemptionValue, 10);
expect(stored.cart.pointsRedeemed, 40);
expect(stored.cart.taxAmount, cart.taxAmount);
expect(stored.cart.subtotal, 620);
});
test('a rebuilt bill does not re-apply the tier discount', () async {
final milk = (await products.findByBarcode('8901234500011'))!;
final member = await goldMember();
final cart = Cart(
lines: [CartLine(product: milk, quantity: 10)],
customer: member,
);
// 620 less the 5% tier discount only.
expect(cart.grandTotal, 589);
await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 589, tendered: 600),
],
cashierName: 'Divya',
);
final stored = (await transactions.history()).single;
expect(stored.cart.billDiscountTotal, 31);
expect(stored.total, 589);
});
test('the shift report reads back the amount actually charged', () async {
final milk = (await products.findByBarcode('8901234500011'))!;
final member = await goldMember();
await checkout(
cart: Cart(
lines: [CartLine(product: milk, quantity: 10)],
customer: member,
billDiscount: const Discount(type: DiscountType.flat, value: 50),
pointsRedeemed: 40,
),
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 529, tendered: 529),
],
cashierName: 'Divya',
);
final report = ShiftReport.fromTransactions(
transactions: await transactions.history(),
businessDate: DateTime.now(),
terminalId: 'TERM-01',
cashierName: 'Divya',
);
expect(report.grossSales, 529);
expect(report.discountGiven, 81);
expect(report.loyaltyPointsRedeemed, 40);
});
test('the bill is stamped with the operator who rang it', () async {
final milk = (await products.findByBarcode('8901234500011'))!;
await checkout(
cart: Cart(lines: [CartLine(product: milk, quantity: 1)]),
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 62, tendered: 100),
],
cashierName: 'Rahul',
terminalId: 'TERM-07',
);
final stored = (await transactions.history()).single;
expect(stored.cashierName, 'Rahul');
expect(stored.terminalId, 'TERM-07');
});
});
group('stock safety', () {
test('a resumed parked bill is re-checked against live stock', () async {
final milk = (await products.findByBarcode('8901234500011'))!;
await transactions.park(ParkedBill(
id: 'p-1',
cart: Cart(lines: [CartLine(product: milk, quantity: milk.stock)]),
parkedAt: DateTime.now(),
),);
// The same stock is sold on another bill in the meantime.
await products.decrementStock({milk.id: milk.stock});
final resumed = (await transactions.parkedBills()).single;
await expectLater(
checkout(
cart: resumed.cart,
payments: [
PaymentSplit(
method: PaymentMethod.cash,
amount: resumed.cart.grandTotal,
tendered: resumed.cart.grandTotal,
),
],
cashierName: 'Divya',
),
throwsA(isA<CheckoutFailure>()),
);
expect(await transactions.history(), isEmpty);
});
test('a re-import does not restore stock already sold', () async {
final milk = (await products.findByBarcode('8901234500011'))!;
final opening = milk.stock;
await checkout(
cart: Cart(lines: [CartLine(product: milk, quantity: 4)]),
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 248, tendered: 250),
],
cashierName: 'Divya',
);
expect((await products.findByBarcode('8901234500011'))!.stock,
opening - 4,);
// The morning catalogue is pulled again before the bills went up.
await store.importCatalogue(
products: SeedData.products(),
customers: SeedData.customers(),
revision: 'seed-2',
at: DateTime.now(),
);
expect(
(await products.findByBarcode('8901234500011'))!.stock,
opening - 4,
reason: 'units sold on unsynced bills must not reappear on the shelf',
);
});
});
group('atomicity', () {
test('nothing is persisted when the sale cannot be completed', () async {
final milk = (await products.findByBarcode('8901234500011'))!;
final opening = milk.stock;
// A customer that was never written to the database.
const ghost = Customer(id: 'missing', name: 'Ghost', mobile: '9999999999');
await expectLater(
checkout(
cart: Cart(
lines: [CartLine(product: milk, quantity: 2)],
customer: ghost,
),
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 124),
],
cashierName: 'Divya',
),
throwsA(isA<CheckoutFailure>()),
);
expect(await transactions.history(), isEmpty,
reason: 'a failed sale must not leave a bill behind',);
expect((await products.findByBarcode('8901234500011'))!.stock, opening,
reason: 'a failed sale must not consume stock',);
});
test('concurrent checkouts never share an invoice sequence', () async {
final numbers = await Future.wait(
List.generate(25, (_) => transactions.nextInvoiceSequence()),
);
expect(numbers.toSet().length, numbers.length);
});
});
group('end of day', () {
test('the archived day totals match what was charged', () async {
final sync = SyncRepositoryImpl(
store,
RemoteCatalogueSource(isOffline: () => false),
RemoteOrderSink(isOffline: () => false),
);
final milk = (await products.findByBarcode('8901234500011'))!;
final member = await goldMember();
await checkout(
cart: Cart(
lines: [CartLine(product: milk, quantity: 10)],
customer: member,
billDiscount: const Discount(type: DiscountType.flat, value: 50),
pointsRedeemed: 40,
),
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 529, tendered: 529),
],
cashierName: 'Divya',
);
final outcome = await sync.syncOrders();
expect(outcome.uploaded, 1);
expect(await sync.unsyncedCount(), 0);
// Synced bills are deleted, so today's figures now come from the archive.
// A wrong row here is permanent — there is nothing left to recompute from.
final report = await sync.todayReport(
terminalId: 'TERM-01',
cashierName: 'Divya',
);
expect(report.billCount, 1);
expect(report.grossSales, 529);
expect(report.discountGiven, 81);
expect(report.loyaltyPointsRedeemed, 40);
expect(report.paymentBreakdown[PaymentMethod.cash], 529);
});
});
group('sync log', () {
test('survives a restart, because it outlives the bills it describes',
() async {
final sync = SyncRepositoryImpl(
store,
RemoteCatalogueSource(isOffline: () => false),
RemoteOrderSink(isOffline: () => false),
);
final milk = (await products.findByBarcode('8901234500011'))!;
await checkout(
cart: Cart(lines: [CartLine(product: milk, quantity: 1)]),
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 62, tendered: 62),
],
cashierName: 'Divya',
);
await sync.syncOrders();
expect(sync.events, isNotEmpty);
final summary = sync.events.first.summary;
// The cache is dropped and rebuilt from disk, as it is on a cold start.
await store.hydrate();
expect(sync.events, isNotEmpty,
reason: 'the only record that those bills went up must persist',);
expect(sync.events.first.summary, summary);
expect(sync.events.first.payload['invoices'], isNotEmpty);
});
test('a failed import is recorded with its error', () async {
final sync = SyncRepositoryImpl(
store,
RemoteCatalogueSource(isOffline: () => true),
RemoteOrderSink(isOffline: () => true),
);
await sync.importCatalogue();
await store.hydrate();
expect(sync.events.first.status, SyncStatus.failed);
expect(sync.events.first.error, isNotNull);
});
});
group('shift report scoping', () {
Future<void> sell(String cashier, double qty) async {
final milk = (await products.findByBarcode('8901234500011'))!;
final due = Cart(lines: [CartLine(product: milk, quantity: qty)]).grandTotal;
await checkout(
cart: Cart(lines: [CartLine(product: milk, quantity: qty)]),
payments: [
PaymentSplit(method: PaymentMethod.cash, amount: due, tendered: due),
],
cashierName: cashier,
);
}
test('a cashier settles their own till, not the terminal', () async {
final sync = SyncRepositoryImpl(
store,
RemoteCatalogueSource(isOffline: () => false),
RemoteOrderSink(isOffline: () => false),
);
await sell('Divya', 2); // 124
await sell('Rahul', 3); // 186
final divya = await sync.todayReport(
terminalId: 'TERM-01',
cashierName: 'Divya',
scopeToCashier: true,
);
final terminal = await sync.todayReport(
terminalId: 'TERM-01',
cashierName: 'Divya',
);
expect(divya.billCount, 1);
expect(divya.grossSales, 124);
expect(terminal.billCount, 2);
expect(terminal.grossSales, 310);
});
test('scoping holds after the bills are uploaded and deleted', () async {
final sync = SyncRepositoryImpl(
store,
RemoteCatalogueSource(isOffline: () => false),
RemoteOrderSink(isOffline: () => false),
);
await sell('Divya', 2);
await sell('Rahul', 3);
await sync.syncOrders();
expect(await sync.unsyncedCount(), 0);
final divya = await sync.todayReport(
terminalId: 'TERM-01',
cashierName: 'Divya',
scopeToCashier: true,
);
final terminal = await sync.todayReport(
terminalId: 'TERM-01',
cashierName: 'Divya',
);
expect(divya.grossSales, 124,
reason: 'the archive must keep each cashier separable',);
expect(divya.billCount, 1);
expect(terminal.grossSales, 310);
expect(terminal.billCount, 2);
});
});
group('customer lookup', () {
test('a mobile number matches however the cashier punctuates it', () async {
await customers.create(const Customer(
id: 'ignored',
name: 'Punctuation Test',
mobile: '9000000042',
),);
for (final query in ['9000000042', '90000 00042', '90-000-00042']) {
expect(
(await customers.search(query)).map((c) => c.name),
contains('Punctuation Test'),
reason: 'searching "$query" should find the customer',
);
}
});
});
group('tax invoice', () {
test('the slab breakdown sums to the GST charged', () async {
// Two different slabs plus a bill discount, so apportioning is in play.
final milk = (await products.findByBarcode('8901234500011'))!; // 5%
final all = await products.getAll();
final eighteen = all.firstWhere((p) => p.gstRate == 0.18);
final cart = Cart(
lines: [
CartLine(product: milk, quantity: 3),
CartLine(product: eighteen, quantity: 7),
],
billDiscount: const Discount(type: DiscountType.percentage, value: 13),
);
final summed = cart.taxBreakdown.values.fold(0.0, (a, b) => a + b);
expect(summed, closeTo(cart.taxAmount, 0.0001));
});
});
}