Two defects that share a shape: a figure landing on the wrong record.
Bill-level discounts were apportioned across every line by a single
factor, so "20% off Beverages" pulled tax out of the atta line as well.
The bill total was right either way, which is what made it easy to ship
— only the slab split on a filed return was wrong. Targeted campaigns
now reduce the lines they name, and bill-wide reductions still spread
pro rata, so the arithmetic is unchanged wherever it was already right.
Shoppers registered at a till only ever reached the back office as three
fields riding along on a bill. Somebody who signed up and bought nothing
existed on one terminal and nowhere else, and two tills registering the
same mobile each minted their own row. Customers are now an outbox of
their own on pos/{store}/{terminal}/customer, and the id is a UUIDv5
over the normalised mobile number — so a hundred terminals agree on who
a shopper is without talking to each other.
Registrations go up before bills, and a failure there cannot strand a
day's takings. No loyalty figures are sent: they belong to the bill
stream, which is idempotent and knows about every counter.
Two things found while building it. Numbers were keyed on raw digits, so
a cashier typing +91 forked a shopper as effectively as a random id
would. And the sale path wrote the customer with ConflictAlgorithm
.replace, which is a DELETE and an INSERT — every column absent from the
row reverts to its schema default, so the new sync flag would have been
cleared by the shopper's next purchase.
Schema v8. Existing customers are queued rather than assumed sent: the
terminal cannot tell an imported row from a locally registered one, and
only one of those mistakes loses somebody.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
242 lines
9.3 KiB
Dart
242 lines
9.3 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'});
|
|
|
|
// A shopper registered before the customer outbox existed. Whether they
|
|
// reach the back office at all depends on what v8 does with this row.
|
|
await db.insert('customers', {
|
|
'id': 'legacy-customer-1',
|
|
'name': 'Meena',
|
|
'mobile': '9840011111',
|
|
'loyalty_points': 40,
|
|
'lifetime_spend': 2400.0,
|
|
'visit_count': 3,
|
|
'created_at': 1000,
|
|
});
|
|
|
|
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(), 8);
|
|
|
|
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',);
|
|
|
|
// v5 adds staff. An upgraded terminal must come up with the table present
|
|
// but empty — seeding is the store's job on first open, not the migration's,
|
|
// so an existing shop is never handed accounts it did not create.
|
|
final staff = await db.query('staff');
|
|
expect(staff, isEmpty);
|
|
|
|
// v6 adds campaigns. Same rule: the table exists, and an upgraded shop is
|
|
// not handed promotions it never created.
|
|
final promos = await db.query('promos');
|
|
expect(promos, isEmpty);
|
|
|
|
// v8 turns customers into an outbox. Every existing shopper is queued
|
|
// rather than assumed sent: the terminal cannot tell which rows came down
|
|
// in a catalogue pull and which were registered at the till, and only one
|
|
// of those two mistakes loses somebody. Re-sending is safe because the
|
|
// uplink is insert-if-absent on id.
|
|
final customer = (await db.query('customers')).single;
|
|
expect(customer['sync_status'], 0);
|
|
expect(customer['synced_at'], isNull);
|
|
|
|
// …and their loyalty standing survives the migration untouched.
|
|
expect(customer['loyalty_points'], 40);
|
|
expect(customer['lifetime_spend'], 2400.0);
|
|
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',);
|
|
});
|
|
}
|