Files
nearle_pos/lib/presentation/payment/providers/payment_controller.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

227 lines
7.0 KiB
Dart

import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/utils/extensions.dart';
import '../../../domain/entities/transaction.dart';
import '../../../domain/usecases/checkout_sale.dart';
import '../../auth/providers/auth_controller.dart';
import '../../pos/providers/cart_controller.dart';
import '../../pos/providers/catalog_providers.dart';
import '../../sync/providers/sync_controller.dart';
/// UI state for the payment screen.
class PaymentState {
const PaymentState({
this.splits = const [],
this.activeMethod = PaymentMethod.cash,
this.cashTendered = 0,
this.reference = '',
this.isProcessing = false,
this.error,
this.result,
});
final List<PaymentSplit> splits;
final PaymentMethod activeMethod;
final double cashTendered;
final String reference;
final bool isProcessing;
final String? error;
final CheckoutResult? result;
double get settled =>
splits.fold(0.0, (sum, s) => sum + s.amount).asMoney;
bool get isComplete => result != null;
PaymentState copyWith({
List<PaymentSplit>? splits,
PaymentMethod? activeMethod,
double? cashTendered,
String? reference,
bool? isProcessing,
String? error,
bool clearError = false,
CheckoutResult? result,
bool clearResult = false,
}) {
return PaymentState(
splits: splits ?? this.splits,
activeMethod: activeMethod ?? this.activeMethod,
cashTendered: cashTendered ?? this.cashTendered,
reference: reference ?? this.reference,
isProcessing: isProcessing ?? this.isProcessing,
error: clearError ? null : (error ?? this.error),
result: clearResult ? null : (result ?? this.result),
);
}
}
class PaymentController extends StateNotifier<PaymentState> {
PaymentController(this._ref) : super(const PaymentState());
final Ref _ref;
double get _billTotal => _ref.read(cartControllerProvider).grandTotal;
/// Amount still outstanding after the tenders recorded so far.
double get balanceDue =>
(_billTotal - state.settled).clamp(0, double.infinity);
double get changeDue {
if (!state.activeMethod.needsChange) return 0;
final diff = state.cashTendered - balanceDue;
return diff > 0 ? diff.asMoney : 0;
}
/// Whether Complete Sale should be enabled.
///
/// Cash is the strict case: the drawer cannot be reconciled and no change can
/// be calculated unless the cashier states what was handed over. Card, UPI
/// and wallet settle on the external terminal, so they need no amount here.
bool get canConfirm {
if (_billTotal <= 0) return false;
// Staged splits already cover the bill.
if (balanceDue <= 0.01) return true;
if (state.activeMethod.needsChange) {
return state.cashTendered >= balanceDue;
}
return true;
}
/// Why the button is disabled, for display next to it.
String? get blockedReason {
if (_billTotal <= 0) return 'Add at least one item before charging.';
if (canConfirm) return null;
if (state.activeMethod.needsChange) {
return 'Enter the cash received, or tap Exact.';
}
return null;
}
void selectMethod(PaymentMethod method) {
state = state.copyWith(
activeMethod: method,
cashTendered: 0,
reference: '',
clearError: true,
);
}
void setCashTendered(double amount) =>
state = state.copyWith(cashTendered: amount, clearError: true);
/// Adds to the tendered amount — powers the quick-cash denomination chips.
void addCash(double amount) => setCashTendered(state.cashTendered + amount);
/// Fills the exact balance, the most common cash case.
void tenderExact() => setCashTendered(balanceDue);
void setReference(String value) =>
state = state.copyWith(reference: value, clearError: true);
/// Records the active tender. For a split payment, call this once per part.
void addSplit({double? amount}) {
final value = (amount ?? balanceDue).clamp(0, balanceDue).toDouble();
if (value <= 0) return;
final split = PaymentSplit(
method: state.activeMethod,
amount: value.asMoney,
tendered: state.activeMethod.needsChange
? (state.cashTendered > 0 ? state.cashTendered : value)
: null,
reference: state.reference.trim().isEmpty ? null : state.reference.trim(),
);
state = state.copyWith(
splits: [...state.splits, split],
cashTendered: 0,
reference: '',
clearError: true,
);
}
void removeSplit(int index) {
final next = [...state.splits]..removeAt(index);
state = state.copyWith(splits: next);
}
void clearSplits() => state = state.copyWith(splits: const []);
/// Finalises the sale. On success the caller navigates to the receipt.
Future<CheckoutResult?> confirm() async {
if (state.isProcessing) return null;
// A single-tender sale needn't be staged first — fold it in automatically.
// Remembered so it can be rolled back if the sale is rejected, otherwise a
// retry starts with a phantom tender already staged.
final stagedSplits = state.splits;
var splits = stagedSplits;
if (splits.isEmpty || balanceDue > 0.01) {
addSplit();
splits = state.splits;
}
state = state.copyWith(isProcessing: true, clearError: true);
try {
final cart = _ref.read(cartControllerProvider);
final session = _ref.read(cashierSessionProvider);
// The signed-in operator owns the bill. Falling back to the seed session
// stamped every sale with the same name, so a bill could not be traced to
// whoever actually rang it.
final user = _ref.read(currentUserProvider);
final result = await _ref.read(checkoutSaleProvider)(
cart: cart,
payments: splits,
cashierName: user?.name ?? session.name,
terminalId: session.terminalId,
);
state = state.copyWith(isProcessing: false, result: result);
// No auto-print: with no roll printer attached this silently failed and
// looked like a bug. The receipt screen shows the bill on the terminal
// and offers Print, WhatsApp and Share explicitly.
unawaited(_ref.read(receiptServiceProvider).openCashDrawer());
unawaited(_ref.read(soundServiceProvider).saleComplete());
// Stock changed, so the grid must refresh; the new order changes the
// unsynced tally and today's totals.
_ref.invalidate(allProductsProvider);
_ref.invalidate(visibleProductsProvider);
_ref.read(orderVersionProvider.notifier).state++;
return result;
} on CheckoutFailure catch (e) {
state = state.copyWith(
isProcessing: false,
error: e.message,
splits: stagedSplits,
);
return null;
} catch (e) {
state = state.copyWith(
isProcessing: false,
error: 'Could not complete the sale. $e',
splits: stagedSplits,
);
return null;
}
}
void reset() => state = const PaymentState();
}
final paymentControllerProvider =
StateNotifierProvider.autoDispose<PaymentController, PaymentState>(
(ref) => PaymentController(ref),
);