Files
nearle_pos/lib/presentation/payment/providers/payment_controller.dart
Suriya 0a49323858 Drain bills to the back office automatically, over MQTT or HTTP
Turns the orders table into a queue that empties itself. Bills were only
uploaded when a cashier pressed Sync at end of day; a till that was never
pressed held a day's takings indefinitely.

Drain engine (lib/data/sync/sync_engine.dart)
- Triggers on sale committed, network regained, 5-minute poll, head-office
  request, and the manual button.
- Single flight: a busy till firing a trigger per sale would otherwise have
  several passes reading the same pending rows and send every bill twice.
  A trigger arriving mid-drain is queued and replayed, so nothing is dropped.
- Exponential backoff with +/-20% jitter to a 5-minute ceiling. The jitter
  matters: a store's terminals all fail at the same instant when the line
  drops, and would retry in lockstep without it.
- Halts rather than loops on a failure retrying cannot fix (bad credential,
  refused batch). Pressing Sync clears the halt.

Transports (lib/data/remote/)
- OrderTransport interface; MQTT, HTTP and simulated implementations. The
  repository does not know which is in use.
- MQTT: QoS 1 uplink, application-level ACK correlated by batch_id on a return
  topic, retained Last Will for terminal-offline detection, downlink for
  catalogue pushes and remote sync requests.
- A broker PUBACK is never treated as acceptance. It means the broker holds
  the bytes, not that the ledger took the sale. Only ids the back office names
  are marked synced; silence leaves a bill pending.
- HTTP carries a stable idempotency key across retries of the same bills.

Retention
- Accepted bills are kept 7 days instead of deleted, so a batch the back
  office later loses can be re-sent in full. Purged after that; archived
  totals stay forever.
- forBusinessDate now reads pending rows only. A retained bill exists in both
  the orders table and day_archive, and summing both would overstate the day.

Fixes found while building this
- SyncEngine._refreshPending wrote state.copyWith(pending: await ...). Dart
  evaluates the receiver before the awaited argument, so a connectivity drop
  during the wait was silently overwritten by the stale snapshot. Caught by
  the first run of the new engine tests.
- PrinterSettingsController wrote state after four awaits with no mounted
  check, throwing "used after dispose" when Settings was left mid-load. This
  was pre-existing and reached the cashier as a red screen.

Also
- Header pill now reports real sync state: LIVE / n QUEUED / SYNCING /
  SYNC HALTED, with an explanation of where the bills are.
- Settings shows the route, last upload, next retry and retention window.
- docs/sync-contract.md states what the back office must implement, including
  the idempotency requirement that at-least-once delivery makes mandatory.

Tests: 90 -> 129 passing. New coverage for backoff shape and jitter band,
single flight, halting, ACK correlation and partial acceptance, at-least-once
duplicate handling, retention and purge, and no double-counting after a sync.
Suite run six times clean.

Not addressed: bills already synced by an older build went up overstated and
still need server-side reconciliation. Broker credentials have no Settings
editor yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 10:57:29 +05:30

233 lines
7.4 KiB
Dart

import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/utils/extensions.dart';
import '../../../data/sync/sync_engine.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++;
// The bill is safely on disk; getting it to the back office is the
// engine's problem now. Deliberately not awaited — the cashier must
// reach the receipt screen at network speed of zero.
_ref.read(syncEngineProvider).nudge(SyncTrigger.saleCommitted);
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),
);