8/11/1
This commit is contained in:
590
lib/controller/admin/register_captain_controller.dart
Normal file
590
lib/controller/admin/register_captain_controller.dart
Normal file
@@ -0,0 +1,590 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:ffi';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../constant/api_key.dart';
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../constant/info.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../constant/style.dart';
|
||||
import '../../main.dart';
|
||||
import '../functions/crud.dart';
|
||||
|
||||
class RegisterCaptainController extends GetxController {
|
||||
bool isDriverSaved = false;
|
||||
bool isCarSaved = false;
|
||||
Map<String, dynamic>? arguments;
|
||||
String? driverId;
|
||||
String? email;
|
||||
String? phone;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
arguments = Get.arguments;
|
||||
initArguments();
|
||||
}
|
||||
|
||||
void driveInit() {
|
||||
arguments = Get.arguments;
|
||||
initArguments();
|
||||
}
|
||||
|
||||
void initArguments() {
|
||||
if (arguments != null) {
|
||||
driverId = arguments!['driverId'];
|
||||
email = arguments!['email'];
|
||||
phone = arguments!['phone_number'];
|
||||
} else {
|
||||
print('Arguments are null');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> responseMap = {};
|
||||
Map<String, dynamic> responseCarLicenseMapJordan = {};
|
||||
Map<String, dynamic> responseBackCarLicenseMap = {};
|
||||
Map<String, dynamic> responseIdCardMap = {};
|
||||
Map<String, dynamic> responseIdCardDriverEgyptBack = {};
|
||||
Map<String, dynamic> responseForComplaint = {};
|
||||
Map<String, dynamic> responseIdCardDriverEgyptFront = {};
|
||||
Map<String, dynamic> responseIdEgyptFront = {};
|
||||
Map<String, dynamic> responseCriminalRecordEgypt = {};
|
||||
Map<String, dynamic> responseIdEgyptBack = {};
|
||||
Map<String, dynamic> responseIdEgyptDriverLicense = {};
|
||||
String? responseIdCardDriverEgypt1;
|
||||
bool isloading = false;
|
||||
var image;
|
||||
DateTime now = DateTime.now();
|
||||
|
||||
bool isLoading = false;
|
||||
Future allMethodForAI(String prompt, imagePath, driverID) async {
|
||||
isLoading = true;
|
||||
update();
|
||||
|
||||
var extractedString = await CRUD().arabicTextExtractByVisionAndAI(
|
||||
imagePath: imagePath, driverID: driverID);
|
||||
var json = jsonDecode(extractedString);
|
||||
var textValues = extractTextFromLines(json);
|
||||
// await Get.put(AI()).geminiAiExtraction(prompt, textValues, imagePath);
|
||||
await Get.put(RegisterCaptainController())
|
||||
.anthropicAI(textValues, prompt, imagePath);
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
String extractTextFromLines(Map<String, dynamic> jsonData) {
|
||||
final readResult = jsonData['readResult'];
|
||||
final blocks = readResult['blocks'];
|
||||
|
||||
final StringBuffer buffer = StringBuffer();
|
||||
|
||||
for (final block in blocks) {
|
||||
final lines = block['lines'];
|
||||
for (final line in lines) {
|
||||
final text = line['text'];
|
||||
buffer.write(text);
|
||||
buffer.write('\n');
|
||||
}
|
||||
}
|
||||
|
||||
return buffer.toString().trim();
|
||||
}
|
||||
|
||||
List driverNotCompleteRegistration = [];
|
||||
getDriverNotCompleteRegistration() async {
|
||||
var res = await CRUD()
|
||||
.get(link: AppLink.getDriverNotCompleteRegistration, payload: {});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res)['message'];
|
||||
driverNotCompleteRegistration = d;
|
||||
update();
|
||||
} else {
|
||||
Get.snackbar(res, '');
|
||||
}
|
||||
}
|
||||
|
||||
final today = DateTime.now();
|
||||
|
||||
Future<void> addDriverAndCarEgypt() async {
|
||||
final expiryDate = responseIdEgyptDriverLicense['expiry_date'];
|
||||
final expiryDateTime = DateTime.tryParse(expiryDate);
|
||||
final isExpired = expiryDateTime != null && expiryDateTime.isBefore(today);
|
||||
|
||||
final taxExpiryDate = responseIdCardDriverEgyptBack['tax_expiry'];
|
||||
|
||||
// Get the inspection date from the response
|
||||
final inspectionDate = responseIdCardDriverEgyptBack['inspection_date'];
|
||||
final year = int.parse(inspectionDate.split('-')[0]);
|
||||
// Try parsing the tax expiry date. If it fails, set it to null.
|
||||
final taxExpiryDateTime = DateTime.tryParse(taxExpiryDate ?? '');
|
||||
final isExpiredCar =
|
||||
taxExpiryDateTime != null && taxExpiryDateTime.isBefore(today);
|
||||
|
||||
// Check if the inspection date is before today
|
||||
final inspectionDateTime = DateTime(year, 1, 1);
|
||||
final isInspectionExpired = inspectionDateTime.isBefore(today);
|
||||
|
||||
if (isExpiredCar || isInspectionExpired) {
|
||||
Get.defaultDialog(
|
||||
title: 'Expired Driver’s License'.tr,
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.warning, size: 48, color: Colors.red),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Your driver’s license and/or car tax has expired. Please renew them before proceeding.'
|
||||
.tr,
|
||||
textAlign: TextAlign.center,
|
||||
style: AppStyle.title,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
// await Get.find<TextToSpeechController>().speakText(
|
||||
// 'Your driver’s license and/or car tax has expired. Please renew them before proceeding.'
|
||||
// .tr,
|
||||
// );
|
||||
},
|
||||
icon: const Icon(Icons.volume_up),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
},
|
||||
child: const Text('OK'),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else if (isExpired) {
|
||||
Get.defaultDialog(
|
||||
title: 'Expired Driver’s License'.tr,
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.warning, size: 48, color: Colors.red),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Your driver’s license has expired. Please renew it before proceeding.'
|
||||
.tr,
|
||||
textAlign: TextAlign.center,
|
||||
style: AppStyle.title,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
// await Get.find<TextToSpeechController>().speakText(
|
||||
// 'Your driver’s license has expired. Please renew it before proceeding.'
|
||||
// .tr,
|
||||
// );
|
||||
},
|
||||
icon: const Icon(Icons.volume_up),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
},
|
||||
child: const Text('OK'),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else if (responseIdEgyptDriverLicense['national_number']
|
||||
.toString()
|
||||
.substring(0, 12) !=
|
||||
responseIdEgyptBack['nationalID'].toString().substring(0, 12)) {
|
||||
Get.defaultDialog(
|
||||
barrierDismissible: false,
|
||||
title: 'ID Mismatch',
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.warning, size: 48, color: Colors.red),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'The national number on your driver’s license does not match the one on your ID document. Please verify and provide the correct documents.'
|
||||
.tr,
|
||||
textAlign: TextAlign.center,
|
||||
style: AppStyle.title,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
// await Get.find<TextToSpeechController>().speakText(
|
||||
// 'The national number on your driver’s license does not match the one on your ID document. Please verify and provide the correct documents.',
|
||||
// );
|
||||
},
|
||||
icon: const Icon(Icons.volume_up),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
},
|
||||
child: const Text('OK'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
// else if (responseCriminalRecordEgypt['FullName'] !=
|
||||
// responseIdEgyptDriverLicense['name_arabic']) {
|
||||
// Get.defaultDialog(
|
||||
// barrierDismissible: false,
|
||||
// title: 'Criminal Record Mismatch',
|
||||
// content: Column(
|
||||
// mainAxisSize: MainAxisSize.min,
|
||||
// children: [
|
||||
// const Icon(Icons.warning, size: 48, color: Colors.red),
|
||||
// const SizedBox(height: 16),
|
||||
// Text(
|
||||
// 'The full name on your criminal record does not match the one on your driver’s license. Please verify and provide the correct documents.'
|
||||
// .tr,
|
||||
// textAlign: TextAlign.center,
|
||||
// style: AppStyle.title,
|
||||
// ),
|
||||
// const SizedBox(height: 16),
|
||||
// IconButton(
|
||||
// onPressed: () async {
|
||||
// await Get.find<TextToSpeechController>().speakText(
|
||||
// 'The full name on your criminal record does not match the one on your driver’s license. Please verify and provide the correct documents.'
|
||||
// .tr,
|
||||
// );
|
||||
// },
|
||||
// icon: const Icon(Icons.volume_up),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// actions: [
|
||||
// TextButton(
|
||||
// onPressed: () {
|
||||
// Get.back();
|
||||
// },
|
||||
// child: const Text('OK'),
|
||||
// ),
|
||||
// ],
|
||||
// );
|
||||
// }
|
||||
else {
|
||||
await addDriverEgypt();
|
||||
await addRegistrationCarEgypt();
|
||||
|
||||
if (isCarSaved && isDriverSaved) {
|
||||
Get.snackbar('added', '',
|
||||
backgroundColor:
|
||||
AppColor.greenColor); // Get.offAll(() => HomeCaptain());
|
||||
// Get.offAll(() => HomeCaptain());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addDriverEgypt() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
|
||||
var payload = {
|
||||
'first_name': responseIdEgyptDriverLicense['firstName']?.toString() ??
|
||||
'Not specified',
|
||||
'last_name': responseIdEgyptDriverLicense['lastName']?.toString() ??
|
||||
'Not specified',
|
||||
'email': email?.toString() ?? 'Not specified',
|
||||
'phone': phone?.toString() ?? 'Not specified',
|
||||
'id': driverId?.toString() ?? 'Not specified',
|
||||
'password': '123456',
|
||||
'gender': responseIdEgyptBack['gender']?.toString() ?? 'Not specified',
|
||||
'license_type':
|
||||
responseIdEgyptDriverLicense['license_type']?.toString() ??
|
||||
'Not specified',
|
||||
'national_number':
|
||||
responseIdEgyptBack['nationalID']?.toString() ?? 'Not specified',
|
||||
'name_arabic': responseIdEgyptDriverLicense['name_arabic']?.toString() ??
|
||||
'Not specified',
|
||||
'name_english':
|
||||
responseIdEgyptDriverLicense['name_english']?.toString() ??
|
||||
'Not specified',
|
||||
'issue_date': responseIdEgyptDriverLicense['issue_date']?.toString() ??
|
||||
'Not specified',
|
||||
'expiry_date': responseIdEgyptDriverLicense['expiry_date']?.toString() ??
|
||||
'Not specified',
|
||||
'license_categories': responseIdEgyptDriverLicense['license_categories']
|
||||
is List
|
||||
? responseIdEgyptDriverLicense['license_categories'].join(', ')
|
||||
: responseIdEgyptDriverLicense['license_categories']?.toString() ??
|
||||
'Not specified',
|
||||
'address': responseIdEgyptFront['address']?.toString() ?? 'Not specified',
|
||||
'card_id': responseIdEgyptFront['card_id']?.toString() ?? 'Not specified',
|
||||
'occupation':
|
||||
responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
|
||||
'education':
|
||||
responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
|
||||
'licenseIssueDate':
|
||||
responseIdEgyptDriverLicense['issue_date']?.toString() ??
|
||||
'Not specified',
|
||||
'religion':
|
||||
responseIdEgyptBack['religion']?.toString() ?? 'Not specified',
|
||||
'status': 'yet',
|
||||
'birthdate': responseIdEgyptFront['dob']?.toString() ?? 'Not specified',
|
||||
'maritalStatus':
|
||||
responseIdEgyptBack['maritalStatus']?.toString() ?? 'Not specified',
|
||||
'site': responseIdEgyptDriverLicense['address']?.toString() ??
|
||||
'Not specified',
|
||||
'employmentType':
|
||||
responseIdEgyptDriverLicense['employmentType']?.toString() ??
|
||||
'Not specified',
|
||||
};
|
||||
var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
|
||||
var status1 = jsonDecode(res);
|
||||
isLoading = false;
|
||||
update();
|
||||
// Handle response
|
||||
if (status1['status'] == 'success') {
|
||||
isDriverSaved = true;
|
||||
Get.snackbar('Success', 'Driver data saved successfully',
|
||||
backgroundColor: AppColor.greenColor);
|
||||
} else {
|
||||
Get.snackbar('Error', 'Failed to save driver data',
|
||||
backgroundColor: Colors.red);
|
||||
}
|
||||
}
|
||||
|
||||
addCriminalDeocuments() async {
|
||||
var res = await CRUD().post(link: AppLink.addCriminalDocuments, payload: {
|
||||
"driverId": box.read(BoxName.driverID),
|
||||
"IssueDate": responseCriminalRecordEgypt['IssueDate'],
|
||||
"InspectionResult": responseCriminalRecordEgypt['InspectionResult'],
|
||||
});
|
||||
if (res != 'failure') {
|
||||
Get.snackbar('uploaded sucssefuly'.tr, '');
|
||||
}
|
||||
}
|
||||
|
||||
Future addRegistrationCarEgypt() async {
|
||||
try {
|
||||
isLoading = true;
|
||||
update();
|
||||
var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: {
|
||||
'driverID': driverId,
|
||||
'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
|
||||
'car_plate': responseIdCardDriverEgyptFront['car_plate'].toString(),
|
||||
'make': responseIdCardDriverEgyptBack['make'].toString(),
|
||||
'model': responseIdCardDriverEgyptBack['model'],
|
||||
'year': responseIdCardDriverEgyptBack['year'].toString(),
|
||||
'expiration_date':
|
||||
responseIdCardDriverEgyptFront['LicenseExpirationDate'].toString(),
|
||||
'color': responseIdCardDriverEgyptBack['color'],
|
||||
'owner': responseIdCardDriverEgyptFront['owner'],
|
||||
'color_hex': responseIdCardDriverEgyptBack['color_hex'].toString(),
|
||||
'address': responseIdCardDriverEgyptFront['address'].toString(),
|
||||
'displacement': responseIdCardDriverEgyptBack['engine'].toString(),
|
||||
'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
|
||||
'registration_date':
|
||||
'${responseIdCardDriverEgyptBack['inspection_date']}',
|
||||
});
|
||||
isLoading = false;
|
||||
update();
|
||||
var status = jsonDecode(res);
|
||||
if (status['status'] == 'success') {
|
||||
isCarSaved = true;
|
||||
Get.snackbar('Success', 'message',
|
||||
backgroundColor: AppColor.greenColor);
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
Future getComplaintDataToAI() async {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getComplaintAllDataForDriver,
|
||||
payload: {'driver_id': driverId.toString()},
|
||||
);
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res)['message'];
|
||||
return d;
|
||||
} else {
|
||||
return [
|
||||
{'data': 'no data'}
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> anthropicAIForComplaint() async {
|
||||
var dataComplaint = await getComplaintDataToAI();
|
||||
var messagesData = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "$dataComplaint ${AppInformation.complaintPrompt} "
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
var requestBody = jsonEncode({
|
||||
"model": "claude-3-haiku-20240307",
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0,
|
||||
"system": "Json output only without any additional ",
|
||||
"messages": messagesData,
|
||||
});
|
||||
final response = await http.post(
|
||||
Uri.parse('https://api.anthropic.com/v1/messages'),
|
||||
headers: {
|
||||
'x-api-key': AK.anthropicAIkeySeferNew,
|
||||
'anthropic-version': '2023-06-01',
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: requestBody,
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
var responseData = jsonDecode(utf8.decode(response.bodyBytes));
|
||||
// Process the responseData as needed
|
||||
|
||||
responseForComplaint = jsonDecode(responseData['content'][0]['text']);
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> anthropicAI(
|
||||
String payload, String prompt, String idType) async {
|
||||
var messagesData = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "$payload $prompt"}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
var requestBody = jsonEncode({
|
||||
"model": "claude-3-haiku-20240307",
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0,
|
||||
"system": "Json output only without any additional ",
|
||||
"messages": messagesData,
|
||||
});
|
||||
|
||||
final response = await http.post(
|
||||
Uri.parse('https://api.anthropic.com/v1/messages'),
|
||||
headers: {
|
||||
'x-api-key': AK.anthropicAIkeySeferNew,
|
||||
'anthropic-version': '2023-06-01',
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: requestBody,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
var responseData = jsonDecode(utf8.decode(response.bodyBytes));
|
||||
// Process the responseData as needed
|
||||
if (idType == 'car_back') {
|
||||
responseIdCardDriverEgyptBack =
|
||||
jsonDecode(responseData['content'][0]['text']);
|
||||
} else if (idType == 'car_front') {
|
||||
responseIdCardDriverEgyptFront =
|
||||
jsonDecode(responseData['content'][0]['text']);
|
||||
} else if (idType == 'id_front') {
|
||||
responseIdEgyptFront = jsonDecode(responseData['content'][0]['text']);
|
||||
} else if (idType == 'id_back') {
|
||||
responseIdEgyptBack = jsonDecode(responseData['content'][0]['text']);
|
||||
} else if (idType == 'driver_license') {
|
||||
responseIdEgyptDriverLicense =
|
||||
jsonDecode(responseData['content'][0]['text']);
|
||||
} else if (idType == 'criminalRecord') {
|
||||
responseCriminalRecordEgypt =
|
||||
jsonDecode(responseData['content'][0]['text']);
|
||||
}
|
||||
|
||||
update();
|
||||
return responseData.toString();
|
||||
}
|
||||
return responseIdCardDriverEgyptBack.toString();
|
||||
}
|
||||
|
||||
Future<void> geminiAiExtraction(String prompt, payload, String idType) async {
|
||||
var requestBody = jsonEncode({
|
||||
"contents": [
|
||||
{
|
||||
"parts": [
|
||||
{"text": "$payload $prompt"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"generationConfig": {
|
||||
"temperature": 1,
|
||||
"topK": 64,
|
||||
"topP": 0.95,
|
||||
"maxOutputTokens": 8192,
|
||||
"stopSequences": []
|
||||
},
|
||||
"safetySettings": [
|
||||
{
|
||||
"category": "HARM_CATEGORY_HARASSMENT",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
},
|
||||
{
|
||||
"category": "HARM_CATEGORY_HATE_SPEECH",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
},
|
||||
{
|
||||
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
},
|
||||
{
|
||||
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
final response = await http.post(
|
||||
Uri.parse(
|
||||
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||||
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${AK.geminiApi}'),
|
||||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key=${AK.geminiApi}'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: requestBody,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
var responseData = jsonDecode(response.body);
|
||||
// Process the responseData as needed
|
||||
|
||||
var result = responseData['candidates'][0]['content']['parts'][0]['text'];
|
||||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||||
String? jsonString =
|
||||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||||
|
||||
if (jsonString != null) {
|
||||
// Convert the JSON object to a String
|
||||
jsonString = jsonEncode(json.decode(jsonString));
|
||||
|
||||
if (idType == 'car_back') {
|
||||
responseIdCardDriverEgyptBack = jsonDecode(jsonString);
|
||||
} else if (idType == 'car_front') {
|
||||
responseIdCardDriverEgyptFront = jsonDecode(jsonString);
|
||||
} else if (idType == 'id_front') {
|
||||
responseIdEgyptFront = jsonDecode(jsonString);
|
||||
} else if (idType == 'id_back') {
|
||||
responseIdEgyptBack = jsonDecode(jsonString);
|
||||
} else if (idType == 'driver_license') {
|
||||
responseIdEgyptDriverLicense = jsonDecode(jsonString);
|
||||
}
|
||||
|
||||
update();
|
||||
} else {
|
||||
Get.snackbar('Error', "JSON string not found",
|
||||
backgroundColor: AppColor.redColor);
|
||||
}
|
||||
|
||||
// Rest of your code...
|
||||
} else {}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,11 @@ import '../functions/crud.dart';
|
||||
class StaticController extends GetxController {
|
||||
Map<String, dynamic> jsonData1 = {};
|
||||
Map<String, dynamic> jsonData2 = {};
|
||||
List staticList = [];
|
||||
var chartDataPassengers;
|
||||
var chartDataDrivers;
|
||||
var chartDataDriversCalling;
|
||||
var chartDataDriversMatchingNotes;
|
||||
bool isLoading = false;
|
||||
String totalMonthlyPassengers = '';
|
||||
String totalMonthlyDrivers = '';
|
||||
@@ -57,17 +60,32 @@ class StaticController extends GetxController {
|
||||
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
|
||||
isLoading = false;
|
||||
final List<dynamic> jsonData = jsonResponse['message'];
|
||||
totalMonthlyDrivers = jsonData[0]['totalMonthly'].toString();
|
||||
staticList = jsonData;
|
||||
totalMonthlyDrivers = jsonData[0]['totalDrivers'].toString();
|
||||
driversData = jsonData.map<MonthlyDriverInstall>((item) {
|
||||
return MonthlyDriverInstall.fromJson(item);
|
||||
}).toList();
|
||||
final List<FlSpot> spots = driversData
|
||||
.map((data) => FlSpot(
|
||||
data.day.toDouble(),
|
||||
data.totalDrivers.toDouble(),
|
||||
data.dailyTotalDrivers.toDouble(),
|
||||
))
|
||||
.toList();
|
||||
chartDataDrivers = spots;
|
||||
final List<FlSpot> spotsCalling = driversData
|
||||
.map((data) => FlSpot(
|
||||
data.day.toDouble(),
|
||||
data.dailyTotalCallingDrivers.toDouble(),
|
||||
))
|
||||
.toList();
|
||||
chartDataDriversCalling = spotsCalling;
|
||||
final List<FlSpot> spotsTotalMatchingNotes = driversData
|
||||
.map((data) => FlSpot(
|
||||
data.day.toDouble(),
|
||||
data.dailyMatchingNotes.toDouble(),
|
||||
))
|
||||
.toList();
|
||||
chartDataDriversMatchingNotes = spotsTotalMatchingNotes;
|
||||
|
||||
update(); // Notify the observers about the data and loading state change
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import '../../constant/links.dart';
|
||||
import '../../constant/style.dart';
|
||||
import '../../main.dart';
|
||||
import '../../views/widgets/elevated_btn.dart';
|
||||
import '../notification_controller.dart';
|
||||
import 'local_notification.dart';
|
||||
|
||||
class FirebaseMessagesController extends GetxController {
|
||||
@@ -20,10 +21,11 @@ class FirebaseMessagesController extends GetxController {
|
||||
List<String> tokens = [];
|
||||
List<String> tokensPassengers = [];
|
||||
List dataTokens = [];
|
||||
List dataTokensPassenger = [];
|
||||
late String driverID;
|
||||
late String driverToken;
|
||||
NotificationSettings? notificationSettings;
|
||||
|
||||
bool isLoading = false;
|
||||
Future<void> getNotificationSettings() async {
|
||||
// Get the current notification settings
|
||||
NotificationSettings? notificationSettings =
|
||||
@@ -78,27 +80,126 @@ class FirebaseMessagesController extends GetxController {
|
||||
}
|
||||
}
|
||||
|
||||
Future getAllTokenDrivers() async {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.getAllTokenDrivers),
|
||||
headers: {
|
||||
'Authorization':
|
||||
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
|
||||
},
|
||||
body: {},
|
||||
);
|
||||
var jsonResponse = jsonDecode(res.body);
|
||||
if (jsonResponse['status'] == 'success') {
|
||||
dataTokens = jsonResponse['data'];
|
||||
for (var i = 0; i < dataTokens.length; i++) {
|
||||
tokens.add(jsonResponse['data'][i]['token']);
|
||||
var currentPage = 1;
|
||||
var totalPages = 1;
|
||||
Future<void> getAllTokenDrivers({int page = 1}) async {
|
||||
isLoading = true;
|
||||
try {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.getAllTokenDrivers),
|
||||
headers: {
|
||||
'Authorization':
|
||||
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
|
||||
},
|
||||
body: {
|
||||
'page': page.toString(),
|
||||
},
|
||||
);
|
||||
|
||||
var jsonResponse = jsonDecode(res.body);
|
||||
if (jsonResponse['status'] == 'success') {
|
||||
var newData = jsonResponse['data'] as List;
|
||||
if (page == 1) {
|
||||
dataTokens.clear();
|
||||
tokens.clear();
|
||||
}
|
||||
dataTokens.addAll(newData);
|
||||
for (var item in newData) {
|
||||
tokens.add(item['token']);
|
||||
}
|
||||
currentPage = int.parse(jsonResponse['currentPage']);
|
||||
totalPages = jsonResponse['totalPages'];
|
||||
box.write(BoxName.tokensDrivers, tokens);
|
||||
} else {
|
||||
Get.defaultDialog(
|
||||
title: "Warning", middleText: "No more data available");
|
||||
}
|
||||
box.write(BoxName.tokensDrivers, tokens);
|
||||
} else {
|
||||
Get.defaultDialog(title: "Warning", middleText: "Server Error");
|
||||
} catch (e) {
|
||||
Get.defaultDialog(title: "Error", middleText: "Server Error: $e");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
var currentPagePassenger = 1;
|
||||
var totalPagesPassenger = 1;
|
||||
Future<void> getAllTokenPassenger({int page = 1}) async {
|
||||
isLoading = true;
|
||||
try {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.getAllTokenDrivers),
|
||||
headers: {
|
||||
'Authorization':
|
||||
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
|
||||
},
|
||||
body: {
|
||||
'page': page.toString(),
|
||||
},
|
||||
);
|
||||
|
||||
var jsonResponse = jsonDecode(res.body);
|
||||
if (jsonResponse['status'] == 'success') {
|
||||
var newData = jsonResponse['data'] as List;
|
||||
if (page == 1) {
|
||||
dataTokensPassenger.clear();
|
||||
tokensPassengers.clear();
|
||||
}
|
||||
dataTokensPassenger.addAll(newData);
|
||||
for (var item in newData) {
|
||||
tokensPassengers.add(item['token']);
|
||||
}
|
||||
currentPagePassenger = int.parse(jsonResponse['currentPage']);
|
||||
totalPagesPassenger = jsonResponse['totalPages'];
|
||||
box.write(BoxName.tokensPassengers, tokensPassengers);
|
||||
} else {
|
||||
Get.defaultDialog(
|
||||
title: "Warning", middleText: "No more data available");
|
||||
}
|
||||
} catch (e) {
|
||||
Get.defaultDialog(title: "Error", middleText: "Server Error: $e");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool isSendingNotifications = false;
|
||||
Future<void> loadAllPagesAndSendNotifications() async {
|
||||
isSendingNotifications = true;
|
||||
currentPage = 1;
|
||||
|
||||
while (currentPage <= totalPages) {
|
||||
await getAllTokenDrivers(page: currentPage);
|
||||
await NotificationController().sendNotificationDrivers();
|
||||
print(tokens);
|
||||
if (currentPage < totalPages) {
|
||||
await Future.delayed(const Duration(seconds: 3));
|
||||
}
|
||||
currentPage++;
|
||||
}
|
||||
|
||||
isSendingNotifications = false;
|
||||
Get.snackbar("Success", "All notifications sent!");
|
||||
}
|
||||
|
||||
bool isSendingNotificationsPassenger = false;
|
||||
Future<void> loadAllPagesAndSendNotificationsPassengers() async {
|
||||
isSendingNotificationsPassenger = true;
|
||||
currentPage = 1;
|
||||
|
||||
while (currentPagePassenger <= totalPagesPassenger) {
|
||||
await getAllTokenPassenger(page: currentPagePassenger);
|
||||
await NotificationController().sendNotificationDrivers();
|
||||
print(tokensPassengers);
|
||||
if (currentPagePassenger < totalPagesPassenger) {
|
||||
await Future.delayed(const Duration(seconds: 3));
|
||||
}
|
||||
currentPagePassenger++;
|
||||
}
|
||||
|
||||
isSendingNotificationsPassenger = false;
|
||||
Get.snackbar("Success", "All notifications sent!");
|
||||
}
|
||||
|
||||
Future getAllTokenPassengers() async {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.getAllTokenPassengers),
|
||||
|
||||
@@ -8,9 +8,7 @@ import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../env/env.dart';
|
||||
import '../../main.dart';
|
||||
import 'gemeni.dart';
|
||||
import 'llama_ai.dart';
|
||||
import 'upload_image.dart';
|
||||
import '../../print.dart';
|
||||
|
||||
class CRUD {
|
||||
Future<dynamic> get({
|
||||
@@ -93,11 +91,11 @@ class CRUD {
|
||||
return response.statusCode;
|
||||
}
|
||||
|
||||
Future allMethodForAI(String prompt, linkPHP, imagePath) async {
|
||||
Future allMethodForAI(String prompt, driverID, imagePath) async {
|
||||
// await ImageController().choosImage(linkPHP, imagePath);
|
||||
Future.delayed(const Duration(seconds: 2));
|
||||
var extractedString =
|
||||
await arabicTextExtractByVisionAndAI(imagePath: imagePath);
|
||||
var extractedString = await arabicTextExtractByVisionAndAI(
|
||||
imagePath: imagePath, driverID: driverID);
|
||||
var json = jsonDecode(extractedString);
|
||||
var textValues = getAllTextValuesWithLineNumbers(json);
|
||||
// List<String> textValues = getAllTextValues(json);
|
||||
@@ -166,23 +164,24 @@ class CRUD {
|
||||
|
||||
Future<dynamic> arabicTextExtractByVisionAndAI({
|
||||
required String imagePath,
|
||||
required String driverID,
|
||||
}) async {
|
||||
var headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Ocp-Apim-Subscription-Key': '21010e54b50f41a4904708c526e102df'
|
||||
'Ocp-Apim-Subscription-Key': AK.ocpApimSubscriptionKey
|
||||
};
|
||||
// var url = Uri.parse(
|
||||
// 'https://ocrhamza.cognitiveservices.azure.com/vision/v2.1/ocr?language=ar',
|
||||
// );
|
||||
String imagePathFull =
|
||||
'${AppLink.server}card_image/$imagePath-${box.read(BoxName.driverID)}.jpg';
|
||||
|
||||
String imagePathFull =
|
||||
'${AppLink.server}/card_image/$imagePath-$driverID.jpg';
|
||||
Log.print('imagePathFull: $imagePathFull');
|
||||
var request = http.Request(
|
||||
'POST',
|
||||
Uri.parse(
|
||||
'https://ocrhamza.cognitiveservices.azure.com/vision/v2.1/ocr?language=ar'));
|
||||
'https://eastus.api.cognitive.microsoft.com/computervision/imageanalysis:analyze?features=caption,read&model-version=latest&language=en&api-version=2024-02-01'));
|
||||
request.body = json.encode({"url": imagePathFull});
|
||||
Log.print('request.body: ${request.body}');
|
||||
request.headers.addAll(headers);
|
||||
Log.print('request.headers: ${request.headers}');
|
||||
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
|
||||
@@ -16,11 +16,12 @@ class NotificationController extends GetxController {
|
||||
List<String> tokensPassengers = [];
|
||||
|
||||
getTokensDrivers() async {
|
||||
await FirebaseMessagesController().getAllTokenDrivers();
|
||||
await FirebaseMessagesController().loadAllPagesAndSendNotifications();
|
||||
}
|
||||
|
||||
getTokensPassengers() async {
|
||||
await FirebaseMessagesController().getAllTokenPassengers();
|
||||
await FirebaseMessagesController()
|
||||
.loadAllPagesAndSendNotificationsPassengers();
|
||||
}
|
||||
|
||||
Future<dynamic> sendNotificationDrivers() {
|
||||
@@ -56,8 +57,9 @@ class NotificationController extends GetxController {
|
||||
tokensDriver = box.read(BoxName.tokensDrivers);
|
||||
if (formKey.currentState!.validate()) {
|
||||
for (var i = 0; i < tokensDriver.length; i++) {
|
||||
FirebaseMessagesController().sendNotificationToAnyWithoutData(
|
||||
title.text, body.text, tokensDriver[i]);
|
||||
print(tokensDriver.length);
|
||||
// FirebaseMessagesController().sendNotificationToAnyWithoutData(
|
||||
// title.text, body.text, tokensDriver[i]);
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user