move to business profile

This commit is contained in:
2025-03-26 11:54:14 +02:00
parent 85b042b44a
commit d2c423a33c
6 changed files with 72 additions and 72 deletions

View File

@@ -0,0 +1,418 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../../../../main.dart';
import '../../../../mih_components/mih_inputs_and_buttons/mih_button.dart';
import '../../../../mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart';
import '../../../../mih_components/mih_inputs_and_buttons/mih_text_input.dart';
import '../../../../mih_components/mih_layout/mih_window.dart';
import '../../../../mih_components/mih_pop_up_messages/mih_delete_message.dart';
import '../../../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../../../mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import '../../../../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../../../../mih_env/env.dart';
import '../../../../mih_objects/arguments.dart';
import '../../../../mih_objects/business_employee.dart';
class BuildEmployeeList extends StatefulWidget {
final List<BusinessEmployee> employees;
final BusinessArguments arguments;
const BuildEmployeeList({
super.key,
required this.employees,
required this.arguments,
});
@override
State<BuildEmployeeList> createState() => _BuildEmployeeListState();
}
class _BuildEmployeeListState extends State<BuildEmployeeList> {
TextEditingController accessController = TextEditingController();
TextEditingController typeController = TextEditingController();
TextEditingController fnameController = TextEditingController();
TextEditingController lnameController = TextEditingController();
final baseAPI = AppEnviroment.baseApiUrl;
Future<void> updateEmployeeAPICall(int index) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.put(
Uri.parse("$baseAPI/business-user/employees/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": widget.employees[index].business_id,
"app_id": widget.employees[index].app_id,
"title": typeController.text,
"access": accessController.text,
}),
);
if (response.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
//setState(() {});
Navigator.of(context).pushNamed(
'/business-profile/manage',
arguments: BusinessArguments(
widget.arguments.signedInUser,
widget.arguments.businessUser,
widget.arguments.business,
),
);
String message = "Your employees details have been updated.";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
Future<void> deleteNoteApiCall(int index) async {
var response = await http.delete(
Uri.parse("$baseAPI/business-user/employees/delete/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": widget.employees[index].business_id,
"app_id": widget.employees[index].app_id,
}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/business-profile/manage',
arguments: BusinessArguments(
widget.arguments.signedInUser,
widget.arguments.businessUser,
widget.arguments.business,
),
);
String message =
"The employee has been deleted successfully. This means it will no longer have access to your business profile";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
void internetConnectionPopUp() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
void successPopUp(String message) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
bool isRequiredFieldsCaptured() {
if (accessController.text.isEmpty || typeController.text.isEmpty) {
return false;
} else {
return true;
}
}
void updateEmployeePopUp(int index) {
setState(() {
accessController.text = widget.employees[index].access;
typeController.text = widget.employees[index].title;
fnameController.text = widget.employees[index].fname;
lnameController.text = widget.employees[index].lname;
});
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => MIHWindow(
fullscreen: false,
windowTitle: "Employee Details",
windowTools: [
IconButton(
onPressed: () {
showDeleteWarning(index);
},
icon: Icon(
Icons.delete,
color: MzanziInnovationHub.of(context)!.theme.secondaryColor(),
size: 35,
),
),
],
onWindowTapClose: () {
Navigator.pop(context);
},
windowBody: [
MIHTextField(
controller: fnameController,
hintText: "First Name",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: lnameController,
hintText: "Surname",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: typeController,
hintText: "Title",
dropdownOptions: const ["Doctor", "Assistant"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: accessController,
hintText: "Access",
dropdownOptions: const ["Full", "Partial"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 15.0),
SizedBox(
width: 300,
height: 50,
child: MIHButton(
buttonText: "Update",
buttonColor:
MzanziInnovationHub.of(context)!.theme.secondaryColor(),
textColor: MzanziInnovationHub.of(context)!.theme.primaryColor(),
onTap: () {
if (isRequiredFieldsCaptured()) {
updateEmployeeAPICall(index);
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
}
},
),
)
],
),
);
// showDialog(
// context: context,
// barrierDismissible: false,
// builder: (context) => Dialog(
// child: Stack(
// children: [
// Container(
// padding: const EdgeInsets.all(10.0),
// width: 700.0,
// //height: 475.0,
// decoration: BoxDecoration(
// color: MzanziInnovationHub.of(context)!.theme.primaryColor(),
// borderRadius: BorderRadius.circular(25.0),
// border: Border.all(
// color:
// MzanziInnovationHub.of(context)!.theme.secondaryColor(),
// width: 5.0),
// ),
// child: SingleChildScrollView(
// padding: const EdgeInsets.symmetric(horizontal: 10),
// child: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// Text(
// "Employee Details",
// textAlign: TextAlign.center,
// style: TextStyle(
// color: MzanziInnovationHub.of(context)!
// .theme
// .secondaryColor(),
// fontSize: 35.0,
// fontWeight: FontWeight.bold,
// ),
// ),
// const SizedBox(height: 25.0),
// MIHTextField(
// controller: fnameController,
// hintText: "First Name",
// editable: false,
// required: true,
// ),
// const SizedBox(height: 10.0),
// MIHTextField(
// controller: lnameController,
// hintText: "Surname",
// editable: false,
// required: true,
// ),
// const SizedBox(height: 10.0),
// MIHDropdownField(
// controller: typeController,
// hintText: "Title",
// dropdownOptions: const ["Doctor", "Assistant"],
// required: true,
// editable: true,
// ),
// const SizedBox(height: 10.0),
// MIHDropdownField(
// controller: accessController,
// hintText: "Access",
// dropdownOptions: const ["Full", "Partial"],
// required: true,
// editable: true,
// ),
// const SizedBox(height: 30.0),
// SizedBox(
// width: 300,
// height: 50,
// child: MIHButton(
// buttonText: "Update",
// buttonColor: MzanziInnovationHub.of(context)!
// .theme
// .secondaryColor(),
// textColor: MzanziInnovationHub.of(context)!
// .theme
// .primaryColor(),
// onTap: () {
// if (isRequiredFieldsCaptured()) {
// updateEmployeeAPICall(index);
// } else {
// showDialog(
// context: context,
// builder: (context) {
// return const MIHErrorMessage(
// errorType: "Input Error");
// },
// );
// }
// },
// ),
// )
// ],
// ),
// ),
// ),
// Positioned(
// top: 5,
// right: 5,
// width: 50,
// height: 50,
// child: IconButton(
// onPressed: () {
// Navigator.pop(context);
// },
// icon: Icon(
// Icons.close,
// color: MzanziInnovationHub.of(context)!.theme.errorColor(),
// size: 35,
// ),
// ),
// ),
// Positioned(
// top: 5,
// left: 5,
// width: 50,
// height: 50,
// child: IconButton(
// onPressed: () {
// showDeleteWarning(index);
// },
// icon: Icon(
// Icons.delete,
// color:
// MzanziInnovationHub.of(context)!.theme.secondaryColor(),
// size: 35,
// ),
// ),
// ),
// ],
// ),
// ),
// );
}
void showDeleteWarning(int index) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => MIHDeleteMessage(
deleteType: "Employee",
onTap: () {
deleteNoteApiCall(index);
}));
}
@override
void dispose() {
accessController.dispose();
typeController.dispose();
fnameController.dispose();
lnameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
separatorBuilder: (BuildContext context, index) {
return Divider(
color: MzanziInnovationHub.of(context)!.theme.secondaryColor(),
);
},
itemCount: widget.employees.length,
itemBuilder: (context, index) {
//final patient = widget.patients[index].id_no.contains(widget.searchString);
//print(index);
var isMe = "";
if (widget.arguments.signedInUser.app_id ==
widget.employees[index].app_id) {
isMe = "(You)";
}
return ListTile(
title: Text(
"${widget.employees[index].fname} ${widget.employees[index].lname} - ${widget.employees[index].title} $isMe"),
subtitle: Text(
"${widget.employees[index].username}\n${widget.employees[index].email}\nAccess: ${widget.employees[index].access}",
style: TextStyle(
color: MzanziInnovationHub.of(context)!.theme.secondaryColor(),
),
),
onTap: () {
updateEmployeePopUp(index);
},
);
},
);
}
}

View File

@@ -0,0 +1,353 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../../../../main.dart';
import '../../../../mih_components/mih_inputs_and_buttons/mih_button.dart';
import '../../../../mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart';
import '../../../../mih_components/mih_inputs_and_buttons/mih_text_input.dart';
import '../../../../mih_components/mih_layout/mih_window.dart';
import '../../../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../../../mih_components/mih_pop_up_messages/mih_loading_circle.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';
class BuildUserList extends StatefulWidget {
final List<AppUser> users;
final BusinessArguments arguments;
const BuildUserList({
super.key,
required this.users,
required this.arguments,
});
@override
State<BuildUserList> createState() => _BuildUserListState();
}
class _BuildUserListState extends State<BuildUserList> {
TextEditingController accessController = TextEditingController();
TextEditingController typeController = TextEditingController();
TextEditingController fnameController = TextEditingController();
TextEditingController lnameController = TextEditingController();
final baseAPI = AppEnviroment.baseApiUrl;
Future<void> createBusinessUserAPICall(int index) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.post(
Uri.parse("$baseAPI/business-user/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": widget.arguments.business!.business_id,
"app_id": widget.users[index].app_id,
"signature": "",
"sig_path": "",
"title": typeController.text,
"access": accessController.text,
}),
);
if (response.statusCode == 201) {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/business-profile/manage',
arguments: BusinessArguments(
widget.arguments.signedInUser,
widget.arguments.businessUser,
widget.arguments.business,
),
);
String message =
"${widget.users[index].username} is now apart of your team with ${accessController.text} access to ${widget.arguments.business!.Name}";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
bool isRequiredFieldsCaptured() {
if (accessController.text.isEmpty || typeController.text.isEmpty) {
return false;
} else {
return true;
}
}
void internetConnectionPopUp() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
void successPopUp(String message) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
String hideEmail(String email) {
var firstLetter = email[0];
var end = email.split("@")[1];
return "$firstLetter********@$end";
}
void addEmployeePopUp(int index) {
setState(() {
//accessController.text = widget.users[index].access;
//typeController.text = widget.users[index].title;
// var fnameInitial = widget.users[index].fname[0];
// var lnameInitial = widget.users[index].lname[0];
fnameController.text = widget.users[index].username;
lnameController.text = hideEmail(widget.users[index].email);
});
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => MIHWindow(
fullscreen: false,
windowTitle: "Add Employee",
windowBody: [
const SizedBox(height: 10.0),
MIHTextField(
controller: fnameController,
hintText: "Username Name",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: lnameController,
hintText: "Email",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: typeController,
hintText: "Title",
dropdownOptions: const ["Doctor", "Assistant"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: accessController,
hintText: "Access",
dropdownOptions: const ["Full", "Partial"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 15.0),
SizedBox(
width: 300,
height: 50,
child: MIHButton(
buttonText: "Add",
buttonColor:
MzanziInnovationHub.of(context)!.theme.secondaryColor(),
textColor:
MzanziInnovationHub.of(context)!.theme.primaryColor(),
onTap: () {
if (isRequiredFieldsCaptured()) {
createBusinessUserAPICall(index);
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(
errorType: "Input Error");
},
);
}
},
),
),
const SizedBox(height: 10.0),
],
windowTools: [],
onWindowTapClose: () {
Navigator.pop(context);
}));
// showDialog(
// context: context,
// barrierDismissible: false,
// builder: (context) => Dialog(
// child: Stack(
// children: [
// Container(
// padding: const EdgeInsets.all(10.0),
// width: 700.0,
// //height: 475.0,
// decoration: BoxDecoration(
// color: MzanziInnovationHub.of(context)!.theme.primaryColor(),
// borderRadius: BorderRadius.circular(25.0),
// border: Border.all(
// color:
// MzanziInnovationHub.of(context)!.theme.secondaryColor(),
// width: 5.0),
// ),
// child: SingleChildScrollView(
// padding: const EdgeInsets.symmetric(horizontal: 10),
// child: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// Text(
// "Add Employee",
// textAlign: TextAlign.center,
// style: TextStyle(
// color: MzanziInnovationHub.of(context)!
// .theme
// .secondaryColor(),
// fontSize: 35.0,
// fontWeight: FontWeight.bold,
// ),
// ),
// const SizedBox(height: 25.0),
// MIHTextField(
// controller: fnameController,
// hintText: "Username Name",
// editable: false,
// required: true,
// ),
// const SizedBox(height: 10.0),
// MIHTextField(
// controller: lnameController,
// hintText: "Email",
// editable: false,
// required: true,
// ),
// const SizedBox(height: 10.0),
// MIHDropdownField(
// controller: typeController,
// hintText: "Title",
// dropdownOptions: const ["Doctor", "Assistant"],
// required: true,
// editable: true,
// ),
// const SizedBox(height: 10.0),
// MIHDropdownField(
// controller: accessController,
// hintText: "Access",
// dropdownOptions: const ["Full", "Partial"],
// required: true,
// editable: true,
// ),
// const SizedBox(height: 30.0),
// SizedBox(
// width: 300,
// height: 50,
// child: MIHButton(
// buttonText: "Add",
// buttonColor: MzanziInnovationHub.of(context)!
// .theme
// .secondaryColor(),
// textColor: MzanziInnovationHub.of(context)!
// .theme
// .primaryColor(),
// onTap: () {
// if (isRequiredFieldsCaptured()) {
// createBusinessUserAPICall(index);
// } else {
// showDialog(
// context: context,
// builder: (context) {
// return const MIHErrorMessage(
// errorType: "Input Error");
// },
// );
// }
// },
// ),
// )
// ],
// ),
// ),
// ),
// Positioned(
// top: 5,
// right: 5,
// width: 50,
// height: 50,
// child: IconButton(
// onPressed: () {
// Navigator.pop(context);
// },
// icon: Icon(
// Icons.close,
// color: MzanziInnovationHub.of(context)!.theme.errorColor(),
// size: 35,
// ),
// ),
// ),
// ],
// ),
// ),
// );
}
@override
void dispose() {
accessController.dispose();
typeController.dispose();
fnameController.dispose();
lnameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
separatorBuilder: (BuildContext context, index) {
return Divider(
color: MzanziInnovationHub.of(context)!.theme.secondaryColor(),
);
},
itemCount: widget.users.length,
itemBuilder: (context, index) {
var isYou = "";
if (widget.arguments.signedInUser.app_id ==
widget.users[index].app_id) {
isYou = "(You)";
}
return ListTile(
title: Text("@${widget.users[index].username} $isYou"),
subtitle: Text(
"Email: ${hideEmail(widget.users[index].email)}",
style: TextStyle(
color: MzanziInnovationHub.of(context)!.theme.secondaryColor(),
),
),
onTap: () {
addEmployeePopUp(index);
},
);
},
);
}
}

View File

@@ -0,0 +1,541 @@
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../main.dart';
import 'package:supertokens_flutter/http.dart' as http;
import 'package:supertokens_flutter/supertokens.dart';
import 'package:http/http.dart' as http2;
import '../../../mih_components/mih_inputs_and_buttons/mih_button.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_file_input.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_text_input.dart';
import '../../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../../mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import '../../../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../../../mih_env/env.dart';
import '../../../mih_objects/arguments.dart';
class BusinessAbout extends StatefulWidget {
final BusinessArguments arguments;
const BusinessAbout({
super.key,
required this.arguments,
});
@override
State<BusinessAbout> createState() => _BusinessAboutState();
}
class BusinessUserScreenArguments {}
class _BusinessAboutState extends State<BusinessAbout> {
final FocusNode _focusNode = FocusNode();
final baseAPI = AppEnviroment.baseApiUrl;
final nameController = TextEditingController();
final typeController = TextEditingController();
final regController = TextEditingController();
final logonameController = TextEditingController();
final fnameController = TextEditingController();
final lnameController = TextEditingController();
final titleController = TextEditingController();
final signtureController = TextEditingController();
final accessController = TextEditingController();
final contactController = TextEditingController();
final emailController = TextEditingController();
late PlatformFile? selectedLogo = null;
late PlatformFile? selectedSignature = null;
// late Future<BusinessUser?> futureBusinessUser;
// BusinessUser? businessUser;
// late Future<Business?> futureBusiness;
// Business? business;
late String business_id;
late String oldLogoPath;
late String oldSigPath;
Future<void> deleteFileApiCall(String filePath) async {
// delete file from minio
var response = await http.delete(
Uri.parse("$baseAPI/minio/delete/file/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"file_path": filePath}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
//SQL delete
} else {
internetConnectionPopUp();
}
}
// Future<BusinessUser?> getBusinessUserDetails() async {
// var response = await http
// .get(Uri.parse("$baseAPI/business-user/${widget.signedInUser.app_id}"));
// if (response.statusCode == 200) {
// String body = response.body;
// var decodedData = jsonDecode(body);
// BusinessUser business_User = BusinessUser.fromJson(decodedData);
// return business_User;
// } else {
// return null;
// }
// }
// Future<Business?> getBusinessAbout() async {
// var response = await http.get(
// Uri.parse("$baseAPI/business/app_id/${widget.signedInUser.app_id}"));
// if (response.statusCode == 200) {
// String body = response.body;
// var decodedData = jsonDecode(body);
// Business business = Business.fromJson(decodedData);
// return business;
// } else {
// return null;
// }
// }
Future<void> uploadSelectedFile(
PlatformFile? file, TextEditingController controller) async {
//to-do delete file when changed
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.arguments.signedInUser.app_id;
request.fields['folder'] = "business_files";
request.files.add(await http2.MultipartFile.fromBytes('file', file!.bytes!,
filename: file.name.replaceAll(RegExp(r' '), '-')));
var response1 = await request.send();
if (response1.statusCode == 200) {
} else {
internetConnectionPopUp();
}
}
Future<void> updateBusinessUserAPICall(String business_id) async {
var response = await http.put(
Uri.parse("$baseAPI/business-user/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": widget.arguments.signedInUser.app_id,
"signature": signtureController.text,
"sig_path":
"${widget.arguments.signedInUser.app_id}/business_files/${signtureController.text}",
"title": titleController.text,
"access": accessController.text,
}),
);
if (response.statusCode == 200) {
if (selectedSignature != null) {
uploadSelectedFile(selectedSignature, signtureController);
deleteFileApiCall(oldSigPath);
}
Navigator.of(context).pushNamed('/');
String message =
"Your business profile is now live! You can now start connecting with customers and growing your business.";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
Future<void> updateBusinessProfileAPICall(String business_id) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.put(
Uri.parse("$baseAPI/business/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"Name": nameController.text,
"type": typeController.text,
"registration_no": regController.text,
"logo_name": logonameController.text,
"logo_path":
"${widget.arguments.signedInUser.app_id}/business_files/${logonameController.text}",
"contact_no": contactController.text,
"bus_email": emailController.text,
}),
);
if (response.statusCode == 200) {
//var businessResponse = jsonDecode(response.body);
//print(selectedLogo != null);
if (selectedLogo != null) {
uploadSelectedFile(selectedLogo, logonameController);
deleteFileApiCall(oldLogoPath);
}
updateBusinessUserAPICall(business_id);
} else {
internetConnectionPopUp();
}
}
void internetConnectionPopUp() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
void successPopUp(String message) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
bool isFieldsFilled() {
if (nameController.text.isEmpty ||
typeController.text.isEmpty ||
regController.text.isEmpty ||
logonameController.text.isEmpty ||
fnameController.text.isEmpty ||
lnameController.text.isEmpty ||
titleController.text.isEmpty ||
signtureController.text.isEmpty ||
accessController.text.isEmpty ||
contactController.text.isEmpty ||
emailController.text.isEmpty) {
return false;
} else {
return true;
}
}
void submitForm(String business_id) {
if (!validEmail()) {
emailError();
} else if (isFieldsFilled()) {
updateBusinessProfileAPICall(business_id);
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
}
}
void emailError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Invalid Email");
},
);
}
bool validEmail() {
String text = emailController.text;
var regex = RegExp(r'^[a-zA-Z0-9]+@[a-zA-Z.-]+\.[a-zA-Z]{2,}$');
return regex.hasMatch(text);
}
bool isFullAccess() {
if (widget.arguments.businessUser!.access == "Partial") {
return false;
} else {
return true;
}
}
@override
void dispose() {
nameController.dispose();
typeController.dispose();
regController.dispose();
logonameController.dispose();
fnameController.dispose();
lnameController.dispose();
titleController.dispose();
signtureController.dispose();
accessController.dispose();
contactController.dispose();
emailController.dispose();
_focusNode.dispose();
super.dispose();
}
@override
void initState() {
setState(() {
//businessUser = results;
titleController.text = widget.arguments.businessUser!.title;
fnameController.text = widget.arguments.signedInUser.fname;
lnameController.text = widget.arguments.signedInUser.lname;
signtureController.text = widget.arguments.businessUser!.signature;
titleController.text = widget.arguments.businessUser!.title;
accessController.text = widget.arguments.businessUser!.access;
oldSigPath = widget.arguments.businessUser!.sig_path;
//business = results;
business_id = widget.arguments.business!.business_id;
regController.text = widget.arguments.business!.registration_no;
nameController.text = widget.arguments.business!.Name;
typeController.text = widget.arguments.business!.type;
logonameController.text = widget.arguments.business!.logo_name;
oldLogoPath = widget.arguments.business!.logo_path;
contactController.text = widget.arguments.business!.contact_no;
emailController.text = widget.arguments.business!.bus_email;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (event) async {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.enter) {
//print(business_id);
submitForm(business_id);
}
},
child: SingleChildScrollView(
child: Column(
children: [
Visibility(
visible: isFullAccess(),
child: Column(
children: [
const Text(
"Business Profile",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
Divider(
color: MzanziInnovationHub.of(context)
?.theme
.secondaryColor(),
),
const SizedBox(height: 10.0),
MIHTextField(
controller: regController,
hintText: "Registration No.",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: nameController,
hintText: "Business Name",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: typeController,
hintText: "Business Type",
dropdownOptions: const ["Doctors Office", "Other"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: contactController,
hintText: "Contact Number",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: emailController,
hintText: "Email",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHFileField(
controller: logonameController,
hintText: "Logo",
editable: false,
required: true,
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result == null) return;
final selectedFile = result.files.first;
setState(() {
selectedLogo = selectedFile;
});
setState(() {
logonameController.text = selectedFile.name;
});
},
),
const SizedBox(height: 15.0),
],
),
),
Column(
children: [
//const SizedBox(height: 15.0),
const Text(
"My Business User",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
Divider(
color:
MzanziInnovationHub.of(context)?.theme.secondaryColor(),
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: titleController,
hintText: "Title",
dropdownOptions: const ["Doctor", "Assistant"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: fnameController,
hintText: "Name",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: lnameController,
hintText: "Surname",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHFileField(
controller: signtureController,
hintText: "Signature",
editable: false,
required: true,
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result == null) return;
final selectedFile = result.files.first;
setState(() {
selectedSignature = selectedFile;
});
setState(() {
signtureController.text = selectedFile.name;
});
},
),
const SizedBox(height: 15.0),
MIHDropdownField(
controller: accessController,
hintText: "Access",
dropdownOptions: const ["Full", "Partial"],
required: true,
editable: false,
enableSearch: false,
),
// const SizedBox(height: 15.0),
// const Text(
// "My Test Data",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// fontSize: 25,
// ),
// ),
// Divider(
// color:
// MzanziInnovationHub.of(context)?.theme.secondaryColor(),
// ),
// const SizedBox(height: 10.0),
// MIHTextField(
// controller: typeController,
// hintText: widget.arguments.business!.type,
// editable: false,
// required: true,
// ),
// const SizedBox(height: 15.0),
// MIHTextField(
// controller: titleController,
// hintText: widget.arguments.businessUser!.title,
// editable: false,
// required: true,
// ),
// const SizedBox(height: 15.0),
// MIHTextField(
// controller: accessController,
// hintText: widget.arguments.businessUser!.access,
// editable: false,
// required: true,
// ),
//const SizedBox(height: 15.0),
const SizedBox(height: 30.0),
SizedBox(
width: 500.0,
height: 50.0,
child: MIHButton(
buttonText: "Update",
buttonColor: MzanziInnovationHub.of(context)!
.theme
.secondaryColor(),
textColor:
MzanziInnovationHub.of(context)!.theme.primaryColor(),
onTap: () {
//print(business_id);
submitForm(business_id);
},
),
),
],
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,601 @@
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../main.dart';
import 'package:supertokens_flutter/http.dart' as http;
import 'package:supertokens_flutter/supertokens.dart';
import 'package:http/http.dart' as http2;
import '../../../mih_apis/mih_location_api.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_button.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_file_input.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_text_input.dart';
import '../../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../../mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import '../../../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../../../mih_env/env.dart';
import '../../../mih_objects/arguments.dart';
class BusinessDetails extends StatefulWidget {
final BusinessArguments arguments;
const BusinessDetails({
super.key,
required this.arguments,
});
@override
State<BusinessDetails> createState() => _BusinessDetailsState();
}
class BusinessUserScreenArguments {}
class _BusinessDetailsState extends State<BusinessDetails> {
final FocusNode _focusNode = FocusNode();
final baseAPI = AppEnviroment.baseApiUrl;
final nameController = TextEditingController();
final typeController = TextEditingController();
final regController = TextEditingController();
final logonameController = TextEditingController();
final fnameController = TextEditingController();
final lnameController = TextEditingController();
final titleController = TextEditingController();
final signtureController = TextEditingController();
final accessController = TextEditingController();
final contactController = TextEditingController();
final emailController = TextEditingController();
final locationController = TextEditingController();
final practiceNoController = TextEditingController();
final vatNoController = TextEditingController();
late PlatformFile? selectedLogo = null;
late PlatformFile? selectedSignature = null;
final ValueNotifier<String> busType = ValueNotifier("");
late String business_id;
late String oldLogoPath;
late String oldSigPath;
Future<void> deleteFileApiCall(String filePath) async {
// delete file from minio
var response = await http.delete(
Uri.parse("$baseAPI/minio/delete/file/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{"file_path": filePath}),
);
//print("Here4");
//print(response.statusCode);
if (response.statusCode == 200) {
//SQL delete
} else {
internetConnectionPopUp();
}
}
Future<void> uploadSelectedFile(
PlatformFile? file, TextEditingController controller) async {
//to-do delete file when changed
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.arguments.signedInUser.app_id;
request.fields['folder'] = "business_files";
request.files.add(await http2.MultipartFile.fromBytes('file', file!.bytes!,
filename: file.name.replaceAll(RegExp(r' '), '-')));
var response1 = await request.send();
if (response1.statusCode == 200) {
} else {
internetConnectionPopUp();
}
}
Future<void> updateBusinessUserAPICall(String business_id) async {
var response = await http.put(
Uri.parse("$baseAPI/business-user/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": widget.arguments.signedInUser.app_id,
"signature": signtureController.text,
"sig_path":
"${widget.arguments.signedInUser.app_id}/business_files/${signtureController.text}",
"title": titleController.text,
"access": accessController.text,
}),
);
if (response.statusCode == 200) {
if (selectedSignature != null) {
uploadSelectedFile(selectedSignature, signtureController);
deleteFileApiCall(oldSigPath);
}
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pushNamed(
'/business-profile/manage',
arguments: BusinessArguments(
widget.arguments.signedInUser,
widget.arguments.businessUser,
widget.arguments.business,
),
);
String message =
"Your business profile is now live! You can now start connecting with customers and growing your business.";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
Future<void> updateBusinessProfileAPICall(String business_id) async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.put(
Uri.parse("$baseAPI/business/update/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"Name": nameController.text,
"type": typeController.text,
"registration_no": regController.text,
"logo_name": logonameController.text,
"logo_path":
"${widget.arguments.signedInUser.app_id}/business_files/${logonameController.text}",
"contact_no": contactController.text,
"bus_email": emailController.text,
"gps_location": locationController.text,
"practice_no": practiceNoController.text,
"vat_no": vatNoController.text,
}),
);
if (response.statusCode == 200) {
//var businessResponse = jsonDecode(response.body);
//print(selectedLogo != null);
if (selectedLogo != null) {
uploadSelectedFile(selectedLogo, logonameController);
deleteFileApiCall(oldLogoPath);
}
updateBusinessUserAPICall(business_id);
} else {
internetConnectionPopUp();
}
}
void internetConnectionPopUp() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
void successPopUp(String message) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
bool isFieldsFilled() {
if (nameController.text.isEmpty ||
typeController.text.isEmpty ||
regController.text.isEmpty ||
logonameController.text.isEmpty ||
fnameController.text.isEmpty ||
lnameController.text.isEmpty ||
titleController.text.isEmpty ||
signtureController.text.isEmpty ||
accessController.text.isEmpty ||
contactController.text.isEmpty ||
emailController.text.isEmpty) {
return false;
} else {
return true;
}
}
void submitForm(String business_id) {
if (!validEmail()) {
emailError();
} else if (isFieldsFilled()) {
updateBusinessProfileAPICall(business_id);
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
}
}
void emailError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Invalid Email");
},
);
}
bool validEmail() {
String text = emailController.text;
var regex = RegExp(r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$');
return regex.hasMatch(text);
}
bool isFullAccess() {
if (widget.arguments.businessUser!.access == "Partial") {
return false;
} else {
return true;
}
}
void typeSelected() {
if (typeController.text.isNotEmpty) {
busType.value = typeController.text;
} else {
busType.value = "";
}
}
@override
void dispose() {
nameController.dispose();
typeController.dispose();
regController.dispose();
logonameController.dispose();
fnameController.dispose();
lnameController.dispose();
titleController.dispose();
signtureController.dispose();
accessController.dispose();
contactController.dispose();
emailController.dispose();
locationController.dispose();
practiceNoController.dispose();
vatNoController.dispose();
_focusNode.dispose();
super.dispose();
}
@override
void initState() {
typeController.addListener(typeSelected);
setState(() {
//businessUser = results;
titleController.text = widget.arguments.businessUser!.title;
fnameController.text = widget.arguments.signedInUser.fname;
lnameController.text = widget.arguments.signedInUser.lname;
signtureController.text = widget.arguments.businessUser!.signature;
titleController.text = widget.arguments.businessUser!.title;
accessController.text = widget.arguments.businessUser!.access;
oldSigPath = widget.arguments.businessUser!.sig_path;
//business = results;
business_id = widget.arguments.business!.business_id;
regController.text = widget.arguments.business!.registration_no;
nameController.text = widget.arguments.business!.Name;
typeController.text = widget.arguments.business!.type;
logonameController.text = widget.arguments.business!.logo_name;
oldLogoPath = widget.arguments.business!.logo_path;
contactController.text = widget.arguments.business!.contact_no;
emailController.text = widget.arguments.business!.bus_email;
locationController.text = widget.arguments.business!.gps_location;
practiceNoController.text = widget.arguments.business!.practice_no;
vatNoController.text = widget.arguments.business!.vat_no;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (event) async {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.enter) {
//print(business_id);
submitForm(business_id);
}
},
child: Column(
children: [
Visibility(
visible: isFullAccess(),
child: Column(
children: [
const Text(
"Business Profile",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
Divider(
color:
MzanziInnovationHub.of(context)?.theme.secondaryColor(),
),
const SizedBox(height: 10.0),
MIHTextField(
controller: regController,
hintText: "Registration No.",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: nameController,
hintText: "Business Name",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: typeController,
hintText: "Business Type",
dropdownOptions: const ["Doctors Office", "Other"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
ValueListenableBuilder(
valueListenable: busType,
builder:
(BuildContext context, String value, Widget? child) {
return Visibility(
visible: value == "Doctors Office",
child: MIHTextField(
controller: practiceNoController,
hintText: "Practice Number",
editable: true,
required: true,
),
);
},
),
const SizedBox(height: 10.0),
MIHTextField(
controller: vatNoController,
hintText: "VAT Number",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: contactController,
hintText: "Contact Number",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: emailController,
hintText: "Email",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHFileField(
controller: logonameController,
hintText: "Logo",
editable: false,
required: true,
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result == null) return;
final selectedFile = result.files.first;
setState(() {
selectedLogo = selectedFile;
});
setState(() {
logonameController.text = selectedFile.name;
});
},
),
const SizedBox(height: 10.0),
Row(
children: [
Flexible(
child: MIHTextField(
controller: locationController,
hintText: "Location",
editable: false,
required: false,
),
),
const SizedBox(width: 10.0),
SizedBox(
width: 80.0,
height: 50.0,
child: MIHButton(
buttonText: "Set",
buttonColor: MzanziInnovationHub.of(context)!
.theme
.secondaryColor(),
textColor: MzanziInnovationHub.of(context)!
.theme
.primaryColor(),
onTap: () {
MIHLocationAPI()
.getGPSPosition(context)
.then((position) {
if (position != null) {
setState(() {
locationController.text =
"${position.latitude}, ${position.longitude}";
});
}
});
},
),
),
],
),
const SizedBox(height: 15.0),
],
),
),
Column(
children: [
//const SizedBox(height: 15.0),
const Text(
"My Business User",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
Divider(
color:
MzanziInnovationHub.of(context)?.theme.secondaryColor(),
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: titleController,
hintText: "Title",
dropdownOptions: const ["Doctor", "Assistant"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: fnameController,
hintText: "Name",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: lnameController,
hintText: "Surname",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHFileField(
controller: signtureController,
hintText: "Signature",
editable: false,
required: true,
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result == null) return;
final selectedFile = result.files.first;
setState(() {
selectedSignature = selectedFile;
});
setState(() {
signtureController.text = selectedFile.name;
});
},
),
const SizedBox(height: 15.0),
MIHDropdownField(
controller: accessController,
hintText: "Access",
dropdownOptions: const ["Full", "Partial"],
required: true,
editable: false,
enableSearch: false,
),
// const SizedBox(height: 15.0),
// const Text(
// "My Test Data",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// fontSize: 25,
// ),
// ),
// Divider(
// color:
// MzanziInnovationHub.of(context)?.theme.secondaryColor(),
// ),
// const SizedBox(height: 10.0),
// MIHTextField(
// controller: typeController,
// hintText: widget.arguments.business!.type,
// editable: false,
// required: true,
// ),
// const SizedBox(height: 15.0),
// MIHTextField(
// controller: titleController,
// hintText: widget.arguments.businessUser!.title,
// editable: false,
// required: true,
// ),
// const SizedBox(height: 15.0),
// MIHTextField(
// controller: accessController,
// hintText: widget.arguments.businessUser!.access,
// editable: false,
// required: true,
// ),
//const SizedBox(height: 15.0),
const SizedBox(height: 30.0),
SizedBox(
width: 500.0,
height: 50.0,
child: MIHButton(
buttonText: "Update",
buttonColor:
MzanziInnovationHub.of(context)!.theme.secondaryColor(),
textColor:
MzanziInnovationHub.of(context)!.theme.primaryColor(),
onTap: () {
//print(business_id);
submitForm(business_id);
},
),
),
],
),
],
),
),
);
}
}

View File

@@ -0,0 +1,538 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swipe_detector/flutter_swipe_detector.dart';
import '../../../main.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../../../mih_components/mih_inputs_and_buttons/mih_search_input.dart';
import '../../../mih_components/mih_layout/mih_action.dart';
import '../../../mih_components/mih_layout/mih_body.dart';
import '../../../mih_components/mih_layout/mih_header.dart';
import '../../../mih_components/mih_layout/mih_layout_builder.dart';
import '../../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../../mih_components/mih_pop_up_messages/mih_loading_circle.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_employee.dart';
import 'builder/build_employee_list.dart';
import 'builder/build_user_list.dart';
import 'business_details.dart';
class ManageBusinessProfile extends StatefulWidget {
final BusinessArguments arguments;
const ManageBusinessProfile({
super.key,
required this.arguments,
});
@override
State<ManageBusinessProfile> createState() => _ManageBusinessProfileState();
}
class _ManageBusinessProfileState extends State<ManageBusinessProfile> {
final FocusNode _focusNode = FocusNode();
final baseAPI = AppEnviroment.baseApiUrl;
final TextEditingController searchController = TextEditingController();
String userSearch = "";
String errorCode = "";
String errorBody = "";
int selectionIndex = 0;
late Future<List<BusinessEmployee>> employeeList;
late Future<List<AppUser>> userSearchResults;
Future<List<BusinessEmployee>> fetchEmployees() async {
//print("Patien manager page: $endpoint");
final response = await http.get(Uri.parse(
"${AppEnviroment.baseApiUrl}/business-user/employees/${widget.arguments.businessUser!.business_id}"));
errorCode = response.statusCode.toString();
errorBody = response.body;
if (response.statusCode == 200) {
//print("Here1");
Iterable l = jsonDecode(response.body);
//print("Here2");
List<BusinessEmployee> patientQueue = List<BusinessEmployee>.from(
l.map((model) => BusinessEmployee.fromJson(model)));
//print("Here3");
//print(patientQueue);
return patientQueue;
} else {
throw Exception('failed to load employees');
}
}
Future<List<AppUser>> fetchUsers(String search) async {
//TODO
final response = await http
.get(Uri.parse("${AppEnviroment.baseApiUrl}/users/search/$search"));
errorCode = response.statusCode.toString();
errorBody = response.body;
if (response.statusCode == 200) {
Iterable l = jsonDecode(response.body);
List<AppUser> users =
List<AppUser>.from(l.map((model) => AppUser.fromJson(model)));
return users;
} else {
throw Exception('failed to load patients');
}
}
Widget employeesview() {
return Column(mainAxisSize: MainAxisSize.max, children: [
const Text(
"Business Team",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
Divider(color: MzanziInnovationHub.of(context)!.theme.secondaryColor()),
const SizedBox(height: 10),
FutureBuilder(
future: employeeList,
builder: (context, snapshot) {
//print("patient Queue List ${snapshot.hasData}");
if (snapshot.connectionState == ConnectionState.waiting) {
return const Mihloadingcircle();
} else if (snapshot.connectionState == ConnectionState.done) {
//List<BusinessEmployee> employeeListResults;
// if (searchString == "") {
// patientQueueList = [];
// } else {
// print(patientQueueList);
// }
return displayEmployeeList(snapshot.requireData);
} else {
return Center(
child: Text(
"$errorCode: Error pulling Patients Data\n${AppEnviroment.baseApiUrl}/business-user/users/${widget.arguments.businessUser!.business_id}\n$errorBody",
style: TextStyle(
fontSize: 25,
color: MzanziInnovationHub.of(context)!.theme.errorColor()),
textAlign: TextAlign.center,
),
);
}
},
),
]);
}
Widget displayEmployeeList(List<BusinessEmployee> employeeList) {
if (employeeList.isNotEmpty) {
return BuildEmployeeList(
employees: employeeList,
arguments: widget.arguments,
);
}
return Center(
child: Text(
"",
style: TextStyle(
fontSize: 25,
color: MzanziInnovationHub.of(context)!.theme.messageTextColor()),
textAlign: TextAlign.center,
),
);
}
Widget displayUserList(List<AppUser> userList) {
if (userList.isNotEmpty) {
return BuildUserList(
users: userList,
arguments: widget.arguments,
);
}
return Center(
child: Text(
"Enter Username or Email to search",
style: TextStyle(
fontSize: 25,
color: MzanziInnovationHub.of(context)!.theme.messageTextColor()),
textAlign: TextAlign.center,
),
);
}
void submitUserForm() {
if (searchController.text != "") {
setState(() {
userSearch = searchController.text;
userSearchResults = fetchUsers(userSearch);
});
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
}
}
Widget userSearchView() {
return KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (event) async {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.enter) {
submitUserForm();
}
},
child: Column(mainAxisSize: MainAxisSize.max, children: [
const Text(
"User Search",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
//spacer
Divider(color: MzanziInnovationHub.of(context)!.theme.secondaryColor()),
const SizedBox(height: 10),
MIHSearchField(
controller: searchController,
hintText: "Username or Email Search",
required: true,
editable: true,
onTap: () {
submitUserForm();
},
),
//spacer
const SizedBox(height: 10),
FutureBuilder(
future: userSearchResults,
builder: (context, snapshot) {
//print("patient Liust ${snapshot.data}");
if (snapshot.connectionState == ConnectionState.waiting) {
return const Mihloadingcircle();
} else if (snapshot.connectionState == ConnectionState.done &&
snapshot.hasData) {
List<AppUser> patientsList;
if (userSearch == "") {
patientsList = [];
} else {
patientsList = snapshot.data!;
//print(patientsList);
}
return displayUserList(patientsList);
} else {
return Center(
child: Text(
"$errorCode: Error pulling Patients Data\n/patients/search/$userSearch\n$errorBody",
style: TextStyle(
fontSize: 25,
color:
MzanziInnovationHub.of(context)!.theme.errorColor()),
textAlign: TextAlign.center,
),
);
}
},
),
]),
);
}
void internetConnectionPopUp() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
void successPopUp(String message) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
void emailError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Invalid Email");
},
);
}
Widget showSelection(int selectionIndex) {
// if (selectionIndex == 0) {
// return BusinessDetails(arguments: widget.arguments);
// } else
if (selectionIndex == 0) {
return BusinessDetails(arguments: widget.arguments);
} else if (selectionIndex == 1) {
return employeesview();
} else {
return userSearchView();
}
}
MIHAction getActionButton() {
return MIHAction(
icon: const Icon(Icons.arrow_back),
iconSize: 35,
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).popAndPushNamed(
'/',
arguments: AuthArguments(false, false),
);
},
);
}
MIHHeader getHeader() {
bool isFullAccess = false;
if (widget.arguments.businessUser!.access == "Full") {
isFullAccess = true;
}
return MIHHeader(
headerAlignment: MainAxisAlignment.end,
headerItems: [
// IconButton(
// onPressed: () {
// setState(() {
// selectionIndex = 0;
// });
// },
// icon: const Icon(
// Icons.info_outline,
// size: 35,
// ),
// ),
//============ Business Details ================
Visibility(
visible: selectionIndex != 0,
child: IconButton(
onPressed: () {
setState(() {
selectionIndex = 0;
});
},
icon: const Icon(
Icons.business,
size: 35,
),
),
),
Visibility(
visible: selectionIndex == 0,
child: IconButton.filled(
onPressed: () {
setState(() {
selectionIndex = 0;
});
},
icon: const Icon(
Icons.business,
size: 35,
),
),
),
//============ Team Manager ================
Visibility(
visible: isFullAccess && selectionIndex != 1,
child: IconButton(
onPressed: () {
setState(() {
selectionIndex = 1;
});
},
icon: const Icon(
Icons.people_outline,
size: 35,
),
),
),
Visibility(
visible: isFullAccess && selectionIndex == 1,
child: IconButton.filled(
onPressed: () {
setState(() {
selectionIndex = 1;
});
},
icon: const Icon(
Icons.people_outline,
size: 35,
),
),
),
//============ Add Team member ================
Visibility(
visible: isFullAccess && selectionIndex != 2,
child: IconButton(
onPressed: () {
setState(() {
selectionIndex = 2;
});
},
icon: const Icon(
Icons.add,
size: 35,
),
),
),
Visibility(
visible: isFullAccess && selectionIndex == 2,
child: IconButton.filled(
onPressed: () {
setState(() {
selectionIndex = 2;
});
},
icon: const Icon(
Icons.add,
size: 35,
),
),
),
],
);
}
MIHBody getBody() {
return MIHBody(
borderOn: true,
bodyItems: [
showSelection(selectionIndex),
],
);
}
@override
void dispose() {
searchController.dispose();
_focusNode.dispose();
super.dispose();
}
@override
void initState() {
userSearchResults = fetchUsers("abc");
employeeList = fetchEmployees();
super.initState();
}
@override
Widget build(BuildContext context) {
return SwipeDetector(
onSwipeLeft: (offset) {
if (selectionIndex < 2) {
setState(() {
selectionIndex += 1;
});
}
//print("swipe left");
},
onSwipeRight: (offset) {
if (selectionIndex > 0) {
setState(() {
selectionIndex -= 1;
});
}
//print("swipe right");
},
child: MIHLayoutBuilder(
actionButton: getActionButton(),
secondaryActionButton: null,
header: getHeader(),
body: getBody(),
actionDrawer: null,
secondaryActionDrawer: null,
bottomNavBar: null,
pullDownToRefresh: false,
onPullDown: () async {},
),
);
// return Scaffold(
// // appBar: const MIHAppBar(
// // barTitle: "Business Profile",
// // propicFile: null,
// // ),
// //drawer: MIHAppDrawer(signedInUser: widget.arguments.signedInUser),
// body: SafeArea(
// child: Stack(
// children: [
// SingleChildScrollView(
// padding: const EdgeInsets.all(15),
// child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
// mainAxisSize: MainAxisSize.max,
// children: [
// //const SizedBox(height: 20),
// SizedBox(
// width: screenWidth,
// child: Row(
// mainAxisSize: MainAxisSize.min,
// crossAxisAlignment: CrossAxisAlignment.end,
// mainAxisAlignment: MainAxisAlignment.end,
// children: [
// IconButton(
// onPressed: () {
// setState(() {
// selectionIndex = 0;
// });
// },
// icon: const Icon(
// Icons.people_outline,
// size: 35,
// ),
// ),
// IconButton(
// onPressed: () {
// setState(() {
// selectionIndex = 1;
// });
// },
// icon: const Icon(
// Icons.add,
// size: 35,
// ),
// ),
// ],
// ),
// ),
// showSelection(selectionIndex, screenWidth, screenHeight),
// ],
// ),
// ),
// Positioned(
// top: 10,
// left: 5,
// width: 50,
// height: 50,
// child: IconButton(
// onPressed: () {
// Navigator.of(context).pop();
// },
// icon: const Icon(Icons.arrow_back),
// ),
// ),
// ],
// ),
// ),
// );
}
}

View File

@@ -0,0 +1,542 @@
import 'dart:convert';
import 'package:Mzansi_Innovation_Hub/mih_objects/arguments.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../main.dart';
import 'package:supertokens_flutter/http.dart' as http;
import 'package:supertokens_flutter/supertokens.dart';
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http2;
import '../../../mih_apis/mih_location_api.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_button.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_file_input.dart';
import '../../../mih_components/mih_inputs_and_buttons/mih_text_input.dart';
import '../../../mih_components/mih_layout/mih_action.dart';
import '../../../mih_components/mih_layout/mih_body.dart';
import '../../../mih_components/mih_layout/mih_header.dart';
import '../../../mih_components/mih_layout/mih_layout_builder.dart';
import '../../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../../mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import '../../../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../../../mih_env/env.dart';
import '../../../mih_objects/app_user.dart';
class ProfileBusinessAdd extends StatefulWidget {
//final BusinessUserScreenArguments arguments;
final AppUser signedInUser;
const ProfileBusinessAdd({
super.key,
required this.signedInUser,
});
@override
State<ProfileBusinessAdd> createState() => _ProfileBusinessAddState();
}
class _ProfileBusinessAddState extends State<ProfileBusinessAdd> {
final FocusNode _focusNode = FocusNode();
final baseAPI = AppEnviroment.baseApiUrl;
final nameController = TextEditingController();
final typeController = TextEditingController();
final regController = TextEditingController();
final addressController = TextEditingController();
final logonameController = TextEditingController();
final fnameController = TextEditingController();
final lnameController = TextEditingController();
final titleController = TextEditingController();
final signtureController = TextEditingController();
final accessController = TextEditingController();
final contactController = TextEditingController();
final emailController = TextEditingController();
final locationController = TextEditingController();
final practiceNoController = TextEditingController();
final vatNoController = TextEditingController();
late PlatformFile selectedLogo;
late PlatformFile selectedSignature;
final ValueNotifier<String> busType = ValueNotifier("");
Future<void> uploadSelectedFile(
PlatformFile file, TextEditingController controller) async {
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'] = widget.signedInUser.app_id;
request.fields['folder'] = "business_files";
request.files.add(await http2.MultipartFile.fromBytes('file', file.bytes!,
filename: file.name.replaceAll(RegExp(r' '), '-')));
var response1 = await request.send();
if (response1.statusCode == 200) {
} else {
internetConnectionPopUp();
}
}
Future<void> createBusinessUserAPICall(String business_id) async {
var response = await http.post(
Uri.parse("$baseAPI/business-user/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"business_id": business_id,
"app_id": widget.signedInUser.app_id,
"signature": signtureController.text,
"sig_path":
"${widget.signedInUser.app_id}/business_files/${signtureController.text}",
"title": titleController.text,
"access": accessController.text,
}),
);
if (response.statusCode == 201) {
uploadSelectedFile(selectedSignature, signtureController);
// Navigator.of(context).pushNamed('/');
Navigator.of(context).popAndPushNamed(
'/',
arguments: AuthArguments(false, false),
);
String message =
"Your business profile is now live! You can now start connecting with customers and growing your business.";
successPopUp(message);
} else {
internetConnectionPopUp();
}
}
Future<void> createBusinessProfileAPICall() async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
var response = await http.post(
Uri.parse("$baseAPI/business/insert/"),
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8"
},
body: jsonEncode(<String, dynamic>{
"Name": nameController.text,
"type": typeController.text,
"registration_no": regController.text,
"logo_name": logonameController.text,
"logo_path":
"${widget.signedInUser.app_id}/business_files/${logonameController.text}",
"contact_no": contactController.text,
"bus_email": emailController.text,
"gps_location": locationController.text,
"practice_no": practiceNoController.text,
"vat_no": vatNoController.text,
}),
);
if (response.statusCode == 201) {
var businessResponse = jsonDecode(response.body);
createBusinessUserAPICall(businessResponse['business_id']);
Navigator.of(context).pop();
// uploadSelectedFile(selectedLogo, logonameController);
} else {
internetConnectionPopUp();
}
}
void internetConnectionPopUp() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Internet Connection");
},
);
}
void successPopUp(String message) {
showDialog(
context: context,
builder: (context) {
return MIHSuccessMessage(
successType: "Success",
successMessage: message,
);
},
);
}
bool isFieldsFilled() {
if (nameController.text.isEmpty ||
typeController.text.isEmpty ||
regController.text.isEmpty ||
logonameController.text.isEmpty ||
fnameController.text.isEmpty ||
lnameController.text.isEmpty ||
titleController.text.isEmpty ||
signtureController.text.isEmpty ||
accessController.text.isEmpty ||
contactController.text.isEmpty ||
emailController.text.isEmpty) {
return false;
} else {
return true;
}
}
void submitForm() {
if (!validEmail()) {
emailError();
} else if (isFieldsFilled()) {
createBusinessProfileAPICall();
} else {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
}
}
void emailError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Invalid Email");
},
);
}
bool validEmail() {
String text = emailController.text;
var regex = RegExp(r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$');
return regex.hasMatch(text);
}
void typeSelected() {
if (typeController.text.isNotEmpty) {
busType.value = typeController.text;
} else {
busType.value = "";
}
}
MIHAction getActionButton() {
return MIHAction(
icon: const Icon(Icons.arrow_back),
iconSize: 35,
onTap: () {
Navigator.of(context).pop();
},
);
}
MIHHeader getHeader() {
return const MIHHeader(
headerAlignment: MainAxisAlignment.center,
headerItems: [
Text(
"Add Business Profile",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
],
);
}
MIHBody getBody() {
return MIHBody(
borderOn: true,
bodyItems: [
KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (event) async {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.enter) {
submitForm();
}
},
child: SingleChildScrollView(
child: Column(
children: [
//const SizedBox(height: 15),
const Text(
"My Business Details",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
Divider(
color: MzanziInnovationHub.of(context)!
.theme
.secondaryColor()),
const SizedBox(height: 10.0),
MIHTextField(
controller: regController,
hintText: "Registration No.",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: nameController,
hintText: "Business Name",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: typeController,
hintText: "Business Type",
dropdownOptions: const ["Doctors Office", "Other"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
ValueListenableBuilder(
valueListenable: busType,
builder: (BuildContext context, String value, Widget? child) {
return Visibility(
visible: value == "Doctors Office",
child: MIHTextField(
controller: practiceNoController,
hintText: "Practice Number",
editable: true,
required: true,
),
);
},
),
const SizedBox(height: 10.0),
MIHTextField(
controller: vatNoController,
hintText: "VAT Number",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: contactController,
hintText: "Contact Number",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: emailController,
hintText: "Email",
editable: true,
required: true,
),
const SizedBox(height: 10.0),
MIHFileField(
controller: logonameController,
hintText: "Logo",
editable: false,
required: true,
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result == null) return;
final selectedFile = result.files.first;
setState(() {
selectedLogo = selectedFile;
});
setState(() {
logonameController.text = selectedFile.name;
});
},
),
const SizedBox(height: 10.0),
Row(
children: [
Flexible(
child: MIHTextField(
controller: locationController,
hintText: "Location",
editable: false,
required: false,
),
),
const SizedBox(width: 10.0),
SizedBox(
width: 80.0,
height: 50.0,
child: MIHButton(
buttonText: "Set",
buttonColor: MzanziInnovationHub.of(context)!
.theme
.secondaryColor(),
textColor: MzanziInnovationHub.of(context)!
.theme
.primaryColor(),
onTap: () {
MIHLocationAPI()
.getGPSPosition(context)
.then((position) {
if (position != null) {
setState(() {
locationController.text =
"${position.latitude}, ${position.longitude}";
});
}
});
},
),
),
],
),
const SizedBox(height: 15.0),
Divider(
color:
MzanziInnovationHub.of(context)?.theme.secondaryColor(),
),
//const SizedBox(height: 15.0),
const Text(
"My Business User",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
Divider(
color: MzanziInnovationHub.of(context)!
.theme
.secondaryColor()),
const SizedBox(height: 10.0),
MIHDropdownField(
controller: titleController,
hintText: "Title",
dropdownOptions: const ["Doctor", "Assistant"],
required: true,
editable: true,
enableSearch: false,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: fnameController,
hintText: "Name",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHTextField(
controller: lnameController,
hintText: "Surname",
editable: false,
required: true,
),
const SizedBox(height: 10.0),
MIHFileField(
controller: signtureController,
hintText: "Signature",
editable: false,
required: true,
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result == null) return;
final selectedFile = result.files.first;
setState(() {
selectedSignature = selectedFile;
});
setState(() {
signtureController.text = selectedFile.name;
});
},
),
const SizedBox(height: 15.0),
MIHDropdownField(
controller: accessController,
hintText: "Access",
dropdownOptions: const ["Full", "Partial"],
required: true,
editable: false,
enableSearch: false,
),
const SizedBox(height: 30.0),
SizedBox(
width: 500.0,
height: 50.0,
child: MIHButton(
buttonText: "Add",
buttonColor:
MzanziInnovationHub.of(context)!.theme.secondaryColor(),
textColor:
MzanziInnovationHub.of(context)!.theme.primaryColor(),
onTap: () {
submitForm();
},
),
),
],
),
),
),
],
);
}
@override
void dispose() {
nameController.dispose();
typeController.dispose();
regController.dispose();
logonameController.dispose();
fnameController.dispose();
lnameController.dispose();
titleController.dispose();
signtureController.dispose();
accessController.dispose();
contactController.dispose();
emailController.dispose();
locationController.dispose();
practiceNoController.dispose();
vatNoController.dispose();
_focusNode.dispose();
super.dispose();
}
@override
void initState() {
typeController.addListener(typeSelected);
setState(() {
fnameController.text = widget.signedInUser.fname;
lnameController.text = widget.signedInUser.lname;
accessController.text = "Full";
});
super.initState();
}
@override
Widget build(BuildContext context) {
return MIHLayoutBuilder(
actionButton: getActionButton(),
secondaryActionButton: null,
header: getHeader(),
body: getBody(),
actionDrawer: null,
secondaryActionDrawer: null,
bottomNavBar: null,
pullDownToRefresh: false,
onPullDown: () async {},
);
}
}