second commit

This commit is contained in:
2026-07-29 11:41:53 +05:30
parent fcccf22bac
commit d72522e737
211 changed files with 19260 additions and 0 deletions

248
test/unit/cart_test.dart Normal file
View File

@@ -0,0 +1,248 @@
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() => 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<double>([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);
});
});
}

View File

@@ -0,0 +1,254 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/data/datasources/local_store.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';
import 'package:nearle_pos/domain/entities/cart.dart';
import 'package:nearle_pos/domain/entities/customer.dart';
import 'package:nearle_pos/domain/entities/transaction.dart';
import 'package:nearle_pos/domain/usecases/checkout_sale.dart';
void main() {
late LocalStore store;
late ProductRepositoryImpl products;
late CustomerRepositoryImpl customers;
late TransactionRepositoryImpl transactions;
late CheckoutSale checkout;
setUp(() async {
store = LocalStore.instance;
// Fresh seed for every test so stock and invoice sequence never leak.
await store.reset();
products = ProductRepositoryImpl(store);
customers = CustomerRepositoryImpl(store);
transactions = TransactionRepositoryImpl(store);
checkout = CheckoutSale(
productRepository: products,
customerRepository: customers,
transactionRepository: transactions,
);
});
/// Amul Milk 1L: 62.00, 5% GST, 50 in stock.
Future<Cart> milkCart({int qty = 2, String? customerId}) async {
final milk = (await products.findByBarcode('8901234500011'))!;
final customer =
customerId == null ? null : await customers.findById(customerId);
return Cart(
lines: [CartLine(product: milk, quantity: qty.toDouble())],
customer: customer,
);
}
group('successful checkout', () {
test('records the sale and returns an invoice', () async {
final cart = await milkCart();
expect(cart.grandTotal, 124);
final result = await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 200),
],
cashierName: 'Suriya',
);
final txn = result.transaction;
expect(txn.total, 124);
expect(txn.amountPaid, 124);
expect(txn.changeDue, 76);
expect(txn.isFullySettled, isTrue);
expect(txn.isSplit, isFalse);
expect(txn.invoiceNumber, contains('00001'));
expect(txn.status, TransactionStatus.completed);
});
test('decrements stock by the quantity sold', () async {
final cart = await milkCart();
await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 124),
],
cashierName: 'Suriya',
);
final milk = await products.findByBarcode('8901234500011');
expect(milk!.stock, 48);
});
test('persists the transaction to history', () async {
final cart = await milkCart();
await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 124),
],
cashierName: 'Suriya',
);
final history = await transactions.history();
expect(history, hasLength(1));
expect(await transactions.salesTotalForDay(DateTime.now()), 124);
});
test('accepts a split across two tenders', () async {
final cart = await milkCart();
final result = await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 100, tendered: 100),
PaymentSplit(
method: PaymentMethod.upi,
amount: 24,
reference: 'UPI-991',
),
],
cashierName: 'Suriya',
);
expect(result.transaction.isSplit, isTrue);
expect(result.transaction.amountPaid, 124);
expect(result.transaction.paymentSummary, 'Cash + UPI');
});
test('moves loyalty points and lifetime spend for a member', () async {
final cart = await milkCart(customerId: 'c001');
// 124 less the 2% silver discount, rounded.
expect(cart.membershipDiscountAmount, 2.48);
expect(cart.grandTotal, 122);
expect(cart.pointsEarned, 12);
final result = await checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 122, tendered: 200),
],
cashierName: 'Suriya',
);
final updated = result.updatedCustomer!;
expect(updated.loyaltyPoints, 332); // 320 + 12
expect(updated.lifetimeSpend, 24622); // 24500 + 122
expect(updated.visitCount, 42);
});
});
group('rejected checkout', () {
test('refuses an empty cart', () async {
expect(
() => checkout(
cart: Cart.empty,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 0),
],
cashierName: 'Suriya',
),
throwsA(isA<CheckoutFailure>()),
);
});
test('refuses a bill with no tender', () async {
final cart = await milkCart();
expect(
() => checkout(cart: cart, payments: const [], cashierName: 'Suriya'),
throwsA(isA<CheckoutFailure>()),
);
});
test('refuses an underpayment', () async {
final cart = await milkCart();
expect(
() => checkout(
cart: cart,
payments: const [
PaymentSplit(method: PaymentMethod.cash, amount: 100, tendered: 100),
],
cashierName: 'Suriya',
),
throwsA(isA<CheckoutFailure>()),
);
});
test('refuses to sell more than is in stock', () async {
final cart = await milkCart(qty: 999);
expect(
() => checkout(
cart: cart,
payments: [
PaymentSplit(
method: PaymentMethod.cash,
amount: cart.grandTotal,
tendered: cart.grandTotal,
),
],
cashierName: 'Suriya',
),
throwsA(isA<CheckoutFailure>()),
);
});
test('leaves stock untouched when validation fails', () async {
final cart = await milkCart();
try {
await checkout(cart: cart, payments: const [], cashierName: 'Suriya');
} on CheckoutFailure {
// expected
}
final milk = await products.findByBarcode('8901234500011');
expect(milk!.stock, 50);
});
});
group('repositories', () {
test('finds a customer by mobile number', () async {
final found = await customers.findByMobile('9876543210');
expect(found?.name, 'Abhishek');
expect(await customers.findByMobile('0000000000'), isNull);
});
test('rejects a duplicate mobile number on create', () async {
// 9876543210 already belongs to the seeded customer c001.
expect(
() => customers.create(
const Customer(id: '', name: 'Impostor', mobile: '9876543210'),
),
throwsA(isA<StateError>()),
);
});
test('creates a customer with a generated id and zeroed loyalty', () async {
final created = await customers.create(
const Customer(id: '', name: 'New Shopper', mobile: '9000011111'),
);
expect(created.id, isNotEmpty);
expect(created.loyaltyPoints, 0);
expect(created.lifetimeSpend, 0);
expect(created.tier, MembershipTier.bronze);
expect(await customers.findByMobile('9000011111'), isNotNull);
});
test('ranks an exact barcode above a fuzzy name match', () async {
final results = await products.search('8901234500011');
expect(results.first.name, 'Amul Milk 1L');
});
test('parks and resumes a bill', () async {
final cart = await milkCart();
await transactions.park(
ParkedBill(id: 'park-1', cart: cart, parkedAt: DateTime.now()),
);
expect(await transactions.parkedBills(), hasLength(1));
await transactions.removeParked('park-1');
expect(await transactions.parkedBills(), isEmpty);
});
});
}

View File

@@ -0,0 +1,91 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:nearle_pos/core/utils/formatters.dart';
import 'package:nearle_pos/core/utils/validators.dart';
void main() {
group('Validators.mobile', () {
test('accepts a valid Indian number', () {
expect(Validators.mobile('9876543210'), isNull);
expect(Validators.mobile('6000000000'), isNull);
});
test('rejects the wrong length', () {
expect(Validators.mobile(''), isNotNull);
expect(Validators.mobile('98765'), isNotNull);
expect(Validators.mobile('98765432101'), isNotNull);
});
test('rejects a leading digit below 6', () {
expect(Validators.mobile('1234567890'), isNotNull);
expect(Validators.mobile('5876543210'), isNotNull);
});
test('ignores separators', () {
expect(Validators.mobile('98765 43210'), isNull);
expect(Validators.mobile('98765-43210'), isNull);
});
});
group('Validators.emailOptional', () {
test('treats empty as valid, since email is optional', () {
expect(Validators.emailOptional(''), isNull);
expect(Validators.emailOptional(null), isNull);
});
test('accepts a well-formed address', () {
expect(Validators.emailOptional('a.b+tag@example.co.in'), isNull);
});
test('rejects a malformed address', () {
expect(Validators.emailOptional('not-an-email'), isNotNull);
expect(Validators.emailOptional('missing@tld'), isNotNull);
});
});
group('Validators.name', () {
test('requires at least two characters', () {
expect(Validators.name('Jo'), isNull);
expect(Validators.name('J'), isNotNull);
expect(Validators.name(' '), isNotNull);
});
});
group('Validators.isLikelyBarcode', () {
test('accepts a long digit string', () {
expect(Validators.isLikelyBarcode('8901234500011'), isTrue);
});
test('rejects short input and anything with letters', () {
expect(Validators.isLikelyBarcode('12345'), isFalse);
expect(Validators.isLikelyBarcode('milk'), isFalse);
expect(Validators.isLikelyBarcode('ABC1234567'), isFalse);
});
});
group('Formatters', () {
test('groups a mobile number into 5 + 5', () {
expect(Formatters.mobile('9876543210'), '98765 43210');
});
test('masks all but the last four digits', () {
expect(Formatters.maskedMobile('9876543210'), endsWith('3210'));
expect(Formatters.maskedMobile('9876543210'), isNot(contains('98765')));
});
test('derives initials', () {
expect(Formatters.initials('Abhishek'), 'A');
expect(Formatters.initials('Meena Lakshmi'), 'ML');
expect(Formatters.initials(' '), '?');
});
test('builds a sequential invoice number', () {
final n = Formatters.invoiceNumber(42, DateTime(2026, 7, 28));
expect(n, 'INV-2607-00042');
});
test('renders a percentage without noise decimals', () {
expect(Formatters.percent(0.05), '5%');
expect(Formatters.percent(0.185), '18.5%');
});
});
}