Files
doormile_customer_app/lib/data/doormile_api.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

226 lines
8.6 KiB
Dart

import 'app_config.dart';
import 'dev_doormile_api.dart';
import 'live_doormile_api.dart';
import 'models.dart';
export 'api_exception.dart';
/// The service surface the app is written against.
///
/// **[LiveDoormileApi] is what ships,** against `/customer/*` on
/// `api.doormile.com`. When the server cannot be reached the screens show their
/// designed error state, which is the only honest answer.
///
/// [DevDoormileApi] answers instead when [AppConfig.useDevData] is set — under
/// `FLUTTER_TEST`, or a debug build given `--dart-define=DM_MOCK=true`. That
/// getter is `false` in a release whatever is passed, so a shipped build has
/// one implementation and a booking a customer makes is one the server
/// accepted.
///
/// ── Why this is guarded so tightly ──
///
/// An offline build was deleted from this app on 15 Sep 2026 after it cost two
/// rounds of hunting for bookings in the admin console that had never left the
/// phone. What made that expensive was not the fake existing — it was that the
/// fake was reachable without announcing itself, and that nothing stopped it
/// reaching a release. Both are closed now: the release guard above, and the
/// Account screen printing DEV DATA (offline) the whole time it is on.
///
/// Screens never see this type at all — they call [AppState], which holds it.
///
/// A method the backend owns but no screen drives yet has a default here that
/// does nothing rather than throwing.
abstract class DoormileApi {
DoormileApi();
static DoormileApi? _instance;
/// The API this build talks to.
///
/// [LiveDoormileApi] unless the build asked for offline data, which a
/// release build cannot do — see [AppConfig.useDevData]. The check is here
/// rather than at the call sites so there is exactly one place that decides,
/// and nothing downstream has to know which one it got.
static DoormileApi get instance =>
_instance ??= AppConfig.useDevData ? DevDoormileApi() : LiveDoormileApi();
/// Replaces the singleton. Tests inject their double through here.
static void overrideInstance(DoormileApi? api) => _instance = api;
/// Called when the refresh chain dies and the customer must sign in again.
/// Set by [AppState].
void Function()? onSessionLost;
// --------------------------------------------------------------------- auth
/// Asks for a code. The answer describes the challenge — how many digits it
/// has and how long before it can be resent — so the screen is built from
/// what the server said rather than from constants.
Future<OtpChallenge> sendOtp(String identifier);
/// Creates the account **and** sends the first code, so it answers with the
/// same challenge [sendOtp] does.
Future<OtpChallenge> signUp({
required String name,
required String phone,
String? email,
});
/// [name] is set when verifying a freshly created account.
Future<Customer> verifyOtp(String identifier, String code, {String? name});
// ── PIN sign-in ──
//
// The paid SMS gateway was switched off, so phone OTP issues codes that
// reach only the server log. These three replace it for phone numbers. Email
// OTP still works and is still offered — see `LoginScreen`.
//
// `setPin` and `verifyPin` return the same session `verifyOtp` does, so
// everything after sign-in — token refresh, restore, logout — is untouched.
/// Which of the three PIN screens this number leads to.
Future<PhoneCheck> checkPhone(String phone);
/// Sets the **first** PIN on a number, creating the account when it is new.
///
/// [name] is required only for a number with no account. Throws
/// [ApiException.pinAlreadySet] when there is already a PIN.
Future<Customer> setPin({
required String phone,
required String pin,
String? name,
});
/// Signs in with an existing PIN. Throws [ApiException.invalidPin] for a
/// wrong PIN *or* an unknown number, and [ApiException.pinNotSet] when the
/// account has none yet.
Future<Customer> verifyPin({required String phone, required String pin});
/// Restores a persisted session at launch, or null when there is none.
Future<Customer?> restoreSession() async => null;
/// Revokes the refresh token and unregisters the push token.
Future<void> signOut() async {}
/// Re-reads the signed-in customer — `GET /customer/auth/me`.
Future<Customer?> me() async => null;
// ----------------------------------------------------------- serviceability
Future<List<ServiceArea>> getServiceableStates();
Future<List<District>> getServiceableDistricts(String stateCode);
/// Synchronous district lookup for a code we already hold, backed by
/// whatever [getServiceableDistricts] last returned.
District? districtByCode(String? code);
// -------------------------------------------------------------------- slots
Future<List<PickupSlot>> getPickupSlots({Place? pickup});
PickupSlot? slotById(String? id);
// ----------------------------------------------------------------- location
Future<Place> reverseGeocode({double? lat, double? lng});
/// An empty query returns the customer's saved and recent places, which is
/// what the search sheet shows the moment it opens.
///
/// [lat]/[lng] bias the results towards where the customer is looking —
/// "MG Road" is in most Indian cities, and the one they mean is the near one.
Future<List<Place>> searchPlaces(String query, {double? lat, double? lng});
// ------------------------------------------------------------------- limits
Future<BookingLimits> getBookingLimits({Place? pickup});
// --------------------------------------------------------------------- fare
Future<FareEstimate> estimateFare({
required Place pickup,
required List<DestinationGroup> destinations,
});
// ------------------------------------------------------------------ booking
/// Creates the pickup booking. No tracking number yet — those are minted per
/// destination when the Miler completes the pickup.
///
/// [idempotencyKey] must be **held across retries of the same intent**. A new
/// key is a new booking, which is exactly what a double tap must not create.
///
/// [contactPhone] is who the Miler calls at the pickup door. Null means the
/// signed-in customer, which is what it was always sending — the parameter
/// exists because the person handing over the parcel is not always the
/// person who booked it.
Future<Booking> createBooking({
required Place pickup,
required List<DestinationGroup> destinations,
required String? slotId,
FareEstimate? fare,
String? contactPhone,
String? contactName,
String? idempotencyKey,
});
Future<void> cancelBooking(String reference, String? reason);
/// One page of the customer's bookings, newest first.
Future<BookingPage> getBookingPage({
BookingStatus? status,
String? cursor,
int limit = 20,
});
/// One booking, fresh. Null means the server answered `304` — nothing has
/// changed since the last read, so the caller keeps what it has.
Future<Booking?> getBooking(String reference);
/// One order by its tracking number — for a push deep link.
Future<Booking?> getOrder(String trackingId) async => null;
/// Adds the optional address and recipient after booking, up to collection.
Future<void> updateDestinationDetails(
String reference,
int index,
DeliveryDetails details,
) async {}
/// Backend policy decides this; the UI only asks.
bool isCancellable(JourneyStage stage);
// ------------------------------------------------------------------ ops QA
/// Moves a booking to [stage] through the backend's own non-production QA
/// helper — `POST /customer/ops/bookings/{reference}/stage`.
///
/// It exists so the tracking screen's stepper can walk a **real** staging
/// booking. The stage that then appears on screen is the one the server
/// recorded, not one the client wished for. Refused on production.
Future<void> setStage(String reference, JourneyStage stage) async {}
// ------------------------------------------------------------------ devices
Future<void> registerDevice(String token) async {}
Future<void> unregisterDevice(String token) async {}
// ------------------------------------------------------- profile & addresses
Future<Customer?> getProfile() async => null;
Future<Customer?> updateProfile({String? name, String? email}) async => null;
Future<List<SavedPlace>> getSavedLocations() async => const [];
Future<SavedPlace?> addSavedLocation(Place place, {String? label}) async =>
null;
Future<SavedPlace?> updateSavedLocation(SavedPlace place) async => null;
Future<void> deleteSavedLocation(String id) async {}
}