Files
nearle_pos/lib/presentation/modules/providers/printer_settings.dart
Suriya fdd90f28d9 Open the cash drawer for real, and persist the back-office route
Cash drawer
- openCashDrawer was a debugPrint. The drawer never opened.
- It cannot go through the PDF pipeline: a PDF is rendered by the platform
  driver, which will not pass raw ESC/POS bytes to the device. So it goes over
  a socket instead — nearly every network thermal printer listens on 9100 and
  forwards whatever arrives straight to the print head, which makes the whole
  protocol five bytes.
- Printer IP and port are configurable in Settings with a Test button that
  saves and fires immediately, because a drawer that does not open is
  indistinguishable from one that is not wired up.
- Every failure explains itself: unreachable, refused, or simply not
  configured — which is the honest state for a USB printer, since there is no
  raw path to one from Flutter.
- Now fires only on a cash tender. A card-only sale that pops the drawer is a
  shrinkage risk, and it is the first thing a shop notices.

Back-office route
- Host, port, TLS and transport persist to the database; username, password
  and API key go to the platform keystore (Keychain / Credential Manager /
  Android Keystore). Writing credentials into SQLite would put them in the
  same file as the bills, on a machine behind a shop counter.
- Loaded at startup. Previously the dialog wrote settings that were silently
  ignored on the next launch, which reads exactly like they never saved — and
  credentials retyped every morning end up on a sticky note instead.
- A saved route never overwrites the terminal's store or terminal id. Those
  belong to the device, and re-pointing a till at a different broker must not
  change who it is, or its bills and presence records stop lining up.

Tests: 168 -> 176. The drawer test stands up a real socket server and asserts
the exact bytes arrive. The config test asserts no credential appears anywhere
in the meta table while the non-secret settings do.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 13:18:56 +05:30

165 lines
5.2 KiB
Dart

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:printing/printing.dart';
import '../../../app/providers.dart';
import '../../../data/local/app_database.dart';
/// Hardware preferences for this terminal.
///
/// Persisted in `app_meta` rather than held in widget state, so the choice
/// survives a restart — a cashier should not have to reselect the printer
/// every morning.
class PrinterSettings {
const PrinterSettings({
this.printerUrl,
this.printerName,
this.autoPrint = false,
this.openDrawer = true,
this.drawerHost,
this.drawerPort = 9100,
});
/// Target passed to `directPrintPdf`. Null means "use the system default".
final String? printerUrl;
/// Shown in Settings. Kept alongside the url because the url is opaque.
final String? printerName;
/// Print silently the moment a sale completes.
///
/// Defaults to **off**: with no printer attached, auto-printing fails
/// invisibly and looks like a bug.
final bool autoPrint;
final bool openDrawer;
/// IP address of the receipt printer the drawer is wired to.
///
/// Separate from [printerUrl] because that is an opaque platform handle for
/// the PDF driver, which cannot carry raw ESC/POS bytes. The drawer kick
/// needs a socket, so it needs an address.
final String? drawerHost;
final int drawerPort;
bool get hasPrinter => printerUrl != null;
bool get hasDrawer => (drawerHost ?? '').isNotEmpty;
PrinterSettings copyWith({
String? printerUrl,
String? printerName,
bool clearPrinter = false,
bool? autoPrint,
bool? openDrawer,
String? drawerHost,
int? drawerPort,
}) {
return PrinterSettings(
printerUrl: clearPrinter ? null : (printerUrl ?? this.printerUrl),
printerName: clearPrinter ? null : (printerName ?? this.printerName),
autoPrint: autoPrint ?? this.autoPrint,
openDrawer: openDrawer ?? this.openDrawer,
drawerHost: drawerHost ?? this.drawerHost,
drawerPort: drawerPort ?? this.drawerPort,
);
}
}
class PrinterSettingsController extends StateNotifier<PrinterSettings> {
PrinterSettingsController(this._ref) : super(const PrinterSettings()) {
_load();
}
final Ref _ref;
Future<void> _load() async {
final store = _ref.read(localStoreProvider);
if (!store.isReady) return;
final dao = store.catalogue;
// Read every value first, then assign. Written inline the four awaits still
// run before the assignment, so leaving Settings mid-read threw
// "used after dispose" — which reaches the cashier as a red screen.
final url = await dao.meta(MetaKeys.printerUrl);
final name = await dao.meta(MetaKeys.printerName);
final autoPrint = await dao.meta(MetaKeys.autoPrint);
final openDrawer = await dao.meta(MetaKeys.openDrawer);
final drawerHost = await dao.meta(MetaKeys.drawerHost);
final drawerPort = await dao.meta(MetaKeys.drawerPort);
if (!mounted) return;
state = PrinterSettings(
printerUrl: url,
printerName: name,
autoPrint: autoPrint == '1',
openDrawer: openDrawer != '0',
drawerHost: drawerHost,
drawerPort: int.tryParse(drawerPort ?? '') ?? 9100,
);
}
Future<void> selectPrinter(Printer? printer) async {
final dao = _ref.read(localStoreProvider).catalogue;
if (printer == null) {
await dao.setMeta(MetaKeys.printerUrl, '');
await dao.setMeta(MetaKeys.printerName, '');
if (!mounted) return;
state = state.copyWith(clearPrinter: true, autoPrint: false);
return;
}
await dao.setMeta(MetaKeys.printerUrl, printer.url);
await dao.setMeta(MetaKeys.printerName, printer.name);
if (!mounted) return;
state = state.copyWith(
printerUrl: printer.url,
printerName: printer.name,
);
}
Future<void> setAutoPrint(bool value) async {
// Auto-print with nothing selected would fail silently on every sale.
if (value && !state.hasPrinter) return;
await _ref
.read(localStoreProvider)
.catalogue
.setMeta(MetaKeys.autoPrint, value ? '1' : '0');
if (!mounted) return;
state = state.copyWith(autoPrint: value);
}
Future<void> setOpenDrawer(bool value) async {
await _ref
.read(localStoreProvider)
.catalogue
.setMeta(MetaKeys.openDrawer, value ? '1' : '0');
if (!mounted) return;
state = state.copyWith(openDrawer: value);
}
/// Points the drawer kick at a printer.
///
/// A blank host disables it — which is the honest state for a USB printer,
/// since there is no raw path to one from Flutter.
Future<void> setDrawerAddress(String host, int port) async {
final dao = _ref.read(localStoreProvider).catalogue;
await dao.setMeta(MetaKeys.drawerHost, host.trim());
await dao.setMeta(MetaKeys.drawerPort, '$port');
if (!mounted) return;
state = state.copyWith(drawerHost: host.trim(), drawerPort: port);
}
}
final printerSettingsProvider =
StateNotifierProvider<PrinterSettingsController, PrinterSettings>(
(ref) => PrinterSettingsController(ref),
);
/// Printers the OS can currently see. Re-read whenever Settings is opened.
final availablePrintersProvider = FutureProvider<List<Printer>>(
(ref) => ref.watch(receiptServiceProvider).availablePrinters(),
);