Merge pull request #174 from yaso-meth/BUG--File-uploud-in-Dev

BUG--File-uploud-in-Dev
This commit is contained in:
yaso-meth
2025-05-20 15:17:54 +02:00
committed by GitHub
15 changed files with 264 additions and 210 deletions

View File

@@ -21,6 +21,7 @@ class MIHClaimStatementGenerationApi {
Future<void> generateClaimStatement(
ClaimStatementGenerationArguments data,
PatientViewArguments args,
String env,
BuildContext context,
) async {
//start loading circle
@@ -31,6 +32,11 @@ class MIHClaimStatementGenerationApi {
},
);
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>{
@@ -39,7 +45,9 @@ class MIHClaimStatementGenerationApi {
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,
@@ -66,10 +74,6 @@ class MIHClaimStatementGenerationApi {
}),
);
//print(response1.statusCode);
DateTime now = new DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
String fileName =
"${data.document_type}-${data.patient_full_name}-${date.toString().substring(0, 10)}.pdf";
if (response1.statusCode == 200) {
//Update this API
var response2 = await http.post(
@@ -176,6 +180,7 @@ class MIHClaimStatementGenerationApi {
/// Returns VOID (TRIGGERS NOTIGICATIOPN ON SUCCESS)
static Future<void> deleteClaimStatementFilesByFileID(
PatientViewArguments args,
String env,
String filePath,
int fileID,
BuildContext context,
@@ -192,7 +197,10 @@ class MIHClaimStatementGenerationApi {
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"file_path": filePath}),
body: jsonEncode(<String, dynamic>{
"file_path": filePath,
"env": env,
}),
);
//print("Here4");
//print(response.statusCode);
@@ -203,7 +211,8 @@ class MIHClaimStatementGenerationApi {
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"idclaim_statement_file": fileID}),
body: jsonEncode(
<String, dynamic>{"idclaim_statement_file": fileID, "env": env}),
);
if (response2.statusCode == 200) {
Navigator.of(context).pop();

View File

@@ -57,6 +57,7 @@ class MihFileApi {
static Future<int> uploadFile(
String app_id,
String env,
String folderName,
PlatformFile? file,
BuildContext context,
@@ -69,6 +70,7 @@ class MihFileApi {
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' '), '-')));
@@ -79,6 +81,7 @@ class MihFileApi {
static Future<int> deleteFile(
String app_id,
String env,
String folderName,
String fileName,
BuildContext context,
@@ -91,7 +94,10 @@ class MihFileApi {
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"file_path": filePath}),
body: jsonEncode(<String, dynamic>{
"file_path": filePath,
"env": env,
}),
);
Navigator.of(context).pop(); // Pop loading dialog
return response.statusCode;

View File

@@ -12,6 +12,7 @@ import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_circle_avatar.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_success_message.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
class MihBusinessDetails extends StatefulWidget {
@@ -38,6 +39,7 @@ class _MihBusinessDetailsState extends State<MihBusinessDetails> {
final contactController = TextEditingController();
final emailController = TextEditingController();
final locationController = TextEditingController();
late String env;
Future<void> submitForm() async {
if (!isEmailValid()) {
@@ -136,6 +138,7 @@ class _MihBusinessDetailsState extends State<MihBusinessDetails> {
int uploadStatusCode = 0;
uploadStatusCode = await MihFileApi.uploadFile(
widget.arguments.business!.business_id,
env,
"business_files",
imageFile!,
context,
@@ -144,6 +147,7 @@ class _MihBusinessDetailsState extends State<MihBusinessDetails> {
int deleteStatusCode = 0;
deleteStatusCode = await MihFileApi.deleteFile(
widget.arguments.business!.logo_path.split("/").first,
env,
"business_files",
widget.arguments.business!.logo_path.split("/").last,
context,
@@ -220,6 +224,11 @@ class _MihBusinessDetailsState extends State<MihBusinessDetails> {
emailController.text = widget.arguments.business!.bus_email;
locationController.text = widget.arguments.business!.gps_location;
});
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
}
@override

View File

@@ -61,6 +61,7 @@ class _MihBusinessProfileState extends State<MihBusinessProfile> {
late String oldLogoPath;
late String oldSigPath;
String logoUri = "";
late String env;
Future<void> updateBusinessProfileAPICall(String business_id) async {
print("inside update business profile api call");
@@ -145,6 +146,7 @@ class _MihBusinessProfileState extends State<MihBusinessProfile> {
print("Inside upload selected file");
var response = await MihFileApi.uploadFile(
widget.arguments.signedInUser.app_id,
env,
"business_files",
file,
context,
@@ -160,6 +162,7 @@ class _MihBusinessProfileState extends State<MihBusinessProfile> {
// delete file from minio
var response = await MihFileApi.deleteFile(
widget.arguments.signedInUser.app_id,
env,
"business_files",
filePath.split("/").last,
context,
@@ -309,6 +312,11 @@ class _MihBusinessProfileState extends State<MihBusinessProfile> {
});
logoPreview = NetworkImage(logoUri);
});
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
super.initState();
}

View File

@@ -13,6 +13,7 @@ import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_image_display.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_success_message.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import 'package:mzansi_innovation_hub/mih_objects/arguments.dart';
class MihMyBusinessUser extends StatefulWidget {
@@ -41,6 +42,7 @@ class _MihMyBusinessUserState extends State<MihMyBusinessUser> {
final lnameController = TextEditingController();
final accessController = TextEditingController();
final signtureController = TextEditingController();
late String env;
bool isFormFilled() {
if (signtureController.text.isEmpty ||
@@ -60,6 +62,7 @@ class _MihMyBusinessUserState extends State<MihMyBusinessUser> {
int uploadStatusCode = 0;
uploadStatusCode = await MihFileApi.uploadFile(
widget.arguments.signedInUser.app_id,
env,
"business_files",
userSignatureFile!,
context,
@@ -68,6 +71,7 @@ class _MihMyBusinessUserState extends State<MihMyBusinessUser> {
int deleteStatusCode = 0;
deleteStatusCode = await MihFileApi.deleteFile(
widget.arguments.signedInUser.app_id,
env,
"business_files",
widget.arguments.businessUser!.sig_path.split("/").last,
context,
@@ -192,6 +196,11 @@ class _MihMyBusinessUserState extends State<MihMyBusinessUser> {
lnameController.text = widget.arguments.signedInUser.lname;
accessController.text = widget.arguments.businessUser!.access;
});
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
}
@override

View File

@@ -60,6 +60,7 @@ class _ProfileBusinessAddState extends State<ProfileBusinessAdd> {
PlatformFile? selectedSignature;
final ValueNotifier<String> busType = ValueNotifier("");
late String env;
// Future<void> uploadSelectedFile(
// PlatformFile file, TextEditingController controller) async {
@@ -85,6 +86,7 @@ class _ProfileBusinessAddState extends State<ProfileBusinessAdd> {
int uploadStatusCode = 0;
uploadStatusCode = await MihFileApi.uploadFile(
id,
env,
"business_files",
selectedFile,
context,
@@ -632,6 +634,11 @@ class _ProfileBusinessAddState extends State<ProfileBusinessAdd> {
lnameController.text = widget.signedInUser.lname;
accessController.text = "Full";
});
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
super.initState();
}

View File

@@ -36,6 +36,7 @@ class _MihPersonalProfileState extends State<MihPersonalProfile> {
late ImageProvider<Object>? propicPreview;
late bool businessUser;
late String oldProPicName;
late String env;
Future<void> submitForm() async {
// print("============\nsubmiit form\n=================");
@@ -82,6 +83,7 @@ class _MihPersonalProfileState extends State<MihPersonalProfile> {
Future<void> uploadSelectedFile(PlatformFile? file) async {
var response = await MihFileApi.uploadFile(
widget.arguments.signedInUser.app_id,
env,
"profile_files",
file,
context,
@@ -144,6 +146,7 @@ class _MihPersonalProfileState extends State<MihPersonalProfile> {
Future<void> deleteFileApiCall(String filename) async {
var response = await MihFileApi.deleteFile(
widget.arguments.signedInUser.app_id,
env,
"profile_files",
filename,
context,
@@ -200,6 +203,11 @@ class _MihPersonalProfileState extends State<MihPersonalProfile> {
if (widget.arguments.signedInUser.pro_pic_path.isNotEmpty) {
proPicName = widget.arguments.signedInUser.pro_pic_path.split("/").last;
}
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
setState(() {
propicPreview = widget.arguments.propicFile;
oldProPicName = proPicName;

View File

@@ -23,12 +23,14 @@ class ClaimStatementWindow extends StatefulWidget {
final AppUser signedInUser;
final Business? business;
final BusinessUser? businessUser;
final String env;
const ClaimStatementWindow({
super.key,
required this.selectedPatient,
required this.signedInUser,
required this.business,
required this.businessUser,
required this.env,
});
@override
@@ -265,6 +267,7 @@ class _ClaimStatementWindowState extends State<ClaimStatementWindow> {
widget.business,
"business",
),
widget.env,
context);
} else {
showDialog(

View File

@@ -31,6 +31,7 @@ class PrescripInput extends StatefulWidget {
final AppUser signedInUser;
final Business? business;
final BusinessUser? businessUser;
final String env;
const PrescripInput({
super.key,
required this.medicineController,
@@ -44,6 +45,7 @@ class PrescripInput extends StatefulWidget {
required this.signedInUser,
required this.business,
required this.businessUser,
required this.env,
});
@override
@@ -98,6 +100,11 @@ class _PrescripInputState extends State<PrescripInput> {
return const Mihloadingcircle();
},
);
DateTime now = new DateTime.now();
// DateTime date = new DateTime(now.year, now.month, now.day);
String fileName =
"Perscription-${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}-${now.toString().substring(0, 19)}.pdf"
.replaceAll(RegExp(r' '), '-');
var response1 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/minio/generate/perscription/"),
@@ -106,8 +113,10 @@ class _PrescripInputState extends State<PrescripInput> {
},
body: jsonEncode(<String, dynamic>{
"app_id": widget.selectedPatient.app_id,
"fullName":
"env": widget.env,
"patient_full_name":
"${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}",
"fileName": fileName,
"id_no": widget.selectedPatient.id_no,
"docfname":
"DR. ${widget.signedInUser.fname} ${widget.signedInUser.lname}",
@@ -121,13 +130,9 @@ class _PrescripInputState extends State<PrescripInput> {
}),
);
//print(response1.statusCode);
DateTime now = new DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
String fileName =
"Perscription-${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}-${date.toString().substring(0, 10)}.pdf";
if (response1.statusCode == 200) {
var response2 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/files/insert/"),
Uri.parse("${AppEnviroment.baseApiUrl}/patient_files/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
@@ -155,6 +160,7 @@ class _PrescripInputState extends State<PrescripInput> {
// end loading circle
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed('/patient-manager/patient',
arguments: PatientViewArguments(
widget.signedInUser,

View File

@@ -1,7 +1,6 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_apis/mih_claim_statement_generation_api.dart';
import 'package:mzansi_innovation_hub/mih_apis/mih_file_api.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_window.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_delete_message.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_error_message.dart';
@@ -15,7 +14,6 @@ import 'package:mzansi_innovation_hub/mih_objects/claim_statement_file.dart';
import 'package:mzansi_innovation_hub/mih_objects/patients.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/list_builders/build_file_view.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
class BuildClaimStatementFileList extends StatefulWidget {
final AppUser signedInUser;
@@ -24,6 +22,7 @@ class BuildClaimStatementFileList extends StatefulWidget {
final Business? business;
final BusinessUser? businessUser;
final String type;
final String env;
const BuildClaimStatementFileList({
super.key,
required this.files,
@@ -32,6 +31,7 @@ class BuildClaimStatementFileList extends StatefulWidget {
required this.business,
required this.businessUser,
required this.type,
required this.env,
});
@override
@@ -47,27 +47,14 @@ class _BuildClaimStatementFileListState
String fileUrl = "";
Future<String> getFileUrlApiCall(String filePath) async {
var url = "$baseAPI/minio/pull/file/${AppEnviroment.getEnv()}/$filePath";
//print(url);
var response = await http.get(Uri.parse(url));
// print("here1");
//print(response.statusCode);
if (response.statusCode == 200) {
//print("here2");
String body = response.body;
//print(body);
//print("here3");
var decodedData = jsonDecode(body);
//print("Dedoced: ${decodedData['minioURL']}");
return decodedData['minioURL'];
//AppUser u = AppUser.fromJson(decodedData);
// print(u.email);
//return "AlometThere";
} else {
throw Exception("Error: GetUserData status code ${response.statusCode}");
}
String teporaryFileUrl = "";
await MihFileApi.getMinioFileUrl(
filePath,
context,
).then((value) {
teporaryFileUrl = value;
});
return teporaryFileUrl;
}
void internetConnectionPopUp() {
@@ -108,6 +95,7 @@ class _BuildClaimStatementFileListState
widget.business,
"business",
),
widget.env,
filePath,
fileID,
context,

View File

@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_apis/mih_file_api.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_window.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_delete_message.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_error_message.dart';
@@ -24,6 +25,7 @@ class BuildFilesList extends StatefulWidget {
final Business? business;
final BusinessUser? businessUser;
final String type;
final String env;
const BuildFilesList({
super.key,
required this.files,
@@ -32,6 +34,7 @@ class BuildFilesList extends StatefulWidget {
required this.business,
required this.businessUser,
required this.type,
required this.env,
});
@override
@@ -45,109 +48,77 @@ class _BuildFilesListState extends State<BuildFilesList> {
String fileUrl = "";
Future<String> getFileUrlApiCall(String filePath) async {
var url = "$baseAPI/minio/pull/file/${AppEnviroment.getEnv()}/$filePath";
//print(url);
var response = await http.get(Uri.parse(url));
// print("here1");
//print(response.statusCode);
if (response.statusCode == 200) {
//print("here2");
String body = response.body;
//print(body);
//print("here3");
var decodedData = jsonDecode(body);
//print("Dedoced: ${decodedData['minioURL']}");
return decodedData['minioURL'];
//AppUser u = AppUser.fromJson(decodedData);
// print(u.email);
//return "AlometThere";
} else {
throw Exception("Error: GetUserData status code ${response.statusCode}");
}
//print(url);
// var response = await http.get(Uri.parse(url));
// // print("here1");
// //print(response.statusCode);
// if (response.statusCode == 200) {
// //print("here2");
// String body = response.body;
// //print(body);
// //print("here3");
// var decodedData = jsonDecode(body);
// //print("Dedoced: ${decodedData['minioURL']}");
// return decodedData['minioURL'];
// //AppUser u = AppUser.fromJson(decodedData);
// // print(u.email);
// //return "AlometThere";
// } else {
// throw Exception("Error: GetUserData status code ${response.statusCode}");
// }
String teporaryFileUrl = "";
await MihFileApi.getMinioFileUrl(
filePath,
context,
).then((value) {
teporaryFileUrl = value;
});
return teporaryFileUrl;
}
Future<void> deleteFileApiCall(String filePath, int fileID) async {
var response = await MihFileApi.deleteFile(
widget.selectedPatient.app_id,
widget.env,
"patient_files",
filePath.split("/").last,
context,
);
if (response == 200) {
// delete file from database
await deletePatientFileLocationToDB(fileID);
} else {
String message =
"The File has not been deleted successfully. Please try again.";
successPopUp(message);
}
}
Future<void> deletePatientFileLocationToDB(int fileID) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
// delete file from minio
var response = await http.delete(
Uri.parse("$baseAPI/minio/delete/file/"),
var response2 = await http.delete(
Uri.parse("$baseAPI/patient_files/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"file_path": filePath}),
body: jsonEncode(<String, dynamic>{
"idpatient_files": fileID,
"env": widget.env,
}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
//SQL delete
var response2 = await http.delete(
Uri.parse("$baseAPI/files/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"idpatient_files": fileID}),
);
if (response2.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
//print(widget.business);
if (widget.business == null) {
Navigator.of(context).pushNamed('/patient-manager/patient',
arguments: PatientViewArguments(
widget.signedInUser,
widget.selectedPatient,
widget.businessUser,
widget.business,
"personal"));
} else {
Navigator.of(context).pushNamed('/patient-manager/patient',
arguments: PatientViewArguments(
widget.signedInUser,
widget.selectedPatient,
widget.businessUser,
widget.business,
"business"));
}
// 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);
if (response2.statusCode == 200) {
Navigator.of(context).pop(); //Remove Loading Dialog
Navigator.of(context).pop(); //Remove Delete Dialog
Navigator.of(context).pop(); //Remove File View Dialog
Navigator.of(context).pop(); //Remove File List Dialog
//print(widget.business);
if (widget.business == null) {
Navigator.of(context).pushNamed('/patient-manager/patient',
arguments: PatientViewArguments(
widget.signedInUser,
widget.selectedPatient,
widget.businessUser,
widget.business,
"personal"));
} else {
internetConnectionPopUp();
Navigator.of(context).pushNamed('/patient-manager/patient',
arguments: PatientViewArguments(
widget.signedInUser,
widget.selectedPatient,
widget.businessUser,
widget.business,
"business"));
}
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);
} else {
internetConnectionPopUp();
}

View File

@@ -4,6 +4,7 @@ import 'package:mzansi_innovation_hub/mih_apis/mih_claim_statement_generation_ap
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih-app_tool_body.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_floating_menu.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_env/env.dart';
import 'package:mzansi_innovation_hub/mih_objects/app_user.dart';
import 'package:mzansi_innovation_hub/mih_objects/business.dart';
import 'package:mzansi_innovation_hub/mih_objects/business_user.dart';
@@ -37,6 +38,7 @@ class PatientClaimOrStatement extends StatefulWidget {
class _PatientClaimOrStatementState extends State<PatientClaimOrStatement> {
late Future<List<ClaimStatementFile>> futueFiles;
late String env;
void claimOrStatementWindow() {
showDialog(
@@ -47,6 +49,7 @@ class _PatientClaimOrStatementState extends State<PatientClaimOrStatement> {
signedInUser: widget.signedInUser,
business: widget.business,
businessUser: widget.businessUser,
env: env,
),
);
}
@@ -100,6 +103,11 @@ class _PatientClaimOrStatementState extends State<PatientClaimOrStatement> {
MIHClaimStatementGenerationApi.getClaimStatementFilesByBusiness(
widget.business!.business_id);
}
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
super.initState();
}
@@ -154,6 +162,7 @@ class _PatientClaimOrStatementState extends State<PatientClaimOrStatement> {
business: widget.business,
businessUser: widget.businessUser,
type: widget.type,
env: env,
),
],
);

View File

@@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_apis/mih_file_api.dart';
import 'package:mzansi_innovation_hub/mih_components/med_cert_input.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_inputs_and_buttons/mih_button.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_inputs_and_buttons/mih_file_input.dart';
@@ -22,9 +23,7 @@ import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/c
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/list_builders/build_files_list.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/supertokens.dart';
import 'package:supertokens_flutter/http.dart' as http;
import 'package:http/http.dart' as http2;
class PatientDocuments extends StatefulWidget {
final int patientIndex;
@@ -61,10 +60,24 @@ class _PatientDocumentsState extends State<PatientDocuments> {
final noRepeatsController = TextEditingController();
final outputController = TextEditingController();
late PlatformFile? selected;
late String env;
Future<void> submitDocUploadForm() async {
if (isFileFieldsFilled()) {
await uploadSelectedFile(selected);
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
}
}
Future<List<PFile>> fetchFiles() async {
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/files/patients/${widget.selectedPatient.app_id}"));
"${AppEnviroment.baseApiUrl}/patient_files/get/${widget.selectedPatient.app_id}"));
//print(response.statusCode);
//print(response.body);
if (response.statusCode == 200) {
@@ -78,63 +91,53 @@ class _PatientDocumentsState extends State<PatientDocuments> {
}
}
Future<void> uploadSelectedFile(PlatformFile? file) async {
print("File: $file");
//var strem = new http.ByteStream.fromBytes(file.bytes.)
//start loading circle
Future<void> addPatientFileLocationToDB(PlatformFile? file) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var token = await SuperTokens.getAccessToken();
//print(t);
print("here1");
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'] = widget.selectedPatient.app_id;
request.fields['folder'] = "patient_files";
request.files.add(await http2.MultipartFile.fromBytes('file', file!.bytes!,
filename: file.name.replaceAll(RegExp(r' '), '-')));
print("here2");
var response1 = await request.send();
print("here3");
print(response1.statusCode);
print(response1.toString());
if (response1.statusCode == 200) {
//print("here3");
var fname = file.name.replaceAll(RegExp(r' '), '-');
var filePath = "${widget.selectedPatient.app_id}/patient_files/$fname";
var response2 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/files/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"file_path": filePath,
"file_name": fname,
"app_id": widget.selectedPatient.app_id
}),
);
//print("here5");
//print(response2.statusCode);
if (response2.statusCode == 201) {
setState(() {
selectedFileController.clear();
futueFiles = fetchFiles();
});
// end loading circle
Navigator.of(context).pop();
String message =
"The file ${file.name.replaceAll(RegExp(r' '), '-')} has been successfully generated and added to ${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}'s record. You can now access and download it for their use.";
successPopUp(message);
} else {
internetConnectionPopUp();
}
var fname = file!.name.replaceAll(RegExp(r' '), '-');
var filePath = "${widget.selectedPatient.app_id}/patient_files/$fname";
var response2 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/patient_files/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"file_path": filePath,
"file_name": fname,
"app_id": widget.selectedPatient.app_id
}),
);
//print("here5");
//print(response2.statusCode);
if (response2.statusCode == 201) {
setState(() {
selectedFileController.clear();
futueFiles = fetchFiles();
});
// end loading circle
Navigator.of(context).pop();
String message =
"The file ${file.name.replaceAll(RegExp(r' '), '-')} has been successfully generated and added to ${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}'s record. You can now access and download it for their use.";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
Future<void> uploadSelectedFile(PlatformFile? file) async {
var response = await MihFileApi.uploadFile(
widget.selectedPatient.app_id,
env,
"patient_files",
file,
context,
);
if (response == 200) {
await addPatientFileLocationToDB(file);
} else {
internetConnectionPopUp();
}
@@ -148,6 +151,11 @@ class _PatientDocumentsState extends State<PatientDocuments> {
return const Mihloadingcircle();
},
);
DateTime now = DateTime.now();
// DateTime date = new DateTime(now.year, now.month, now.day);
String fileName =
"Med-Cert-${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}-${now.toString().substring(0, 19)}.pdf"
.replaceAll(RegExp(r' '), '-');
var response1 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/minio/generate/med-cert/"),
headers: <String, String>{
@@ -155,8 +163,10 @@ class _PatientDocumentsState extends State<PatientDocuments> {
},
body: jsonEncode(<String, dynamic>{
"app_id": widget.selectedPatient.app_id,
"fullName":
"env": env,
"patient_full_name":
"${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}",
"fileName": fileName,
"id_no": widget.selectedPatient.id_no,
"docfname":
"DR. ${widget.signedInUser.fname} ${widget.signedInUser.lname}",
@@ -172,13 +182,9 @@ class _PatientDocumentsState extends State<PatientDocuments> {
}),
);
print(response1.statusCode);
DateTime now = new DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
String fileName =
"Med-Cert-${widget.selectedPatient.first_name} ${widget.selectedPatient.last_name}-${date.toString().substring(0, 10)}.pdf";
if (response1.statusCode == 200) {
var response2 = await http.post(
Uri.parse("${AppEnviroment.baseApiUrl}/files/insert/"),
Uri.parse("${AppEnviroment.baseApiUrl}/patient_files/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
@@ -256,7 +262,8 @@ class _PatientDocumentsState extends State<PatientDocuments> {
textColor: MzanziInnovationHub.of(context)!.theme.primaryColor(),
onTap: () {
if (isFileFieldsFilled()) {
uploadSelectedFile(selected);
submitDocUploadForm();
// uploadSelectedFile(selected);
Navigator.pop(context);
} else {
showDialog(
@@ -350,6 +357,7 @@ class _PatientDocumentsState extends State<PatientDocuments> {
signedInUser: widget.signedInUser,
business: widget.business,
businessUser: widget.businessUser,
env: env,
),
],
),
@@ -576,6 +584,11 @@ class _PatientDocumentsState extends State<PatientDocuments> {
@override
void initState() {
futueFiles = fetchFiles();
if (AppEnviroment.getEnv() == "Prod") {
env = "Prod";
} else {
env = "Dev";
}
super.initState();
}
@@ -629,6 +642,7 @@ class _PatientDocumentsState extends State<PatientDocuments> {
business: widget.business,
businessUser: widget.businessUser,
type: widget.type,
env: env,
),
]);
} else {

View File

@@ -31,10 +31,13 @@ class minioPullRequest(BaseModel):
class minioDeleteRequest(BaseModel):
file_path: str
env: str
class medCertUploud(BaseModel):
app_id: str
fullName: str
env: str
patient_full_name: str
fileName: str
id_no: str
docfname: str
busName: str
@@ -60,7 +63,9 @@ class perscription(BaseModel):
class perscriptionList(BaseModel):
app_id: str
fullName: str
env: str
patient_full_name: str
fileName: str
id_no: str
docfname: str
busName: str
@@ -74,7 +79,9 @@ class perscriptionList(BaseModel):
class claimStatementUploud(BaseModel):
document_type: str
patient_app_id: str
env: str
patient_full_name: str
fileName: str
patient_id_no: str
has_med_aid: str
med_aid_no: str
@@ -131,11 +138,11 @@ async def pull_File_from_user(app_id: str, folder: str, file_name: str, env: str
}
@router.post("/minio/upload/file/", tags=["Minio"])
async def upload_File_to_user(file: UploadFile = File(...), app_id: str= Form(...), folder: str= Form(...), session: SessionContainer = Depends(verify_session())):
async def upload_File_to_user(file: UploadFile = File(...), app_id: str= Form(...), env: str= Form(...), folder: str= Form(...), session: SessionContainer = Depends(verify_session())):
extension = file.filename.split(".")
content = file.file
try:
uploudFile(app_id, folder, file.filename, extension[1], content)
uploudFile(app_id, env, folder, file.filename, extension[1], content)
except Exception as error:
raise HTTPException(status_code=404, detail="Failed to Uploud Record")
return {"message": f"Successfully Uploaded {file.filename}"}
@@ -152,7 +159,7 @@ async def delete_File_of_user(requestItem: minioDeleteRequest, session: SessionC
path = requestItem.file_path
try:
# uploudFile(app_id, file.filename, extension[1], content)
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
minioError = client.remove_object("mih", path)
except Exception as error:
@@ -182,8 +189,8 @@ async def upload_perscription_to_user(requestItem: claimStatementUploud, session
uploudClaimStatement(requestItem)
return {"message": "Successfully Generated File"}
def uploudFile(app_id, folder, fileName, extension, content):
client = Minio_Storage.minioConnection.minioConnect("Prod")
def uploudFile(app_id, env, folder, fileName, extension, content):
client = Minio_Storage.minioConnection.minioConnect(env)
found = client.bucket_exists("mih")
if not found:
client.make_bucket("mih")
@@ -198,7 +205,7 @@ def uploudFile(app_id, folder, fileName, extension, content):
content_type=f"application/{extension}")
def uploudMedCert(requestItem: medCertUploud):
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
generateMedCertPDF(requestItem)
today = datetime.today().strftime('%Y-%m-%d')
found = client.bucket_exists("mih")
@@ -206,11 +213,11 @@ def uploudMedCert(requestItem: medCertUploud):
client.make_bucket("mih")
else:
print("Bucket already exists")
fileName = f"{requestItem.app_id}/patient_files/Med-Cert-{requestItem.fullName}-{today}.pdf"
fileName = f"{requestItem.app_id}/patient_files/{requestItem.fileName}"
client.fput_object("mih", fileName, "temp-med-cert.pdf")
def generateMedCertPDF(requestItem: medCertUploud):
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
new_logo_path = requestItem.logo_path.replace(" ","-")
new_sig_path = requestItem.sig_path.replace(" ","-")
minioLogo = client.get_object("mih", new_logo_path).read()
@@ -243,7 +250,7 @@ def generateMedCertPDF(requestItem: medCertUploud):
#Body
myCanvas.setFont('Helvetica', 12)
body = ""
body += "This is to certify that " + requestItem.fullName.upper() + " (" + requestItem.id_no+ ") was seen by " + requestItem.docfname.upper() + " on " + requestItem.startDate + "."
body += "This is to certify that " + requestItem.patient_full_name.upper() + " (" + requestItem.id_no+ ") was seen by " + requestItem.docfname.upper() + " on " + requestItem.startDate + "."
body += "\nHe/She is unfit to attend work/school from " + requestItem.startDate + " up to and including " + requestItem.endDate + "."
body += "\nHe/She will return on " + requestItem.returnDate + "."
@@ -261,7 +268,7 @@ def generateMedCertPDF(requestItem: medCertUploud):
myCanvas.drawString(50, h-720, requestItem.docfname.upper())
#QR Verification
qrText = requestItem.fullName.upper() + " booked off from " + requestItem.startDate + " to " + requestItem.endDate + " by " + requestItem.docfname.upper() + ".\nPowered by Mzansi Innovation Hub."
qrText = requestItem.patient_full_name.upper() + " booked off from " + requestItem.startDate + " to " + requestItem.endDate + " by " + requestItem.docfname.upper() + ".\nPowered by Mzansi Innovation Hub."
qrText = qrText.replace(" ","+")
url = f"https://api.qrserver.com/v1/create-qr-code/?data={qrText}&size=100x100"
@@ -275,7 +282,7 @@ def generateMedCertPDF(requestItem: medCertUploud):
myCanvas.save()
def uploudPerscription(requestItem: perscriptionList):
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
generatePerscriptionPDF(requestItem)
today = datetime.today().strftime('%Y-%m-%d')
found = client.bucket_exists("mih")
@@ -283,11 +290,11 @@ def uploudPerscription(requestItem: perscriptionList):
client.make_bucket("mih")
else:
print("Bucket already exists")
fileName = f"{requestItem.app_id}/patient_files/Perscription-{requestItem.fullName}-{today}.pdf"
fileName = f"{requestItem.app_id}/patient_files/{requestItem.fileName}"
client.fput_object("mih", fileName, "temp-perscription.pdf")
def generatePerscriptionPDF(requestItem: perscriptionList):
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
new_logo_path = requestItem.logo_path.replace(" ","-")
new_sig_path = requestItem.sig_path.replace(" ","-")
minioLogo = client.get_object("mih", new_logo_path).read()
@@ -297,7 +304,7 @@ def generatePerscriptionPDF(requestItem: perscriptionList):
w,h = A4
myCanvas = canvas.Canvas("temp-claim.pdf", pagesize=A4)
myCanvas = canvas.Canvas("temp-perscription.pdf", pagesize=A4)
#Business Logo
myCanvas.drawImage(imageLogo, 50, h - 125,100,100, mask='auto')
@@ -321,7 +328,7 @@ def generatePerscriptionPDF(requestItem: perscriptionList):
#Body
myCanvas.setFont('Helvetica-Bold', 12)
myCanvas.drawString(50, h-250, f"Patient: {requestItem.fullName}")
myCanvas.drawString(50, h-250, f"Patient: {requestItem.patient_full_name}")
myCanvas.drawString(50, h-270, f"Patient ID: {requestItem.id_no}")
#boday headings
@@ -362,7 +369,7 @@ def generatePerscriptionPDF(requestItem: perscriptionList):
myCanvas.drawString(50, h-y-30, requestItem.docfname.upper())
#QR Verification
qrText = f"Perscription generated on {issueDate} by {requestItem.docfname} for {requestItem.fullName}.\nPowered by Mzansi Innovation Hub."
qrText = f"Perscription generated on {issueDate} by {requestItem.docfname} for {requestItem.patient_full_name}.\nPowered by Mzansi Innovation Hub."
qrText = qrText.replace(" ","+")
url = f"https://api.qrserver.com/v1/create-qr-code/?data={qrText}&size=100x100"
@@ -377,7 +384,7 @@ def generatePerscriptionPDF(requestItem: perscriptionList):
def uploudClaimStatement(requestItem: claimStatementUploud):
try:
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
print("connected")
except Exception:
print("error")
@@ -389,11 +396,11 @@ def uploudClaimStatement(requestItem: claimStatementUploud):
client.make_bucket("mih")
else:
print("Bucket already exists")
fileName = f"{requestItem.patient_app_id}/claims-statements/{requestItem.document_type}-{requestItem.patient_full_name}-{today}.pdf"
fileName = f"{requestItem.patient_app_id}/claims-statements/{requestItem.fileName}"
client.fput_object("mih", fileName, "temp-claim-statement.pdf")
def generateClaimStatementPDF(requestItem: claimStatementUploud):
client = Minio_Storage.minioConnection.minioConnect("Prod")
client = Minio_Storage.minioConnection.minioConnect(requestItem.env)
# print("buckets: " + client.list_buckets)
new_logo_path = requestItem.logo_path.replace(" ","-")
new_sig_path = requestItem.sig_path.replace(" ","-")

View File

@@ -41,7 +41,7 @@ class fileInsertRequest(BaseModel):
# return items
# Get List of all files by patient
@router.get("/files/patients/{app_id}", tags=["Patients Files"])
@router.get("/patient_files/get/{app_id}", tags=["Patients Files"])
async def read_all_patient_files_by_app_id(app_id: str, session: SessionContainer = Depends(verify_session())):
db = database.dbConnection.dbPatientManagerConnect()
cursor = db.cursor()
@@ -89,7 +89,7 @@ async def read_all_patient_files_by_app_id(app_id: str, session: SessionContaine
# return items
# Delete Patient note on table
@router.delete("/files/delete/", tags=["Patients Files"])
@router.delete("/patient_files/delete/", tags=["Patients Files"])
async def Delete_Patient_File(itemRequest : fileDeleteRequest, session: SessionContainer = Depends(verify_session())): #session: SessionContainer = Depends(verify_session())
# today = date.today()
db = database.dbConnection.dbPatientManagerConnect()
@@ -108,7 +108,7 @@ async def Delete_Patient_File(itemRequest : fileDeleteRequest, session: SessionC
return {"message": "Successfully deleted Record"}
# Insert Patient note into table
@router.post("/files/insert/", tags=["Patients Files"], status_code=201)
@router.post("/patient_files/insert/", tags=["Patients Files"], status_code=201)
async def insert_Patient_Files(itemRequest : fileInsertRequest, session: SessionContainer = Depends(verify_session())):
today = date.today()
db = database.dbConnection.dbPatientManagerConnect()