Files
doormile_customer_app/lib/data/api_exception.dart
Thiru-tenext 8757b16cf5 PIN sign-in, because the code could never arrive
── What was actually broken ──

The SMS gateway was switched off, and `POST /auth/otp/request` does not fail
when that happens: it still answers `sent: true`, still issues a valid 4-digit
code, and writes it to the **server log**. So the phone path walked customers
to a code screen for a code that could not arrive, and every digit they
eventually typed was wrong. The failure read to them as "I entered it wrong".

Phone sign-in is now a PIN, which needs no gateway.

── Email still sends codes, so email is untouched ──

Email OTP goes over SMTP and works. Deleting a working way in to tidy up a
broken one is a net loss for anyone with an email on their account, so "Use
email instead" and the code screen stay exactly as they were.
`login_otp_guard_test` moves to that path — the `sent: false` guard still
matters there, and that is now the only place it can fire.

── One screen, three entrances ──

`POST /auth/login` says which of them a number is before anything is asked, so
the app never guesses. Guessing is not cosmetic: offer "create a PIN" to a
returning customer and the server answers `pin_already_set` on a screen that
cannot succeed; offer "enter your PIN" to somebody who has never set one and
every attempt is wrong.

The separate sign-up screen is deleted rather than hidden. It asked for a name
and then sent an SMS code — a second entrance asking the same questions and
posting a letter that never lands. A new number now gives its name and PIN on
the same screen.

── A second sign-in path found a latent bug ──

`AppState.signIn` only started `refreshOrders`, and the OTP screen called
`detectPickupLocation` itself afterwards to make up the difference. That held
exactly as long as there was one sign-in screen. PIN sign-in did not know about
the extra call, so Home opened with no pickup and no serviceable cities.

The work belongs to signing in, not to whichever screen happened to be last, so
it moved into `signIn` and the OTP screen's copy is gone.

── What the screen deliberately does not do ──

It does not greet by name. `POST /auth/login` returns the account holder's
name, which tells anybody who types a number who owns it; the field is read but
never displayed, so it disappears quietly when the backend drops it.

It does not say whether the number or the PIN was wrong — the server answers
identically for both on purpose, and narrowing it here would turn sign-in into
a way of testing whether a number has an account.

"Forgot your PIN?" renders only when a support contact is configured. There is
no reset endpoint, so it can only point at a human — and telling somebody
locked out that help exists without saying where is worse than silence.

── The handover note does not reach the Miler ──

The app said "we pass this to your Miler as a note". It does not: `remarks`
reaches the admin console and stops, because the rider app reads a `notes`
field per stop that the backend never sends. A customer could hand their parcel
to a neighbour believing the Miler had been told. Both screens now say it is
recorded on the booking, and that the Miler still calls the account's number.

── Also ──

DmTextField gains `obscure`, and PinScreen carries a back button — without one
the only correction for a mistyped digit was killing the app.
2026-09-30 10:44:22 +05:30

133 lines
5.6 KiB
Dart

/// Thrown for every failed call so the UI can show one consistent error state.
///
/// [code] is the contract's machine-readable key and is the **only** thing
/// callers may branch on. [message] is customer-safe English written by the
/// server and is rendered verbatim — never parsed.
class ApiException implements Exception {
ApiException(
this.code, [
String? message,
this.status,
this.requestId,
String? serverCode,
]) : message = message ?? 'Something went wrong',
serverCode = serverCode ?? code;
final String code;
final String message;
/// Exactly what the server put in `error.code` — `SLOT_CAPACITY_FULL`,
/// `UNSERVICEABLE_PINCODE`, and so on. [code] is that value translated into
/// the vocabulary below; this one is kept for the log line and for a support
/// report, and nothing branches on it.
final String serverCode;
/// HTTP status, when there was one. Null for a transport failure.
final int? status;
/// The server's `X-Request-Id`, so a support report can be correlated.
final String? requestId;
/// The client vocabulary: the contract's codes translated by [normalise],
/// plus the ones the client raises itself.
static const String network = 'network';
static const String invalid = 'invalid';
static const String invalidName = 'invalid_name';
static const String invalidOtp = 'invalid_otp';
static const String unauthorized = 'unauthorized';
static const String forbidden = 'forbidden';
static const String notFound = 'not_found';
static const String conflict = 'conflict';
static const String unserviceable = 'unserviceable';
static const String rateLimited = 'rate_limited';
static const String serverError = 'server_error';
/// The slot is gone — filled up, or its window passed. Its own code because
/// the recovery is specific: re-read the slots and go back to picking one.
static const String slotUnavailable = 'slot_unavailable';
/// The Miler has already arrived, so the cancel window has closed.
static const String notCancellable = 'not_cancellable';
// ── PIN sign-in ──
//
// Three codes, three different next screens, which is why none of them can
// be folded into [invalid]. The server uses the same message for a wrong PIN
// and an unknown number on purpose — so the app must not guess which, and
// says "That number or PIN is incorrect" rather than naming one.
/// Wrong PIN, **or** a phone with no account. Deliberately ambiguous.
static const String invalidPin = 'invalid_pin';
/// The account exists and has no PIN yet — send them to create one.
static const String pinNotSet = 'pin_not_set';
/// The account already has a PIN — send them to enter it.
static const String pinAlreadySet = 'pin_already_set';
/// Too many wrong PINs on this account. Not in the contract yet: the backend
/// is adding a per-account lockout, and the app reads it the moment it lands
/// rather than needing a release to catch up. Until then the server answers
/// [invalidPin] and this simply never fires.
static const String pinLocked = 'pin_locked';
/// Translates the contract's `error.code` into the vocabulary above.
///
/// The wire spells its codes in capitals; the client's are lowercase, and
/// mapping them is not cosmetic — an untranslated `UNAUTHORIZED` does not
/// satisfy [isAuthFailure], which is what triggers the token refresh, so a
/// signed-in customer would have been dropped at the first expired token
/// instead of silently getting a new one.
///
/// A code that is already lowercase is passed through untouched, and an
/// unrecognised one falls back to whatever the HTTP status means.
static String normalise(String raw, String Function() fromStatus) {
final trimmed = raw.trim();
if (trimmed.isEmpty) return fromStatus();
if (trimmed != trimmed.toUpperCase()) return trimmed;
return switch (trimmed) {
'INVALID_PIN' => invalidPin,
'PIN_NOT_SET' => pinNotSet,
'PIN_ALREADY_SET' => pinAlreadySet,
'PIN_LOCKED' || 'ACCOUNT_LOCKED' => pinLocked,
'UNAUTHORIZED' || 'TOKEN_EXPIRED' => unauthorized,
'FORBIDDEN' => forbidden,
'NOT_FOUND' => notFound,
'INVALID_INPUT' || 'VALIDATION_ERROR' => invalid,
'SLOT_UNAVAILABLE' || 'SLOT_EXPIRED' || 'SLOT_CAPACITY_FULL' =>
slotUnavailable,
'BOOKING_NOT_CANCELLABLE' => notCancellable,
'UNSERVICEABLE_PINCODE' => unserviceable,
'RATE_LIMITED' => rateLimited,
'INTERNAL_ERROR' => serverError,
_ => fromStatus(),
};
}
/// True when retrying the identical request could plausibly succeed.
bool get isTransient =>
code == network || code == serverError || code == rateLimited;
/// The session is gone; the customer has to sign in again.
bool get isAuthFailure => code == unauthorized;
/// The slot the customer picked is no longer bookable — either it filled up
/// or its window has passed. Both recover the same way: re-fetch the slots
/// and put them back on slot selection.
///
/// The server distinguishes them (`409 conflict` for a genuine capacity race,
/// `400 invalid` for a window that has passed) but the customer's next action
/// is identical, so the client does not.
bool get needsFreshSlots =>
code == slotUnavailable ||
code == conflict ||
(code == invalid && message.toLowerCase().contains('pickup'));
@override
String toString() =>
'ApiException($code'
'${serverCode == code ? '' : '/$serverCode'}'
'${status == null ? '' : ' $status'}): $message'
'${requestId == null ? '' : ' [req $requestId]'}';
}