Miler rider app: surface system, visible design language, backend lifecycle
Design system - MilerSurface ladder (canvas → working → raised → floating) with MilerPanel as layer 1; canvas moved to #DEE3EA so white separates at 1.290:1. - Visible vocabulary applied across Home, Deliveries, Activity, Account and the sheets: hero heads (tabular numeral + small caption, clamped at 1.3x), canvas wells for anything that opens, small filled tags for shelf labels, demoted placeholders. Recorded in DESIGN_SYSTEM.md §6. - One icon family: 222 Material glyphs migrated to Lucide; none left outside lib/xpress. - Colour semantics corrected: amber only for what is genuinely owed, brand red reserved for the live stop, disabled primaries go neutral rather than pale. Data and lifecycle - lib/data/lifecycle.dart reads mutations for what they prove; route_order.dart makes admin sequence the single ordering authority; service_day.dart, and stop_area.dart rewritten against live Coimbatore addresses (digit-token stripping, city stoplist, street suffixes, stammer collapse). - countLabel states the load once, in bags. Testing - 1440 tests passing; golden shot harnesses for Home, Deliveries, Activity, sheets and verify, with test/failures/ now gitignored (diff debris). - New pins: home_gutter_test, stop_area_test, plus updated structural bounds. Note: this commit also carries pre-existing working-tree deletions that were present before this work (API_SPEC.md, README.md, demo test fixtures). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
55
lib/xpress/controllers/connectivity_mixin.dart
Normal file
55
lib/xpress/controllers/connectivity_mixin.dart
Normal 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();
|
||||
}
|
||||
}
|
||||
2004
lib/xpress/controllers/deliveries_controller.dart
Normal file
2004
lib/xpress/controllers/deliveries_controller.dart
Normal file
File diff suppressed because it is too large
Load Diff
123
lib/xpress/controllers/delivery.dart
Normal file
123
lib/xpress/controllers/delivery.dart
Normal file
@@ -0,0 +1,123 @@
|
||||
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 = '';
|
||||
}
|
||||
}
|
||||
183
lib/xpress/controllers/logcontroller.dart
Normal file
183
lib/xpress/controllers/logcontroller.dart
Normal 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:miler/xpress/providers/deliverylog/deliverylog_provider.dart';
|
||||
import 'package:miler/xpress/views/helpers/constants/apiconstants.dart';
|
||||
import 'package:miler/xpress/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: 'doormile_bg_service',
|
||||
channelName: 'Background Service',
|
||||
channelDescription:
|
||||
'Keeps Doormile 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: 'Doormile 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
44
lib/xpress/controllers/profile_controller.dart
Normal file
44
lib/xpress/controllers/profile_controller.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
52
lib/xpress/controllers/rewards_controller.dart
Normal file
52
lib/xpress/controllers/rewards_controller.dart
Normal 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;
|
||||
import 'package:miler/xpress/data/delivery_api.dart';
|
||||
|
||||
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('${DeliveryApi.bonusSummary}?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;
|
||||
}
|
||||
}
|
||||
}
|
||||
31
lib/xpress/controllers/riderkm.dart
Normal file
31
lib/xpress/controllers/riderkm.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:miler/xpress/Models/summary/riderweeklykms.dart';
|
||||
import 'package:miler/xpress/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})");
|
||||
}
|
||||
}
|
||||
}
|
||||
1287
lib/xpress/controllers/riderlog.dart
Normal file
1287
lib/xpress/controllers/riderlog.dart
Normal file
File diff suppressed because it is too large
Load Diff
34
lib/xpress/controllers/summary_controller.dart
Normal file
34
lib/xpress/controllers/summary_controller.dart
Normal file
@@ -0,0 +1,34 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:miler/xpress/models/summary/deliverystats.dart';
|
||||
import 'package:miler/xpress/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;
|
||||
}
|
||||
}
|
||||
}
|
||||
211
lib/xpress/controllers/support_ticket.dart
Normal file
211
lib/xpress/controllers/support_ticket.dart
Normal file
@@ -0,0 +1,211 @@
|
||||
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:miler/xpress/Models/supportticket/support_ticket.dart';
|
||||
import 'package:miler/xpress/data/delivery_api.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('${DeliveryApi.getSupportTickets}?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 = String.fromEnvironment('SPACES_KEY');
|
||||
const String secretKey = String.fromEnvironment('SPACES_SECRET');
|
||||
const String bucketName = "doormile";
|
||||
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 = DeliveryApi.image(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 it's 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(DeliveryApi.createSupportTicket),
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user