Answers "which of my 100 tills are alive and healthy", and fixes three things that were fine on one device and broken on a hundred. Terminal identity (lib/data/local/terminal_identity.dart) - Every device mints a UUID on first run, stored in its own database, plus a short code (T4A9) derived from it. Renaming keeps the device id, so history keeps pointing at the same physical till. - Replaces the literal 'TERM-01', which was hardcoded in five places. The whole fleet reported as one terminal: shift reports merged, MQTT topics collided, and a second connection with the same client id evicts the first from the broker — so two tills would have knocked each other offline in a loop. Invoice numbers now carry the terminal code - INV-2608-T4A9-00042. The sequence counter lives in each till's own database and starts at 1, so without this every terminal in the fleet minted INV-2608-00001 for its first sale of the month. The order UUID kept the data distinct; the number a customer quotes on a receipt was not. SQLite pragmas - WAL, so the product grid refreshing does not block the sale being written, and the file is never left mid-rewrite by a power cut. - busy_timeout 5s, so a contended lock waits instead of throwing "database is locked" — which at checkout is a failed sale with a customer standing there. - synchronous NORMAL, the right trade under WAL for a till. Fleet presence (lib/data/sync/presence_reporter.dart) - Retained status record on connect and once a minute: device id, code, name, app version, pending bill count, last upload, catalogue revision, sync halt state. Retained so a dashboard connecting at noon gets all 100 terminals immediately rather than a blank board. - The Last Will already said "reachable". A till can be connected and still be holding 200 unsent bills or running last month's prices; only pending_bills and catalogue_revision say so. NATS - The MQTT gateway maps / to . so the existing transport works unchanged. SyncConfig.asNatsSubject() exposes the translation, and the contract doc gives the JetStream subjects (pos.*.*.order, pos.*.*.status) plus the two server-side requirements: a file-backed stream, and the ack published by the consumer after commit rather than by the ingest handler. Tests: 129 -> 140. New coverage for identity minting and stability, per-device invoice uniqueness, topic and client-id separation, NATS subject mapping, and the two pragmas. Suite run three times clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
192 lines
6.8 KiB
Dart
192 lines
6.8 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
|
|
import '../core/config/sync_config.dart';
|
|
import '../core/services/connectivity_service.dart';
|
|
import '../core/services/receipt_service.dart';
|
|
import '../core/services/sound_service.dart';
|
|
import '../data/datasources/local_store.dart';
|
|
import '../data/repositories/customer_repository_impl.dart';
|
|
import '../data/repositories/product_repository_impl.dart';
|
|
import '../data/datasources/remote_catalogue_source.dart';
|
|
import '../data/remote/http_order_transport.dart';
|
|
import '../data/remote/mqtt_order_transport.dart';
|
|
import '../data/remote/order_transport.dart';
|
|
import '../data/remote/simulated_order_transport.dart';
|
|
import '../data/repositories/sync_repository_impl.dart';
|
|
import '../data/repositories/transaction_repository_impl.dart';
|
|
import '../data/local/terminal_identity.dart';
|
|
import '../data/sync/sync_engine.dart';
|
|
import '../domain/repositories/customer_repository.dart';
|
|
import '../domain/repositories/product_repository.dart';
|
|
import '../domain/repositories/sync_repository.dart';
|
|
import '../domain/repositories/transaction_repository.dart';
|
|
import '../domain/usecases/checkout_sale.dart';
|
|
|
|
/// Root data source. Overridden in tests with an in-memory double.
|
|
final localStoreProvider = Provider<LocalStore>((ref) => LocalStore.instance);
|
|
|
|
// ---------------------------------------------------------- Repositories
|
|
final productRepositoryProvider = Provider<ProductRepository>(
|
|
(ref) => ProductRepositoryImpl(ref.watch(localStoreProvider)),
|
|
);
|
|
|
|
final customerRepositoryProvider = Provider<CustomerRepository>(
|
|
(ref) => CustomerRepositoryImpl(ref.watch(localStoreProvider)),
|
|
);
|
|
|
|
final transactionRepositoryProvider = Provider<TransactionRepository>(
|
|
(ref) => TransactionRepositoryImpl(ref.watch(localStoreProvider)),
|
|
);
|
|
|
|
/// Mirrors the Settings "Simulate offline" switch so the header can show it.
|
|
///
|
|
/// Without this the terminal claims LIVE while every call is being failed on
|
|
/// purpose, which reads as a real network fault.
|
|
final simulateOfflineProvider = StateProvider<bool>((ref) => false);
|
|
|
|
/// Simulated back-office endpoints. Held as singletons so the offline toggle
|
|
/// in Settings affects every call.
|
|
final remoteCatalogueProvider = Provider<RemoteCatalogueSource>(
|
|
(ref) => RemoteCatalogueSource(
|
|
isOffline: () => ref.read(simulateOfflineProvider),
|
|
),
|
|
);
|
|
|
|
// ------------------------------------------------------------------- Sync
|
|
/// How this terminal reaches the back office.
|
|
///
|
|
/// Defaults to the simulated route so a fresh install is usable with no broker
|
|
/// and no endpoint; Settings re-points it.
|
|
///
|
|
/// Store and terminal ids always come from this device's own identity, never
|
|
/// from a literal — two terminals publishing on the same topic is the failure
|
|
/// this exists to prevent.
|
|
final syncConfigProvider = StateProvider<SyncConfig>((ref) {
|
|
final terminal = ref.watch(terminalIdentityProvider);
|
|
return SyncConfig(
|
|
storeId: terminal.storeId,
|
|
terminalId: terminal.code,
|
|
);
|
|
});
|
|
|
|
/// Real network state, folded with the Settings offline switch.
|
|
final connectivityServiceProvider = Provider<ConnectivityService>((ref) {
|
|
final service = ConnectivityService(
|
|
isSimulatedOffline: () => ref.read(simulateOfflineProvider),
|
|
);
|
|
ref.onDispose(service.dispose);
|
|
return service;
|
|
});
|
|
|
|
/// The wire itself. Rebuilt when the configuration changes, and the old one is
|
|
/// closed so a re-pointed terminal does not keep a stale broker session open.
|
|
final orderTransportProvider = Provider<OrderTransport>((ref) {
|
|
final config = ref.watch(syncConfigProvider);
|
|
|
|
final transport = switch (config.transport) {
|
|
TransportKind.mqtt => MqttOrderTransport(config: config),
|
|
TransportKind.http => HttpOrderTransport(config: config),
|
|
TransportKind.simulated => SimulatedOrderTransport(
|
|
isOffline: () => ref.read(simulateOfflineProvider),
|
|
),
|
|
};
|
|
|
|
ref.onDispose(transport.dispose);
|
|
return transport;
|
|
});
|
|
|
|
final syncRepositoryProvider = Provider<SyncRepository>(
|
|
(ref) => SyncRepositoryImpl(
|
|
ref.watch(localStoreProvider),
|
|
ref.watch(remoteCatalogueProvider),
|
|
ref.watch(orderTransportProvider),
|
|
batchSize: ref.watch(syncConfigProvider).batchSize,
|
|
),
|
|
);
|
|
|
|
/// Decides when bills are uploaded. Started once, by the app shell.
|
|
final syncEngineProvider = Provider<SyncEngine>((ref) {
|
|
final transport = ref.watch(orderTransportProvider);
|
|
|
|
final engine = SyncEngine(
|
|
repository: ref.watch(syncRepositoryProvider),
|
|
connectivity: ref.watch(connectivityServiceProvider).onlineChanges,
|
|
downlink: transport.downlink,
|
|
onCatalogueChanged: () async {
|
|
await ref.read(syncRepositoryProvider).importCatalogue();
|
|
ref.invalidate(localStoreProvider);
|
|
},
|
|
);
|
|
|
|
ref.onDispose(engine.dispose);
|
|
return engine;
|
|
});
|
|
|
|
/// Live engine state for the header pill and the events screen.
|
|
final syncEngineStateProvider = StreamProvider<SyncEngineState>((ref) {
|
|
final engine = ref.watch(syncEngineProvider);
|
|
return engine.states.map((s) => s);
|
|
});
|
|
|
|
// ------------------------------------------------------------- Use cases
|
|
final checkoutSaleProvider = Provider<CheckoutSale>(
|
|
(ref) => CheckoutSale(
|
|
productRepository: ref.watch(productRepositoryProvider),
|
|
customerRepository: ref.watch(customerRepositoryProvider),
|
|
transactionRepository: ref.watch(transactionRepositoryProvider),
|
|
),
|
|
);
|
|
|
|
// -------------------------------------------------------------- Services
|
|
final soundServiceProvider =
|
|
Provider<SoundService>((ref) => SoundService.instance);
|
|
|
|
final receiptServiceProvider =
|
|
Provider<ReceiptService>((ref) => ReceiptService.instance);
|
|
|
|
// --------------------------------------------------------------- Session
|
|
class CashierSession {
|
|
const CashierSession({
|
|
required this.name,
|
|
required this.role,
|
|
required this.terminalId,
|
|
});
|
|
|
|
final String name;
|
|
final String role;
|
|
final String terminalId;
|
|
}
|
|
|
|
/// Identity of the physical till, read from its own database.
|
|
///
|
|
/// Falls back only before the store has opened; every real read happens after
|
|
/// `LocalStore.init`, which mints the identity if this device has never run
|
|
/// before.
|
|
final terminalIdentityProvider = Provider<TerminalIdentity>((ref) {
|
|
final store = ref.watch(localStoreProvider);
|
|
return store.isReady
|
|
? store.terminal
|
|
: const TerminalIdentity(
|
|
deviceId: 'unopened',
|
|
code: 'T0000',
|
|
name: 'Terminal',
|
|
storeId: 'store-01',
|
|
);
|
|
});
|
|
|
|
final cashierSessionProvider = StateProvider<CashierSession>((ref) {
|
|
final terminal = ref.watch(terminalIdentityProvider);
|
|
return CashierSession(
|
|
name: 'Suriya',
|
|
role: 'ADMIN',
|
|
terminalId: terminal.code,
|
|
);
|
|
});
|
|
|
|
/// Ticks once a minute to drive the header clock without rebuilding on every
|
|
/// frame.
|
|
final clockProvider = StreamProvider<DateTime>((ref) async* {
|
|
yield DateTime.now();
|
|
yield* Stream.periodic(const Duration(seconds: 20), (_) => DateTime.now());
|
|
});
|