change folder name

This commit is contained in:
2025-06-11 09:32:07 +02:00
parent 57cb3ac1e3
commit 9824cbc220
55 changed files with 93 additions and 93 deletions

View File

@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_package_alert.dart';
class MihAlertServices {
void formNotFilledCompletely(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MihPackageAlert(
alertIcon: Icon(
Icons.warning_amber_rounded,
size: 150,
color: MzanziInnovationHub.of(context)!.theme.errorColor(),
),
alertTitle: "Oops! Looks like some fields are missing.",
alertBody: Column(
children: [
Text(
"We noticed that some required fields are still empty. To ensure your request is processed smoothly, please fill out all the highlighted fields before submitting the form again.",
style: TextStyle(
color:
MzanziInnovationHub.of(context)!.theme.secondaryColor(),
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 25),
RichText(
text: TextSpan(
style: TextStyle(
color:
MzanziInnovationHub.of(context)!.theme.secondaryColor(),
fontSize: 15,
fontWeight: FontWeight.bold,
),
children: <TextSpan>[
TextSpan(
text: "Here's a quick tip: ",
style: TextStyle(
fontStyle: FontStyle.italic,
color: MzanziInnovationHub.of(context)!
.theme
.errorColor())),
const TextSpan(
text:
"Look for fields without the \"(Optional)\" indicator next to them, as these are mandatory."),
],
),
),
],
),
alertColour: MzanziInnovationHub.of(context)!.theme.errorColor(),
);
},
);
}
}

View File

@@ -0,0 +1,684 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_services/mih_file_api.dart';
import 'package:mzansi_innovation_hub/mih_services/mih_notification_apis.dart';
import 'package:flutter/material.dart';
// import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
// import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
// import '../mih_env/env.dart';
// import '../mih_objects/app_user.dart';
// import '../mih_objects/arguments.dart';
// import '../mih_objects/business.dart';
// import '../mih_objects/business_user.dart';
// import '../mih_objects/notification.dart';
// import '../mih_objects/patient_access.dart';
// import '../mih_objects/patient_queue.dart';
// import '../mih_objects/patients.dart';
import 'package:supertokens_flutter/supertokens.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../mih_env/env.dart';
import '../mih_objects/app_user.dart';
import '../mih_objects/arguments.dart';
import '../mih_objects/business.dart';
import '../mih_objects/business_user.dart';
import '../mih_objects/notification.dart';
import '../mih_objects/patient_access.dart';
import '../mih_objects/patient_queue.dart';
import '../mih_objects/patients.dart';
class MIHApiCalls {
final baseAPI = AppEnviroment.baseApiUrl;
//================== PROFILE DATA ==========================================================================
/// This function is used to get profile details of signed in user.
///
/// Patameters: int notificationAmount which is used to get number of notifications to show.
///
/// Returns HomeArguments which contains:-
/// - Signed In user data.
/// - Business user belongs to.
/// - Business User details.
/// - notifications.
/// - user profile picture.
Future<HomeArguments> getProfile(
int notificationAmount,
BuildContext context,
) async {
AppUser userData;
Business? busData;
BusinessUser? bUserData;
Patient? patientData;
List<MIHNotification> notifi;
String userPic;
// Get Userdata
var uid = await SuperTokens.getUserId();
var responseUser = await http.get(Uri.parse("$baseAPI/user/$uid"));
if (responseUser.statusCode == 200) {
// print("here");
String body = responseUser.body;
var decodedData = jsonDecode(body);
AppUser u = AppUser.fromJson(decodedData);
userData = u;
} else {
throw Exception(
"Error: GetUserData status code ${responseUser.statusCode}");
}
// Get BusinessUserdata
var responseBUser = await http.get(
Uri.parse("$baseAPI/business-user/$uid"),
);
if (responseBUser.statusCode == 200) {
String body = responseBUser.body;
var decodedData = jsonDecode(body);
BusinessUser business_User = BusinessUser.fromJson(decodedData);
bUserData = business_User;
} else {
bUserData = null;
}
// Get Businessdata
var responseBusiness =
await http.get(Uri.parse("$baseAPI/business/app_id/$uid"));
if (responseBusiness.statusCode == 200) {
String body = responseBusiness.body;
var decodedData = jsonDecode(body);
Business business = Business.fromJson(decodedData);
busData = business;
} else {
busData = null;
}
//get profile picture
if (userData.pro_pic_path == "") {
userPic = "";
}
// else if (AppEnviroment.getEnv() == "Dev") {
// userPic = "${AppEnviroment.baseFileUrl}/mih/${userData.pro_pic_path}";
// }
else {
userPic =
await MihFileApi.getMinioFileUrl(userData.pro_pic_path, context);
}
//Get Notifications
var responseNotification = await http.get(
Uri.parse("$baseAPI/notifications/$uid?amount=$notificationAmount"));
if (responseNotification.statusCode == 200) {
String body = responseNotification.body;
// var decodedData = jsonDecode(body);
// MIHNotification notifications = MIHNotification.fromJson(decodedData);
Iterable l = jsonDecode(body);
//print("Here2");
List<MIHNotification> notifications = List<MIHNotification>.from(
l.map((model) => MIHNotification.fromJson(model)));
notifi = notifications;
} else {
notifi = [];
}
//get patient profile
//print("Patien manager page: $endpoint");
final response = await http.get(
Uri.parse("${AppEnviroment.baseApiUrl}/patients/${userData.app_id}"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// var errorCode = response.statusCode.toString();
// var errorBody = response.body;
if (response.statusCode == 200) {
// print("Here1");
var decodedData = jsonDecode(response.body);
// print("Here2");
Patient patients = Patient.fromJson(decodedData as Map<String, dynamic>);
// print("Here3");
// print(patients);
patientData = patients;
} else {
patientData = null;
}
//print(userPic);
return HomeArguments(
userData, bUserData, busData, patientData, notifi, userPic);
}
/// This function is used to get business details by business _id.
///
/// Patameters: String business_id & app_id (app_id of patient).
///
/// Returns List<PatientAccess> (List of access that match the above parameters).
static Future<Business?> getBusinessDetails(String business_id) async {
var responseBusiness = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/business/business_id/$business_id"));
if (responseBusiness.statusCode == 200) {
String body = responseBusiness.body;
var decodedData = jsonDecode(body);
Business business = Business.fromJson(decodedData);
return business;
} else {
return null;
}
}
//================== BUSINESS PATIENT/PERSONAL ACCESS ==========================================================================
/// This function is used to check if a business has access to a specific patients profile.
///
/// Patameters: String business_id & app_id (app_id of patient).
///
/// Returns List<PatientAccess> (List of access that match the above parameters).
static Future<List<PatientAccess>> checkBusinessAccessToPatient(
String business_id,
String app_id,
) async {
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/access-requests/patient/check/$business_id?app_id=$app_id"));
// var errorCode = response.statusCode.toString();
//print(response.body);
if (response.statusCode == 200) {
Iterable l = jsonDecode(response.body);
List<PatientAccess> patientAccesses = List<PatientAccess>.from(
l.map((model) => PatientAccess.fromJson(model)));
return patientAccesses;
} else {
throw Exception('failed to pull patient access for business');
}
}
/// This function is used to get list of access the business has.
///
/// Patameters: String business_id.
///
/// Returns List<PatientAccess> (List of access that match the above parameters).
static Future<List<PatientAccess>> getPatientAccessListOfBusiness(
String business_id) async {
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/access-requests/business/patient/$business_id"));
// var errorCode = response.statusCode.toString();
// print(response.statusCode);
// print(response.body);
if (response.statusCode == 200) {
Iterable l = jsonDecode(response.body);
List<PatientAccess> patientAccesses = List<PatientAccess>.from(
l.map((model) => PatientAccess.fromJson(model)));
return patientAccesses;
} else {
throw Exception('failed to pull patient access List for business');
}
}
/// This function is used to get list of access the business has.
///
/// Patameters: String business_id.
///
/// Returns List<PatientAccess> (List of access that match the above parameters).
static Future<List<PatientAccess>> getBusinessAccessListOfPatient(
String app_id) async {
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/access-requests/personal/patient/$app_id"));
// var errorCode = response.statusCode.toString();
// print(response.statusCode);
// print(response.body);
if (response.statusCode == 200) {
Iterable l = jsonDecode(response.body);
List<PatientAccess> patientAccesses = List<PatientAccess>.from(
l.map((model) => PatientAccess.fromJson(model)));
return patientAccesses;
} else {
throw Exception('failed to pull patient access List for business');
}
}
/// This function is used to UPDATE access the business has.
///
/// Patameters:-
/// String business_id,
/// String business_name,
/// String app_id,
/// String status,
/// String approved_by,
/// AppUser signedInUser,
/// BuildContext context,
///
/// Returns void (on success 200 navigate to /mih-access ).
static Future<void> updatePatientAccessAPICall(
String business_id,
String business_name,
String app_id,
String status,
String approved_by,
AppUser signedInUser,
BuildContext context,
) async {
var response = await http.put(
Uri.parse(
"${AppEnviroment.baseApiUrl}/access-requests/update/permission/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
// business_id: str
// app_id: str
// status: str
// approved_by: str
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": app_id,
"status": status,
"approved_by": approved_by,
}),
);
if (response.statusCode == 200) {
//Navigator.of(context).pushNamed('/home');
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/mih-access',
arguments: signedInUser,
);
String message = "";
if (status == "approved") {
message =
"You've successfully approved the access request! $business_name now has access to your profile forever.";
} else {
message =
"You've declined the access request. $business_name will not have access to your profile.";
}
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to reapply for access to patient.
///
/// Patameters:-
/// String business_id,
/// String app_id,
/// BuildContext context,
///
/// Returns void (on success 200 navigate to /mih-access ).
static Future<void> reapplyPatientAccessAPICall(
String business_id,
String app_id,
bool personalSelected,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/access-requests/re-apply/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
// business_id: str
// app_id: str
// status: str
// approved_by: str
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": app_id,
}),
);
if (response.statusCode == 200) {
MihNotificationApis.reapplyAccessRequestNotificationAPICall(
app_id, personalSelected, args, context);
//notification here
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to create patient access and trigger notification to patient
///
/// Patameters:-
/// String business_id,
/// String app_id,
/// String type,
/// String requested_by,
/// BuildContext context,
///
/// Returns void (triggers notification of success 201).
static Future<void> addPatientAccessAPICall(
String business_id,
String app_id,
String type,
String requested_by,
bool personalSelected,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/access-requests/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
// business_id: str
// app_id: str
// type: str
// requested_by: str
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": app_id,
"type": type,
"requested_by": requested_by,
}),
);
if (response.statusCode == 201) {
MihNotificationApis.addAccessRequestNotificationAPICall(
app_id, requested_by, personalSelected, args, context);
} else {
internetConnectionPopUp(context);
}
}
//================== PATIENT DATA ==========================================================================
/// This function is used to fetch a list of patients matching a search criteria
///
/// Patameters: String dsearch.
///
/// Returns List<Patient>.
static Future<List<Patient>> fetchPatients(String search) async {
final response = await http
.get(Uri.parse("${AppEnviroment.baseApiUrl}/patients/search/$search"));
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
Iterable l = jsonDecode(response.body);
List<Patient> patients =
List<Patient>.from(l.map((model) => Patient.fromJson(model)));
return patients;
} else {
throw Exception('failed to load patients');
}
}
/// This function is used to fetch a patient matching a app_id
///
/// Patameters: String app_id.
///
/// Returns Patient.
static Future<Patient> fetchPatientByAppId(
String app_id,
) async {
final response = await http
.get(Uri.parse("${AppEnviroment.baseApiUrl}/patients/$app_id"));
// errorCode = response.statusCode.toString();
// errorBody = response.body;
//print(response.body);
if (response.statusCode == 200) {
Patient patient = Patient.fromJson(jsonDecode(response.body));
// userData = u;
// Iterable l = jsonDecode(response.body);
// List<Patient> patients =
// List<Patient>.from(l.map((model) => Patient.fromJson(model)));
return patient;
} else {
throw Exception('failed to load patient');
}
}
//================== APPOINTMENT/ PATIENT QUEUE ==========================================================================
/// This function is used to fetch a list of appointments for a doctors office for a date.
///
/// Patameters: String date & business_id .
///
/// Returns List<PatientQueue>.
static Future<List<PatientQueue>> fetchBusinessAppointmentsAPICall(
String date,
String business_id,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/queue/appointments/business/$business_id?date=$date"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<PatientQueue> patientQueue = List<PatientQueue>.from(
l.map((model) => PatientQueue.fromJson(model)));
//print("Here3");
//print(patientQueue);
return patientQueue;
} else {
throw Exception('failed to fatch patient queue');
}
}
/// This function is used to fetch a list of appointments for a doctors office for a date.
///
/// Patameters: String date & business_id .
///
/// Returns List<PatientQueue>.
static Future<List<PatientQueue>> fetchPersonalAppointmentsAPICall(
String date,
String app_id,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/queue/appointments/personal/$app_id?date=$date"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<PatientQueue> patientQueue = List<PatientQueue>.from(
l.map((model) => PatientQueue.fromJson(model)));
//print("Here3");
//print(patientQueue);
return patientQueue;
} else {
throw Exception('failed to fatch patient queue');
}
}
/// This function is used to UPDATE AN appointments for a doctors office for a date.
///
/// Patameters:-
/// int idpatient_queue,
/// String app_id,
/// String business_name,
/// String origDate_time,
/// String date,
/// String time,
/// BusinessArguments args,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> updateApointmentAPICall(
int idpatient_queue,
String app_id,
bool personalSelected,
String business_name,
String origDate_time,
String date,
String time,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/queue/appointment/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"idpatient_queue": idpatient_queue,
"date": date,
"time": time,
}),
);
if (response.statusCode == 200) {
MihNotificationApis.addRescheduledAppointmentNotificationAPICall(
app_id,
personalSelected,
business_name,
origDate_time,
date,
time,
args,
context,
);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to Delete/ cancel AN appointments for a doctors office for a date.
///
/// Patameters:-
/// int idpatient_queue,
/// PatientViewArguments args,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> deleteApointmentAPICall(
int idpatient_queue,
String app_id,
bool personalSelected,
String date_time,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.delete(
Uri.parse("${AppEnviroment.baseApiUrl}/queue/appointment/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"idpatient_queue": idpatient_queue}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
MihNotificationApis.addCancelledAppointmentNotificationAPICall(
app_id,
personalSelected,
date_time,
args,
context,
);
// Navigator.of(context).pop();
// Navigator.of(context).pop();
// String message =
// "The note has been deleted successfully. This means it will no longer be visible on your and cannot be used for future appointments.";
// successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to create AN appointments for a doctors office for a date.
///
/// Patameters:-
/// int idpatient_queue,
/// PatientViewArguments args,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> addAppointmentAPICall(
String business_id,
String app_id,
bool personalSelected,
String date,
String time,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/queue/appointment/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": app_id,
"date": date,
"time": time,
}),
);
if (response.statusCode == 201) {
// Navigator.pushNamed(context, '/patient-manager/patient',
// arguments: widget.signedInUser);
// String message =
// "The appointment has been successfully booked!\n\nAn approval request as been sent to the patient.Once the access request has been approved, you will be able to access the patientAccesses profile. ou can check the status of your request in patient queue under the appointment.";
// "${fnameController.text} ${lnameController.text} patient profiole has been successfully added!\n";
// Navigator.pop(context);
// Navigator.pop(context);
// Navigator.pop(context);
// setState(() {
// dateController.text = "";
// timeController.text = "";
// });
// Navigator.of(context).pushNamed(
// '/patient-manager',
// arguments: BusinessArguments(
// widget.arguments.signedInUser,
// widget.arguments.businessUser,
// widget.arguments.business,
// ),
// );
// successPopUp(message);
// String app_id,
// String date,
// String time,
// BusinessArguments args,
// BuildContext context,
MihNotificationApis.addNewAppointmentNotificationAPICall(
app_id,
personalSelected,
date,
time,
args,
context,
);
} else {
internetConnectionPopUp(context);
}
}
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
}

View File

@@ -0,0 +1,107 @@
import 'dart:convert';
import 'package:http/http.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:flutter/material.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
import 'package:supertokens_flutter/http.dart' as http;
class MihBusinessDetailsApi {
Future<Response> createBusinessDetails(
String appId,
String busineName,
String businessType,
String businessRegistrationNo,
String businessPracticeNo,
String businessVatNo,
String businessEmail,
String businessPhoneNumber,
String businessLocation,
String businessLogoFilename,
BuildContext context,
) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/business/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"Name": busineName,
"type": businessType,
"registration_no": businessRegistrationNo,
"logo_name": businessLogoFilename,
"logo_path": "$appId/business_files/$businessLogoFilename",
"contact_no": businessPhoneNumber,
"bus_email": businessEmail,
"gps_location": businessLocation,
"practice_no": businessPracticeNo,
"vat_no": businessVatNo,
}),
);
Navigator.of(context).pop();
return response;
}
Future<int> updateBusinessDetails(
String business_id,
String business_name,
String business_type,
String business_registration_no,
String business_practice_no,
String business_vat_no,
String business_email,
String business_phone_number,
String business_location,
String business_logo_name,
BuildContext context,
) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/business/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"Name": business_name,
"type": business_type,
"registration_no": business_registration_no,
"logo_name": business_logo_name,
"logo_path": "$business_id/business_files/$business_logo_name",
"contact_no": business_phone_number,
"bus_email": business_email,
"gps_location": business_location,
"practice_no": business_practice_no,
"vat_no": business_vat_no,
}),
);
Navigator.of(context).pop();
if (response.statusCode == 200) {
return 200;
} else {
internetConnectionPopUp(context);
return 500;
}
}
void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
}

View File

@@ -0,0 +1,265 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
import 'package:mzansi_innovation_hub/mih_objects/claim_statement_file.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../mih_env/env.dart';
class MIHClaimStatementGenerationApi {
final baseAPI = AppEnviroment.baseApiUrl;
/// This function is used to generate and store a claim/ statement.
///
/// Patameters: TBC .
///
/// Returns TBC.
Future<void> generateClaimStatement(
ClaimStatementGenerationArguments data,
PatientViewArguments args,
String env,
BuildContext context,
) async {
//start loading circle
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
DateTime now = new DateTime.now();
// DateTime date = new DateTime(now.year, now.month, now.day);
String fileName =
"${data.document_type}-${data.patient_full_name}-${now.toString().substring(0, 19)}.pdf"
.replaceAll(RegExp(r' '), '-');
var response1 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/minio/generate/claim-statement/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"document_type": data.document_type,
"patient_app_id": data.patient_app_id,
"env": env,
"patient_full_name": data.patient_full_name,
"fileName": fileName,
"patient_id_no": data.patient_id_no,
"has_med_aid": data.has_med_aid,
"med_aid_no": data.med_aid_no,
"med_aid_code": data.med_aid_code,
"med_aid_name": data.med_aid_name,
"med_aid_scheme": data.med_aid_scheme,
"busName": data.busName,
"busAddr": data.busAddr,
"busNo": data.busNo,
"busEmail": data.busEmail,
"provider_name": data.provider_name,
"practice_no": data.practice_no,
"vat_no": data.vat_no,
"service_date": data.service_date,
"service_desc": data.service_desc,
"service_desc_option": data.service_desc_option,
"procedure_name": data.procedure_name,
"procedure_additional_info": data.procedure_additional_info,
"icd10_code": data.icd10_code,
"amount": data.amount,
"pre_auth_no": data.pre_auth_no,
"logo_path": data.logo_path,
"sig_path": data.sig_path,
}),
);
//print(response1.statusCode);
if (response1.statusCode == 200) {
//Update this API
var response2 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/files/claim-statement/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": data.patient_app_id,
"business_id": args.business!.business_id,
"file_path": "${data.patient_app_id}/claims-statements/$fileName",
"file_name": fileName
}),
);
if (response2.statusCode == 201) {
// end loading circle
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context)
.pushNamed('/patient-manager/patient', arguments: args);
String message =
"The ${data.document_type}: $fileName has been successfully generated and added to ${data.patient_full_name}'s record. You can now access and download it for their use.";
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to fetch a list of claim/ statement files for a ptient.
///
/// Patameters: app_id .
///
/// Returns List<ClaimStatementFile>.
static Future<List<ClaimStatementFile>> getClaimStatementFilesByPatient(
String app_id,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/files/claim-statement/patient/$app_id"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<ClaimStatementFile> docList = List<ClaimStatementFile>.from(
l.map((model) => ClaimStatementFile.fromJson(model)));
//print("Here3");
//print(patientQueue);
return docList;
} else {
throw Exception(
'failed to fatch patient claims statement files with api');
}
}
/// This function is used to fetch a list of claim/ statement files for a business.
///
/// Patameters: business_id .
///
/// Returns List<ClaimStatementFile>.
static Future<List<ClaimStatementFile>> getClaimStatementFilesByBusiness(
String business_id,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/files/claim-statement/business/$business_id"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<ClaimStatementFile> docList = List<ClaimStatementFile>.from(
l.map((model) => ClaimStatementFile.fromJson(model)));
//print("Here3");
//print(patientQueue);
return docList;
} else {
throw Exception(
'failed to fatch business claims statement files with api');
}
}
/// This function is used to Delete loyalty card from users mzansi wallet.
///
/// Patameters:-
/// AppUser signedInUser,
/// int idloyalty_cards,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> deleteClaimStatementFilesByFileID(
PatientViewArguments args,
String env,
String filePath,
int fileID,
BuildContext context,
) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
// delete file from minio
var response = await http.delete(
Uri.parse("${AppEnviroment.baseApiUrl}/minio/delete/file/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"file_path": filePath,
"env": env,
}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
//SQL delete
var response2 = await http.delete(
Uri.parse("${AppEnviroment.baseApiUrl}/files/claim-statement/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(
<String, dynamic>{"idclaim_statement_file": fileID, "env": env}),
);
if (response2.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
//print(widget.business);
Navigator.of(context)
.pushNamed('/patient-manager/patient', arguments: args);
// Navigator.of(context)
// .pushNamed('/patient-profile', arguments: widget.signedInUser);
// setState(() {});
String message =
"The File has been deleted successfully. This means it will no longer be visible on your and cannot be used for future appointments.";
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
} else {
internetConnectionPopUp(context);
}
}
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
}

View File

@@ -0,0 +1,152 @@
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_error_message.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_success_message.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
import 'package:http/http.dart' as http2;
import 'package:supertokens_flutter/supertokens.dart';
class MihFileApi {
final baseAPI = AppEnviroment.baseApiUrl;
static Future<String> getMinioFileUrl(
String filePath,
BuildContext context,
) async {
// loadingPopUp(context);
// print("here");
// var url =
// "${AppEnviroment.baseApiUrl}/minio/pull/file/${AppEnviroment.getEnv()}/$filePath";
// var response = await http.get(Uri.parse(url));
String fileUrl = "";
// print(response.statusCode);
// if (response.statusCode == 200) {
// String body = response.body;
// var decodedData = jsonDecode(body);
// fileUrl = decodedData['minioURL'];
// } else {
// fileUrl = "";
// }
// Navigator.of(context).pop(); // Pop loading dialog
// return fileUrl;
try {
var url =
"${AppEnviroment.baseApiUrl}/minio/pull/file/${AppEnviroment.getEnv()}/$filePath";
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
fileUrl = decodedData['minioURL'];
} else {
// internetConnectionPopUp(context);
print("Error: ${response.statusCode}");
print("Error: ${response.body}");
}
} catch (e) {
// internetConnectionPopUp(context);
print("Error getting url");
} finally {
// Navigator.of(context).pop(); // Always pop loading dialog
}
return fileUrl;
}
static Future<int> uploadFile(
String app_id,
String env,
String folderName,
PlatformFile? file,
BuildContext context,
) async {
loadingPopUp(context);
var token = await SuperTokens.getAccessToken();
var request = http2.MultipartRequest(
'POST', Uri.parse("${AppEnviroment.baseApiUrl}/minio/upload/file/"));
request.headers['accept'] = 'application/json';
request.headers['Authorization'] = 'Bearer $token';
request.headers['Content-Type'] = 'multipart/form-data';
request.fields['app_id'] = app_id;
request.fields['env'] = env;
request.fields['folder'] = folderName;
request.files.add(await http2.MultipartFile.fromBytes('file', file!.bytes!,
filename: file.name.replaceAll(RegExp(r' '), '-')));
var response = await request.send();
Navigator.of(context).pop(); // Pop loading dialog
return response.statusCode;
}
static Future<int> deleteFile(
String app_id,
String env,
String folderName,
String fileName,
BuildContext context,
) async {
loadingPopUp(context);
var fname = fileName.replaceAll(RegExp(r' '), '-');
var filePath = "$app_id/$folderName/$fname";
var response = await http.delete(
Uri.parse("${AppEnviroment.baseApiUrl}/minio/delete/file/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"file_path": filePath,
"env": env,
}),
);
Navigator.of(context).pop(); // Pop loading dialog
return response.statusCode;
}
// Future<void> signOut() async {
// await SuperTokens.signOut(completionHandler: (error) {
// print(error);
// });
// if (await SuperTokens.doesSessionExist() == false) {
// Navigator.of(context).pop();
// Navigator.of(context).popAndPushNamed(
// '/',
// arguments: AuthArguments(true, false),
// );
// }
// }
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
static void loadingPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
}
}

View File

@@ -0,0 +1,55 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_objects/icd10_code.dart.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../mih_env/env.dart';
class MIHIcd10CodeApis {
final baseAPI = AppEnviroment.baseApiUrl;
/// This function is used to fetch a list of icd 10 codes based on a search .
///
/// Patameters: String search, BuildContext context
///
/// Returns List<ICD10Code>.
static Future<List<ICD10Code>> getIcd10Codes(
String search, BuildContext context) async {
//print("Patien manager page: $endpoint");
mihLoadingPopUp(context);
final response = await http
.get(Uri.parse("${AppEnviroment.baseApiUrl}/icd10-codes/$search"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<ICD10Code> icd10Codes =
List<ICD10Code>.from(l.map((model) => ICD10Code.fromJson(model)));
//print("Here3");
//print(patientQueue);
Navigator.of(context).pop();
return icd10Codes;
} else {
Navigator.of(context).pop();
throw Exception('failed to fetch icd-10 codes with api');
}
}
static void mihLoadingPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
}
}

View File

@@ -0,0 +1,64 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:pwa_install/pwa_install.dart';
// import 'package:universal_html/js.dart' as js;
import 'package:url_launcher/url_launcher.dart';
class MihInstallServices {
String? errorMessage;
Future<void> launchSocialUrl(Uri linkUrl) async {
if (!await launchUrl(linkUrl)) {
throw Exception('Could not launch $linkUrl');
}
}
void installMihTrigger(BuildContext context) {
final isWebAndroid =
kIsWeb && (defaultTargetPlatform == TargetPlatform.android);
final isWebIos = kIsWeb && (defaultTargetPlatform == TargetPlatform.iOS);
if (isWebAndroid) {
launchSocialUrl(
Uri.parse(
"https://play.google.com/store/apps/details?id=za.co.mzansiinnovationhub.mih",
),
);
} else if (isWebIos) {
//Show pop up for IOS
launchSocialUrl(
Uri.parse(
"https://apps.apple.com/za/app/mzansi-innovation-hub/id6743310890",
),
);
} else if (MzanziInnovationHub.of(context)!.theme.getPlatform() ==
"Android") {
//Installed Android App
launchSocialUrl(
Uri.parse(
"https://play.google.com/store/apps/details?id=za.co.mzansiinnovationhub.mih",
),
);
} else if (MzanziInnovationHub.of(context)!.theme.getPlatform() == "iOS") {
launchSocialUrl(
Uri.parse(
"https://apps.apple.com/za/app/mzansi-innovation-hub/id6743310890",
),
);
} else {
//Web
if (PWAInstall().installPromptEnabled) {
try {
PWAInstall().promptInstall_();
} catch (e) {
errorMessage = e.toString();
debugPrint('Error prompting install: $e');
}
} else {
// Fallback for unsupported platforms
debugPrint('Install prompt not available for this platform.');
}
// js.context.callMethod("presentAddToHome");
}
}
}

View File

@@ -0,0 +1,67 @@
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
class MIHLocationAPI {
final LocationSettings locationSettings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
///This function is to get the current location of the signed in user.
///First checks the permission, if permission is denied (new user), request permission from user.
///if user has blocked permission (denied or denied forver), user will get error pop up.
///if user has granted permission (while in use), function will return Position object.
Future<Position?> getGPSPosition(BuildContext context) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
//Check the type of permission granted
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
//First time user (auto denied pernission) request permission from user
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
//User denied permission
showPermissionError(context);
return null;
} else if (permission == LocationPermission.deniedForever) {
//User denied permission Forever
showPermissionError(context);
return null;
} else {
Position location = await Geolocator.getCurrentPosition(
locationSettings: locationSettings);
//print(location);
return location;
}
} else if (permission == LocationPermission.deniedForever) {
showPermissionError(context);
return null;
} else {
Position location = await Geolocator.getCurrentPosition(
locationSettings: locationSettings);
//print(location);
Navigator.of(context).pop();
return location;
}
}
double getDistanceInMeaters(Position startPosition, Position endPosition) {
return Geolocator.distanceBetween(startPosition.latitude,
startPosition.longitude, endPosition.latitude, endPosition.longitude);
}
void showPermissionError(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Location Denied");
},
);
}
}

View File

@@ -0,0 +1,112 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:flutter/material.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
import 'package:supertokens_flutter/http.dart' as http;
class MihMyBusinessUserApi {
Future<int> createBusinessUser(
String business_id,
String app_id,
String signatureFilename,
String title,
String access,
BuildContext context,
) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/business-user/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": app_id,
"signature": signatureFilename,
"sig_path": "$business_id/business_files/$signatureFilename",
"title": title,
"access": access,
}),
);
Navigator.of(context).pop();
if (response.statusCode == 201) {
return 201;
} else {
internetConnectionPopUp(context);
return 500;
}
}
/// This function updates the business user details.
Future<int> updateBusinessUser(
String app_id,
String business_id,
String bUserTitle,
String bUserAccess,
String signatureFileName,
BuildContext context,
) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/business-user/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": app_id,
"signature": signatureFileName,
"sig_path": "$app_id/business_files/$signatureFileName",
"title": bUserTitle,
"access": bUserAccess,
}),
);
// var response = await http.put(
// Uri.parse("${AppEnviroment.baseApiUrl}/business/update/"),
// headers: <String, String>{
// "Content-Type": "application/json; charset=UTF-8"
// },
// body: jsonEncode(<String, dynamic>{
// "business_id": business_id,
// "Name": business_name,
// "type": business_type,
// "registration_no": business_registration_no,
// "logo_name": business_logo_name,
// "logo_path": "$business_id/business_files/$business_logo_name",
// "contact_no": business_phone_number,
// "bus_email": business_email,
// "gps_location": business_location,
// "practice_no": business_practice_no,
// "vat_no": business_vat_no,
// }),
// );
Navigator.of(context).pop();
if (response.statusCode == 200) {
return 200;
} else {
internetConnectionPopUp(context);
return 500;
}
}
void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
}

View File

@@ -0,0 +1,577 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_services/mih_notification_apis.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_objects/app_user.dart';
import 'package:mzansi_innovation_hub/mih_objects/appointment.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
import 'package:mzansi_innovation_hub/mih_objects/business.dart';
import 'package:mzansi_innovation_hub/mih_objects/business_user.dart';
import 'package:flutter/material.dart';
// import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
// import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
// import '../mih_env/env.dart';
// import '../mih_objects/app_user.dart';
// import '../mih_objects/arguments.dart';
// import '../mih_objects/business.dart';
// import '../mih_objects/business_user.dart';
// import '../mih_objects/notification.dart';
// import '../mih_objects/patient_access.dart';
// import '../mih_objects/patient_queue.dart';
// import '../mih_objects/patients.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../mih_env/env.dart';
class MihMzansiCalendarApis {
final baseAPI = AppEnviroment.baseApiUrl;
/// This function is used to fetch a list of appointment for a personal user.
///
/// Patameters:
/// app_id,
/// date (yyyy-mm-dd),
///
/// Returns Future<List<Appointment>>.
static Future<List<Appointment>> getPersonalAppointments(
String app_id,
String date,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/appointments/personal/$app_id?date=$date"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<Appointment> personalAppointments =
List<Appointment>.from(l.map((model) => Appointment.fromJson(model)));
//print("Here3");
//print(patientQueue);
return personalAppointments;
} else {
throw Exception('failed to fatch personal appointments');
}
}
/// This function is used to fetch a list of appointment for a personal user.
///
/// Patameters:
/// app_id,
/// date (yyyy-mm-dd),
///
/// Returns Future<List<Appointment>>.
static Future<List<Appointment>> getBusinessAppointments(
String business_id,
bool waitingRoom,
String date,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/appointments/business/$business_id?date=$date"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<Appointment> businessAppointments =
List<Appointment>.from(l.map((model) => Appointment.fromJson(model)));
//print("Here3");
//print(patientQueue);
// if (waitingRoom == true) {
// businessAppointments = businessAppointments
// .where((element) => element.app_id != "")
// .toList();
// } else {
// businessAppointments = businessAppointments
// .where((element) => element.app_id == "")
// .toList();
// }
return businessAppointments;
} else {
throw Exception('failed to fatch business appointments');
}
}
/// This function is used to Delete loyalty card from users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// int idloyalty_cards,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> deleteAppointmentAPICall(
AppUser signedInUser,
bool personalSelected,
Business? business,
BusinessUser? businessUser,
bool inWaitingRoom,
int idappointments,
BuildContext context,
) async {
var response = await http.delete(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"idappointments": idappointments}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
if (inWaitingRoom == true && personalSelected == false) {
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
signedInUser,
false,
business,
businessUser,
),
);
} else {
Navigator.of(context).pushNamed(
'/calendar',
arguments: CalendarArguments(
signedInUser,
personalSelected,
business,
businessUser,
),
);
}
String message =
"The appointment has been deleted successfully. This means it will no longer be visible in your Calendar.";
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to add an appointment to users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// String title,
/// String description,
/// String date,
/// String time,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> addPersonalAppointment(
AppUser signedInUser,
String title,
String description,
String date,
String time,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": signedInUser.app_id,
"business_id": "",
"title": title,
"description": description,
"date": date,
"time": time,
}),
);
if (response.statusCode == 201) {
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
String message =
"Your appointment \"$title\" for the $date $title has been deleted.";
// Navigator.pop(context);
Navigator.of(context).pushNamed(
'/calendar',
arguments: CalendarArguments(
signedInUser,
true,
null,
null,
),
);
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to add an appointment to users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// String title,
/// String description,
/// String date,
/// String time,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> addBusinessAppointment(
AppUser signedInUser,
Business business,
BusinessUser businessUser,
bool inWaitingRoom,
String title,
String description,
String date,
String time,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": "",
"business_id": business.business_id,
"title": title,
"description": description,
"date": date,
"time": time,
}),
);
if (response.statusCode == 201) {
// Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
String message =
"Your appointment \"$title\" for the $date $title has been deleted.";
// Navigator.pop(context);
if (inWaitingRoom) {
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
signedInUser,
false,
business,
businessUser,
),
);
} else {
Navigator.of(context).pushNamed(
'/calendar',
arguments: CalendarArguments(
signedInUser,
false,
business,
businessUser,
),
);
}
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to add an appointment to users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// String title,
/// String description,
/// String date,
/// String time,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> addPatientAppointment(
AppUser signedInUser,
bool personalSelected,
String patientAppId,
BusinessArguments businessArgs,
String title,
String description,
String date,
String time,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": patientAppId,
"business_id": businessArgs.business?.business_id,
"title": title,
"description": description,
"date": date,
"time": time,
}),
);
if (response.statusCode == 201) {
MihNotificationApis.addNewAppointmentNotificationAPICall(
patientAppId,
personalSelected,
date,
time,
businessArgs,
context,
);
// Navigator.pop(context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to update an appointment to users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// int idappointments,
/// String title,
/// String description,
/// String date,
/// String time,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> updatePersonalAppointment(
AppUser signedInUser,
Business? business,
BusinessUser? businessUser,
int idappointments,
String title,
String description,
String date,
String time,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"idappointments": idappointments,
"title": title,
"description": description,
"date": date,
"time": time,
}),
);
if (response.statusCode == 200) {
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
String message =
"Your appointment \"$title\" has been updates to the $date $title.";
Navigator.pop(context);
Navigator.of(context).pushNamed(
'/calendar',
arguments: CalendarArguments(
signedInUser,
true,
business,
businessUser,
),
);
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to update an appointment to users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// int idappointments,
/// String title,
/// String description,
/// String date,
/// String time,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> updateBusinessAppointment(
AppUser signedInUser,
Business? business,
BusinessUser? businessUser,
int idappointments,
String title,
String description,
String date,
String time,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"idappointments": idappointments,
"title": title,
"description": description,
"date": date,
"time": time,
}),
);
if (response.statusCode == 200) {
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
String message =
"Your appointment \"$title\" has been updates to the $date $title.";
Navigator.pop(context);
Navigator.of(context).pushNamed(
'/calendar',
arguments: CalendarArguments(
signedInUser,
false,
business,
businessUser,
),
);
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to update an appointment to users mzansi Calendar.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// int idappointments,
/// String title,
/// String description,
/// String date,
/// String time,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> updatePatientAppointment(
AppUser signedInUser,
Business? business,
BusinessUser? businessUser,
int idappointments,
String title,
String description,
String date,
String time,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.put(
Uri.parse("${AppEnviroment.baseApiUrl}/appointment/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"idappointments": idappointments,
"title": title,
"description": description,
"date": date,
"time": time,
}),
);
if (response.statusCode == 200) {
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
String message =
"Your appointment \"$title\" has been updates to the $date $title.";
// Navigator.pop(context);
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
signedInUser,
false,
business,
businessUser,
),
);
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
static void loadingPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
}
}

View File

@@ -0,0 +1,270 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_objects/app_user.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
import 'package:mzansi_innovation_hub/mih_objects/loyalty_card.dart';
import 'package:flutter/material.dart';
// import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
// import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
// import '../mih_env/env.dart';
// import '../mih_objects/app_user.dart';
// import '../mih_objects/arguments.dart';
// import '../mih_objects/business.dart';
// import '../mih_objects/business_user.dart';
// import '../mih_objects/notification.dart';
// import '../mih_objects/patient_access.dart';
// import '../mih_objects/patient_queue.dart';
// import '../mih_objects/patients.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../mih_env/env.dart';
class MIHMzansiWalletApis {
final baseAPI = AppEnviroment.baseApiUrl;
/// This function is used to fetch a list of loyalty cards for a user.
///
/// Patameters: app_id .
///
/// Returns List<PatientQueue>.
static Future<List<MIHLoyaltyCard>> getLoyaltyCards(
String app_id,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/mzasni-wallet/loyalty-cards/$app_id"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<MIHLoyaltyCard> patientQueue = List<MIHLoyaltyCard>.from(
l.map((model) => MIHLoyaltyCard.fromJson(model)));
//print("Here3");
//print(patientQueue);
return patientQueue;
} else {
throw Exception('failed to fatch loyalty cards');
}
}
/// This function is used to fetch a list of loyalty cards for a user.
///
/// Patameters: app_id .
///
/// Returns List<PatientQueue>.
static Future<List<MIHLoyaltyCard>> getFavouriteLoyaltyCards(
String app_id,
) async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/mzasni-wallet/loyalty-cards/favourites/$app_id"));
// print("Here");
// print("Body: ${response.body}");
// print("Code: ${response.statusCode}");
// errorCode = response.statusCode.toString();
// errorBody = response.body;
if (response.statusCode == 200) {
// print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<MIHLoyaltyCard> patientQueue = List<MIHLoyaltyCard>.from(
l.map((model) => MIHLoyaltyCard.fromJson(model)));
//print("Here3");
//print(patientQueue);
return patientQueue;
} else {
throw Exception('failed to fatch loyalty cards');
}
}
/// This function is used to Delete loyalty card from users mzansi wallet.
///
/// Patameters:-
/// AppUser signedInUser,
/// int idloyalty_cards,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> deleteLoyaltyCardAPICall(
AppUser signedInUser,
int idloyalty_cards,
int navIndex,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.delete(
Uri.parse(
"${AppEnviroment.baseApiUrl}/mzasni-wallet/loyalty-cards/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"idloyalty_cards": idloyalty_cards}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/mzansi-wallet',
arguments: WalletArguments(signedInUser, navIndex),
);
String message =
"The loyalty card has been deleted successfully. This means it will no longer be visible in your Mzansi Wallet.";
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to add a lopyalty card to users mzansi wallet.
///
/// Patameters:-
/// AppUser signedInUser,
/// String app_id,
/// String shop_name,
/// String card_number,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS SUCCESS pop up)
static Future<void> addLoyaltyCardAPICall(
AppUser signedInUser,
String app_id,
String shop_name,
String card_number,
String favourite,
int priority_index,
String nickname,
int navIndex,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.post(
Uri.parse(
"${AppEnviroment.baseApiUrl}/mzasni-wallet/loyalty-cards/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"shop_name": shop_name,
"card_number": card_number,
"favourite": favourite,
"priority_index": priority_index,
"nickname": nickname,
}),
);
if (response.statusCode == 201) {
Navigator.pop(context);
String message =
"Your $shop_name Loyalty Card was successfully added to your Mzansi Wallet.";
Navigator.pop(context);
Navigator.pop(context);
Navigator.of(context).pushNamed(
'/mzansi-wallet',
arguments: WalletArguments(signedInUser, navIndex),
);
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
/// This function is used to Update loyalty card from users mzansi wallet.
///
/// Patameters:-
/// AppUser signedInUser,
/// int idloyalty_cards,
/// BuildContext context,
///
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> updateLoyaltyCardAPICall(
AppUser signedInUser,
int idloyalty_cards,
String favourite,
int priority_index,
String nickname,
String card_number,
int navIndex,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.put(
Uri.parse(
"${AppEnviroment.baseApiUrl}/mzasni-wallet/loyalty-cards/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"idloyalty_cards": idloyalty_cards,
"favourite": favourite,
"priority_index": priority_index,
"nickname": nickname,
"card_number": card_number,
}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/mzansi-wallet',
arguments: WalletArguments(signedInUser, navIndex),
);
String message = "The loyalty card has been added to your favourites.";
successPopUp(message, context);
} else {
Navigator.pop(context);
internetConnectionPopUp(context);
}
}
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
static void loadingPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
}
}

View File

@@ -0,0 +1,296 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_error_message.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_success_message.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
class MihNotificationApis {
final baseAPI = AppEnviroment.baseApiUrl;
//================== Notifications ==========================================================================
/// This function is used to create notification to patient for access reviews
///
/// Patameters:-
/// String app_id,
/// String business_name,
/// BuildContext context,
///
/// Returns void. (ON SUCCESS 201 , NAVIGATE TO /patient-manager)
static Future<void> addAccessRequestNotificationAPICall(
String app_id,
String business_name,
bool personalSelected,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/notifications/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"notification_type": "Forever Access Request",
"notification_message":
"A new Forever Access Request has been sent by $business_name in order to access your Patient Profile. Please review request.",
"action_path": "/mih-access",
}),
);
if (response.statusCode == 201) {
String message =
"A request has been sent to the patient advising that you have requested access to their profile. Only once access has been granted will you be able to book an appointment.";
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
args.signedInUser,
personalSelected,
args.business,
args.businessUser,
),
);
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to create notification to patient for access reviews
///
/// Patameters:-
/// String app_id,
/// String business_name,
/// BuildContext context,
///
/// Returns void. (ON SUCCESS 201 , NAVIGATE TO /patient-manager)
static Future<void> reapplyAccessRequestNotificationAPICall(
String app_id,
bool personalSelected,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/notifications/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"notification_type": "Re-applying for Access",
"notification_message":
"${args.business!.Name} is re-applying for access to your Patient Profile. Please review request.",
"action_path": "/mih-access",
}),
);
if (response.statusCode == 201) {
String message =
"A request has been sent to the patient advising that you have re-applied for access to their profile. Only once access has been granted will you be able to book an appointment.";
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
args.signedInUser,
personalSelected,
args.business,
args.businessUser,
),
);
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to create notification to patient for access reviews
///
/// Patameters:-
/// String app_id,
/// String business_name,
/// String origDate_time,
/// String date,
/// String time,
/// BusinessArguments args,
/// BuildContext context,
///
/// Returns void. (ON SUCCESS 201 , NAVIGATE TO /patient-manager)
static Future<void> addRescheduledAppointmentNotificationAPICall(
String app_id,
bool personalSelected,
String business_name,
String origDate_time,
String date,
String time,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/notifications/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"notification_type": "Appointment Rescheduled",
"notification_message":
"Your appointment with $business_name for the ${origDate_time.replaceAll("T", " ").substring(0, origDate_time.length - 3)} has been rescheduled to the ${date} ${time}.",
"action_path": "/appointments",
}),
);
if (response.statusCode == 201) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
args.signedInUser,
personalSelected,
args.business,
args.businessUser,
),
);
String message = "The appointment has been successfully rescheduled.";
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to create notification to patient for access reviews
///
/// Patameters:-
/// String app_id,
/// String business_name,
/// String origDate_time,
/// String date,
/// String time,
/// BusinessArguments args,
/// BuildContext context,
///
/// Returns void. (ON SUCCESS 201 , NAVIGATE TO /patient-manager)
static Future<void> addCancelledAppointmentNotificationAPICall(
String app_id,
bool personalSelected,
String date_time,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/notifications/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"notification_type": "Appointment Cancelled",
"notification_message":
"Your appointment with ${args.business!.Name} for the ${date_time.replaceAll("T", " ")} has been cancelled.",
"action_path": "/appointments",
}),
);
if (response.statusCode == 201) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
args.signedInUser,
personalSelected,
args.business,
args.businessUser,
),
);
String message =
"The appointment has been cancelled successfully. This means it will no longer be visible in your waiting room and calender.";
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
/// This function is used to create notification to patient for access reviews
///
/// Patameters:-
/// String app_id,
/// String business_name,
/// String origDate_time,
/// String date,
/// String time,
/// BusinessArguments args,
/// BuildContext context,
///
/// Returns void. (ON SUCCESS 201 , NAVIGATE TO /patient-manager)
static Future<void> addNewAppointmentNotificationAPICall(
String app_id,
bool personalSelected,
String date,
String time,
BusinessArguments args,
BuildContext context,
) async {
var response = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/notifications/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"notification_type": "New Appointment Booked",
"notification_message":
"An appointment with ${args.business!.Name} has been booked for the $date $time.",
"action_path": "/appointments",
}),
);
if (response.statusCode == 201) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/patient-manager',
arguments: PatManagerArguments(
args.signedInUser,
personalSelected,
args.business,
args.businessUser,
),
);
String message =
"The appointment was been created successfully. This means it will now be visible in your waiting room and calender.";
successPopUp(message, context);
} else {
internetConnectionPopUp(context);
}
}
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
}

View File

@@ -0,0 +1,117 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_error_message.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_success_message.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
import 'package:supertokens_flutter/supertokens.dart';
class MihUserApis {
final baseAPI = AppEnviroment.baseApiUrl;
static Future<bool> isUsernameUnique(
String username,
BuildContext context,
) async {
var response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/users/validate/username/$username"));
if (response.statusCode == 200) {
String body = response.body;
var jsonBody = jsonDecode(body);
return jsonBody["available"];
} else {
throw Exception(
"Error: isUsernameUnique status code ${response.statusCode}");
}
}
static Future<void> deleteAccount(
String app_id,
BuildContext context,
) async {
loadingPopUp(context);
var response = await http.delete(
Uri.parse("${AppEnviroment.baseApiUrl}/user/delete/all/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"app_id": app_id,
"env": AppEnviroment.getEnv(),
}),
);
if (response.statusCode == 200) {
await SuperTokens.signOut(completionHandler: (error) {
print(error);
});
if (await SuperTokens.doesSessionExist() == false) {
Navigator.of(context).pop(); // Pop loading dialog
Navigator.of(context).pop(); // Pop delete account dialog
Navigator.of(context).pop(); // Pop Mzansi Profile
Navigator.of(context).popAndPushNamed(
'/',
arguments: AuthArguments(true, false),
); //Pop and push to login page
successPopUp(
"Account Deleted Successfully",
context,
); // Show success message.
}
} else {
Navigator.of(context).pop(); // Pop loading dialog
internetConnectionPopUp(context);
}
}
// Future<void> signOut() async {
// await SuperTokens.signOut(completionHandler: (error) {
// print(error);
// });
// if (await SuperTokens.doesSessionExist() == false) {
// Navigator.of(context).pop();
// Navigator.of(context).popAndPushNamed(
// '/',
// arguments: AuthArguments(true, false),
// );
// }
// }
//================== POP UPS ==========================================================================
static void internetConnectionPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Internet Connection",
);
},
);
}
static void successPopUp(String message, BuildContext context) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
static void loadingPopUp(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
}
}

View File

@@ -0,0 +1,105 @@
class MihValidationServices {
String? isEmpty(String? value) {
if (value == null || value.isEmpty) {
return "This field is required";
}
return null;
}
String? validateLength(String? value, int maxLength) {
if (value == null || value.isEmpty) {
return "This field is required";
}
if (value.length > maxLength) {
return "Length must not exceed $maxLength characters";
}
return null;
}
String? validateEmail(String? email) {
if (email == null || email.isEmpty) {
return "Email is required";
}
final emailRegex =
RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');
if (!emailRegex.hasMatch(email)) {
return "Invalid Email Format";
}
return null;
}
String? validateUsername(String? username) {
String? errorMessage = "";
if (username == null || username.isEmpty) {
errorMessage += "Username is required";
return errorMessage;
}
if (!RegExp(r'^[a-zA-Z]').hasMatch(username)) {
errorMessage += "\n• Your username should start with a letter.";
}
if (!RegExp(r'^[a-zA-Z0-9_]+$').hasMatch(username)) {
errorMessage +=
"\n• You can use letters, numbers, and/or underscores only.";
}
if (username.length < 6 || username.length > 30) {
errorMessage += "\n• Keep it between 6 and 30 characters.";
}
if (RegExp(r'[@#\$]').hasMatch(username)) {
errorMessage += "\n• Avoid special characters like @, #, or \$.";
}
if (errorMessage.isEmpty) {
return null; // No errors, username is valid
}
return "Let's create a great username for you!$errorMessage";
}
String? validateNumber(String? number, int? minValue, int? maxValue) {
String? errorMessage = "";
if (number == null || number.isEmpty) {
errorMessage += "This field is required";
return errorMessage;
}
int? value = int.tryParse(number);
if (value == null) {
errorMessage += "Please enter a valid number";
return errorMessage;
}
if (value < (minValue ?? 0)) {
errorMessage += "Value must be >= ${minValue ?? 0}";
}
if (maxValue != null && value > maxValue) {
if (errorMessage.isNotEmpty) errorMessage += "\n";
errorMessage += "Value must be <= $maxValue";
}
return errorMessage.isEmpty ? null : errorMessage;
}
String? validatePassword(String? password) {
String? errorMessage = "";
if (password == null || password.isEmpty) {
errorMessage += "Password is required";
return errorMessage;
}
if (password.length < 8) {
errorMessage += "\n• Contains at least 8 characters long";
}
if (!RegExp(r'[A-Z]').hasMatch(password)) {
errorMessage += "\n• Contains at least 1 uppercase letter";
}
if (!RegExp(r'[a-z]').hasMatch(password)) {
errorMessage += "\n• Contains at least 1 lowercase letter";
}
if (!RegExp(r'[0-9]').hasMatch(password)) {
errorMessage += "\n• Contains at least 1 digit";
}
if (!RegExp(r'[!@#$%^&*]').hasMatch(password)) {
errorMessage += "\n• Contains at least 1 special character (!@#\$%^&*)";
}
if (errorMessage.isEmpty) {
return null; // No errors, password is valid
}
errorMessage = "Let's create a great password for you!$errorMessage";
return errorMessage;
}
}