Files
doormile_milderapp/lib/controllers/duty_controller.dart
2026-08-11 13:16:33 +05:30

67 lines
2.6 KiB
Dart

import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Single source of truth for the rider's online / on-duty state.
///
/// Duty state used to be re-derived from raw SharedPreferences in a dozen
/// places (homepage field, pickups gate, done screen…), and the `onduty` int is
/// clobbered by a flaky server rider-log sync — which is what auto-kicked riders
/// offline after a pickup. This controller centralises the read with the
/// corrected priority so every screen agrees.
///
/// Priority when resolving "is the rider online?":
/// 1. onduty == 1 → a fresh server shift is authoritative.
/// 2. explicit `online` → the rider's toggle; SURVIVES the flaky onduty sync
/// (every legit offline path — manual toggle, auto
/// shift-end — sets online=false, so it's trustworthy).
/// 3. onduty == 0 → offline.
/// 4. otherwise → default online.
class DutyController extends GetxController {
/// Whether the rider is online (on duty) and may receive bookings / act.
final RxBool isOnline = false.obs;
static const String _kOnduty = 'onduty';
static const String _kOnline = 'online';
/// Convenience accessor — registers the controller on first use.
static DutyController get to => Get.isRegistered<DutyController>()
? Get.find<DutyController>()
: Get.put(DutyController(), permanent: true);
/// True if the rider may receive bookings and start pickups/deliveries.
bool get canWork => isOnline.value;
/// Resolves and broadcasts the current online state from persisted prefs.
Future<bool> load() async {
final prefs = await SharedPreferences.getInstance();
final int onduty = prefs.getInt(_kOnduty) ?? -1;
final bool? savedOnline = prefs.getBool(_kOnline);
bool online;
if (onduty == 1) {
online = true;
} else if (savedOnline != null) {
online = savedOnline;
} else if (onduty == 0) {
online = false;
} else {
online = true;
}
// Keep the persisted bool consistent so the fallback stays correct.
await prefs.setBool(_kOnline, online);
isOnline.value = online;
return online;
}
/// Persists + broadcasts a new online state. Call after a successful duty
/// toggle so every listener updates immediately. Going offline also clears
/// the raw onduty flag so a stale `1` can't resurrect an online state.
Future<void> setOnlineLocal(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_kOnline, value);
if (!value) await prefs.setInt(_kOnduty, 0);
isOnline.value = value;
}
}