initial commit: push everything

This commit is contained in:
2026-07-06 20:27:53 +05:30
commit df4e044d74
329 changed files with 36620 additions and 0 deletions

712
lib/controllers/auth.dart Normal file
View File

@@ -0,0 +1,712 @@
import 'dart:io' show Platform;
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:nearle/views/helpers/constants/Font_constant.dart';
import 'package:nearle/views/helpers/constants/Colorconstants.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:nearle/providers/auth/auth_provider.dart';
import 'package:nearle/utils/device.dart';
import 'package:sms_autofill/sms_autofill.dart';
import 'package:nearle/controllers/profile_controller.dart';
// ignore: unused_import
import 'package:nearle/controllers/riderlog.dart';
import 'package:nearle/Models/login/login.dart';
import 'dart:convert';
enum AuthNext { verifyPin, otp, notRegistered, error }
class AuthController extends GetxController {
final RxBool sendingOtp = false.obs;
String? currentPhone;
final AuthProvider _api = AuthProvider();
AuthNext? lastDecision;
// Optional callback used by MPIN screen to clear and refocus fields when user taps "Retry"
VoidCallback? onPinRetry;
static const String _prefsUserIdKey = 'userid';
static const String _prefsPendingPinUserIdKey = 'pending_pin_userid';
static const String _prefsUserNameKey = 'user_name';
static const String _prefsUserEmailKey = 'user_email';
static const String _prefsContactNoKey = 'contactno';
static const String _prefsAddressKey = 'user_address';
static const String _prefsForceMasterPinKey = 'force_master_pin';
static const String _masterPinValue = '1234';
static const String forceMasterPinPrefKey = _prefsForceMasterPinKey;
static const String masterPinValue = _masterPinValue;
bool _forceMasterPinFlow = false;
void _log(String msg) => debugPrint('[AUTH] $msg');
Future<void> _notifyProfileController() async {
try {
if (Get.isRegistered<ProfileController>()) {
final prefs = await SharedPreferences.getInstance();
final pc = Get.find<ProfileController>();
await pc.loadFromPrefs();
pc.setProfile(
name: prefs.getString(_prefsUserNameKey),
email: prefs.getString(_prefsUserEmailKey),
contact: prefs.getString(_prefsContactNoKey),
address: prefs.getString(_prefsAddressKey),
);
}
} catch (_) {}
}
String _normalizePhone(String input) {
final digitsOnly = input.replaceAll(RegExp(r'\D'), '');
if (digitsOnly.length >= 10) {
return digitsOnly.substring(digitsOnly.length - 10);
}
return digitsOnly;
}
void _showBottomSheet({required String title, required String message}) {
Get.bottomSheet(
SafeArea(
child: Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(
Icons.info_outline,
color: Color(0xFF662582),
size: 40,
),
const SizedBox(height: 12),
Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w700,
fontFamily: FontConstants.fontFamily,
fontSize: 20,
),
),
const SizedBox(height: 8),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 16),
SizedBox(
height: 50,
width: double.infinity,
child: ElevatedButton(
onPressed: () {
Get.back();
// If MPIN screen has registered a retry callback, run it
onPinRetry?.call();
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF662582),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: const Text(
'Retry',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
],
),
),
),
isScrollControlled: true,
backgroundColor: Colors.transparent,
);
}
Future<AuthNext> precheckPhone(String phone) async {
try {
final normalized = _normalizePhone(phone);
final prefs = await SharedPreferences.getInstance();
_forceMasterPinFlow = false;
await prefs.remove(_prefsForceMasterPinKey);
String deviceId;
try {
deviceId = await DeviceUtils.ensureDeviceId(prefs);
} catch (e) {
_showBottomSheet(
title: 'Device Error',
message:
'Failed to get device ID. Please restart the app and try again.',
);
lastDecision = AuthNext.error;
return lastDecision!;
}
final String fcmToken = await DeviceUtils.ensureFcmToken(prefs);
final bool fcmWasEmpty = fcmToken.isEmpty;
_log(
'POST /users/rider/login body=${jsonEncode({'contactno': normalized, 'devicetype': Platform.operatingSystem, 'configid': 6, 'deviceid': deviceId, 'userfcmtoken': fcmToken})}',
);
final Login loginRes = await _api.loginParsed(
contactNo: normalized,
deviceType: Platform.operatingSystem,
configId: 6,
deviceId: deviceId,
fcmToken: fcmToken,
);
debugPrint('RAW LOGIN RESPONSE: $loginRes');
final String serverMessage = (loginRes.message ?? '').toLowerCase();
final bool masterPinFlow = (loginRes.authmode ?? 0) == 1;
final bool requiresPinSetup =
serverMessage.contains('pin not set') ||
serverMessage.contains('mpin not set') ||
serverMessage.contains('please set your pin') ||
(loginRes.code != null && loginRes.code == 201);
if (serverMessage.contains('not registered') ||
serverMessage.contains('register first') ||
serverMessage.contains('not found') ||
serverMessage.contains('no user')) {
currentPhone = null;
_showBottomSheet(
title: 'Not Registered',
message: 'Please contact admin and register first.',
);
lastDecision = AuthNext.notRegistered;
return lastDecision!;
}
if (serverMessage.contains('inactive')) {
currentPhone = null;
_showBottomSheet(
title: 'Rider Inactive',
message: 'Rider is inactive. Please contact admin.',
);
lastDecision = AuthNext.notRegistered;
return lastDecision!;
}
final bool messageSaysEnterPin = (loginRes.message ?? '')
.toLowerCase()
.contains('enter your pin');
if (loginRes.status == true) {
try {
final SharedPreferences prefsSave =
await SharedPreferences.getInstance();
// Persist from model
if (loginRes.userid != null) {
await prefsSave.setInt(_prefsUserIdKey, loginRes.userid!);
final SharedPreferences prefs =
await SharedPreferences.getInstance();
await prefs.setString(
'username',
loginRes.fullname ?? loginRes.firstname.toString(),
);
await prefs.setInt('userid', loginRes.userid ?? 0);
await prefs.setInt('userId', loginRes.userid ?? 0);
await prefs.setInt('shiftid', loginRes.shiftid ?? 0);
await prefs.setInt('shiftId', loginRes.shiftid ?? 0);
await prefs.setInt('logid', loginRes.logid ?? 0);
await prefs.setInt('logId', loginRes.logid ?? 0);
await prefs.setInt('riderid', loginRes.riderid ?? 0);
await prefs.setInt('partnerid', loginRes.partnerid ?? 0);
await prefs.setInt('partnerId', loginRes.partnerid ?? 0);
await prefs.setInt('rconfigid', loginRes.configid ?? 0);
await prefs.setInt('locationid', loginRes.locationid ?? 0);
await prefs.setInt('tenantid', loginRes.tenantid ?? 0);
await prefs.setInt('applocationid', loginRes.applocationid ?? 0);
if (loginRes.userfcmtoken != null && loginRes.userfcmtoken!.isNotEmpty) {
await prefs.setString('userfcmtoken', loginRes.userfcmtoken!);
}
debugPrint('saved on shared pref :${loginRes.fullname}');
}
final String? name = loginRes.fullname ?? loginRes.firstname;
final String? email = loginRes.email;
final String contact = (loginRes.contactno ?? normalized).toString();
final String? address = loginRes.address;
_log(
'Saving from model: name=$name, email=$email, contact=$contact, address=$address',
);
if (name != null && name.trim().isNotEmpty) {
await prefsSave.setString(_prefsUserNameKey, name.trim());
}
if (email != null && email.trim().isNotEmpty) {
await prefsSave.setString(_prefsUserEmailKey, email.trim());
}
if (contact.isNotEmpty) {
await prefsSave.setString(
_prefsContactNoKey,
_normalizePhone(contact),
);
}
if (address != null && address.trim().isNotEmpty) {
await prefsSave.setString(_prefsAddressKey, address.trim());
}
await _notifyProfileController();
} catch (_) {}
}
// Persist basic user profile details from model even if above branch didn't run
try {
final prefs2 = await SharedPreferences.getInstance();
final String? name = loginRes.fullname ?? loginRes.firstname;
final String? email = loginRes.email;
final String contact = (loginRes.contactno ?? normalized).toString();
final String? address = loginRes.address;
if (name != null && name.trim().isNotEmpty) {
await prefs2.setString(_prefsUserNameKey, name.trim());
}
if (email != null && email.trim().isNotEmpty) {
await prefs2.setString(_prefsUserEmailKey, email.trim());
}
if (contact.isNotEmpty) {
final normalizedContact = _normalizePhone(contact);
await prefs2.setString(_prefsContactNoKey, normalizedContact);
}
if (address != null && address.trim().isNotEmpty) {
await prefs2.setString(_prefsAddressKey, address.trim());
}
await _notifyProfileController();
} catch (_) {}
if (masterPinFlow) {
currentPhone = _normalizePhone(phone);
_forceMasterPinFlow = true;
await prefs.setBool(_prefsForceMasterPinKey, true);
await prefs.remove('dbPin');
if (loginRes.userid != null) {
await prefs.setInt(_prefsUserIdKey, loginRes.userid!);
}
Get.snackbar(
'Temporary PIN',
'Use $_masterPinValue as PIN to continue.',
snackPosition: SnackPosition.BOTTOM,
duration: const Duration(seconds: 4),
backgroundColor: ColorConstants.primaryColor,
colorText: Colors.white,
);
lastDecision = AuthNext.verifyPin;
return lastDecision!;
}
if (messageSaysEnterPin) {
currentPhone = _normalizePhone(phone);
lastDecision = AuthNext.verifyPin;
return lastDecision!;
}
if (requiresPinSetup && !masterPinFlow) {
currentPhone = _normalizePhone(phone);
await prefs.remove('dbPin');
if (loginRes.userid != null) {
await prefs.setInt(_prefsPendingPinUserIdKey, loginRes.userid!);
}
lastDecision = AuthNext.otp;
return lastDecision!;
}
// Immediately create rider log entry after successful login
currentPhone = normalized;
String? dbPin = loginRes.pin?.toString();
if (dbPin != null && dbPin.isNotEmpty) {
await prefs.setString('dbPin', dbPin);
lastDecision = AuthNext.verifyPin;
return lastDecision!;
}
await prefs.remove('dbPin');
lastDecision = AuthNext.verifyPin;
// If FCM was empty during the request, try to refresh session once token becomes available
if (fcmWasEmpty) {
try {
final String newToken = await DeviceUtils.ensureFcmToken(prefs);
if (newToken.isNotEmpty) {
await refreshSession(phone: normalized);
}
} catch (_) {}
}
return lastDecision!;
} catch (e) {
debugPrint('Precheck phone error: $e');
lastDecision = AuthNext.error;
return lastDecision!;
}
}
Future<bool> sendOtp([String? phoneArg]) async {
if (sendingOtp.value) return false;
if (phoneArg != null && phoneArg.isNotEmpty) {
currentPhone = _normalizePhone(phoneArg);
}
if (currentPhone == null) {
Get.snackbar(
'Error',
'Phone number not set. Please enter your number again.',
);
return false;
}
sendingOtp.value = true;
try {
final prefs = await SharedPreferences.getInstance();
final phone = currentPhone!;
// Get cached SMS provider settings or use defaults
String templateId =
prefs.getString('smsTemplateId') ?? '1107173468024541800';
String smsContent =
prefs.getString('smsContent') ??
'<#> Dear customer, use this One Time Password {#var#} to sign-in to Nearle App. This OTP will be valid for the next 5 mins.';
// Only fetch SMS provider settings if not cached or cache is old (older than 1 hour)
final lastProviderFetch = prefs.getInt('lastProviderFetch') ?? 0;
final now = DateTime.now().millisecondsSinceEpoch;
if (now - lastProviderFetch > 3600000) {
// 1 hour in milliseconds
try {
final providerUri = Uri.parse(
'https://jupiter.nearle.app/live/api/v1/platform/getsmsprovider?templatetypeid=1',
);
final provRes = await http
.get(providerUri)
.timeout(const Duration(seconds: 10));
if (provRes.statusCode == 200) {
final Map<String, dynamic> prov = json.decode(provRes.body);
final details = prov['details'] as Map<String, dynamic>?;
if (details != null) {
templateId = (details['templateid'] ?? templateId).toString();
smsContent = (details['content'] ?? smsContent).toString();
// Cache the settings
await prefs.setString('smsTemplateId', templateId);
await prefs.setString('smsContent', smsContent);
await prefs.setInt('lastProviderFetch', now);
}
}
} catch (_) {}
}
// Append app hash for Android SMS Retriever so auto-fill works silently
String appHash = '';
try {
appHash = await SmsAutoFill().getAppSignature;
if (appHash.isNotEmpty) {
_log('Using app hash for SMS Retriever: $appHash');
}
} catch (_) {}
// Generate OTP ourselves (like the original implementation)
String actualOtp = _generateOtp();
await prefs.setString('lastOtp', actualOtp);
_log('Generated OTP: $actualOtp');
// Replace {#var#} with actual OTP before sending to Lion SMS
final composedSmsBase = smsContent.replaceAll('{#var#}', actualOtp);
final composedSms = appHash.isNotEmpty
? ('$composedSmsBase\n$appHash')
: composedSmsBase;
final phoneWithCountry = phone.startsWith('+') ? phone : '+91$phone';
final encodedSms = Uri.encodeComponent(composedSms);
final smsUrl = Uri.parse(
'https://msg.lionsms.com/api/smsapi?key=e57f5c9679af26077be1a7eadabb1b2a&route=7&sender=NEARLE&number=$phoneWithCountry&templateid=$templateId&sms=$encodedSms',
);
final smsRes = await http
.get(smsUrl)
.timeout(const Duration(seconds: 10));
if (smsRes.statusCode == 200 &&
!(smsRes.body.contains('108') ||
smsRes.body.contains('110') ||
smsRes.body.toLowerCase().contains('error'))) {
return true;
} else {
Get.snackbar(
'OTP Send Failed',
'Provider: ${smsRes.statusCode} ${smsRes.body}',
);
return false;
}
} catch (e) {
debugPrint('sendOtp error: $e');
Get.snackbar('Error', 'An unexpected error occurred while sending OTP.');
return false;
} finally {
sendingOtp.value = false;
}
}
Future<bool> verifyOtp(String code) async {
try {
final prefs = await SharedPreferences.getInstance();
final sentOtp = prefs.getString('lastOtp');
if (sentOtp != null && code == sentOtp) {
await prefs.remove('lastOtp');
_log('OTP verification successful: $code');
return true;
}
_log('OTP verification failed. Expected: $sentOtp, Got: $code');
return false;
} catch (e) {
_log('OTP verification error: $e');
return false;
}
}
// Generate 6-digit OTP (same as original implementation)
String _generateOtp() {
final random = Random();
final otp = 100000 + random.nextInt(900000); // Generates 100000-999999
return otp.toString();
}
Future<bool> setPin(String newPin) async {
try {
final prefs = await SharedPreferences.getInstance();
int? userId =
prefs.getInt(_prefsPendingPinUserIdKey) ??
prefs.getInt(_prefsUserIdKey);
if (newPin.length != 4 || int.tryParse(newPin) == null) {
_showBottomSheet(
title: 'Invalid PIN',
message: 'Please enter a valid 4-digit PIN.',
);
return false;
}
if (userId == null) {
_showBottomSheet(
title: 'Error',
message: 'User ID not found. Please try again.',
);
return false;
}
final int pinNum = int.parse(newPin);
final res = await _api.updatePin(userId: userId, pin: pinNum);
if (res.statusCode >= 200 && res.statusCode < 300) {
await prefs.setString('dbPin', newPin);
await prefs.remove(_prefsPendingPinUserIdKey);
return true;
}
final bodyPreview = res.body.length > 200
? '${res.body.substring(0, 200)}...'
: res.body;
_showBottomSheet(
title: 'Failed (${res.statusCode})',
message: 'Unable to set PIN. Server said: $bodyPreview',
);
return false;
} catch (e) {
debugPrint('setPin error: $e');
_showBottomSheet(
title: 'Error',
message: 'Something went wrong while setting the PIN.',
);
return false;
}
}
/// Refresh session on backend with latest deviceId/FCM for the current phone.
Future<bool> refreshSession({String? phone}) async {
try {
final prefs = await SharedPreferences.getInstance();
final String? usePhone = phone ?? currentPhone;
if (usePhone == null || usePhone.isEmpty) {
return false;
}
final deviceId = await DeviceUtils.ensureDeviceId(prefs);
final fcmToken = await DeviceUtils.ensureFcmToken(prefs);
final Login loginRes = await _api.loginParsed(
contactNo: usePhone,
deviceType: Platform.operatingSystem,
configId: 6,
deviceId: deviceId,
fcmToken: fcmToken,
);
if (loginRes.userid != null) {
await prefs.setInt(_prefsUserIdKey, loginRes.userid!);
}
try {
final String? name = loginRes.fullname ?? loginRes.firstname;
final String? email = loginRes.email;
final String contact = (loginRes.contactno ?? usePhone).toString();
final String? address = loginRes.address;
if (name != null && name.trim().isNotEmpty) {
await prefs.setString(_prefsUserNameKey, name.trim());
}
if (email != null && email.trim().isNotEmpty) {
await prefs.setString(_prefsUserEmailKey, email.trim());
}
if (contact.isNotEmpty) {
final normalizedContact = _normalizePhone(contact);
await prefs.setString(_prefsContactNoKey, normalizedContact);
}
if (address != null && address.trim().isNotEmpty) {
await prefs.setString(_prefsAddressKey, address.trim());
}
await _notifyProfileController();
} catch (_) {}
currentPhone = _normalizePhone(usePhone);
return loginRes.status == true;
} catch (_) {
return false;
}
}
Future<bool> verifyPinWithServer(String inputPin) async {
try {
if (inputPin.length != 4 || int.tryParse(inputPin) == null) {
_showBottomSheet(
title: 'Invalid PIN',
message: 'Please enter a valid 4-digit PIN.',
);
return false;
}
final prefs = await SharedPreferences.getInstance();
final String? phone = currentPhone;
if (phone == null || phone.isEmpty) {
_showBottomSheet(
title: 'Session Expired',
message: 'Please enter your number again.',
);
return false;
}
final bool masterPinActive =
_forceMasterPinFlow ||
(prefs.getBool(_prefsForceMasterPinKey) ?? false);
if (masterPinActive) {
if (inputPin != _masterPinValue) {
_showBottomSheet(title: 'Invalid PIN', message: 'Please try again.');
return false;
}
_forceMasterPinFlow = false;
await prefs.remove(_prefsForceMasterPinKey);
await prefs.setString('dbPin', _masterPinValue);
await prefs.setBool('logged_out', false);
// Call loginParsed with the master pin to fetch and save all API data
// This ensures shared_preferences has all the necessary data like regular pins
String deviceId;
try {
deviceId = await DeviceUtils.ensureDeviceId(prefs);
} catch (e) {
_showBottomSheet(
title: 'Device Error',
message:
'Failed to get device ID. Please restart the app and try again.',
);
return false;
}
final String fcmToken = await DeviceUtils.ensureFcmToken(prefs);
final Login loginRes = await _api.loginParsed(
contactNo: phone,
deviceType: Platform.operatingSystem,
configId: 6,
deviceId: deviceId,
fcmToken: fcmToken,
pin: int.parse(_masterPinValue),
);
// Save user details from API response
if (loginRes.userid != null) {
await prefs.setInt(_prefsUserIdKey, loginRes.userid!);
}
final String? name = loginRes.fullname ?? loginRes.firstname;
final String? email = loginRes.email;
final String contact = (loginRes.contactno ?? currentPhone ?? '')
.toString();
final String? address = loginRes.address;
if (name != null && name.trim().isNotEmpty) {
await prefs.setString(_prefsUserNameKey, name.trim());
}
if (email != null && email.trim().isNotEmpty) {
await prefs.setString(_prefsUserEmailKey, email.trim());
}
if (contact.isNotEmpty) {
await prefs.setString(_prefsContactNoKey, _normalizePhone(contact));
}
if (address != null && address.trim().isNotEmpty) {
await prefs.setString(_prefsAddressKey, address.trim());
}
try {
if (currentPhone != null && currentPhone!.isNotEmpty) {
currentPhone = _normalizePhone(currentPhone!);
}
await _notifyProfileController();
} catch (_) {}
return true;
}
String deviceId;
try {
deviceId = await DeviceUtils.ensureDeviceId(prefs);
} catch (e) {
_showBottomSheet(
title: 'Device Error',
message:
'Failed to get device ID. Please restart the app and try again.',
);
return false;
}
final String fcmToken = await DeviceUtils.ensureFcmToken(prefs);
final Login loginRes = await _api.loginParsed(
contactNo: phone,
deviceType: Platform.operatingSystem,
configId: 6,
deviceId: deviceId,
fcmToken: fcmToken,
pin: int.parse(inputPin),
);
final String msg = (loginRes.message ?? '').toLowerCase();
if ((loginRes.code != null && loginRes.code == 401) ||
msg.contains('invalid pin')) {
_showBottomSheet(
title: 'Invalid PIN',
message: 'Incorrect PIN. Please try again.',
);
return false;
}
if (loginRes.status == true || msg.contains('success')) {
await prefs.setString('dbPin', inputPin);
if (loginRes.userid != null) {
await prefs.setInt(_prefsUserIdKey, loginRes.userid!);
}
await prefs.setBool('logged_out', false);
final String? name = loginRes.fullname ?? loginRes.firstname;
final String? email = loginRes.email;
final String contact = (loginRes.contactno ?? currentPhone ?? '')
.toString();
final String? address = loginRes.address;
if (name != null && name.trim().isNotEmpty) {
await prefs.setString(_prefsUserNameKey, name.trim());
}
if (email != null && email.trim().isNotEmpty) {
await prefs.setString(_prefsUserEmailKey, email.trim());
}
if (contact.isNotEmpty) {
await prefs.setString(_prefsContactNoKey, _normalizePhone(contact));
}
if (address != null && address.trim().isNotEmpty) {
await prefs.setString(_prefsAddressKey, address.trim());
}
try {
if (currentPhone != null && currentPhone!.isNotEmpty) {
currentPhone = _normalizePhone(currentPhone!);
}
await _notifyProfileController();
} catch (_) {}
// Ensure backend session is refreshed on this device with latest FCM/device id
try {
await refreshSession(phone: currentPhone);
} catch (_) {}
return true;
}
_showBottomSheet(
title: 'Invalid PIN',
message: 'Incorrect PIN. Please try again.',
);
return false;
} catch (e) {
debugPrint('verifyPinWithServer error: $e');
_showBottomSheet(
title: 'Error',
message: 'Failed to verify PIN. Try again.',
);
return false;
}
}
}

View File

@@ -0,0 +1,55 @@
import 'dart:async';
import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/foundation.dart';
mixin ConnectivityControllerMixin on GetxController {
final RxBool isOnline = true.obs;
Timer? _tick;
@protected
Future<bool> checkInternet() async {
try {
final result = await InternetAddress.lookup('example.com');
return result.isNotEmpty && result.first.rawAddress.isNotEmpty;
} catch (_) {
return false;
}
}
@protected
void onConnectivityOnline() {}
@protected
void onConnectivityOffline() {}
void _startWatcher() {
_tick?.cancel();
_tick = Timer.periodic(const Duration(seconds: 5), (_) async {
final ok = await checkInternet();
final prev = isOnline.value;
if (ok != prev) {
isOnline.value = ok;
if (ok) {
onConnectivityOnline();
} else {
onConnectivityOffline();
}
} else {
isOnline.value = ok;
}
});
}
@override
void onInit() {
super.onInit();
_startWatcher();
}
@override
void onClose() {
_tick?.cancel();
super.onClose();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,125 @@
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DeliveryController extends GetxController {
// Exposed reactive fields if needed in UI
final RxString orderId = ''.obs;
final RxString orderStatus = ''.obs;
final RxInt tenantId = 0.obs;
final RxInt partnerId = 0.obs;
final RxInt locationId = 0.obs;
final RxInt orderHeaderId = 0.obs;
final RxInt deliveryId = 0.obs;
final RxInt userId = 0.obs;
final RxString latitude = ''.obs;
final RxString longitude = ''.obs;
// Preference keys (aligned with existing usage in app)
static const String kTenantId = 'delivery_tenantid';
static const String kPartnerId = 'delivery_partnerid';
static const String kLocationId = 'delivery_locationid';
static const String kOrderHeaderId = 'delivery_orderheaderid';
static const String kDeliveryId = 'delivery_deliveryid';
static const String kUserId = 'delivery_userid';
static const String kOrderId = 'delivery_orderid';
static const String kOrderStatus = 'delivery_orderstatus';
static const String kLat = 'delivery_latitude';
static const String kLng = 'delivery_longitude';
Future<void> saveFromQueueItem(Map<String, dynamic> delivery) async {
final prefs = await SharedPreferences.getInstance();
final int? tenantid = delivery['tenantid'] is int
? delivery['tenantid'] as int
: int.tryParse('${delivery['tenantid'] ?? ''}');
final int? partnerid = delivery['partnerid'] is int
? delivery['partnerid'] as int
: int.tryParse('${delivery['partnerid'] ?? ''}');
final int? locationid = delivery['locationid'] is int
? delivery['locationid'] as int
: int.tryParse('${delivery['locationid'] ?? ''}');
final int? orderheaderid = delivery['orderheaderid'] is int
? delivery['orderheaderid'] as int
: int.tryParse('${delivery['orderheaderid'] ?? ''}');
final int? deliveryid = delivery['deliveryid'] is int
? delivery['deliveryid'] as int
: int.tryParse('${delivery['deliveryid'] ?? ''}');
final int? userid = delivery['userid'] is int
? delivery['userid'] as int
: int.tryParse('${delivery['userid'] ?? ''}');
final String oid = (delivery['orderid'] ?? '').toString();
final String ostatus = (delivery['orderstatus'] ?? '').toString();
// Prefer deliverylat/long, fallback to droplat/lon
final String lat = (delivery['deliverylat'] ?? delivery['droplat'] ?? '')
.toString();
final String lon = (delivery['deliverylong'] ?? delivery['droplon'] ?? '')
.toString();
if (tenantid != null) await prefs.setInt(kTenantId, tenantid);
if (partnerid != null) await prefs.setInt(kPartnerId, partnerid);
if (locationid != null) await prefs.setInt(kLocationId, locationid);
if (orderheaderid != null) await prefs.setInt(kOrderHeaderId, orderheaderid);
if (deliveryid != null) await prefs.setInt(kDeliveryId, deliveryid);
if (userid != null) await prefs.setInt(kUserId, userid);
if (oid.isNotEmpty) await prefs.setString(kOrderId, oid);
if (ostatus.isNotEmpty) await prefs.setString(kOrderStatus, ostatus);
if (lat.isNotEmpty) await prefs.setString(kLat, lat);
if (lon.isNotEmpty) await prefs.setString(kLng, lon);
// Update observables
orderId.value = oid;
orderStatus.value = ostatus;
tenantId.value = tenantid ?? 0;
partnerId.value = partnerid ?? 0;
locationId.value = locationid ?? 0;
orderHeaderId.value = orderheaderid ?? 0;
deliveryId.value = deliveryid ?? 0;
userId.value = userid ?? 0;
latitude.value = lat;
longitude.value = lon;
}
Future<void> loadFromPrefs() async {
final prefs = await SharedPreferences.getInstance();
tenantId.value = prefs.getInt(kTenantId) ?? 0;
partnerId.value = prefs.getInt(kPartnerId) ?? 0;
locationId.value = prefs.getInt(kLocationId) ?? 0;
orderHeaderId.value = prefs.getInt(kOrderHeaderId) ?? 0;
deliveryId.value = prefs.getInt(kDeliveryId) ?? 0;
userId.value = prefs.getInt(kUserId) ?? 0;
orderId.value = prefs.getString(kOrderId) ?? '';
orderStatus.value = prefs.getString(kOrderStatus) ?? '';
latitude.value = prefs.getString(kLat) ?? '';
longitude.value = prefs.getString(kLng) ?? '';
}
Future<void> clear() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(kTenantId);
await prefs.remove(kPartnerId);
await prefs.remove(kLocationId);
await prefs.remove(kOrderHeaderId);
await prefs.remove(kDeliveryId);
await prefs.remove(kUserId);
await prefs.remove(kOrderId);
await prefs.remove(kOrderStatus);
await prefs.remove(kLat);
await prefs.remove(kLng);
orderId.value = '';
orderStatus.value = '';
tenantId.value = 0;
partnerId.value = 0;
locationId.value = 0;
orderHeaderId.value = 0;
deliveryId.value = 0;
userId.value = 0;
latitude.value = '';
longitude.value = '';
}
}

View File

@@ -0,0 +1,183 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:nearle/providers/deliverylog/deliverylog_provider.dart';
import 'package:nearle/views/helpers/constants/apiconstants.dart';
import 'package:nearle/background/foreground_service.dart' as fg;
import 'package:geolocator/geolocator.dart';
/// Controller for managing active delivery logs
/// Now delegates to the background service for actual logging
class LogController extends GetxController {
final CreateDeliveryLogProvider _logProvider = CreateDeliveryLogProvider();
static const String _offlineLogKey = 'offline_delivery_logs';
bool _isFlushing = false;
/// Start the delivery log streaming service (via foreground service)
Future<void> startLogging() async {
debugPrint('[ACTIVE_DELIVERY_LOG] Requesting start logging...');
// Attempt to flush offline logs on start
flushOfflineLogs();
// Only show foreground notification when rider is actually on duty
try {
final prefs = await SharedPreferences.getInstance();
final int onduty = prefs.getInt('onduty') ?? 0;
if (onduty != 1) {
debugPrint(
'[ACTIVE_DELIVERY_LOG] Skipping startLogging because onduty=$onduty',
);
return;
}
} catch (_) {
// If prefs fail, continue with best-effort start
}
if (Platform.isAndroid) {
if (await FlutterForegroundTask.isRunningService) {
debugPrint('[ACTIVE_DELIVERY_LOG] Foreground service already running');
return;
}
debugPrint(
'[ACTIVE_DELIVERY_LOG] Starting foreground service for delivery logs',
);
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'nearle_bg_service',
channelName: 'Background Service',
channelDescription:
'Keeps Nearle online updates running in background.',
channelImportance: NotificationChannelImportance.LOW,
priority: NotificationPriority.LOW,
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: ForegroundTaskOptions(
interval: 30000, // 30 seconds
isOnceEvent: false,
autoRunOnBoot: false,
allowWakeLock: true,
allowWifiLock: true,
),
);
// Check permissions before starting service to prevent Android 14 crash
final permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
debugPrint(
'[ACTIVE_DELIVERY_LOG] Location permission missing, skipping service start',
);
return;
}
try {
await FlutterForegroundTask.startService(
notificationTitle: 'Nearle is running',
notificationText: 'You are Currently on Duty !',
callback: fg.riderLogCallback,
);
} catch (e) {
debugPrint('[ACTIVE_DELIVERY_LOG] Failed to start service: $e');
}
} else {
debugPrint(
'[ACTIVE_DELIVERY_LOG] iOS/Web not fully supported for background service yet',
);
}
}
/// Stop the delivery log streaming service
/// Note: This might stop rider logs too if they share the service.
/// Usually we only stop if the user goes off-duty or logs out.
void stopLogging() {
debugPrint(
'[ACTIVE_DELIVERY_LOG] Stop logging requested (no-op to preserve rider logs)',
);
// We do not stop the service here because it might be running for Rider Logs.
// The service should be stopped by RiderLogController when going off-duty.
}
// ---------------- Offline Queue Logic (Foreground Helper) ----------------
/// Call this on app start or network restoration
Future<void> flushOfflineLogs() async {
if (_isFlushing) return;
_isFlushing = true;
try {
final prefs = await SharedPreferences.getInstance();
final List<String> queue = prefs.getStringList(_offlineLogKey) ?? [];
if (queue.isEmpty) return;
debugPrint(
'[ACTIVE_DELIVERY_LOG][OFFLINE] Flushing ${queue.length} offline logs...',
);
final List<String> remaining = [];
bool anySuccess = false;
// Determine API endpoint
final url = ApiConstants.mainRoute == 'live'
? ApiConstants.createDeliveryLogLive
: ApiConstants.createDeliveryLogDev;
for (final itemStr in queue) {
try {
final Map<String, dynamic> item = jsonDecode(itemStr);
final String orderId = item['orderId'] ?? '';
final Map<String, dynamic> payload = Map<String, dynamic>.from(
item['payload'] ?? {},
);
if (payload.isEmpty) continue;
debugPrint(
'[ACTIVE_DELIVERY_LOG][OFFLINE] Retrying for orderId: $orderId',
);
final result = await _logProvider
.createDeliveryLog(url, payload)
.timeout(const Duration(seconds: 8));
if (result != null) {
debugPrint(
'[ACTIVE_DELIVERY_LOG][OFFLINE] Success for orderId: $orderId',
);
anySuccess = true;
} else {
remaining.add(itemStr);
}
} catch (e) {
debugPrint(
'[ACTIVE_DELIVERY_LOG][OFFLINE] Error processing item: $e',
);
remaining.add(itemStr);
}
}
if (anySuccess || remaining.length != queue.length) {
await prefs.setStringList(_offlineLogKey, remaining);
debugPrint(
'[ACTIVE_DELIVERY_LOG][OFFLINE] Flush complete. Remaining: ${remaining.length}',
);
}
} catch (e) {
debugPrint('[ACTIVE_DELIVERY_LOG][OFFLINE] Flush error: $e');
} finally {
_isFlushing = false;
}
}
}

View File

@@ -0,0 +1,36 @@
import 'dart:io';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ProfileController extends GetxController {
final RxString imagePath = ''.obs;
final RxString userName = ''.obs;
final RxString userEmail = ''.obs;
final RxString userContact = ''.obs;
final RxString userAddress = ''.obs;
void setImagePath(String path) {
imagePath.value = path;
}
Future<void> loadFromPrefs() async {
final prefs = await SharedPreferences.getInstance();
userName.value = (prefs.getString('user_name') ?? '').trim();
userEmail.value = (prefs.getString('user_email') ?? '').trim();
userContact.value = (prefs.getString('contactno') ?? '').trim();
userAddress.value = (prefs.getString('user_address') ?? '').trim();
}
void setProfile({String? name, String? email, String? contact, String? address}) {
if (name != null && name.trim().isNotEmpty) userName.value = name.trim();
if (email != null && email.trim().isNotEmpty) userEmail.value = email.trim();
if (contact != null && contact.trim().isNotEmpty) userContact.value = contact.trim();
if (address != null && address.trim().isNotEmpty) userAddress.value = address.trim();
}
File? get fileOrNull {
final path = imagePath.value;
if (path.isEmpty) return null;
return File(path);
}
}

View File

@@ -0,0 +1,52 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
class RewardsController extends GetxController {
final RxInt totalPoints = 0.obs;
final RxBool isLoading = true.obs;
final RxString error = ''.obs;
Future<void> fetchBonusSummary(int userId) async {
try {
isLoading.value = true;
// Using dynamic userid passed from ProfilePage
final url = Uri.parse(
'https://jupiter.nearle.app/live/api/v1/utils/getuserbonussummary/?userid=$userId',
);
final response = await http.get(
url,
headers: {'Accept': 'application/json'},
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data is Map<String, dynamic> && data['status'] == true) {
// Check 'details' first, then 'data'
final dynamic content = data['details'] ?? data['data'];
if (content is Map<String, dynamic>) {
// "bonuspts": 40
totalPoints.value =
int.tryParse((content['bonuspts'] ?? '0').toString()) ?? 0;
debugPrint('[REWARDS] Fetched bonuspts: ${totalPoints.value}');
} else if (content is List && content.isNotEmpty) {
final first = content.first;
if(first is Map<String, dynamic>) {
totalPoints.value = int.tryParse((first['bonuspts'] ?? '0').toString()) ?? 0;
}
}
}
} else {
error.value = 'Failed to load rewards';
}
} catch (e) {
error.value = e.toString();
debugPrint('[REWARDS] Error: $e');
} finally {
isLoading.value = false;
}
}
}

View File

@@ -0,0 +1,33 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:nearle/Models/summary/riderweeklykms.dart';
import 'package:nearle/views/helpers/constants/apiconstants.dart';
class RiderWeeklyKmController {
final String baseUrl = ApiConstants.summaryriderkmLive;
Future<Map<String, dynamic>> getRiderWeeklyKms(int userId) async {
final url = Uri.parse("$baseUrl/getriderweeklykms?userid=$userId");
final response = await http.get(url);
if (response.statusCode == 200) {
final body = json.decode(response.body);
if (body['status'] == true) {
final details = (body['details'] as List)
.map((e) => RiderWeeklyKms.fromJson(e))
.toList();
return {
'details': details,
'total_kms': double.tryParse('${body['total_kms'] ?? 0}') ?? 0.0,
};
} else {
throw Exception(body['message'] ?? "API returned false status");
}
} else {
throw Exception("Failed to fetch (code: ${response.statusCode})");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
import 'package:get/get.dart';
import 'package:nearle/models/summary/deliverystats.dart';
import 'package:nearle/providers/summary/summary.dart';
class SummaryController extends GetxController {
final SummaryProvider _provider = SummaryProvider();
// Observables
var today = 0.obs;
var week = 0.obs;
var month = 0.obs;
var total = 0.obs;
var cancelled = 0.obs;
var isLoading = false.obs;
// Fetch stats and update values
Future<void> fetchSummaryStats(int userId) async {
try {
isLoading.value = true;
final DeliveryStats? stats = await _provider.fetchSummaryStats(userId);
if (stats != null) {
today.value = stats.today;
week.value = stats.week;
month.value = stats.month;
total.value = stats.total;
cancelled.value = stats.cancelled;
}
} catch (e) {
print('Controller error: $e');
} finally {
isLoading.value = false;
}
}
}

View File

@@ -0,0 +1,209 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math' show Random;
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:minio/io.dart';
import 'package:minio/minio.dart';
import 'package:nearle/Models/supportticket/support_ticket.dart';
// Minimal local stub for DigitalOcean Spaces client to avoid undefined name errors.
// Replace this with a real package or implementation for production uploads.
class dospace {
static DOSpaceClient DOSpace({
required String region,
required String accessKey,
required String secretKey,
}) =>
DOSpaceClient(region: region, accessKey: accessKey, secretKey: secretKey);
static final ACL = _ACL();
}
class _ACL {
final String publicRead = 'public-read';
}
class DOSpaceClient {
final String region;
final String accessKey;
final String secretKey;
DOSpaceClient({
required this.region,
required this.accessKey,
required this.secretKey,
});
Future<void> putObject({
required String bucketName,
required String objectName,
required File file,
required String acl,
required String contentType,
}) async {
// No-op stub: implement actual upload logic here or use a proper package.
await Future<void>.value();
}
}
class SupportTicketController extends GetxController {
final RxList<SupportTicketModel> tickets = <SupportTicketModel>[].obs;
final RxBool isLoading = true.obs;
final RxString errorMessage = ''.obs;
final RxBool isSubmitting = false.obs;
@override
void onInit() {
super.onInit();
fetchTickets();
}
// ---------- FETCH TICKETS ----------
Future<void> fetchTickets() async {
try {
isLoading(true);
errorMessage('');
const userId = 1242;
final url = Uri.parse(
'https://jupiter.nearle.app/live/api/v1/partners/getridersupport/?userid=$userId');
final response = await http.get(url, headers: {
'Accept': 'application/json',
});
if (response.statusCode != 200) {
throw Exception('Server error: ${response.statusCode}');
}
final Map<String, dynamic> jsonResponse = json.decode(response.body);
if (jsonResponse['status'] != true) {
throw Exception(jsonResponse['message'] ?? 'Unknown error');
}
final List<dynamic> data = jsonResponse['data'];
tickets.assignAll(data.map((e) => SupportTicketModel.fromJson(e)).toList());
} catch (e) {
errorMessage(e.toString());
} finally {
isLoading(false);
}
}
// ---------- UPLOAD IMAGE TO DO SPACES ----------
Future<String?> uploadImageToDOSpaces(File imageFile, int userId) async {
try {
final rng = Random();
const String region = "sgp1";
const String accessKey = "DO00NQER7N2FRYZAB2HR";
const String secretKey = "nMDewX25IBEu1FM5dakK+v28/WbW3TzBAwq913+dxP0";
const String bucketName = "nearle";
const String folderName = "support";
// File name
final String fileName = 'ticket-${rng.nextInt(10000)}-$userId.jpg';
// Object path inside the bucket
final String objectPath = "$folderName/$fileName";
// CDN URL you want
final String cdnUrl = "https://images.nearle.app/$objectPath";
// Initialize Minio
final minio = Minio(
endPoint: "$region.digitaloceanspaces.com",
accessKey: accessKey,
secretKey: secretKey,
region: region,
useSSL: true,
);
print("Uploading: $objectPath");
// Upload to DO Spaces
await minio.fPutObject(
bucketName,
objectPath,
imageFile.path,
metadata: {
"Content-Type": "image/jpeg",
"x-amz-acl": "public-read",
},
);
print("Uploaded Successfully: $cdnUrl");
return cdnUrl;
} catch (e) {
print("Upload error: $e");
Get.snackbar("Error", "Image upload failed.");
return null;
}
}
// ---------- CREATE TICKET ----------
// ---------- CREATE TICKET ----------
Future<bool> createTicket({
required int userid,
required String category,
required String priority,
required String subject,
required String issue,
List<XFile>? attachments,
}) async {
try {
isSubmitting(true);
String imageUrl = "";
// Upload first image if attached
if (attachments != null && attachments.isNotEmpty) {
final XFile xFile = attachments.first;
final File file = File(xFile.path);
final uploadedUrl = await uploadImageToDOSpaces(file, userid);
// Only assign if a valid URL (short length)
if (uploadedUrl != null && uploadedUrl.length < 200) {
imageUrl = uploadedUrl;
} else {
print("⚠️ Skipping image URL because its too long or invalid.");
}
}
// Create ticket request body
final Map<String, dynamic> payload = {
'userid': userid,
'category': category,
'priority': priority,
'subject': subject,
'issue': issue,
'image': imageUrl, // ✅ Always short string or empty
};
final response = await http.post(
Uri.parse('https://jupiter.nearle.app/live/api/v1/partners/createridersupport/'),
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: jsonEncode(payload),
);
if (response.statusCode != 200) {
throw Exception('Ticket creation failed: ${response.statusCode}');
}
final jsonResponse = jsonDecode(response.body);
if (jsonResponse['status'] != true) {
throw Exception(jsonResponse['message'] ?? 'Unknown error');
}
await fetchTickets(); // Refresh list after success
return true;
} catch (e) {
errorMessage(e.toString());
return false;
} finally {
isSubmitting(false);
}
}
}