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>
205 lines
7.8 KiB
Dart
205 lines
7.8 KiB
Dart
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',);
|
|
});
|
|
}
|