pos changes

This commit is contained in:
2026-08-06 19:26:53 +05:30
parent cb065a0f69
commit eebd10da6d
42 changed files with 3451 additions and 2531 deletions

View File

@@ -1,9 +1,6 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../data/local/staff_dao.dart';
import '../../../data/remote/pos_auth_api.dart';
import '../../../domain/entities/pos_session.dart';
import '../../../domain/entities/store_account.dart';
/// Sign-in state for the terminal.
@@ -22,10 +19,23 @@ class Authenticating extends AuthState {
}
class Authenticated extends AuthState {
const Authenticated({required this.store, required this.user});
const Authenticated({
required this.store,
required this.user,
required this.login,
});
final StoreAccount store;
final StaffUser user;
/// Which credential opened this session. The authority on what the terminal
/// is allowed to show — not [user], which can be swapped at the till.
final TerminalLogin login;
StaffRole get role => login.role;
bool get isAdmin => login == TerminalLogin.admin;
bool get isCashier => login == TerminalLogin.cashier;
}
class AuthFailure extends AuthState {
@@ -34,150 +44,110 @@ class AuthFailure extends AuthState {
final String message;
}
/// Signs the terminal in against the back office and holds the session.
/// The two ways into this terminal.
///
/// This used to compare against two constants compiled into the app —
/// `admin@nearle.in` / `nearle123` — with a 600ms delay standing in for a
/// network call that was never made. Two things were wrong with that, and the
/// second was the serious one:
/// Store-level credentials, not a person's: they are replaced wholesale when
/// the terminal is registered against a real back office. Staff PINs — the
/// credential that actually opens a till drawer — are not here. They live
/// hashed in the database.
///
/// 1. every install of a build shared one password, and changing it meant a
/// rebuild; and
/// 2. because nothing was checked with the back office, the *outlet* could not
/// come from the sign-in. It came from a store id typed into Settings — so
/// a till named its own shop and was believed, and one number changed on
/// one screen moved a terminal into another tenant's books.
/// The split is what the two roles are *for*, not decoration:
///
/// Now a person signs in with their own back-office account, and the outlet
/// arrives as a consequence: sealed in a signed token, checked server-side on
/// every request, and not editable from this device.
/// * [admin] runs the whole shell and is the only login that can pull the
/// catalogue. Signing out leaves the products on the terminal.
/// * [cashier] gets the billing screen and nothing else, and signing out
/// takes the catalogue with it.
enum TerminalLogin {
admin(
label: 'Admin',
email: 'admin@nearle.in',
password: 'nearle123',
role: StaffRole.admin,
blurb: 'Full shell — import products, promos, settings.',
),
cashier(
label: 'Cashier',
email: 'cashier@nearle.in',
password: 'cashier123',
role: StaffRole.cashier,
blurb: 'Billing only, on the products the admin imported.',
);
const TerminalLogin({
required this.label,
required this.email,
required this.password,
required this.role,
required this.blurb,
});
final String label;
final String email;
final String password;
final StaffRole role;
final String blurb;
/// The catalogue is pulled once by an admin and billed against by whoever is
/// on the counter, so only the cashier's sign-out drops it. An admin closing
/// the shell is a handover, not the end of the day.
bool get clearsCatalogueOnSignOut => this == TerminalLogin.cashier;
static TerminalLogin? byEmail(String email) {
final normalised = email.trim().toLowerCase();
for (final login in TerminalLogin.values) {
if (login.email == normalised) return login;
}
return null;
}
}
/// Kept for the store record, which is keyed on the outlet's own address.
class DemoCredentials {
const DemoCredentials._();
static const String email = 'admin@nearle.in';
static const String password = 'nearle123';
static const String cashierEmail = 'cashier@nearle.in';
static const String cashierPassword = 'cashier123';
}
/// Validates store credentials and holds the signed-in session.
class AuthController extends StateNotifier<AuthState> {
AuthController(this._ref) : super(const Unauthenticated());
final Ref _ref;
/// The back office's answer to the last sign-in, if there is one.
/// Whether signing out right now would wipe the products off this terminal.
///
/// Held so the outlet picker can offer a proprietor their other shops without
/// asking for the password a second time.
PosSession? _session;
PosSession? get session => _session;
/// Restores a session saved on a previous run.
///
/// Called at start-up so a till that was rebooted mid-shift comes back
/// trading rather than showing a login screen to a queue of customers.
/// Returns false when there is nothing usable, which includes an expired
/// session — [SessionStore] treats those as absent.
Future<bool> restore() async {
final saved = await _ref.read(sessionStoreProvider).read();
if (saved == null) return false;
await _adopt(saved);
return state is Authenticated;
/// Read *before* [signOut] by anything that needs to warn the operator, since
/// the session is gone by the time it returns.
bool get clearsCatalogueOnSignOut {
final current = state;
return current is Authenticated && current.login.clearsCatalogueOnSignOut;
}
Future<bool> signIn({
required String email,
required String password,
int? locationId,
}) async {
state = const Authenticating();
final terminal = _ref.read(terminalIdentityProvider);
// Stand-in for the network round trip.
await Future<void>.delayed(const Duration(milliseconds: 600));
final PosSession session;
try {
session = await _ref.read(posAuthApiProvider).login(
authname: email,
password: password,
terminalId: terminal.code,
deviceId: terminal.deviceId,
locationId: locationId,
);
} on PosAuthException catch (e) {
state = AuthFailure(e.message);
return false;
} on Object {
state = const AuthFailure(
'Sign-in failed for an unexpected reason. Please try again.',
);
final login = TerminalLogin.byEmail(email);
if (login == null) {
state = const AuthFailure('No account is registered against that email.');
return false;
}
await _ref.read(sessionStoreProvider).write(session);
await _adopt(session);
if (password != login.password) {
state = const AuthFailure('Incorrect password. Please try again.');
return false;
}
return state is Authenticated;
}
/// Moves this terminal to another of the signed-in account's outlets.
///
/// A fresh sign-in rather than a local switch, because the outlet is inside
/// the signed token: the back office has to issue a new one, and re-checking
/// entitlement at that moment is the point. Requires the password again,
/// which is correct — moving a till between shops changes whose books it
/// writes to.
Future<bool> switchOutlet({
required String password,
required int locationId,
}) async {
final current = _session;
if (current == null) return false;
return signIn(
email: current.email.isNotEmpty ? current.email : current.fullName,
password: password,
locationId: locationId,
);
}
/// Adopts a session: points the terminal at its outlet, then opens it.
///
/// Order matters. The store id and token are written *before* the catalogue
/// or any uplink can run, so a terminal can never spend even one request
/// pointed at the outlet it had yesterday while claiming to be signed in as
/// today's.
Future<void> _adopt(PosSession session) async {
_session = session;
await _ref.read(localStoreProvider).identityStore.rename(
storeId: session.storeId,
);
_ref.invalidate(terminalIdentityProvider);
_ref.read(syncConfigProvider.notifier).state =
_ref.read(syncConfigProvider).copyWith(
storeId: session.storeId,
sessionToken: session.token,
);
// Store details for the receipt come from the back office now, not from
// constants compiled into the build. A GSTIN is a legal requirement on a
// tax invoice; it should not need a rebuild to correct.
await _ref.read(storeRepositoryProvider).save(
name: session.locationName.isNotEmpty
? session.locationName
: session.tenantName,
address: session.address,
gstin: session.gstin,
phone: session.phone,
);
// Who may ring a bill here, per the back office.
//
// This is what retires the seeded logins. The till ships with three names
// and three PINs compiled into it — the same three on every install — and
// they exist only so a shop whose back office has no staff recorded can
// still trade on day one. The moment real staff arrive they are
// deactivated, which is the whole point of importing rather than merging.
//
// Empty is the common case rather than an error: most outlets have nobody
// recorded, including the one this build ships pointed at. The import
// no-ops, the seeds survive, and the shop keeps selling.
await _importStaff(session);
_ref.invalidate(storeAccountProvider);
final store = await _ref.read(storeAccountProvider.future);
final staff = store.staff;
@@ -185,61 +155,29 @@ class AuthController extends StateNotifier<AuthState> {
state = const AuthFailure(
'This terminal has no staff accounts. Reinstall to seed them.',
);
return;
return false;
}
// The first admin, or whoever is there. A person switches to their own
// account at the till.
// Whoever on this terminal matches the role that just signed in. Falls
// back rather than failing: the session's permissions come from [login],
// so a shop with no cashier row still gets a usable till — the bills are
// just stamped with the account that is there.
final opener = staff.firstWhere(
(s) => s.role == StaffRole.admin,
(s) => s.role == login.role,
orElse: () => staff.first,
);
state = Authenticated(store: store, user: opener);
state = Authenticated(store: store, user: opener, login: login);
return true;
}
/// Writes the back office's staff over this terminal's.
///
/// Failures are swallowed. A shop must be able to open its till even when the
/// staff import fails — the seeded or previously-synced accounts are still
/// there, and refusing the sign-in would trade a working counter for a
/// tidier database.
Future<void> _importStaff(PosSession session) async {
if (session.staff.isEmpty) return;
try {
await _ref.read(localStoreProvider).staff.replaceFromBackOffice([
for (final member in session.staff)
StaffImportRecord(
localId: member.localId,
name: member.fullName,
role: _roleFor(member.role),
pin: member.pin,
),
]);
} on Object {
// Deliberately silent — see above.
}
}
/// Maps the back office's role names onto the till's three.
///
/// `app_roles` holds six rows for four distinct roles — Admin and Manager are
/// each in there twice — and most accounts carry a `roleid` that is not in
/// the table at all. So this matches on the name and falls back to the least
/// privileged answer: an unrecognised role must not silently become an admin.
StaffRole _roleFor(String backOfficeRole) =>
switch (backOfficeRole.trim().toLowerCase()) {
'super admin' || 'admin' => StaffRole.admin,
'manager' || 'operations' => StaffRole.manager,
_ => StaffRole.cashier,
};
/// Switches the active operator, checking their PIN.
///
/// Every bill is stamped with whoever is active, so this is the boundary that
/// decides who a sale is attributed to — it cannot be a bare selection from a
/// list.
/// list. It changes who the bill names, never what the session may open:
/// [Authenticated.login] is untouched, so a cashier terminal stays a cashier
/// terminal.
Future<bool> switchUser(String pin) async {
final current = state;
if (current is! Authenticated) return false;
@@ -248,7 +186,11 @@ class AuthController extends StateNotifier<AuthState> {
final user = await store.staff.authenticate(pin);
if (user == null) return false;
state = Authenticated(store: current.store, user: user);
state = Authenticated(
store: current.store,
user: user,
login: current.login,
);
return true;
}
@@ -266,25 +208,25 @@ class AuthController extends StateNotifier<AuthState> {
// Signed out if the active operator was just deactivated — carrying on
// would keep stamping bills with an account the shop has revoked.
user: me.isEmpty ? store.staff.first : me.first,
login: current.login,
);
}
/// The next shift should only ever bill against what the back office
/// answers with, never a catalogue instance carried over from this
/// session — so the local product table is dropped before the session
/// itself is.
/// Ends the session, and — for a cashier only — the catalogue with it.
///
/// The token goes with it, from the keystore and from the live configuration
/// both. Leaving it in place would let a signed-out terminal keep uploading
/// as the shop that signed in this morning.
/// Every way out of a cashier session clears the products: ending a shift,
/// and a temporary logout alike. There is no exception for stepping away for
/// ten minutes, because the terminal is left unattended either way and the
/// next session should bill against what the back office answers with rather
/// than a catalogue carried over.
///
/// An admin signing out is the opposite case. They have just pulled the
/// products *so that* a cashier can pick the terminal up, so dropping the
/// table here would make the import pointless.
Future<void> signOut() async {
await _ref.read(localStoreProvider).clearCatalogue();
await _ref.read(sessionStoreProvider).clear();
_ref.read(syncConfigProvider.notifier).state =
_ref.read(syncConfigProvider).copyWith(sessionToken: '');
_session = null;
if (clearsCatalogueOnSignOut) {
await _ref.read(localStoreProvider).clearCatalogue();
}
state = const Unauthenticated();
}
@@ -309,6 +251,24 @@ final currentUserProvider = Provider<StaffUser?>((ref) {
return s is Authenticated ? s.user : null;
});
/// Which credential is holding this session open, or null before sign-in.
final terminalLoginProvider = Provider<TerminalLogin?>((ref) {
final s = ref.watch(authControllerProvider);
return s is Authenticated ? s.login : null;
});
/// True when the terminal is locked down to the billing screen.
///
/// The one flag the shell reads: no sidebar, no back-office modules, sign-out
/// and events promoted to the header.
final isCashierModeProvider = Provider<bool>(
(ref) => ref.watch(terminalLoginProvider) == TerminalLogin.cashier,
);
final isAdminModeProvider = Provider<bool>(
(ref) => ref.watch(terminalLoginProvider) == TerminalLogin.admin,
);
/// True while anyone is still on a seeded or admin-reset PIN.
final mustChangePinProvider = Provider<bool>((ref) {
final user = ref.watch(currentUserProvider);