From d60bfdeb13dc5ec9a5b8a589a4a6ada76546235a Mon Sep 17 00:00:00 2001 From: Venba Date: Tue, 4 Jun 2024 08:28:14 +0530 Subject: [PATCH] CHANGE_ --- lib/addons.dart | 711 +++++++++++------------------ lib/customAppBar/customAppBar.dart | 95 ++-- lib/empDetails.dart | 207 ++++----- lib/empReview.dart | 218 ++++----- lib/excel_verification.dart | 4 + lib/hrDashboard.dart | 616 +++++++++++++------------ lib/hrPolicyDetails.dart | 44 +- lib/hrVerify.dart | 8 +- lib/oldPolicy.dart | 4 +- lib/service/api_service.dart | 502 ++++++++++++++++++++ lib/verify.dart | 6 +- 11 files changed, 1342 insertions(+), 1073 deletions(-) create mode 100644 lib/service/api_service.dart diff --git a/lib/addons.dart b/lib/addons.dart index 59a6f4c..afc3525 100644 --- a/lib/addons.dart +++ b/lib/addons.dart @@ -4,6 +4,7 @@ import 'package:google_fonts/google_fonts.dart'; import 'package:nhancepolicy/customAppBar/toastHelper.dart'; import 'package:nhancepolicy/models/environment.dart'; import 'package:nhancepolicy/responsive.dart'; +import 'package:nhancepolicy/service/api_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'customAppBar/customAppBar.dart'; import 'package:jwt_decode/jwt_decode.dart'; @@ -22,6 +23,7 @@ class addOnsDetails extends StatefulWidget { } class _addOnsDetailsState extends State { + late ApiService apiService; bool isChecked = false; bool _addOnsDependentSwitcher = false; // Declare the _isSwitched variable here @@ -116,10 +118,13 @@ class _addOnsDetailsState extends State { dynamic gmcDataIsEmpty = 1; dynamic gpaDataIsEmpty = 1; + dynamic empRefId; + dynamic empClientBranchId; @override void initState() { super.initState(); + apiService = ApiService(context); // Initialize ApiService here _dobController = TextEditingController(); _memberNameController = TextEditingController(); _relationShipController = TextEditingController(); @@ -154,6 +159,7 @@ class _addOnsDetailsState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); print(decodedToken); + empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); print(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); @@ -184,23 +190,18 @@ class _addOnsDetailsState extends State { } Future getClientLogoAndDetails() async { - var url = Uri.parse(Environment.apiUrl + - 'getClientDetails?client_id=$client_id&emp_code=$empCodeString'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print(data); - - if (data.containsKey('data')) { - dynamic clientDetails = data['data']; + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getClientLogoAndDetailsToApi( + client_id!, empCodeString!, empClientBranchId!); + print('check 1'); + if (response['status'] == 'success') { + if (response.containsKey('data')) { + dynamic clientDetails = response['data']; print(clientDetails); clientName = clientDetails['client']['client_name']; print(clientName); @@ -210,13 +211,13 @@ class _addOnsDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -225,23 +226,17 @@ class _addOnsDetailsState extends State { } Future getGpaEmpPolicyDetails(empPrimaryId) async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeePolicy?id=$empPrimaryId&emp_code=$empCodeString&client_id=$client_id&policy=GPA'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print(data); - - if (data.containsKey('data')) { - gpaPolicies = data['data']; + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGpaEmpPolicyDetailsToApi( + empPrimaryId, empCodeString!, client_id!, 'GPA', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { + gpaPolicies = response['data']; print(gpaPolicies); // Assuming data is a List print(gpaPolicies); @@ -283,7 +278,7 @@ class _addOnsDetailsState extends State { } else { // Handle other status messages if needed // ToastHelper.showWarningToast(context, 'Something went wrong'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { setState(() { @@ -291,7 +286,7 @@ class _addOnsDetailsState extends State { }); // Handle other status codes ToastHelper.showWarningToast(context, 'Something went wrong'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -300,37 +295,21 @@ class _addOnsDetailsState extends State { } Future getGmcEmpPolicyDetails(empPrimaryId) async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeePolicy?id=$empPrimaryId&emp_code=$empCodeString&client_id=$client_id&policy=GMC'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('GMC response.statusCode == 200'); - Map data = json.decode(response.body); - print(data); - - if (data['status'] == 'success') { - // setState(() { - gmcPolicies = data['data']; - print('gmcPolicies'); - // }); - // Assuming data is a List - print(gmcPolicies); - } else { - setState(() { - gmcDataIsEmpty = 0; - }); - // Handle other status messages if needed - // ToastHelper.showErrorToast( - // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); - } + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcEmpPolicyDetailsToApi( + empPrimaryId, empCodeString!, client_id!, 'GMC', empClientBranchId!); + if (response['status'] == 'success') { + // setState(() { + gmcPolicies = response['data']; + print('gmcPolicies'); + // }); + // Assuming data is a List + print(gmcPolicies); } else { setState(() { gmcDataIsEmpty = 0; @@ -338,7 +317,7 @@ class _addOnsDetailsState extends State { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -347,25 +326,18 @@ class _addOnsDetailsState extends State { } Future getGmcSiTopUp() async { - var url = Uri.parse(Environment.apiUrl + - 'getAddOnPolicy?client_id=$client_id&emp_code=$empCodeString&policy=GMC-SI-TOPUP'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print('222222222'); - print(data); - - if (data.containsKey('data')) { + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcSiTopUpToApi( + client_id!, empCodeString!, 'GMC-SI-TOPUP', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { setState(() { - topUpSiPolicies = data['data']; + topUpSiPolicies = response['data']; print('topUpSiPolicies'); print(topUpSiPolicies); }); @@ -430,13 +402,13 @@ class _addOnsDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -445,25 +417,18 @@ class _addOnsDetailsState extends State { } Future getGmcSiParentTopUp() async { - var url = Uri.parse(Environment.apiUrl + - 'getAddOnPolicy?client_id=$client_id&emp_code=$empCodeString&policy=GMC-SI-PARENT-TOPUP'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print('parent'); - print(data); - - if (data.containsKey('data')) { + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcSiParentTopUpToApi(client_id!, + empCodeString!, 'GMC-SI-PARENT-TOPUP', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { setState(() { - topUpSiParentPolicies = data['data']; + topUpSiParentPolicies = response['data']; print('topUpSiParentPolicies'); print(topUpSiParentPolicies); }); @@ -539,13 +504,13 @@ class _addOnsDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -554,25 +519,18 @@ class _addOnsDetailsState extends State { } Future getGmcDependentAddOns() async { - var url = Uri.parse(Environment.apiUrl + - 'getAddOnPolicy?client_id=$client_id&emp_code=$empCodeString&policy=GMC-DEPENDENT-ADDON'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print('222222222'); - print(data); - - if (data.containsKey('data')) { + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcDependentAddOnsToApi(client_id!, + empCodeString!, 'GMC-DEPENDENT-ADDON', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { setState(() { - addOnsDependentPolicies = data['data']; + addOnsDependentPolicies = response['data']; print('addOnsDependentPolicies'); print(addOnsDependentPolicies); }); @@ -653,13 +611,13 @@ class _addOnsDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -669,18 +627,10 @@ class _addOnsDetailsState extends State { Future fetchRelationshipList() async { // Replace the URL with your API endpoint - final url = Uri.parse(Environment.apiUrl + 'relationshipList'); try { - final response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - final List data = jsonDecode(response.body)['data']; - for (var item in data) { + final response = await apiService.fetchRelationshipListToApi(); + if (response['status'] == 'success') { + for (var item in response['data']) { String relationshipName = item['relationship_name']; String dependent = item['dependent']; @@ -763,22 +713,12 @@ class _addOnsDetailsState extends State { Future deleteItem(Map deletedItem) async { print(deletedItem); - // Define your API endpoint - var id = deletedItem['employee_id']; - final String apiUrl = Environment.apiUrl + 'deleteDependence?id=$id'; - try { - // Make the DELETE request to the API endpoint - final http.Response response = await http.get( - Uri.parse(apiUrl), - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); + var id = deletedItem['employee_id']; + final response = await apiService.deleteItemToApi(id); // Check if the request was successful (status code 200) - if (response.statusCode == 200) { + if (response['status'] == 'success') { formDataList.clear(); selectedRelationships.clear(); _relationShipController.clear(); @@ -796,8 +736,6 @@ class _addOnsDetailsState extends State { } else { // Handle errors ToastHelper.showErrorToast(context, 'Failed to delete item'); - print('Failed to delete item. Status code: ${response.statusCode}'); - print('Response body: ${response.body}'); } } catch (error) { // Handle network errors @@ -821,26 +759,18 @@ class _addOnsDetailsState extends State { 'is_addon_value': 1, 'basic_cover_si': addOnsSelectedDependent, 'created_by': empPrimaryId, + 'client_branch_id': empClientBranchId, // Add the 'id' field only if action is 'Edit' if (action == 'Edit') 'id': floatedData['employee_id'], }); // Convert the list of objects to JSON - String formDataJson = jsonEncode(formDataList); + // String formDataJson = jsonEncode(formDataList); - // Prepare the API request - var url = Uri.parse(Environment.apiUrl + 'addEmployeeAndDependence'); - var response = await http.post( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - body: formDataJson, - ); + final response = await apiService.saveAddOnsDetailsToApi(formDataList); // Check the response - if (response.statusCode == 200) { + if (response['status'] == 'success') { formDataList.clear(); selectedRelationships.clear(); _relationShipController.clear(); @@ -859,7 +789,7 @@ class _addOnsDetailsState extends State { } else { // Request failed, handle error ToastHelper.showErrorToast(context, 'Failed'); - print('Failed to send form data. Error: ${response.reasonPhrase}'); + print('Failed to send form data. Error: ${response}'); } } @@ -917,31 +847,20 @@ class _addOnsDetailsState extends State { print(selectedValues); } // Iterate through familyMembers list and send each member's data to the API - final url = Uri.parse( - Environment.apiUrl + 'createOrUpdateEmployeePolicySiAmount'); - final response = await http.post( - url, - body: jsonEncode(selectedValues), - headers: { - 'Content-Type': 'application/json', - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - // Member saved successfully - formDataList.clear(); - selectedRelationships.clear(); - _relationShipController.clear(); - _memberNameController.clear(); - _dobController.clear(); - // Navigator.pushNamed(context, 'empReviewDetails'); - // ToastHelper.showSuccessToast(context, 'Saved successfully!'); - print('Saved successfully!'); - } + final response = + await apiService.sendAddonsGmcDependentToAPI(selectedValues); + + if (response['status'] == 'success') { + // Member saved successfully + formDataList.clear(); + selectedRelationships.clear(); + _relationShipController.clear(); + _memberNameController.clear(); + _dobController.clear(); + // Navigator.pushNamed(context, 'empReviewDetails'); + // ToastHelper.showSuccessToast(context, 'Saved successfully!'); + print('Saved successfully!'); } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); @@ -1005,32 +924,19 @@ class _addOnsDetailsState extends State { print(selectedValues); } - // Iterate through familyMembers list and send each member's data to the API - final url = Uri.parse( - Environment.apiUrl + 'createOrUpdateEmployeePolicySiAmount'); - final response = await http.post( - url, - body: jsonEncode(selectedValues), - headers: { - 'Content-Type': 'application/json', - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); + final response = + await apiService.sendAddonsGmcSiToAPI(selectedValues); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - // Member saved successfully - formDataList.clear(); - selectedRelationships.clear(); - _relationShipController.clear(); - _memberNameController.clear(); - _dobController.clear(); - // Navigator.pushNamed(context, 'empReviewDetails'); - // ToastHelper.showSuccessToast(context, 'Saved successfully!'); - print('Saved successfully!'); - } + if (response['status'] == 'success') { + // Member saved successfully + formDataList.clear(); + selectedRelationships.clear(); + _relationShipController.clear(); + _memberNameController.clear(); + _dobController.clear(); + // Navigator.pushNamed(context, 'empReviewDetails'); + // ToastHelper.showSuccessToast(context, 'Saved successfully!'); + print('Saved successfully!'); } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); @@ -1094,32 +1000,19 @@ class _addOnsDetailsState extends State { print(selectedValues); } - // Iterate through familyMembers list and send each member's data to the API - final url = Uri.parse( - Environment.apiUrl + 'createOrUpdateEmployeePolicySiAmount'); - final response = await http.post( - url, - body: jsonEncode(selectedValues), - headers: { - 'Content-Type': 'application/json', - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); + final response = + await apiService.sendAddonsGmcParentSiToAPI(selectedValues); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - // Member saved successfully - formDataList.clear(); - selectedRelationships.clear(); - _relationShipController.clear(); - _memberNameController.clear(); - _dobController.clear(); - // Navigator.pushNamed(context, 'empReviewDetails'); - // ToastHelper.showSuccessToast(context, 'Saved successfully!'); - print('Saved successfully!'); - } + if (response['status'] == 'success') { + // Member saved successfully + formDataList.clear(); + selectedRelationships.clear(); + _relationShipController.clear(); + _memberNameController.clear(); + _dobController.clear(); + // Navigator.pushNamed(context, 'empReviewDetails'); + // ToastHelper.showSuccessToast(context, 'Saved successfully!'); + print('Saved successfully!'); } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); @@ -1137,24 +1030,19 @@ class _addOnsDetailsState extends State { } Future removeAddonsGmcDependentToAPI() async { - var url = Uri.parse(Environment.apiUrl + - 'removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$addOnsDependentClientPolicyId'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - print(data); + if (empCodeString == null || addOnsDependentClientPolicyId == null) { + return; + } + final response = await apiService.removeAddonsGmcDependentToAPI( + empCodeString!, addOnsDependentClientPolicyId!); + if (response['status'] == 'success') { + print(response['data']); } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -1163,24 +1051,19 @@ class _addOnsDetailsState extends State { } Future removeAddonsGmcSiToAPI() async { - var url = Uri.parse(Environment.apiUrl + - 'removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$topUpClientPolicyId'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - print(data); + if (empCodeString == null || topUpClientPolicyId == null) { + return; + } + final response = await apiService.removeAddonsGmcSiToAPI( + empCodeString!, topUpClientPolicyId!); + if (response['status'] == 'success') { + print(response['data']); } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -1189,24 +1072,19 @@ class _addOnsDetailsState extends State { } Future removeAddonsGmcParentSiToAPI() async { - var url = Uri.parse(Environment.apiUrl + - 'removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$topUpParentClientPolicyId'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - print(data); + if (empCodeString == null || topUpParentClientPolicyId == null) { + return; + } + final response = await apiService.removeAddonsGmcParentSiToAPI( + empCodeString!, topUpParentClientPolicyId!); + if (response['status'] == 'success') { + print(response['data']); } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -1250,61 +1128,50 @@ class _addOnsDetailsState extends State { print(calculation); // Iterate through familyMembers list and send each member's data to the API - final url = Uri.parse(Environment.apiUrl + 'calculatePremium'); - final response = await http.post( - url, - body: jsonEncode(calculation), - headers: { - 'Content-Type': 'application/json', - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - print(data); - List? topUpEmpArray; - for (var item in data['data']) { - if (item.containsKey(empCodeString)) { - topUpEmpArray = item[empCodeString]; - break; + final response = await apiService.topUpSiCalculationToAPI(calculation); + + if (response['status'] == 'success') { + print(response); + List? topUpEmpArray; + for (var item in response['data']) { + if (item.containsKey(empCodeString)) { + topUpEmpArray = item[empCodeString]; + break; + } + } + + if (topUpEmpArray != null) { + print('Array for emp_code $empCodeString:'); + print(topUpEmpArray); + double topUpRataPremimumSum = 0; + for (var item in topUpEmpArray) { + var topUpRataPremimum = item['policy_details']['rata_premimum']; + if (topUpRataPremimum != null) { + topUpRataPremimumSum += topUpRataPremimum; } } + print('Sum of rata_premimum: $topUpRataPremimumSum'); - if (topUpEmpArray != null) { - print('Array for emp_code $empCodeString:'); - print(topUpEmpArray); - double topUpRataPremimumSum = 0; - for (var item in topUpEmpArray) { - var topUpRataPremimum = item['policy_details']['rata_premimum']; - if (topUpRataPremimum != null) { - topUpRataPremimumSum += topUpRataPremimum; - } + double topUpGstSum = 0; + for (var item in topUpEmpArray) { + var topUpGst = item['policy_details']['gst']; + if (topUpGst != null) { + topUpGstSum += topUpGst; } - print('Sum of rata_premimum: $topUpRataPremimumSum'); - - double topUpGstSum = 0; - for (var item in topUpEmpArray) { - var topUpGst = item['policy_details']['gst']; - if (topUpGst != null) { - topUpGstSum += topUpGst; - } - } - print('Sum of gst: $topUpGstSum'); - setState(() { - topUpSiPremiumValue = topUpRataPremimumSum; - print(topUpSiPremiumValue); - topUpSiPremiumGst = topUpGstSum; - print(topUpSiPremiumGst); - topUpSiTotalAmt = topUpSiPremiumValue + topUpSiPremiumGst; - print(topUpSiTotalAmt); - }); - sendAddonsGmcSiToAPI(); - } else { - print('Array not found for emp_code $empCodeString'); } + print('Sum of gst: $topUpGstSum'); + setState(() { + topUpSiPremiumValue = topUpRataPremimumSum; + print(topUpSiPremiumValue); + topUpSiPremiumGst = topUpGstSum; + print(topUpSiPremiumGst); + topUpSiTotalAmt = topUpSiPremiumValue + topUpSiPremiumGst; + print(topUpSiTotalAmt); + }); + sendAddonsGmcSiToAPI(); + } else { + print('Array not found for emp_code $empCodeString'); } } else { print('Operation Failed!'); @@ -1327,62 +1194,52 @@ class _addOnsDetailsState extends State { print(calculation); // Iterate through familyMembers list and send each member's data to the API - final url = Uri.parse(Environment.apiUrl + 'calculatePremium'); - final response = await http.post( - url, - body: jsonEncode(calculation), - headers: { - 'Content-Type': 'application/json', - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - print(data); - List? topUpEmpArray; - for (var item in data['data']) { - if (item.containsKey(empCodeString)) { - topUpEmpArray = item[empCodeString]; - break; + final response = + await apiService.topUpParentSiCalculationToAPI(calculation); + + if (response['status'] == 'success') { + print(response['data']); + List? topUpEmpArray; + for (var item in response['data']) { + if (item.containsKey(empCodeString)) { + topUpEmpArray = item[empCodeString]; + break; + } + } + + if (topUpEmpArray != null) { + print('Array for emp_code $empCodeString:'); + print(topUpEmpArray); + double topUpRataPremimumSum = 0; + for (var item in topUpEmpArray) { + var topUpRataPremimum = item['policy_details']['rata_premimum']; + if (topUpRataPremimum != null) { + topUpRataPremimumSum += topUpRataPremimum; } } + print('Sum of rata_premimum: $topUpRataPremimumSum'); - if (topUpEmpArray != null) { - print('Array for emp_code $empCodeString:'); - print(topUpEmpArray); - double topUpRataPremimumSum = 0; - for (var item in topUpEmpArray) { - var topUpRataPremimum = item['policy_details']['rata_premimum']; - if (topUpRataPremimum != null) { - topUpRataPremimumSum += topUpRataPremimum; - } + double topUpGstSum = 0; + for (var item in topUpEmpArray) { + var topUpGst = item['policy_details']['gst']; + if (topUpGst != null) { + topUpGstSum += topUpGst; } - print('Sum of rata_premimum: $topUpRataPremimumSum'); - - double topUpGstSum = 0; - for (var item in topUpEmpArray) { - var topUpGst = item['policy_details']['gst']; - if (topUpGst != null) { - topUpGstSum += topUpGst; - } - } - print('Sum of gst: $topUpGstSum'); - setState(() { - topUpParentSiPremiumValue = topUpRataPremimumSum; - print(topUpParentSiPremiumValue); - topUpParentSiPremiumGst = topUpGstSum; - print(topUpSiPremiumGst); - topUpParentSiTotalAmt = - topUpParentSiPremiumValue + topUpParentSiPremiumGst; - print(topUpParentSiTotalAmt); - }); - sendAddonsGmcParentSiToAPI(); - } else { - print('Array not found for emp_code $empCodeString'); } + print('Sum of gst: $topUpGstSum'); + setState(() { + topUpParentSiPremiumValue = topUpRataPremimumSum; + print(topUpParentSiPremiumValue); + topUpParentSiPremiumGst = topUpGstSum; + print(topUpSiPremiumGst); + topUpParentSiTotalAmt = + topUpParentSiPremiumValue + topUpParentSiPremiumGst; + print(topUpParentSiTotalAmt); + }); + sendAddonsGmcParentSiToAPI(); + } else { + print('Array not found for emp_code $empCodeString'); } } else { print('Operation Failed!'); @@ -1405,61 +1262,51 @@ class _addOnsDetailsState extends State { print(calculation); // Iterate through familyMembers list and send each member's data to the API - final url = Uri.parse(Environment.apiUrl + 'calculatePremium'); - final response = await http.post( - url, - body: jsonEncode(calculation), - headers: { - 'Content-Type': 'application/json', - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - print(data); - List? addOnsEmpArray; - for (var item in data['data']) { - if (item.containsKey(empCodeString)) { - addOnsEmpArray = item[empCodeString]; - break; + final response = + await apiService.addOnsDependentCalculationToAPI(calculation); + + if (response['status'] == 'success') { + print(response['data']); + List? addOnsEmpArray; + for (var item in response['data']) { + if (item.containsKey(empCodeString)) { + addOnsEmpArray = item[empCodeString]; + break; + } + } + + if (addOnsEmpArray != null) { + print('Array for emp_code $empCodeString:'); + print(addOnsEmpArray); + double addOnsRataPremimumSum = 0; + for (var item in addOnsEmpArray) { + var addOnsRataPremimum = item['policy_details']['rata_premimum']; + if (addOnsRataPremimum != null) { + addOnsRataPremimumSum += addOnsRataPremimum; } } + print('Sum of rata_premimum: $addOnsRataPremimumSum'); - if (addOnsEmpArray != null) { - print('Array for emp_code $empCodeString:'); - print(addOnsEmpArray); - double addOnsRataPremimumSum = 0; - for (var item in addOnsEmpArray) { - var addOnsRataPremimum = item['policy_details']['rata_premimum']; - if (addOnsRataPremimum != null) { - addOnsRataPremimumSum += addOnsRataPremimum; - } + double addOnsGstSum = 0; + for (var item in addOnsEmpArray) { + var addOnsGst = item['policy_details']['gst']; + if (addOnsGst != null) { + addOnsGstSum += addOnsGst; } - print('Sum of rata_premimum: $addOnsRataPremimumSum'); - - double addOnsGstSum = 0; - for (var item in addOnsEmpArray) { - var addOnsGst = item['policy_details']['gst']; - if (addOnsGst != null) { - addOnsGstSum += addOnsGst; - } - } - print('Sum of gst: $addOnsGstSum'); - setState(() { - addOnDependentPremiumValue = addOnsRataPremimumSum; - print(addOnDependentPremiumValue); - addOnsDependentPremiumGst = addOnsGstSum; - print(addOnsDependentPremiumGst); - addOnsDependentTotalAmt = - addOnDependentPremiumValue + addOnsDependentPremiumGst; - print(topUpSiTotalAmt); - }); - } else { - print('Array not found for emp_code $empCodeString'); } + print('Sum of gst: $addOnsGstSum'); + setState(() { + addOnDependentPremiumValue = addOnsRataPremimumSum; + print(addOnDependentPremiumValue); + addOnsDependentPremiumGst = addOnsGstSum; + print(addOnsDependentPremiumGst); + addOnsDependentTotalAmt = + addOnDependentPremiumValue + addOnsDependentPremiumGst; + print(topUpSiTotalAmt); + }); + } else { + print('Array not found for emp_code $empCodeString'); } } else { print('Operation Failed!'); @@ -1496,26 +1343,18 @@ class _addOnsDetailsState extends State { }; // Convert the list of objects to JSON - String formDataJson = jsonEncode(apiParams); + // String formDataJson = jsonEncode(apiParams); - var url = Uri.parse(Environment.apiUrl + 'iAgreeForAddOn'); try { - var response = await http.post( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - body: formDataJson, - ); + final response = await apiService.sendAddOnToAPI(apiParams); - if (response.statusCode == 200) { + if (response['status'] == 'success') { print('response.statusCode == 200'); ToastHelper.showSuccessToast(context, 'Saved Successfully...'); } else { // Handle other status codes ToastHelper.showErrorToast(context, 'failed to save'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions diff --git a/lib/customAppBar/customAppBar.dart b/lib/customAppBar/customAppBar.dart index e60e363..015d0c9 100644 --- a/lib/customAppBar/customAppBar.dart +++ b/lib/customAppBar/customAppBar.dart @@ -5,9 +5,49 @@ import 'package:nhancepolicy/responsive.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:nhancepolicy/responsive.dart'; -class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { +class CustomAppBar extends StatefulWidget implements PreferredSizeWidget { + @override + _CustomAppBarState createState() => _CustomAppBarState(); + @override Size get preferredSize => Size.fromHeight(kToolbarHeight); +} + +class _CustomAppBarState extends State { + bool showBackToHR = true; + bool hideInactiveStatus = true; + + @override + void initState() { + super.initState(); + _checkTokens(); + } + + Future _checkTokens() async { + final prefs = await SharedPreferences.getInstance(); + final String? hrtoken = prefs.getString('hrtoken'); + final String? token = prefs.getString('token'); + + setState(() { + showBackToHR = (hrtoken != null && hrtoken.isNotEmpty) && + (token != null && token.isNotEmpty); + + hideInactiveStatus = token != null && token.isNotEmpty; + }); + } + + Future hrLogout(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + final String? hrtoken = prefs.getString('hrtoken'); + + if (hrtoken != null && hrtoken.isNotEmpty) { + prefs.remove('token'); + Navigator.pushNamed(context, 'hrDashboard'); + } else { + await prefs.clear(); + Navigator.pushNamed(context, 'phone'); + } + } Future logout(BuildContext context) async { final prefs = await SharedPreferences.getInstance(); @@ -16,8 +56,8 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { if (token != null && token.isNotEmpty) { if (hrtoken != null && hrtoken.isNotEmpty) { - prefs.remove('token'); - Navigator.pushNamed(context, 'hrDashboard'); + await prefs.clear(); + Navigator.pushNamed(context, 'hrLogin'); } else { await prefs.clear(); Navigator.pushNamed(context, 'phone'); @@ -26,7 +66,6 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { await prefs.clear(); Navigator.pushNamed(context, 'hrLogin'); } - // Navigator.pushNamed(context, "phone"); } @override @@ -36,7 +75,7 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { return Scaffold( backgroundColor: Color(0xFFFFFCE5), // Set background color for AppBar appBar: PreferredSize( - preferredSize: preferredSize, + preferredSize: widget.preferredSize, child: SafeArea( child: Container( padding: Responsive.isDesktop(context) @@ -50,8 +89,7 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { child: Row( mainAxisAlignment: Responsive.isDesktop(context) ? MainAxisAlignment.spaceEvenly - : MainAxisAlignment - .start, // Adjust the alignment as needed + : MainAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(top: 10, bottom: 10), @@ -59,19 +97,9 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { height: 230, child: Image.asset( 'assets/nhance_client_logo.png', - fit: BoxFit.contain, // Adjust the fit as needed + fit: BoxFit.contain, ), ), - // SizedBox(width: 0), // Adjust the space between the images - // Container( - // margin: EdgeInsets.only(top: 10, bottom: 10), - // width: 150, - // height: 150, - // child: Image.asset( - // 'assets/partnerLogo.png', - // fit: BoxFit.contain, // Adjust the fit as needed - // ), - // ), ], ), ), @@ -86,35 +114,24 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { title: Text(''), navBarItems: [ if (Responsive.isDesktop(context)) + if (hideInactiveStatus) + NavBarItem( + text: "Inactive Policy", + onTap: () { + Navigator.pushNamed(context, 'oldPolicy'); + }, + ), + if (showBackToHR) NavBarItem( - text: "", + text: "Back To HR", onTap: () { - Navigator.pushNamed(context, "routeName"); + hrLogout(context); }, ), - if (Responsive.isDesktop(context)) - NavBarItem( - text: "", - onTap: () { - Navigator.pushNamed(context, "routeName"); - }, - ), - NavBarItem( - text: "Inactive Policy", - onTap: () { - Navigator.pushNamed(context, 'oldPolicy'); - }, - ), NavBarItem( text: "Logout", onTap: () async { logout(context); - // Clear local storage (SharedPreferences) - // final prefs = await SharedPreferences.getInstance(); - // prefs.clear(); - // ToastHelper.showSuccessToast( - // context, 'Logout Successfully...'); - // Navigator.pushNamed(context, "phone"); }, ), ], diff --git a/lib/empDetails.dart b/lib/empDetails.dart index 452103a..b22d149 100644 --- a/lib/empDetails.dart +++ b/lib/empDetails.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:nhancepolicy/customAppBar/toastHelper.dart'; import 'package:nhancepolicy/models/environment.dart'; +import 'package:nhancepolicy/service/api_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'customAppBar/customAppBar.dart'; import 'package:jwt_decode/jwt_decode.dart'; @@ -24,6 +25,7 @@ class empDetails extends StatefulWidget { } class _empDetailsState extends State { + late ApiService apiService; bool isLoading = true; dynamic _token; dynamic empCodeString; @@ -85,10 +87,13 @@ class _empDetailsState extends State { dynamic gmcDataIsEmpty = 1; dynamic gpaDataIsEmpty = 1; dynamic hrPrimaryId; + dynamic empRefId; + dynamic empClientBranchId; @override void initState() { super.initState(); + apiService = ApiService(context); // Initialize ApiService here _dobController = TextEditingController(); _memberNameController = TextEditingController(); _relationShipController = TextEditingController(); @@ -151,15 +156,19 @@ class _empDetailsState extends State { Map data = json.decode(response.body); print(data); String status = data['status']; - print(status); + if (status == 'success') { + print(status); // final SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('token', data['data']); // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(data['data']); print(decodedToken); - empCodeString = decodedToken['emp_code'].toString(); + empClientBranchId = decodedToken['client_branch_id']; + prefs.setString('empClientBranchId', empClientBranchId); + print(empClientBranchId); + empCodeString = decodedToken['emp_code']; prefs.setString('empCode', empCodeString); empPrimaryId = decodedToken['id']; prefs.setString('empPrimaryId', empPrimaryId); @@ -224,6 +233,7 @@ class _empDetailsState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); print(decodedToken); + empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); print(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); @@ -252,23 +262,19 @@ class _empDetailsState extends State { } Future getClientLogoAndDetails() async { - var url = Uri.parse(Environment.apiUrl + - 'getClientDetails?client_id=$client_id&emp_code=$empCodeString'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - // print('response.statusCode == 200'); - Map data = json.decode(response.body); - // print(data); + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getClientLogoAndDetailsToApi( + client_id!, empCodeString!, empClientBranchId!); + print('check 1'); - if (data.containsKey('data')) { - dynamic clientDetails = data['data']; + if (response['status'] == 'success') { + if (response.containsKey('data')) { + dynamic clientDetails = response['data']; final SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('clientLogo', clientDetails['client']['client_logo']); prefs.setString('clientName', clientDetails['client']['client_name']); @@ -284,13 +290,13 @@ class _empDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -299,24 +305,19 @@ class _empDetailsState extends State { } Future getSelfEmployeeProfile() async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeeProfile?emp_code=$empCodeString&client_id=$client_id'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - // print('response.statusCode == 200'); - Map data = json.decode(response.body); - // print(data); + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getSelfEmployeeProfileToApi( + client_id!, empCodeString!, empClientBranchId!); - if (data.containsKey('data')) { + if (response['status'] == 'success') { + if (response.containsKey('data')) { setState(() { - dynamic selfDetails = data['data']; + dynamic selfDetails = response['data']; print(selfDetails); mobileNumber = selfDetails['relationship']; selfRelationship = selfDetails['relationship']; @@ -339,13 +340,13 @@ class _empDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -368,23 +369,18 @@ class _empDetailsState extends State { } Future getGpaEmpPolicyDetails(empPrimaryId) async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeePolicy?id=$empPrimaryId&emp_code=$empCodeString&client_id=$client_id&policy=GPA'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print(data); + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGpaEmpPolicyDetailsToApi( + empPrimaryId, empCodeString!, client_id!, 'GPA', empClientBranchId!); - if (data.containsKey('data')) { - gpaPolicies = data['data']; + if (response['status'] == 'success') { + if (response.containsKey('data')) { + gpaPolicies = response['data']; print('gpaPolicies'); // Assuming data is a List print(gpaPolicies); @@ -422,12 +418,12 @@ class _empDetailsState extends State { } else { // Handle other status messages if needed // ToastHelper.showErrorToast(context, 'Something went wrong'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes ToastHelper.showWarningToast(context, 'Something went wrong'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -436,42 +432,29 @@ class _empDetailsState extends State { } Future getGmcEmpPolicyDetails(empPrimaryId) async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeePolicy?id=$empPrimaryId&emp_code=$empCodeString&client_id=$client_id&policy=GMC'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('GMC response.statusCode == 200'); - Map data = json.decode(response.body); - print(data); - - if (data['status'] == 'success') { - setState(() { - gmcPolicies = data['data']; - print('gmcPolicies'); - }); - // Assuming data is a List - print(gmcPolicies); - } else { - setState(() { - gmcDataIsEmpty = 0; - }); - // Handle other status messages if needed - // ToastHelper.showErrorToast( - // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); - } + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcEmpPolicyDetailsToApi( + empPrimaryId, empCodeString!, client_id!, 'GMC', empClientBranchId!); + if (response['status'] == 'success') { + setState(() { + gmcPolicies = response['data']; + print('gmcPolicies'); + }); + // Assuming data is a List + print(gmcPolicies); } else { - // Handle other status codes + setState(() { + gmcDataIsEmpty = 0; + }); + // Handle other status messages if needed // ToastHelper.showErrorToast( - // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + // context, 'API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } catch (e) { // Handle exceptions @@ -481,18 +464,10 @@ class _empDetailsState extends State { Future fetchRelationshipList() async { // Replace the URL with your API endpoint - final url = Uri.parse(Environment.apiUrl + 'relationshipList'); try { - final response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - final List data = jsonDecode(response.body)['data']; - for (var item in data) { + final response = await apiService.fetchRelationshipListToApi(); + if (response['status'] == 'success') { + for (var item in response['data']) { String relationshipName = item['relationship_name']; String dependent = item['dependent']; @@ -573,22 +548,12 @@ class _empDetailsState extends State { Future deleteItem(Map deletedItem) async { print(deletedItem); - // Define your API endpoint - var id = deletedItem['employee_id']; - final String apiUrl = Environment.apiUrl + 'deleteDependence?id=$id'; - try { - // Make the DELETE request to the API endpoint - final http.Response response = await http.get( - Uri.parse(apiUrl), - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); + var id = deletedItem['employee_id']; + final response = await apiService.deleteItemToApi(id); // Check if the request was successful (status code 200) - if (response.statusCode == 200) { + if (response['status'] == 'success') { formDataList.clear(); selectedRelationships.clear(); _relationShipController.clear(); @@ -603,8 +568,8 @@ class _empDetailsState extends State { } else { // Handle errors ToastHelper.showErrorToast(context, 'Failed to delete item'); - print('Failed to delete item. Status code: ${response.statusCode}'); - print('Response body: ${response.body}'); + print('Failed to delete item. Status code: ${response['code']}'); + print('Response body: ${response}'); } } catch (error) { // Handle network errors @@ -631,6 +596,7 @@ class _empDetailsState extends State { } formDataList.add({ + 'client_branch_id': empClientBranchId, 'relationship': formData['relationship'], 'name': formData['memberName'], 'dob': formData['dateOfBirth'], @@ -644,21 +610,14 @@ class _empDetailsState extends State { }); // Convert the list of objects to JSON - String formDataJson = jsonEncode(formDataList); + // String formDataJson = jsonEncode(formDataList); // Prepare the API request - var url = Uri.parse(Environment.apiUrl + 'addEmployeeAndDependence'); - var response = await http.post( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - body: formDataJson, - ); + final response = + await apiService.saveFamilyMemberDetailsToApi(formDataList); // Check the response - if (response.statusCode == 200) { + if (response['status'] == 'success') { formDataList.clear(); selectedRelationships.clear(); _relationShipController.clear(); @@ -674,7 +633,7 @@ class _empDetailsState extends State { } else { // Request failed, handle error ToastHelper.showErrorToast(context, 'Failed'); - print('Failed to send form data. Error: ${response.reasonPhrase}'); + print('Failed to send form data. Error: ${response}'); } } diff --git a/lib/empReview.dart b/lib/empReview.dart index cbe9aff..9c57143 100644 --- a/lib/empReview.dart +++ b/lib/empReview.dart @@ -5,6 +5,7 @@ import 'package:intl/intl.dart'; import 'package:nhancepolicy/customAppBar/toastHelper.dart'; import 'package:nhancepolicy/models/environment.dart'; import 'package:nhancepolicy/responsive.dart'; +import 'package:nhancepolicy/service/api_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'customAppBar/customAppBar.dart'; import 'package:jwt_decode/jwt_decode.dart'; @@ -22,6 +23,7 @@ class empReviewDetails extends StatefulWidget { } class _empReviewDetailsState extends State { + late ApiService apiService; bool isChecked = false; // Declare the _isSwitched variable here dynamic _token; dynamic empCodeString; @@ -114,10 +116,12 @@ class _empReviewDetailsState extends State { int activePremiumSummary = 0; dynamic gmcDataIsEmpty = 1; dynamic gpaDataIsEmpty = 1; + dynamic empClientBranchId; @override void initState() { super.initState(); + apiService = ApiService(context); // Initialize ApiService here _loadToken(); } @@ -143,7 +147,7 @@ class _empReviewDetailsState extends State { setState(() { _token = token; }); - + empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); print(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); @@ -246,23 +250,17 @@ class _empReviewDetailsState extends State { } Future getClientLogoAndDetails() async { - var url = Uri.parse(Environment.apiUrl + - 'getClientDetails?client_id=$client_id&emp_code=$empCodeString'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = await json.decode(response.body); - print(data); - - if (data.containsKey('data')) { - dynamic clientDetails = data['data']; + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getClientLogoAndDetailsToApi( + client_id!, empCodeString!, empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { + dynamic clientDetails = response['data']; print(clientDetails); clientName = clientDetails['client']['client_name']; print(clientName); @@ -270,11 +268,11 @@ class _empReviewDetailsState extends State { print(clientLogo); } else { // Handle other status messages if needed - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -283,23 +281,17 @@ class _empReviewDetailsState extends State { } Future getGpaEmpPolicyDetails(empPrimaryId) async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeePolicy?id=$empPrimaryId&emp_code=$empCodeString&client_id=$client_id&policy=GPA'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = await json.decode(response.body); - print(data); - - if (data.containsKey('data')) { - gpaPolicies = data['data']; + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGpaEmpPolicyDetailsToApi( + empPrimaryId, empCodeString!, client_id!, 'GPA', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { + gpaPolicies = response['data']; print(gpaPolicies); // Assuming data is a List print(gpaPolicies); @@ -346,7 +338,7 @@ class _empReviewDetailsState extends State { } else { // Handle other status messages if needed ToastHelper.showWarningToast(context, 'Something went wrong'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { setState(() { @@ -354,7 +346,7 @@ class _empReviewDetailsState extends State { }); // Handle other status codes ToastHelper.showErrorToast(context, 'Something went wrong'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -363,37 +355,21 @@ class _empReviewDetailsState extends State { } Future getGmcEmpPolicyDetails(empPrimaryId) async { - var url = Uri.parse(Environment.apiUrl + - 'getEmployeePolicy?id=$empPrimaryId&emp_code=$empCodeString&client_id=$client_id&policy=GMC'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = await json.decode(response.body); - print(data); - - if (data['status'] == 'success') { - setState(() { - gmcPolicies = data['data']; - print('gmcPolicies'); - }); - // Assuming data is a List - print(gmcPolicies); - } else { - setState(() { - gmcDataIsEmpty = 0; - }); - // Handle other status messages if needed - // ToastHelper.showErrorToast( - // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); - } + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcEmpPolicyDetailsToApi( + empPrimaryId, empCodeString!, client_id!, 'GMC', empClientBranchId!); + if (response['status'] == 'success') { + setState(() { + gmcPolicies = response['data']; + print('gmcPolicies'); + }); + // Assuming data is a List + print(gmcPolicies); } else { setState(() { gmcDataIsEmpty = 0; @@ -401,7 +377,7 @@ class _empReviewDetailsState extends State { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -410,23 +386,17 @@ class _empReviewDetailsState extends State { } Future getGmcSiTopUp() async { - var url = Uri.parse(Environment.apiUrl + - 'getAddOnPolicy?client_id=$client_id&emp_code=$empCodeString&policy=GMC-SI-TOPUP'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print(data); - - if (data.containsKey('data')) { - dynamic topUpSiPolicies = data['data']; + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcSiTopUpToApi( + client_id!, empCodeString!, 'GMC-SI-TOPUP', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { + dynamic topUpSiPolicies = response['data']; print(topUpSiPolicies); if (topUpSiPolicies.isNotEmpty) { // setState(() { @@ -468,13 +438,13 @@ class _empReviewDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -483,25 +453,18 @@ class _empReviewDetailsState extends State { } Future getGmcSiParentTopUp() async { - var url = Uri.parse(Environment.apiUrl + - 'getAddOnPolicy?client_id=$client_id&emp_code=$empCodeString&policy=GMC-SI-PARENT-TOPUP'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print('parent'); - print(data); - - if (data.containsKey('data')) { + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcSiParentTopUpToApi(client_id!, + empCodeString!, 'GMC-SI-PARENT-TOPUP', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { setState(() { - topUpSiParentPolicies = data['data']; + topUpSiParentPolicies = response['data']; print('topUpSiParentPolicies'); print(topUpSiParentPolicies); }); @@ -568,13 +531,13 @@ class _empReviewDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -583,24 +546,17 @@ class _empReviewDetailsState extends State { } Future getGmcDependentAddOns() async { - var url = Uri.parse(Environment.apiUrl + - 'getAddOnPolicy?client_id=$client_id&emp_code=$empCodeString&policy=GMC-DEPENDENT-ADDON'); try { - var response = await http.get( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - ); - if (response.statusCode == 200) { - print('response.statusCode == 200'); - Map data = json.decode(response.body); - print('222222222'); - print(data); - - if (data.containsKey('data')) { - dynamic addOnsDependentPolicies = data['data']; + if (client_id == null || + empCodeString == null || + empClientBranchId == null) { + return; + } + final response = await apiService.getGmcDependentAddOnsToApi(client_id!, + empCodeString!, 'GMC-DEPENDENT-ADDON', empClientBranchId!); + if (response['status'] == 'success') { + if (response.containsKey('data')) { + dynamic addOnsDependentPolicies = response['data']; print('addOnsDependentPolicies'); print(addOnsDependentPolicies); if (addOnsDependentPolicies.isNotEmpty) { @@ -646,13 +602,13 @@ class _empReviewDetailsState extends State { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + print('API request failed with status: ${response['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions @@ -728,24 +684,16 @@ class _empReviewDetailsState extends State { // Convert the list of objects to JSON String formDataJson = jsonEncode(apiParams); - var url = Uri.parse(Environment.apiUrl + 'iAgreeForAddOn'); try { - var response = await http.post( - url, - headers: { - 'Authorization': - 'Bearer $_token', // Add token to the Authorization header - }, - body: formDataJson, - ); + final response = await apiService.sendAddOnToAPI(apiParams); - if (response.statusCode == 200) { + if (response['status'] == 'success') { print('response.statusCode == 200'); ToastHelper.showSuccessToast(context, 'Saved Successfully...'); } else { // Handle other status codes ToastHelper.showErrorToast(context, 'Failed to Save'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions diff --git a/lib/excel_verification.dart b/lib/excel_verification.dart index b0dba63..535b37e 100644 --- a/lib/excel_verification.dart +++ b/lib/excel_verification.dart @@ -51,6 +51,8 @@ class _excelVerifyState extends State { List> nonExcelFilteredData = []; dynamic invalidRelationships = 0; dynamic dobAgeCheckCount = 0; + dynamic empRefId; + @override void initState() { super.initState(); @@ -72,6 +74,7 @@ class _excelVerifyState extends State { }); Map? decodedToken = Jwt.parseJwt(token); clintID = decodedToken['client_id'].toString(); + empRefId = prefs.getString('empRefId'); await getPolicyDetails(); } else { // Token is empty or null, handle accordingly (e.g., navigate to login screen) @@ -418,6 +421,7 @@ class _excelVerifyState extends State { print('clientPolicyId: $clientPolicyId'); // if (policyFirstPart == 'GPA') { request.fields['policy_id'] = clientPolicyId; + request.fields['client_branch_id'] = empRefId; // } else { // request.fields['policy_id'] = '3'; // } diff --git a/lib/hrDashboard.dart b/lib/hrDashboard.dart index 9f1d1ca..621f0a4 100644 --- a/lib/hrDashboard.dart +++ b/lib/hrDashboard.dart @@ -6,6 +6,7 @@ import 'package:google_fonts/google_fonts.dart'; import 'package:jwt_decode/jwt_decode.dart'; import 'package:nhancepolicy/models/environment.dart'; import 'package:nhancepolicy/responsive.dart'; +import 'package:nhancepolicy/service/api_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; import 'customAppBar/customAppBar.dart'; @@ -21,6 +22,7 @@ class hrDashboard extends StatefulWidget { } class _hrDashboardState extends State { + late ApiService apiService; bool isLoading = true; late String _token; dynamic getPolicyNo; @@ -31,6 +33,7 @@ class _hrDashboardState extends State { dynamic getCardArrays = []; dynamic clientName; dynamic clientLogo; + dynamic empRefId; final List cardColors = [ Color(0xFFFFE3D9), Color(0xFFFFD9EE), @@ -41,6 +44,7 @@ class _hrDashboardState extends State { @override void initState() { super.initState(); + apiService = ApiService(context); // Initialize ApiService here _loadToken(); Future.delayed(Duration(seconds: 3), () { setState(() { @@ -63,6 +67,8 @@ class _hrDashboardState extends State { }); Map? decodedToken = Jwt.parseJwt(token); clintID = decodedToken['client_id'].toString(); + empRefId = prefs.getString('empRefId'); + print(empRefId); print(clintID); if (prefs.containsKey('clientLogo') && prefs.containsKey('clientName')) { clientLogo = prefs.getString('clientLogo'); @@ -70,7 +76,7 @@ class _hrDashboardState extends State { } else { getClientLogoAndDetails(); } - await getCashDepositDetails(clintID); + getCashDepositDetails(clintID); } else { // Token is empty or null, handle accordingly (e.g., navigate to login screen) // For now, let's navigate to the login screen @@ -80,8 +86,8 @@ class _hrDashboardState extends State { } Future getClientLogoAndDetails() async { - var url = - Uri.parse(Environment.apiUrl + 'getClientDetails?client_id=$clintID'); + var url = Uri.parse(Environment.apiUrl + + 'getClientDetails?client_id=$clintID&client_branch_id=$empRefId'); try { var response = await http.get( url, @@ -130,26 +136,17 @@ class _hrDashboardState extends State { setState(() { _isLoading = true; }); - var url = Uri.parse( - Environment.apiUrl + 'getCashDepositData?client_id=' + clintID); try { - var response = await http.get( - url, - headers: { - 'Authorization': 'Bearer $_token', - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - setState(() { - getCardArrays = List>.from(data['data']); - print(getCardArrays); - }); - } else { - // No matching policy found - print('No matching policy found for'); - } + if (clintID == null || empRefId == null) { + return; + } + final response = + await apiService.getCashDepositDetailsToApi(clintID!, empRefId!); + if (response['status'] == 'success') { + setState(() { + getCardArrays = List>.from(response['data']); + print(getCardArrays); + }); } else { print('API request failed with status'); } @@ -158,12 +155,12 @@ class _hrDashboardState extends State { } } - Future downloadExcel(clintId, clintIdclintId, insurerName) async { + Future downloadExcel(clintId, insurerId, insurerName) async { // API endpoint to download the Excel file // Send GET request to the API var url = Uri.parse(Environment.apiUrl + - 'exportCashDepositData?client_id=$clintId&insurer_id=$clintIdclintId'); + 'exportCashDepositData?client_id=$clintId&insurer_id=$insurerId'); var response = await http.get( url, @@ -300,329 +297,328 @@ class _hrDashboardState extends State { ), ), SizedBox(height: 16), - Card( - elevation: 0, - child: Container( - width: double.infinity, - padding: Responsive.isDesktop(context) - ? EdgeInsets.all(20) - : EdgeInsets.all( - 10), // Add padding to the container - child: Column(children: [ - Row(children: [ - Text( - 'Cash Transaction', - style: GoogleFonts.poppins( - fontSize: 18, - fontWeight: FontWeight.w600, - color: Colors.black, - ), - ) - ]), - SizedBox(height: 8), - Row( - children: [ - // Create an Expanded widget with flex of 4 for each card - for (var cardData in getCardArrays) - Container( - width: - 300, // Set a fixed width for the card - height: cardHeight, - child: Card( - elevation: 3, - color: cardColors[ - getCardArrays.indexOf(cardData) % - cardColors.length], - child: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - ListTile( - title: SizedBox( - height: 50, - child: Text( - cardData['insurerName'], + if (getCardArrays.length != 0) + Card( + elevation: 0, + child: Container( + width: double.infinity, + padding: Responsive.isDesktop(context) + ? EdgeInsets.all(20) + : EdgeInsets.all( + 10), // Add padding to the container + child: Column(children: [ + Row(children: [ + Text( + 'Cash Transaction', + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black, + ), + ) + ]), + SizedBox(height: 8), + Row( + children: [ + // Create an Expanded widget with flex of 4 for each card + for (var cardData in getCardArrays) + Container( + width: + 300, // Set a fixed width for the card + height: cardHeight, + child: Card( + elevation: 3, + color: cardColors[ + getCardArrays.indexOf(cardData) % + cardColors.length], + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + ListTile( + title: SizedBox( + height: 50, + child: Text( + cardData['insurerName'], + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w500, + color: Color(0xFF000000), + height: 1.5, + ), + ), + ), + subtitle: Text( + 'Balance: ₹ ${cardData['balance']}', style: GoogleFonts.poppins( - fontSize: 18, - fontWeight: FontWeight.w500, + fontSize: 16, + fontWeight: FontWeight.w400, color: Color(0xFF000000), height: 1.5, ), ), ), - subtitle: Text( - 'Balance: ₹ ${cardData['balance']}', - style: GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w400, - color: Color(0xFF000000), - height: 1.5, - ), - ), - ), - SizedBox(height: 10), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 15), - child: GestureDetector( - onTap: () { - openForm( - cardData['depositData'], - cardData['insurerName'], - cardData['clientId'], - cardData['insurerId'], - cardColors[getCardArrays - .indexOf(cardData) % - cardColors.length], - ); - }, - child: MouseRegion( - cursor: - SystemMouseCursors.click, - child: Align( - alignment: - Alignment.centerRight, - child: Text( - 'View Details', - style: GoogleFonts.poppins( - color: Color(0xFF000000), - fontSize: 14, - fontWeight: - FontWeight.w300, - height: 1.5, + SizedBox(height: 10), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 15), + child: GestureDetector( + onTap: () { + openForm( + cardData['depositData'], + cardData['insurerName'], + cardData['clientId'], + cardData['insurerId'], + cardColors[getCardArrays + .indexOf(cardData) % + cardColors.length], + ); + }, + child: MouseRegion( + cursor: + SystemMouseCursors.click, + child: Align( + alignment: + Alignment.centerRight, + child: Text( + 'View Details', + style: + GoogleFonts.poppins( + color: + Color(0xFF000000), + fontSize: 14, + fontWeight: + FontWeight.w300, + height: 1.5, + ), ), ), ), ), ), - ), - ], + ], + ), ), ), - ), - ], - ), - ])), - ), + ], + ), + ])), + ), SizedBox(height: 16), - Card( - elevation: 0, - child: Padding( - padding: Responsive.isDesktop(context) - ? EdgeInsets.all(20) - : EdgeInsets.all(10), - child: Column( - children: [ - Row( - children: [ - Expanded( - child: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: List.generate( - numExpanded, - (index) { - var insurerName = getCardArrays[index] - ['insurerName']; - var policyDetails = - getCardArrays[index] - ['policyDetails']; + if (getCardArrays.length != 0) + Card( + elevation: 0, + child: Padding( + padding: Responsive.isDesktop(context) + ? EdgeInsets.all(20) + : EdgeInsets.all(10), + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: List.generate( + numExpanded, + (index) { + var insurerName = + getCardArrays[index] + ['insurerName']; + var policyDetails = + getCardArrays[index] + ['policyDetails']; - // Determine the color for the policyDetails based on the index of the card in getCardArrays - var cardColorIndex = - getCardArrays.indexOf( - getCardArrays[index]) % - cardColors.length; - var cardColor = - cardColors[cardColorIndex]; + // Determine the color for the policyDetails based on the index of the card in getCardArrays + var cardColorIndex = + getCardArrays.indexOf( + getCardArrays[index]) % + cardColors.length; + var cardColor = + cardColors[cardColorIndex]; - return Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - insurerName, - style: GoogleFonts.poppins( - fontSize: 18, - fontWeight: FontWeight.w600, - color: Colors.black, + return Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + insurerName, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black, + ), ), - ), - SizedBox(height: 8), - Row( - children: List.generate( - policyDetails.length, - (index) => Container( - width: 300, - height: policyHeight, - child: GestureDetector( - onTap: () { - Navigator.pushNamed( - context, - 'hrPolicyDetails', - arguments: - policyDetails[ - index]); - }, - child: MouseRegion( - cursor: - SystemMouseCursors - .click, - child: Card( - elevation: 3, - color: - cardColor, // Use the determined color - child: Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - children: [ - ListTile( - title: SizedBox( - height: 50, - child: Text( - '${policyDetails[index]['policy_name']} - (${policyDetails[index]['type']})', - style: GoogleFonts - .poppins( - fontSize: - 16, - fontWeight: - FontWeight - .w500, - color: Color( - 0xFF000000), - height: - 1.5, + SizedBox(height: 8), + Row( + children: List.generate( + policyDetails.length, + (index) => Container( + width: 300, + height: policyHeight, + child: GestureDetector( + onTap: () { + Navigator.pushNamed( + context, + 'hrPolicyDetails', + arguments: + policyDetails[ + index]); + }, + child: MouseRegion( + cursor: + SystemMouseCursors + .click, + child: Card( + elevation: 3, + color: + cardColor, // Use the determined color + child: Column( + crossAxisAlignment: + CrossAxisAlignment + .start, + children: [ + ListTile( + title: + SizedBox( + height: 50, + child: Text( + '${policyDetails[index]['policy_name']} - (${policyDetails[index]['type']})', + style: GoogleFonts + .poppins( + fontSize: + 16, + fontWeight: + FontWeight.w500, + color: Color( + 0xFF000000), + height: + 1.5, + ), + softWrap: + true, // Allow text to wrap to the next line if needed ), - softWrap: - true, // Allow text to wrap to the next line if needed ), ), - ), - SizedBox( - height: 8), - Padding( - padding: EdgeInsets - .only( - left: - 15, - right: - 15), - child: Row( - children: [ - Expanded( - flex: 4, - child: - Column( - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - Text( - 'Draft', - style: - GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF000000), - height: 1.5, + SizedBox( + height: 8), + Padding( + padding: EdgeInsets + .only( + left: + 15, + right: + 15), + child: Row( + children: [ + Expanded( + flex: 4, + child: + Column( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + Text( + 'Draft', + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF000000), + height: 1.5, + ), ), - ), - Text( - policyDetails[index]['membersCountOfDraft'].toString(), - style: - GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w400, - color: Color(0xFF000000), - height: 1.5, + Text( + policyDetails[index]['membersCountOfDraft'].toString(), + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Color(0xFF000000), + height: 1.5, + ), ), - ), - ], + ], + ), ), - ), - Expanded( - flex: 4, - child: - Column( - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - Text( - 'Enrolled', - style: - GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF000000), - height: 1.5, + Expanded( + flex: 4, + child: + Column( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + Text( + 'Enrolled', + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF000000), + height: 1.5, + ), ), - ), - Text( - policyDetails[index]['membersCountOfEnrolled'].toString(), - style: - GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w400, - color: Color(0xFF000000), - height: 1.5, + Text( + policyDetails[index]['membersCountOfEnrolled'].toString(), + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Color(0xFF000000), + height: 1.5, + ), ), - ), - ], + ], + ), ), - ), - Expanded( - flex: 4, - child: - Column( - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - Text( - 'Total', - style: - GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF000000), - height: 1.5, + Expanded( + flex: 4, + child: + Column( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + Text( + 'Total', + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF000000), + height: 1.5, + ), ), - ), - Text( - policyDetails[index]['totalMembersCount'].toString(), - style: - GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w400, - color: Color(0xFF000000), - height: 1.5, + Text( + policyDetails[index]['totalMembersCount'].toString(), + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Color(0xFF000000), + height: 1.5, + ), ), - ), - ], + ], + ), ), - ), - ], - ), // Adjust the horizontal padding as needed - ) - ], + ], + ), // Adjust the horizontal padding as needed + ) + ], + ), ), ), ), ), ), ), - ), - SizedBox(height: 20), - ], - ); - }, + SizedBox(height: 20), + ], + ); + }, + ), ), ), - ), - ], - ) - ], - ), - )) + ], + ) + ], + ), + )) ], ), ), diff --git a/lib/hrPolicyDetails.dart b/lib/hrPolicyDetails.dart index 809fe4c..e3effa7 100644 --- a/lib/hrPolicyDetails.dart +++ b/lib/hrPolicyDetails.dart @@ -3,6 +3,7 @@ import 'package:google_fonts/google_fonts.dart'; import 'package:nhancepolicy/customAppBar/customAppBar.dart'; import 'package:nhancepolicy/excel_verification.dart'; import 'package:nhancepolicy/models/environment.dart'; +import 'package:nhancepolicy/service/api_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:jwt_decode/jwt_decode.dart'; import 'dart:convert'; @@ -42,12 +43,15 @@ class _HrPolicyDetailsState extends State dynamic policyName; dynamic clientPolicyId; dynamic clientId; + dynamic empRefId; int inceptionType = 0; TextEditingController searchController = TextEditingController(); + late ApiService apiService; @override void initState() { super.initState(); + apiService = ApiService(context); // Initialize ApiService here _tabController = TabController(length: 4, vsync: this); _loadToken(); } @@ -66,6 +70,7 @@ class _HrPolicyDetailsState extends State _token = token; }); Map? decodedToken = Jwt.parseJwt(token); + empRefId = prefs.getString('empRefId'); // clintID = decodedToken['client_id']; getPolicyDetails(); } else { @@ -131,35 +136,22 @@ class _HrPolicyDetailsState extends State setState(() { _isLoading = true; }); - var url = Uri.parse(Environment.apiUrl + - 'getEmployeeAndDependenceByClientId?client_id=$clintID&client_policy_id=$getPolicyNo'); try { - var response = await http.get( - url, - headers: { - 'Authorization': 'Bearer $_token', - }, - ); - if (response.statusCode == 200) { - Map data = json.decode(response.body); - if (data['status'] == 'success') { - setState(() { - getEmpDependenceByClintId = - List>.from(data['data']); - originalData = getEmpDependenceByClintId; - filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); - }); - } else { - // ToastHelper.showWarningToast( - // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); - } + final response = await apiService.getEmployeeAndDependenceToApi( + clintID!, getPolicyNo!, empRefId!); + if (response['status'] == 'success') { + setState(() { + getEmpDependenceByClintId = + List>.from(response['data']); + originalData = getEmpDependenceByClintId; + filteredData = List.from(originalData); + print('filteredData'); + print(filteredData); + }); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + print('Request failed with status: ${response['code']}'); } } catch (e) { print('Exception occurred: $e'); @@ -258,7 +250,7 @@ class _HrPolicyDetailsState extends State // Send GET request to the API var url = Uri.parse(Environment.apiUrl + - 'exportDataByClientPolicyId?client_id=$clientId&client_policy_id=$clientPolicyId'); + 'exportDataByClientPolicyId?client_id=$clientId&client_policy_id=$clientPolicyId&client_branch_id=$empRefId'); var response = await http.get( url, diff --git a/lib/hrVerify.dart b/lib/hrVerify.dart index 0528640..7de0e2c 100644 --- a/lib/hrVerify.dart +++ b/lib/hrVerify.dart @@ -31,6 +31,7 @@ class _MyVerifyState extends State { dynamic client_id; dynamic clientName; dynamic clientLogo; + dynamic empRefId; @override void initState() { @@ -137,7 +138,12 @@ class _MyVerifyState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(data['data']); + print('decodedToken'); print(decodedToken); + empRefId = decodedToken['ref_id']; + print('empRefId'); + print(empRefId); + prefs.setString('empRefId', empRefId); empCodeString = decodedToken['emp_code'].toString(); prefs.setString('empCode', empCodeString); empPrimaryId = decodedToken['id']; @@ -188,7 +194,7 @@ class _MyVerifyState extends State { Future getClientLogoAndDetails() async { var url = Uri.parse(Environment.apiUrl + - 'getClientDetails?client_id=$client_id&emp_code=$empCodeString'); + 'getClientDetails?client_id=$client_id&client_branch_id=$empRefId'); try { var response = await http.get( url, diff --git a/lib/oldPolicy.dart b/lib/oldPolicy.dart index ea7ed8a..6a3ce3b 100644 --- a/lib/oldPolicy.dart +++ b/lib/oldPolicy.dart @@ -39,6 +39,7 @@ class _oldPolicyState extends State { dynamic oldPolicyFloaterTextHeading; dynamic oldPolicyStartDate; dynamic oldPolicyEndDate; + dynamic empClientBranchId; @override void initState() { @@ -62,6 +63,7 @@ class _oldPolicyState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); print(decodedToken); + empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); print(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); @@ -79,7 +81,7 @@ class _oldPolicyState extends State { Future getOldPolicyDetails() async { var url = Uri.parse(Environment.apiUrl + - 'getEmployeeActiveOrInactivePolicy?client_id=$client_id&emp_code=$empCodeString&type=Inactive'); + 'getEmployeeActiveOrInactivePolicy?client_id=$client_id&emp_code=$empCodeString&type=Inactive&client_branch_id=$empClientBranchId'); try { var response = await http.get( url, diff --git a/lib/service/api_service.dart b/lib/service/api_service.dart new file mode 100644 index 0000000..56b1f2e --- /dev/null +++ b/lib/service/api_service.dart @@ -0,0 +1,502 @@ +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; +import 'dart:convert'; + +import '../customAppBar/toastHelper.dart'; +import '../models/environment.dart'; + +class ApiService { + final BuildContext context; + String? _token; + String? _hrtoken; + bool _isSessionOutToastShown = false; // Flag to track toast message + + ApiService(this.context) { + _initializeToken(); + } + + Future _initializeToken() async { + final prefs = await SharedPreferences.getInstance(); + _token = prefs.getString('token') ?? ''; + final hrprefs = await SharedPreferences.getInstance(); + _hrtoken = hrprefs.getString('hrtoken') ?? ''; + } + + Future> getClientLogoAndDetailsToApi( + String clientId, String empCode, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getClientDetails?client_id=$clientId&emp_code=$empCode&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getSelfEmployeeProfileToApi( + String clientId, String empCode, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getEmployeeProfile?emp_code=$empCode&client_id=$clientId&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> fetchRelationshipListToApi() async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse('${Environment.apiUrl}relationshipList'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getGpaEmpPolicyDetailsToApi(String empPrimaryId, + String empCode, String clientId, String policy, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getEmployeePolicy?id=$empPrimaryId&emp_code=$empCode&client_id=$clientId&policy=$policy&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getGmcEmpPolicyDetailsToApi(String empPrimaryId, + String empCode, String clientId, String policy, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getEmployeePolicy?id=$empPrimaryId&emp_code=$empCode&client_id=$clientId&policy=$policy&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getGmcSiTopUpToApi( + String client_id, String emp_code, String policy, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getAddOnPolicy?client_id=$client_id&emp_code=$emp_code&policy=$policy&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getGmcSiParentTopUpToApi( + String client_id, String emp_code, String policy, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getAddOnPolicy?client_id=$client_id&emp_code=$emp_code&policy=$policy&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getGmcDependentAddOnsToApi( + String client_id, String emp_code, String policy, String branchID) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getAddOnPolicy?client_id=$client_id&emp_code=$emp_code&policy=$policy&client_branch_id=$branchID'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> removeAddonsGmcDependentToAPI( + String empCodeString, String addOnsDependentClientPolicyId) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$addOnsDependentClientPolicyId'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> removeAddonsGmcSiToAPI( + String empCodeString, String topUpClientPolicyId) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$topUpClientPolicyId'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> removeAddonsGmcParentSiToAPI( + String empCodeString, String topUpParentClientPolicyId) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$topUpParentClientPolicyId'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> deleteItemToApi(id) async { + print(_token); + if (_token == null) { + await _initializeToken(); + } + final url = Uri.parse('${Environment.apiUrl}deleteDependence?id=$id'); + final headers = { + 'Authorization': _token ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> saveFamilyMemberDetailsToApi( + List> formDataList) async { + print('saveFamilyMemberDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = Uri.parse('${Environment.apiUrl}addEmployeeAndDependence'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> saveAddOnsDetailsToApi( + List> formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = Uri.parse('${Environment.apiUrl}addEmployeeAndDependence'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> sendAddonsGmcDependentToAPI( + List> formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = + Uri.parse('${Environment.apiUrl}createOrUpdateEmployeePolicySiAmount'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> sendAddonsGmcSiToAPI( + List> formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = + Uri.parse('${Environment.apiUrl}createOrUpdateEmployeePolicySiAmount'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> sendAddonsGmcParentSiToAPI( + List> formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = + Uri.parse('${Environment.apiUrl}createOrUpdateEmployeePolicySiAmount'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> sendAddOnToAPI( + Map formData) async { + print('sendAddOnToAPI API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = Uri.parse('${Environment.apiUrl}iAgreeForAddOn'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formData); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> topUpSiCalculationToAPI(formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = Uri.parse('${Environment.apiUrl}calculatePremium'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> topUpParentSiCalculationToAPI( + formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = Uri.parse('${Environment.apiUrl}calculatePremium'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + Future> addOnsDependentCalculationToAPI( + formDataList) async { + print('saveAddOnsDetailsToApi API SERVICE'); + if (_token == null) { + await _initializeToken(); + } + + final url = Uri.parse('${Environment.apiUrl}calculatePremium'); + final headers = { + 'Authorization': _token ?? '', + 'Content-Type': 'application/json', // Ensure content type is JSON + }; + + // Convert formDataList to JSON string + final formDataJson = jsonEncode(formDataList); + + // Send formDataJson as the body + final response = await _makePostRequest(url, formDataJson, headers); + return response; + } + + //HR API STARTS + + Future> getCashDepositDetailsToApi( + String clintID, String empRefId) async { + print(_hrtoken); + if (_hrtoken == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getCashDepositData?client_id=$clintID&client_branch_id=$empRefId'); + final headers = { + 'Authorization': _hrtoken ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + Future> getEmployeeAndDependenceToApi( + String clintID, String getPolicyNo, String empRefId) async { + print(_hrtoken); + if (_hrtoken == null) { + await _initializeToken(); + } + final url = Uri.parse( + '${Environment.apiUrl}getEmployeeAndDependenceByClientId?client_id=$clintID&client_policy_id=$getPolicyNo&client_branch_id=$empRefId'); + final headers = { + 'Authorization': _hrtoken ?? '', + }; + final response = await _makeGetRequest(url, headers); + return response; + } + + // Future> getTrackClaimsList( + // String empMobileNo, String empCode) async { + // final url = Uri.parse( + // '${Environment.apiUrlTicket}/ticket/get_ticket_data?emp_code=$empCode&mobile_number=$empMobileNo'); + // final response = await _makeGetRequest(url, { + // 'Token': Environment.ticketToken, + // }); + // return response; + // } + // + // Future> fetchDepartmentList() async { + // final url = Uri.parse('${Environment.apiUrlTicket}/departments'); + // final response = await _makeGetRequest(url, { + // 'Token': Environment.ticketToken, + // }); + // return response; + // } + // + // Future> sendFormDataToApi( + // Map formData) async { + // final url = Uri.parse('${Environment.apiUrlTicket}/tickets/create'); + // // Convert formData to Map + // Map stringFormData = + // formData.map((key, value) => MapEntry(key, value.toString())); + // final response = await _makePostRequest(url, stringFormData, { + // 'Content-Type': 'application/x-www-form-urlencoded', + // 'Token': Environment.ticketToken, + // }); + // return response; + // } + // + // Future> sendClaimsMessageToApi( + // Map formData) async { + // final url = Uri.parse('${Environment.apiUrlTicket}/messages/create'); + // // Convert formData to Map + // Map stringFormData = + // formData.map((key, value) => MapEntry(key, value.toString())); + // final response = await _makePostRequest(url, stringFormData, { + // 'Content-Type': 'application/x-www-form-urlencoded', + // 'Token': Environment.ticketToken, + // }); + // return response; + // } + + Future> _makeGetRequest( + Uri url, Map headers) async { + final response = await http.get(url, headers: headers); + return _handleResponse(response); + } + + Future> _makePostRequest( + Uri url, String body, Map headers) async { + final response = await http.post(url, headers: headers, body: body); + return _handleResponse(response); + } + + Future> _handleResponse(http.Response response) async { + if (response.statusCode == 200) { + return jsonDecode(response.body); + } else if (response.statusCode == 401) { + if (!_isSessionOutToastShown) { + _isSessionOutToastShown = true; + await _clearLocalStorageAndRedirect(); + } + return {}; + } else { + throw Exception('Failed to load data'); + } + } + + Future _clearLocalStorageAndRedirect() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.clear(); + // Assuming you have access to the context + ToastHelper.showErrorToast(context, 'Session Out'); + Navigator.pushNamed(context, 'phone'); + } +} diff --git a/lib/verify.dart b/lib/verify.dart index 3e709b3..6d3cbbb 100644 --- a/lib/verify.dart +++ b/lib/verify.dart @@ -32,6 +32,7 @@ class _MyVerifyState extends State { dynamic _token; dynamic clientName; dynamic clientLogo; + dynamic empClientBranchId; @override void initState() { @@ -131,6 +132,8 @@ class _MyVerifyState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(data['data']); print(decodedToken); + empClientBranchId = decodedToken['client_branch_id']; + prefs.setString('empClientBranchId', empClientBranchId); empCodeString = decodedToken['emp_code'].toString(); prefs.setString('empCode', empCodeString); empPrimaryId = decodedToken['id']; @@ -139,6 +142,7 @@ class _MyVerifyState extends State { prefs.setString('gpaEmpName', gpaEmpName); client_id = decodedToken['client_id']; prefs.setString('client_id', client_id); + getClientLogoAndDetails(); print('Successfully Login'); @@ -177,7 +181,7 @@ class _MyVerifyState extends State { Future getClientLogoAndDetails() async { var url = Uri.parse(Environment.apiUrl + - 'getClientDetails?client_id=$client_id&emp_code=$empCodeString'); + 'getClientDetails?client_id=$client_id&emp_code=$empCodeString&client_branch_id=$empClientBranchId'); try { var response = await http.get( url,