Files
nearle_pos/test/unit/cart_test.dart
Suriya af3933092f 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>
2026-07-31 18:34:10 +05:30

249 lines
7.4 KiB
Dart

import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/domain/entities/cart.dart';
import 'package:nearle_pos/domain/entities/customer.dart';
import 'package:nearle_pos/domain/entities/product.dart';
/// Plain 18% GST item priced at a round number so expected values stay exact.
const _item = Product(
id: 'test-1',
name: 'Test Item',
barcode: '8900000000001',
sku: 'TST-001',
category: ProductCategory.grocery,
price: 100,
stock: 50,
gstRate: 0.18,
);
Customer _silver() => const Customer(
id: 'cust-1',
name: 'Silver Shopper',
mobile: '9876543210',
loyaltyPoints: 320,
// Above the 10,000 silver threshold, below the 50,000 gold one.
lifetimeSpend: 24500,
);
void main() {
group('Discount', () {
test('percentage resolves against the base', () {
const d = Discount(type: DiscountType.percentage, value: 10);
expect(d.amountOn(200), 20);
});
test('flat discount never exceeds the base', () {
const d = Discount(type: DiscountType.flat, value: 500);
expect(d.amountOn(200), 200);
});
test('none is inactive and worth nothing', () {
expect(Discount.none.isActive, isFalse);
expect(Discount.none.amountOn(200), 0);
});
});
group('CartLine', () {
test('splits GST out of a tax-inclusive price', () {
const line = CartLine(product: _item, quantity: 2);
expect(line.grossAmount, 200);
expect(line.payable, 200);
// 200 / 1.18 = 169.4915... -> 169.49
expect(line.taxableValue, 169.49);
expect(line.taxAmount, 30.51);
expect(line.cgst + line.sgst, closeTo(line.taxAmount, 0.01));
});
test('line discount reduces the payable', () {
const line = CartLine(
product: _item,
quantity: 2,
discount: Discount(type: DiscountType.percentage, value: 10),
);
expect(line.discountAmount, 20);
expect(line.payable, 180);
});
test('flags a quantity beyond available stock', () {
const ok = CartLine(product: _item, quantity: 50);
const over = CartLine(product: _item, quantity: 51);
expect(ok.exceedsStock, isFalse);
expect(over.exceedsStock, isTrue);
});
});
group('Cart totals', () {
test('empty cart is all zeroes', () {
const cart = Cart.empty;
expect(cart.isEmpty, isTrue);
expect(cart.subtotal, 0);
expect(cart.grandTotal, 0);
expect(cart.pointsEarned, 0);
});
test('sums lines into a subtotal', () {
const cart = Cart(lines: [CartLine(product: _item, quantity: 2)]);
expect(cart.lineCount, 1);
expect(cart.totalQuantity, 2);
expect(cart.subtotal, 200);
expect(cart.grandTotal, 200);
expect(cart.roundOff, 0);
});
test('rounds the payable to the nearest rupee', () {
const odd = Product(
id: 'test-2',
name: 'Odd Price',
barcode: '8900000000002',
sku: 'TST-002',
category: ProductCategory.grocery,
price: 99.99,
stock: 10,
);
const cart = Cart(lines: [CartLine(product: odd, quantity: 1)]);
expect(cart.netAmount, 99.99);
expect(cart.grandTotal, 100);
expect(cart.roundOff, closeTo(0.01, 0.001));
});
test('applies the membership discount automatically', () {
final cart = Cart(
lines: const [CartLine(product: _item, quantity: 2)],
customer: _silver(),
);
expect(cart.customer!.tier, MembershipTier.silver);
// Silver is 2% off 200.
expect(cart.membershipDiscountAmount, 4);
expect(cart.netAmount, 196);
expect(cart.grandTotal, 196);
});
test('walk-in bills get no membership discount', () {
const cart = Cart(lines: [CartLine(product: _item, quantity: 2)]);
expect(cart.isWalkIn, isTrue);
expect(cart.membershipDiscountAmount, 0);
expect(cart.grandTotal, 200);
});
test('stacks a manual discount on top of the membership one', () {
final cart = Cart(
lines: const [CartLine(product: _item, quantity: 2)],
customer: _silver(),
billDiscount: const Discount(type: DiscountType.flat, value: 16),
);
// 4 (silver) + 16 (manual) = 20 off 200.
expect(cart.billDiscountTotal, 20);
expect(cart.grandTotal, 180);
});
test('apportions bill-level discounts across the GST charged', () {
final full = Cart(
lines: const [CartLine(product: _item, quantity: 2)],
customer: _silver(),
);
// Bill fell to 98% of subtotal, so GST should fall in step.
expect(full.taxAmount, closeTo(30.51 * 0.98, 0.02));
expect(full.taxableAmount, closeTo(full.netAmount - full.taxAmount, 0.01));
});
test('breaks GST out by slab', () {
const zeroRated = Product(
id: 'test-3',
name: 'Onion 1kg',
barcode: '8900000000003',
sku: 'TST-003',
category: ProductCategory.vegetables,
price: 35,
stock: 20,
gstRate: 0,
);
const cart = Cart(lines: [
CartLine(product: _item, quantity: 1),
CartLine(product: zeroRated, quantity: 1),
],);
final breakdown = cart.taxBreakdown;
expect(breakdown.keys, containsAll([0.18, 0.0]));
expect(breakdown[0.0], 0);
expect(breakdown[0.18]!, greaterThan(0));
});
});
group('Loyalty', () {
test('earns one point per ten rupees, floored', () {
final cart = Cart(
lines: const [CartLine(product: _item, quantity: 2)],
customer: _silver(),
);
// Grand total 196 -> 19 points.
expect(cart.grandTotal, 196);
expect(cart.pointsEarned, 19);
});
test('caps redemption at the point balance', () {
final cart = Cart(
lines: const [CartLine(product: _item, quantity: 2)],
customer: _silver(),
);
// 320 points held; the bill could absorb far more.
expect(cart.maxRedeemablePoints, 320);
});
test('redeemed points come off the payable at 25 paise each', () {
final cart = Cart(
lines: const [CartLine(product: _item, quantity: 2)],
customer: _silver(),
pointsRedeemed: 320,
);
expect(cart.loyaltyRedemptionValue, 80);
// 200 - 4 (silver) - 80 (points) = 116.
expect(cart.netAmount, 116);
expect(cart.grandTotal, 116);
});
test('a walk-in can never redeem', () {
const cart = Cart(lines: [CartLine(product: _item, quantity: 2)]);
expect(cart.maxRedeemablePoints, 0);
});
test('the payable can never go below zero', () {
final cart = Cart(
lines: const [CartLine(product: _item, quantity: 1)],
customer: _silver(),
billDiscount: const Discount(type: DiscountType.flat, value: 9999),
);
expect(cart.netAmount, 0);
expect(cart.grandTotal, 0);
});
});
group('MembershipTier', () {
test('maps lifetime spend onto the right tier', () {
expect(MembershipTier.forSpend(0), MembershipTier.bronze);
expect(MembershipTier.forSpend(9999), MembershipTier.bronze);
expect(MembershipTier.forSpend(10000), MembershipTier.silver);
expect(MembershipTier.forSpend(50000), MembershipTier.gold);
expect(MembershipTier.forSpend(150000), MembershipTier.platinum);
expect(MembershipTier.forSpend(999999), MembershipTier.platinum);
});
test('platinum is the ceiling', () {
expect(MembershipTier.platinum.next, isNull);
expect(MembershipTier.bronze.next, MembershipTier.silver);
});
});
}