This commit is contained in:
2026-08-07 14:34:25 +05:30
parent 829e5a8188
commit 0988d39d8b
19 changed files with 850 additions and 932 deletions

View File

@@ -1,9 +1,10 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/config/api_config.dart';
import '../../../data/local/app_database.dart';
import '../../../data/local/staff_dao.dart';
import '../../../data/remote/pos_auth_api.dart';
import '../../../domain/entities/pos_session.dart';
import '../../../data/remote/auth_api.dart';
import '../../../domain/entities/store_account.dart';
/// Sign-in state for the terminal.
@@ -26,19 +27,35 @@ class Authenticated extends AuthState {
required this.store,
required this.user,
required this.login,
this.session,
});
final StoreAccount store;
final StaffUser user;
/// What this session may open. The authority on what the terminal shows —
/// not [user], which can be swapped at the till without re-authenticating.
/// 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;
/// What the back office answered with. Null only on the offline demo path,
/// where there was no back office to answer.
///
/// Everything downstream reads from here rather than from a constant: the
/// bearer token for the catalogue pull and the order push, the location id
/// they are scoped to, and the tenant name shown beside the logo.
final LoginSession? session;
StaffRole get role => login.role;
bool get isAdmin => login == TerminalLogin.admin;
bool get isCashier => login == TerminalLogin.cashier;
/// The name beside the logo: the tenant, then the outlet, then whatever the
/// store record on this terminal says.
String get storeName {
final fromApi = session?.displayStoreName ?? '';
return fromApi.isNotEmpty ? fromApi : store.name;
}
}
class AuthFailure extends AuthState {
@@ -47,92 +64,80 @@ class AuthFailure extends AuthState {
final String message;
}
/// What a signed-in account may do with this terminal.
/// What this terminal is allowed to open.
///
/// Two shapes, because the terminal only ever behaves in two ways, and the
/// split is what the roles are *for* rather than decoration:
/// No longer a credential — the back office decides the role now, and
/// [AuthController.signIn] maps its answer onto one of these. The two values
/// remain because the whole shell keys off them:
///
/// * [admin] runs the whole shell and is the only login that can pull the
/// * [admin] runs the full 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.
/// * [cashier] gets the billing screen and nothing else, and every way out of
/// the session takes the catalogue with it.
///
/// This used to carry an email and a password per entry, and the terminal
/// decided which role you were by comparing what you typed against those
/// constants. That made the role a property of the *build* — every install
/// shared two logins, and a shop could not add a third person or revoke the
/// two it had without shipping a new APK.
///
/// The role now arrives from the back office as a property of the *account*.
/// [forSession] is the only way to construct one, so there is no path left
/// where the terminal grants itself a permission the server did not send.
/// The email and password fields are the built-in demo accounts, used only by
/// the offline path — see [ApiConfig.allowOfflineDemoLogin].
enum TerminalLogin {
admin(
label: 'Supervisor',
label: 'Admin',
email: 'admin@nearle.in',
password: 'nearle123',
role: StaffRole.admin,
blurb: 'Full shell — import products, promos, staff, settings.',
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 supervisor imported.',
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 a supervisor and billed against by
/// whoever is on the counter, so only the cashier's sign-out drops it. A
/// supervisor closing the shell is a handover, not the end of the day.
/// 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;
/// Which shell the back office says this account gets.
///
/// Reads `can_manage_staff` rather than the role name or id. The name is
/// free text and often blank, and `app_roles` holds six rows for four
/// distinct roles with a great many accounts carrying a `roleid` that is not
/// in the table at all — so matching on either here would mean keeping a
/// copy of the role table in the app and keeping the two in step for ever.
/// One boolean, decided by the server, cannot drift.
static TerminalLogin forSession(PosSession session) =>
session.canManageStaff ? TerminalLogin.admin : 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;
}
}
/// The built-in accounts, used only by the offline path.
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';
}
/// Signs the terminal in against the back office and holds the session.
///
/// This used to compare against constants compiled into the app, 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:
///
/// 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.
///
/// Now a person signs in with their own back-office account, and both the
/// outlet and the role arrive as a consequence: sealed in a signed token,
/// checked server-side on every request, and not editable from this device.
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.
///
/// 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;
/// Whether signing out right now would wipe the products off this terminal.
///
/// Read *before* [signOut] by anything that needs to warn the operator, since
@@ -142,196 +147,158 @@ class AuthController extends StateNotifier<AuthState> {
return current is Authenticated && current.login.clearsCatalogueOnSignOut;
}
/// Restores a session saved on a previous run.
/// Signs in against `POST /login`.
///
/// 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;
}
/// The back office decides everything the terminal then does: the role that
/// picks admin shell or billing screen, the location the catalogue is pulled
/// for, and the token every later call carries. Nothing here is chosen at
/// the login screen any more.
Future<bool> signIn({
required String email,
required String password,
int? locationId,
}) async {
state = const Authenticating();
final terminal = _ref.read(terminalIdentityProvider);
final store = _ref.read(localStoreProvider);
// This till's own minted identity, not a fresh uuid — the back office can
// recognise a terminal across restarts and refuse one it has not
// registered.
final deviceId = store.isReady ? store.terminal.deviceId : 'unopened';
final PosSession session;
LoginSession session;
try {
session = await _ref.read(posAuthApiProvider).login(
session = await _ref.read(authApiProvider).login(
authname: email,
password: password,
terminalId: terminal.code,
deviceId: terminal.deviceId,
locationId: locationId,
deviceId: deviceId,
);
} on PosAuthException catch (e) {
} on ApiException catch (e) {
// A refusal is final. Only a shop with no line at all may fall through,
// and only onto the built-in accounts — a wrong password must never
// quietly become a local sign-in.
if (ApiConfig.allowOfflineDemoLogin && e.isNetworkFault) {
final offline = await _signInOffline(email, password);
if (offline) return true;
}
state = AuthFailure(e.message);
return false;
} on Object {
state = const AuthFailure(
'Sign-in failed for an unexpected reason. Please try again.',
}
try {
await _applySession(session);
} on Object catch (e) {
state = AuthFailure(
'Signed in, but this terminal could not store the store details: $e',
);
return false;
}
await _ref.read(sessionStoreProvider).write(session);
await _adopt(session);
return state is Authenticated;
return true;
}
/// Moves this terminal to another of the signed-in account's outlets.
/// Writes everything the session decided into the terminal, then opens it.
///
/// 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;
/// Order matters. The store id and terminal identity are written first,
/// because `syncConfigProvider` is derived from them and from the session —
/// setting the session last means the catalogue and order transports are
/// rebuilt once, already pointing at the right location with the right
/// token.
Future<void> _applySession(LoginSession session) async {
final store = _ref.read(localStoreProvider);
final catalogue = store.catalogue;
return signIn(
email: current.email.isNotEmpty ? current.email : current.fullName,
password: password,
locationId: locationId,
);
}
// 1. The outlet, as the back office describes it. These are printed on
// every GST invoice, so they come from the server rather than from the
// build's constants.
await catalogue.setMeta(MetaKeys.storeId, session.storeId);
if (session.displayStoreName.isNotEmpty) {
await catalogue.setMeta(MetaKeys.storeName, session.displayStoreName);
}
if (session.address.isNotEmpty) {
await catalogue.setMeta(MetaKeys.storeAddress, session.address);
}
if (session.phone.isNotEmpty) {
await catalogue.setMeta(MetaKeys.storePhone, session.phone);
}
/// 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,
);
// 2. This till now belongs to that outlet. Reloaded rather than left to a
// restart: the cached identity is what every bill and topic reads.
await store.identityStore.rename(storeId: session.storeId);
await store.reloadTerminal();
_ref.invalidate(terminalIdentityProvider);
_ref.read(syncConfigProvider.notifier).state =
_ref.read(syncConfigProvider).copyWith(
storeId: session.storeId,
sessionToken: session.token,
);
// 3. The staff list, so PIN switching at the counter works against the
// people head office actually employs.
final me = await _syncStaff(session);
// 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,
// 4. Open the session. syncConfigProvider watches this, so the catalogue
// pull and the order push pick up the token and location id from here.
final account = await _ref.read(storeRepositoryProvider).load(
email: session.email.isEmpty ? DemoCredentials.email : session.email,
);
// 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);
state = Authenticated(
store: account,
user: me,
login: session.isAdmin ? TerminalLogin.admin : TerminalLogin.cashier,
session: session,
);
_ref.invalidate(storeAccountProvider);
final store = await _ref.read(storeAccountProvider.future);
final staff = store.staff;
}
if (staff.isEmpty) {
state = const AuthFailure(
'This terminal has no staff accounts. Reinstall to seed them.',
/// Mirrors the back office's staff list onto this terminal, and returns the
/// row for whoever just signed in.
///
/// Additive on purpose. Deactivating everyone the server did not mention
/// would lock a shop out of its own till the first time the endpoint answers
/// with an empty array — which is exactly what the sample response does.
Future<StaffUser> _syncStaff(LoginSession session) async {
final dao = _ref.read(localStoreProvider).staff;
for (final member in session.staff) {
if (member.userId == 0) continue;
await dao.upsertFromServer(
id: StaffDao.serverId(member.userId),
name: member.fullName,
role: member.staffRole,
pin: member.pin,
isActive: member.isActive,
);
return;
}
state = Authenticated(
store: store,
user: _opener(staff, session),
login: TerminalLogin.forSession(session),
// The person who signed in may not appear in that list — `staff` comes
// back empty for a single-operator shop. They still need a row, because
// every bill is stamped with a staff id.
return dao.upsertFromServer(
id: StaffDao.serverId(session.userId),
name: session.displayUserName,
role: session.staffRole,
pin: session.whoAmI?.pin,
);
}
/// Who the terminal attributes bills to the moment it opens.
/// The built-in accounts, for a terminal with no line to the back office.
///
/// The person who just signed in, if the import wrote them — matched on the
/// back office id rather than the name, which is neither unique nor stable.
/// Falls back to anyone rather than failing: the session's permissions come
/// from the token, so a shop whose staff list is empty or unsynced still gets
/// a usable till, and the bills are simply stamped with the account that is
/// there until someone switches with their PIN.
StaffUser _opener(List<StaffUser> staff, PosSession session) {
final mine = 'boffice-${session.userId}';
for (final s in staff) {
if (s.id == mine) return s;
}
/// Development only — see [ApiConfig.allowOfflineDemoLogin]. It reaches no
/// server, so it sets no token: the catalogue cannot be pulled and bills
/// cannot be pushed until a real sign-in happens.
Future<bool> _signInOffline(String email, String password) async {
final login = TerminalLogin.byEmail(email);
if (login == null || password != login.password) return false;
final wanted = TerminalLogin.forSession(session).role;
return staff.firstWhere((s) => s.role == wanted, orElse: () => staff.first);
final store = await _ref.read(storeRepositoryProvider).load(email: email);
if (store.staff.isEmpty) return false;
final opener = store.staff.firstWhere(
(s) => s.role == login.role,
orElse: () => store.staff.first,
);
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.
///
/// Supervisor is the role a shop actually hands out; it sits with Admin
/// because a supervisor *is* the till's administrator.
StaffRole _roleFor(String backOfficeRole) =>
switch (backOfficeRole.trim().toLowerCase()) {
'super admin' || 'admin' || 'supervisor' => 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
@@ -339,11 +306,6 @@ class AuthController extends StateNotifier<AuthState> {
/// 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.
///
/// That is deliberate. A PIN is four digits typed at an unattended counter;
/// it is shift attribution, not a privilege boundary. Escalating to the full
/// shell takes a real sign-in, because that is the only thing the back office
/// sees and signs.
Future<bool> switchUser(String pin) async {
final current = state;
if (current is! Authenticated) return false;
@@ -356,6 +318,7 @@ class AuthController extends StateNotifier<AuthState> {
store: current.store,
user: user,
login: current.login,
session: current.session,
);
return true;
}
@@ -375,34 +338,28 @@ class AuthController extends StateNotifier<AuthState> {
// would keep stamping bills with an account the shop has revoked.
user: me.isEmpty ? store.staff.first : me.first,
login: current.login,
session: current.session,
);
}
/// Ends the session, and — for a cashier only — the catalogue with it.
///
/// The token always goes, 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, so that half is a security
/// matter and takes no exception.
///
/// The catalogue is a workflow matter and does take one. Every way out of a
/// cashier session clears the products — ending a shift and a temporary
/// logout alike — because the terminal is left unattended either way and the
/// 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. A supervisor 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.
/// 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.
///
/// The bearer token needs no clearing: it lives on the session, so it goes
/// when the state does, and `syncConfigProvider` is derived from it.
Future<void> signOut() async {
if (clearsCatalogueOnSignOut) {
await _ref.read(localStoreProvider).clearCatalogue();
}
await _ref.read(sessionStoreProvider).clear();
_ref.read(syncConfigProvider.notifier).state =
_ref.read(syncConfigProvider).copyWith(sessionToken: '');
_session = null;
state = const Unauthenticated();
}
@@ -427,6 +384,31 @@ final currentUserProvider = Provider<StaffUser?>((ref) {
return s is Authenticated ? s.user : null;
});
/// What the back office answered with, or null before sign-in.
///
/// `select` rather than a plain watch: the whole sync configuration is derived
/// from this, and rebuilding the transports on every intermediate auth state
/// would tear down a connection mid-request.
final apiSessionProvider = Provider<LoginSession?>((ref) {
return ref.watch(
authControllerProvider.select(
(s) => s is Authenticated ? s.session : null,
),
);
});
/// The name shown beside the logo — tenant first, then the outlet, then the
/// store record on this terminal.
final storeDisplayNameProvider = Provider<String>((ref) {
final s = ref.watch(authControllerProvider);
return s is Authenticated ? s.storeName : '';
});
/// The outlet, for the line under the store name.
final locationDisplayNameProvider = Provider<String>((ref) {
return ref.watch(apiSessionProvider)?.locationName.trim() ?? '';
});
/// Which credential is holding this session open, or null before sign-in.
final terminalLoginProvider = Provider<TerminalLogin?>((ref) {
final s = ref.watch(authControllerProvider);