Initial commit for Intaleq Driver

This commit is contained in:
Hamza-Ayed
2025-09-01 19:04:50 +03:00
parent 889c67a691
commit 8c7f3e3a75
46 changed files with 4300 additions and 6192 deletions

View File

@@ -3,17 +3,30 @@ import '../../constant/links.dart';
import '../../main.dart';
import 'crud.dart';
addError(String error, where) async {
CRUD().post(link: AppLink.addError, payload: {
'error': error.toString(), // Example error description
'userId': box.read(BoxName.driverID) ??
box.read(BoxName.passengerID), // Example user ID
'userType': box.read(BoxName.driverID) != null
? 'Driver'
: 'passenger', // Example user type
'phone': box.read(BoxName.phone) ??
box.read(BoxName.phoneDriver), // Example phone number
addError1(String error, String details, String where) async {
try {
// Get user information for the error log
final userId = box.read(BoxName.driverID) ?? box.read(BoxName.passengerID);
final userType =
box.read(BoxName.driverID) != null ? 'Driver' : 'passenger';
final phone = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);
'device': where
});
// Send the error data to the server
// Note: This is a fire-and-forget call. We don't await it or handle its response
// to prevent an infinite loop if the addError endpoint itself is failing.
CRUD().post(
link: AppLink.addError,
payload: {
'error': error.toString(),
'userId': userId.toString(),
'userType': userType,
'phone': phone.toString(),
'device': where, // The location of the error
'details': details, // The detailed stack trace or context
},
);
} catch (e) {
// If logging the error itself fails, print to the console to avoid infinite loops.
print("Failed to log error to server: $e");
}
}

View File

@@ -17,6 +17,201 @@ import 'gemeni.dart';
import 'upload_image.dart';
class CRUD {
/// Stores the signature of the last logged error to prevent duplicates.
static String _lastErrorSignature = '';
/// Stores the timestamp of the last logged error.
static DateTime _lastErrorTimestamp =
DateTime(2000); // Initialize with an old date
/// The minimum time that must pass before logging the same error again.
static const Duration _errorLogDebounceDuration = Duration(minutes: 1);
/// Asynchronously logs an error to the server with debouncing to prevent log flooding.
///
/// [error]: A concise description of the error.
/// [details]: Detailed information, such as a stack trace or the server response body.
/// [where]: The location in the code where the error occurred (e.g., 'ClassName.methodName').
static Future<void> addError(
String error, String details, String where) async {
try {
// Create a unique signature for the current error
final currentErrorSignature = '$where-$error';
final now = DateTime.now();
// Check if the same error occurred recently
if (currentErrorSignature == _lastErrorSignature &&
now.difference(_lastErrorTimestamp) < _errorLogDebounceDuration) {
// If it's the same error within the debounce duration, ignore it.
print("Debounced a duplicate error: $error");
return;
}
// Update the signature and timestamp for the new error
_lastErrorSignature = currentErrorSignature;
_lastErrorTimestamp = now;
// Get user information for the error log
final userId =
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID);
final userType =
box.read(BoxName.driverID) != null ? 'Driver' : 'passenger';
final phone = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);
// Send the error data to the server
// Note: This is a fire-and-forget call. We don't await it or handle its response
// to prevent an infinite loop if the addError endpoint itself is failing.
CRUD().post(
link: AppLink.addError,
payload: {
'error': error.toString(),
'userId': userId.toString(),
'userType': userType,
'phone': phone.toString(),
'device': where, // The location of the error
'details': details, // The detailed stack trace or context
},
);
} catch (e) {
// If logging the error itself fails, print to the console to avoid infinite loops.
print("Failed to log error to server: $e");
}
}
Future<dynamic> _makeRequest({
required String link,
Map<String, dynamic>? payload,
required Map<String, String> headers,
}) async {
var url = Uri.parse(link);
try {
var response = await http.post(
url,
body: payload,
headers: headers,
);
// Handle successful response (200 OK)
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData; // Return the full JSON object on success
} else {
// The API reported a logical failure (e.g., validation error)
addError(
'API Logic Error: ${jsonData['status']}',
'Response: ${response.body}',
'CRUD._makeRequest - $link',
);
return jsonData['status']; // Return the specific status string
}
} catch (e, stackTrace) {
// Error decoding the JSON response from the server
addError(
'JSON Decode Error: $e',
'Response Body: ${response.body}\nStack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
return 'failure';
}
}
// Handle Unauthorized (401) - typically means token expired
else if (response.statusCode == 401) {
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// The token refresh logic is handled before the call,
// but we log this case if it still happens.
// addError(
// 'Token Expired',
// 'A new token should have been fetched before this call.',
// 'CRUD._makeRequest - $link',
// );
return 'token_expired';
} else {
// Other 401 errors (e.g., invalid token)
addError(
'Unauthorized Error: ${jsonData['error']}',
'Status Code: 401',
'CRUD._makeRequest - $link',
);
return 'failure';
}
}
// Handle all other non-successful status codes
else {
addError(
'HTTP Error',
'Status Code: ${response.statusCode}\nResponse Body: ${response.body}',
'CRUD._makeRequest - $link',
);
return 'failure';
}
} catch (e, stackTrace) {
// Handle network exceptions (e.g., no internet, DNS error)
addError(
'HTTP Request Exception: $e',
'Stack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
return 'failure';
}
}
Future<dynamic> post({
required String link,
Map<String, dynamic>? payload,
}) async {
// 1. Check if the token is expired
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
// 2. If expired, get a new one
if (isTokenExpired) {
await LoginDriverController().getJWT();
}
// 3. Prepare the headers with the valid token
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
};
// 4. Make the request using the centralized helper
return await _makeRequest(
link: link,
payload: payload,
headers: headers,
);
}
/// Performs an authenticated POST request to the wallet endpoints.
/// Uses a separate JWT and HMAC for authentication.
Future<dynamic> postWallet({
required String link,
Map<String, dynamic>? payload,
}) async {
// 1. Get the specific JWT and HMAC for the wallet
var jwt = await LoginDriverController().getJwtWallet();
final hmac = box.read(BoxName.hmac);
// 2. Prepare the headers
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $jwt',
'X-HMAC-Auth': hmac.toString(),
};
// 3. Make the request using the centralized helper
return await _makeRequest(
link: link,
payload: payload,
headers: headers,
);
}
Future<dynamic> get({
required String link,
Map<String, dynamic>? payload,
@@ -125,132 +320,132 @@ class CRUD {
}
}
Future<dynamic> postWallet(
{required String link, Map<String, dynamic>? payload}) async {
var s = await LoginDriverController().getJwtWallet();
// Log.print('jwt: ${s}');
final hmac = box.read(BoxName.hmac);
// Log.print('hmac: ${hmac}');
var url = Uri.parse(link);
// Log.print('url: ${url}');
try {
// await LoginDriverController().getJWT();
// Future<dynamic> postWallet(
// {required String link, Map<String, dynamic>? payload}) async {
// var s = await LoginDriverController().getJwtWallet();
// // Log.print('jwt: ${s}');
// final hmac = box.read(BoxName.hmac);
// // Log.print('hmac: ${hmac}');
// var url = Uri.parse(link);
// // Log.print('url: ${url}');
// try {
// // await LoginDriverController().getJWT();
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $s',
'X-HMAC-Auth': hmac.toString(),
},
);
// Log.print('response.request:${response.request}');
// Log.print('response.body: ${response.body}');
// Log.print('payload:$payload');
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData;
} else {
return jsonData['status'];
}
} catch (e) {
// addError(e.toString(), 'crud().post - JSON decoding');
return 'failure';
}
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
// var response = await http.post(
// url,
// body: payload,
// headers: {
// "Content-Type": "application/x-www-form-urlencoded",
// 'Authorization': 'Bearer $s',
// 'X-HMAC-Auth': hmac.toString(),
// },
// );
// // Log.print('response.request:${response.request}');
// // Log.print('response.body: ${response.body}');
// // Log.print('payload:$payload');
// if (response.statusCode == 200) {
// try {
// var jsonData = jsonDecode(response.body);
// if (jsonData['status'] == 'success') {
// return jsonData;
// } else {
// return jsonData['status'];
// }
// } catch (e) {
// // addError(e.toString(), 'crud().post - JSON decoding');
// return 'failure';
// }
// } else if (response.statusCode == 401) {
// // Specifically handle 401 Unauthorized
// var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
// addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
return 'failure';
}
} else {
// addError('Non-200 response code: ${response.statusCode}',
// 'crud().post - Other');
return 'failure';
}
} catch (e) {
// addError('HTTP request error: $e', 'crud().post - HTTP');
return 'failure';
}
}
// if (jsonData['error'] == 'Token expired') {
// return 'token_expired'; // Return a specific value for token expiration
// } else {
// // Other 401 errors
// // addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
// return 'failure';
// }
// } else {
// // addError('Non-200 response code: ${response.statusCode}',
// // 'crud().post - Other');
// return 'failure';
// }
// } catch (e) {
// // addError('HTTP request error: $e', 'crud().post - HTTP');
// return 'failure';
// }
// }
Future<dynamic> post(
{required String link, Map<String, dynamic>? payload}) async {
var url = Uri.parse(link);
try {
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
if (isTokenExpired) {
await LoginDriverController().getJWT();
}
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
// 'Authorization': 'Bearer ${box.read(BoxName.jwt)}'
},
);
// print(response.request);
// Log.print('response.body: ${response.body}');
// print(payload);
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData;
} else {
return jsonData['status'];
}
} catch (e) {
// addError(e.toString(), url);
return 'failure';
}
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
// Future<dynamic> post(
// {required String link, Map<String, dynamic>? payload}) async {
// var url = Uri.parse(link);
// try {
// bool isTokenExpired = JwtDecoder.isExpired(X
// .r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
// .toString()
// .split(AppInformation.addd)[0]);
// if (isTokenExpired) {
// await LoginDriverController().getJWT();
// }
// var response = await http.post(
// url,
// body: payload,
// headers: {
// "Content-Type": "application/x-www-form-urlencoded",
// 'Authorization':
// 'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
// // 'Authorization': 'Bearer ${box.read(BoxName.jwt)}'
// },
// );
// print(response.request);
// Log.print('response.body: ${response.body}');
// print(payload);
// if (response.statusCode == 200) {
// try {
// var jsonData = jsonDecode(response.body);
// if (jsonData['status'] == 'success') {
// return jsonData;
// } else {
// return jsonData['status'];
// }
// } catch (e) {
// // addError(e.toString(), url);
// return 'failure';
// }
// } else if (response.statusCode == 401) {
// // Specifically handle 401 Unauthorized
// var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
// await Get.put(LoginDriverController()).getJWT();
// MyDialog().getDialog(
// 'Session expired. Please log in again.'.tr,
// '',
// () {
// Get.put(LoginController()).loginUsingCredentials(
// box.read(BoxName.passengerID), box.read(BoxName.email));
// Get.back();
// },
// );
// if (jsonData['error'] == 'Token expired') {
// // Show snackbar prompting to re-login
// // await Get.put(LoginDriverController()).getJWT();
// // MyDialog().getDialog(
// // 'Session expired. Please log in again.'.tr,
// // '',
// // () {
// // Get.put(LoginController()).loginUsingCredentials(
// // box.read(BoxName.passengerID), box.read(BoxName.email));
// // Get.back();
// // },
// // );
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
// addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
return 'failure';
}
} else {
// addError('Non-200 response code: ${response.statusCode}',
// 'crud().post - Other');
return 'failure';
}
} catch (e) {
// addError('HTTP request error: $e', 'crud().post - HTTP');
return 'failure';
}
}
// return 'token_expired'; // Return a specific value for token expiration
// } else {
// // Other 401 errors
// // addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
// return 'failure';
// }
// } else {
// // addError('Non-200 response code: ${response.statusCode}',
// // 'crud().post - Other');
// return 'failure';
// }
// } catch (e) {
// // addError('HTTP request error: $e', 'crud().post - HTTP');
// return 'failure';
// }
// }
Future<dynamic> getAgoraToken({
required String channelName,
@@ -579,7 +774,10 @@ class CRUD {
url,
body: payload,
);
Log.print('esponse.body: ${response.body}');
Log.print('esponse.body: ${response.request}');
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'OK') {
return jsonData;
}

View File

@@ -290,7 +290,6 @@ class AI extends GetxController {
'site': (idBackSy['address'].toString()) ?? 'Not specified',
'employmentType': 'Not specified',
};
Log.print('payload driver: ${payload}');
try {
var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
@@ -303,7 +302,6 @@ class AI extends GetxController {
isDriverSaved = true;
box.write(BoxName.emailDriver,
'${box.read(BoxName.phoneDriver)}${Env.email}');
Log.print('BoxName.emailDriver: ${box.read(BoxName.emailDriver)}');
mySnackbarSuccess('Driver data saved successfully');
} else {
mySnackeBarError('${'Failed to save driver data'.tr}: }');
@@ -345,7 +343,6 @@ class AI extends GetxController {
'color_hex': vehicleFrontSy['colorHex'].toString(),
'fuel': vehicleBackSy['fuel'].toString(),
};
Log.print('payload: ${payload}');
var res =
await CRUD().post(link: AppLink.addRegisrationCar, payload: payload);
isLoading = false;
@@ -500,7 +497,6 @@ class AI extends GetxController {
final response = await request.send();
final result = await http.Response.fromStream(response);
Log.print('result: ${result.body}');
if (result.statusCode == 200) {
final responseData = jsonDecode(result.body);
@@ -557,7 +553,6 @@ class AI extends GetxController {
isloading = false;
update();
MyDialog().getDialog("Error".tr, e.toString(), () => Get.back());
Log.print('e: ${e}');
}
}
@@ -620,10 +615,7 @@ class AI extends GetxController {
var extractedString =
await CRUD().arabicTextExtractByVisionAndAI(imagePath: imagePath);
var json = jsonDecode(extractedString);
// Log.print('extractedString: ${extractedString}');
var textValues = CRUD().extractTextFromLines(json);
Log.print('textValues: $textValues');
// Log.print('json: ${json}');
DocumentType detectedType = checkDocumentType(textValues);
String expectedDocument = getExpectedDocument(imagePath);
@@ -930,7 +922,6 @@ class AI extends GetxController {
jsonDecode(responseData['content'][0]['text']);
} else if (idType == 'non_id_front') {
responseNonIdCardFront = jsonDecode(responseData['content'][0]['text']);
Log.print('responseNonIdCardFront: $responseNonIdCardFront');
} else if (idType == 'non_id_back') {
responseNonIdCardBack = jsonDecode(responseData['content'][0]['text']);
}