From 9a3367e802cdc19f6065ce2cca607467bdd012dd Mon Sep 17 00:00:00 2001 From: SurendarSuri30 Date: Thu, 26 Mar 2026 09:45:12 +0530 Subject: [PATCH] log clear --- lib/addons.dart | 411 ++++----- lib/branch/branch_card_widget.dart | 9 +- lib/branch/branch_selection_page.dart | 44 +- lib/config/environment.dart | 5 +- lib/config/main_dev.dart | 2 - lib/config/main_prod.dart | 3 - lib/config/main_prod1.dart | 3 - lib/config/main_uat.dart | 3 - lib/customAppBar/base_layout.dart | 33 +- lib/customAppBar/customAppBar.dart | 6 +- lib/customAppBar/enrollmentAppBar.dart | 7 +- lib/customAppBar/side_bar.dart | 57 +- lib/customAppBar/toastHelper.dart | 53 +- lib/customAppBar/top_app_bar.dart | 85 +- lib/email_verify.dart | 187 ++-- lib/empDetails.dart | 180 ++-- lib/empReview.dart | 171 ++-- lib/home.dart | 193 +++-- lib/hrHome.dart | 79 +- lib/hrLogin.dart | 161 ++-- lib/hrVerify.dart | 28 +- lib/logger.dart | 111 +++ lib/main.dart | 123 ++- lib/oldPolicy.dart | 23 +- lib/phone.dart | 14 +- lib/presentation/RaiseClaimForm.dart | 799 +++++++++--------- lib/presentation/cdList.dart | 145 ++-- lib/presentation/cdTransactionDetails.dart | 443 +++++----- lib/presentation/claims.dart | 657 +++++++------- lib/presentation/claimshistory.dart | 77 +- lib/presentation/excelVerification.dart | 388 +++++---- lib/presentation/hrDashboard.dart | 113 ++- lib/presentation/hrPolicyDetails.dart | 586 ++++++------- lib/presentation/policies.dart | 628 +++++++------- lib/presentation/postFileUpload.dart | 450 +++++----- lib/presentation/preFileUpload.dart | 231 ++--- lib/service/_ResponsiveGridConfig.dart | 6 +- lib/service/api_service.dart | 210 ++--- lib/service/file_upload_service.dart | 6 +- .../hrDashboardTabs/activePolicies.dart | 44 +- lib/service/hrDashboardTabs/cd.dart | 40 +- .../hrDashboardTabs/preEnrollment.dart | 42 +- lib/service/multi_file_upload_widget.dart | 12 +- lib/service/secure_pop_scope.dart | 34 +- lib/service/svg_service.dart | 1 - lib/service/token_storage_service.dart | 63 +- lib/verify.dart | 50 +- 47 files changed, 3600 insertions(+), 3416 deletions(-) create mode 100644 lib/logger.dart diff --git a/lib/addons.dart b/lib/addons.dart index 7b6e60f..1b566bc 100755 --- a/lib/addons.dart +++ b/lib/addons.dart @@ -15,6 +15,7 @@ import 'package:intl/intl.dart'; import 'package:url_launcher/url_launcher.dart'; import 'customAppBar/customFooter.dart'; +import 'package:nhancepolicy/logger.dart'; class addOnsDetails extends StatefulWidget { const addOnsDetails({Key? key}) : super(key: key); @@ -171,17 +172,17 @@ class _addOnsDetailsState extends State { }); // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); - print(decodedToken); + logDebug(decodedToken); selfEmpStatus = prefs.getString('selfEmpStatus'); empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); - print(empCodeString); // Check if emp_code is correct + logDebug(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); gpaEmpName = prefs.getString('gpaEmpName'); client_id = prefs.getString('client_id'); - print(client_id); + logDebug(client_id); - // print(empPrimaryId); + // logDebug(empPrimaryId); // Call the API when the page enters if (prefs.containsKey('clientLogo') && prefs.containsKey('clientName')) { clientLogo = prefs.getString('clientLogo'); @@ -212,30 +213,30 @@ class _addOnsDetailsState extends State { } final response = await apiService.getClientLogoAndDetailsToApi( client_id!, empCodeString!, empClientBranchId!); - print('check 1'); + logDebug('check 1'); if (response['status'] == 'success') { if (response.containsKey('data')) { dynamic clientDetails = response['data']; - print(clientDetails); + logDebug(clientDetails); clientName = clientDetails['client']['client_name']; - print(clientName); + logDebug(clientName); clientLogo = clientDetails['client']['client_logo']; - print(clientLogo); + logDebug(clientLogo); } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -263,7 +264,7 @@ class _addOnsDetailsState extends State { if (response['status'] == 'success') { setState(() { gpaPolicies = response['data']; - print('gpaPolicies'); + logDebug('gpaPolicies'); }); } else { setState(() { @@ -271,11 +272,11 @@ class _addOnsDetailsState extends State { }); // Handle other status codes ToastHelper.showWarningToast(context, 'Something went wrong'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -302,10 +303,10 @@ class _addOnsDetailsState extends State { if (response['status'] == 'success') { // setState(() { gmcPolicies = response['data']; - print('gmcPolicies'); + logDebug('gmcPolicies'); // }); // Assuming data is a List - print(gmcPolicies); + logDebug(gmcPolicies); } else { setState(() { gmcDataIsEmpty = 0; @@ -313,11 +314,11 @@ class _addOnsDetailsState extends State { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -334,8 +335,8 @@ class _addOnsDetailsState extends State { if (response.containsKey('data')) { setState(() { topUpSiPolicies = response['data']; - print('topUpSiPolicies'); - print(topUpSiPolicies); + logDebug('topUpSiPolicies'); + logDebug(topUpSiPolicies); }); if (topUpSiPolicies.isNotEmpty) { // setState(() { @@ -343,8 +344,8 @@ class _addOnsDetailsState extends State { await topUpSiPolicies['gmc_si_topup']['client_policy_id']; topUpSlabRates = await topUpSiPolicies['gmc_si_topup']['SlabRates']; - print('topUpSlabRates'); - print(topUpSlabRates); + logDebug('topUpSlabRates'); + logDebug(topUpSlabRates); topUpPolicyName = await topUpSiPolicies['gmc_si_topup']['policy_name']; @@ -353,22 +354,22 @@ class _addOnsDetailsState extends State { topUpFamilyFloater = await topUpSiPolicies['gmc_si_topup'] ['policy_terms']['family_floater']; - print('topUpFamilyFloater'); - print(topUpFamilyFloater); + logDebug('topUpFamilyFloater'); + logDebug(topUpFamilyFloater); topUpMappedFamilyFloatersSi = await topUpSiPolicies['gmc_si_topup'] ['family_floaters_of_only_si_array']; - print('topUpMappedFamilyFloatersSi'); - print(topUpMappedFamilyFloatersSi); + logDebug('topUpMappedFamilyFloatersSi'); + logDebug(topUpMappedFamilyFloatersSi); - print('topUpECardDownload'); + logDebug('topUpECardDownload'); topUpECardDownload = topUpSiPolicies['gmc_si_topup']['eCardDownload']; - print(topUpECardDownload); + logDebug(topUpECardDownload); String intOpenForEnrollment = topUpSiPolicies['gmc_si_topup']['OpenForEnrollment']; topUpOpenForEnrollment = int.parse(intOpenForEnrollment); - print(topUpOpenForEnrollment); + logDebug(topUpOpenForEnrollment); topUpTypeName = topUpSiPolicies['gmc_si_topup']['type']; @@ -377,7 +378,7 @@ class _addOnsDetailsState extends State { topUpSiSelectedSI = topUpSiValue != 0 ? topUpSiValue.toString() : null; if (topUpSiSelectedSI != null) { - print('topUpSiSelectedSI'); + logDebug('topUpSiSelectedSI'); setState(() { _topUpSiSwitcher = true; topUpSiPremiumValue = (topUpSiPolicies['gmc_si_topup'] @@ -395,23 +396,23 @@ class _addOnsDetailsState extends State { } else { // ToastHelper.showErrorToast( // context, 'No data found in the response'); - print('No data found in the response'); + logDebug('No data found in the response'); } } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -428,8 +429,8 @@ class _addOnsDetailsState extends State { if (response.containsKey('data')) { setState(() { topUpSiParentPolicies = response['data']; - print('topUpSiParentPolicies'); - print(topUpSiParentPolicies); + logDebug('topUpSiParentPolicies'); + logDebug(topUpSiParentPolicies); }); if (topUpSiParentPolicies.isNotEmpty) { // setState(() { @@ -439,8 +440,8 @@ class _addOnsDetailsState extends State { topUpParentSlabRates = await topUpSiParentPolicies['gmc_si_parent_topup']['SlabRates']; - print('topUpParentSlabRates'); - print(topUpParentSlabRates); + logDebug('topUpParentSlabRates'); + logDebug(topUpParentSlabRates); topUpParentPolicyName = await topUpSiParentPolicies['gmc_si_parent_topup'] @@ -452,24 +453,24 @@ class _addOnsDetailsState extends State { topUpParentFamilyFloater = await topUpSiParentPolicies['gmc_si_parent_topup'] ['policy_terms']['family_floater']; - print('topUpParentFamilyFloater'); - print(topUpParentFamilyFloater); + logDebug('topUpParentFamilyFloater'); + logDebug(topUpParentFamilyFloater); topUpParentMappedFamilyFloatersSi = await topUpSiParentPolicies['gmc_si_parent_topup'] ['family_floaters_of_only_si_array']; - print('topUpParentMappedFamilyFloatersSi'); - print(topUpParentMappedFamilyFloatersSi); + logDebug('topUpParentMappedFamilyFloatersSi'); + logDebug(topUpParentMappedFamilyFloatersSi); - print('topUpECardDownload'); + logDebug('topUpECardDownload'); topUpParentECardDownload = topUpSiParentPolicies['gmc_si_parent_topup']['eCardDownload']; - print(topUpParentECardDownload); + logDebug(topUpParentECardDownload); String intOpenForEnrollment = topUpSiParentPolicies['gmc_si_parent_topup'] ['OpenForEnrollment']; topUpParentOpenForEnrollment = int.parse(intOpenForEnrollment); - print(topUpParentOpenForEnrollment); + logDebug(topUpParentOpenForEnrollment); topUpParentTypeName = topUpSiParentPolicies['gmc_si_parent_topup']['type']; @@ -480,7 +481,7 @@ class _addOnsDetailsState extends State { topUpParentSiSelectedSI = topUpParentSiValue != 0 ? topUpParentSiValue.toString() : null; if (topUpParentSiSelectedSI != null) { - print('topUpParentSiSelectedSI'); + logDebug('topUpParentSiSelectedSI'); setState(() { _topUpParentSiSwitcher = true; topUpParentSiPremiumValue = @@ -502,23 +503,23 @@ class _addOnsDetailsState extends State { } else { // ToastHelper.showErrorToast( // context, 'No data found in the response'); - print('No data found in the response'); + logDebug('No data found in the response'); } } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -535,8 +536,8 @@ class _addOnsDetailsState extends State { if (response.containsKey('data')) { setState(() { addOnsDependentPolicies = response['data']; - print('addOnsDependentPolicies'); - print(addOnsDependentPolicies); + logDebug('addOnsDependentPolicies'); + logDebug(addOnsDependentPolicies); }); if (addOnsDependentPolicies.isNotEmpty) { // setState(() { @@ -547,7 +548,7 @@ class _addOnsDetailsState extends State { addOnsDependentSlabRates = await addOnsDependentPolicies['gmc_dependent_addon'] ['SlabRates']; - print(addOnsDependentSlabRates); + logDebug(addOnsDependentSlabRates); addOnsDependentPolicyName = await addOnsDependentPolicies['gmc_dependent_addon'] @@ -559,15 +560,15 @@ class _addOnsDetailsState extends State { addOnsDependentFamilyFloater = await addOnsDependentPolicies['gmc_dependent_addon'] ['policy_terms']['family_floater']; - print('addOnsDependentFamilyFloater'); - print(addOnsDependentFamilyFloater); + logDebug('addOnsDependentFamilyFloater'); + logDebug(addOnsDependentFamilyFloater); setState(() { addOnsDependentMappedFamilyFloatersDependent = addOnsDependentPolicies['gmc_dependent_addon'] ['family_floaters_of_dependent_and_si_array']; - print('addOnsDependentMappedFamilyFloatersDependent'); - print(addOnsDependentMappedFamilyFloatersDependent); + logDebug('addOnsDependentMappedFamilyFloatersDependent'); + logDebug(addOnsDependentMappedFamilyFloatersDependent); }); addOnsdependentValue = @@ -599,8 +600,8 @@ class _addOnsDetailsState extends State { addOnsDependentECardDownload = addOnsDependentPolicies['gmc_dependent_addon'] ['eCardDownload']; - print('addOnsDependentECardDownload'); - print(addOnsDependentECardDownload); + logDebug('addOnsDependentECardDownload'); + logDebug(addOnsDependentECardDownload); String intOpenForEnrollment = addOnsDependentPolicies['gmc_dependent_addon'] @@ -616,23 +617,23 @@ class _addOnsDetailsState extends State { } else { // ToastHelper.showErrorToast( // context, 'No data found in the response'); - print('No data found in the response'); + logDebug('No data found in the response'); } } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -663,29 +664,29 @@ class _addOnsDetailsState extends State { } catch (error) { // ToastHelper.showErrorToast( // context, 'Error fetching relationship list: $error'); - print('Error fetching relationship list: $error'); + logDebug('Error fetching relationship list: $error'); // Handle error accordingly, e.g., show a snackbar with an error message } } Future _selectDate(BuildContext context, formType) async { - print(formType); + logDebug(formType); var ageValidation = formType['age_validation']; int min = int.parse(ageValidation['min']); // Parsing the string to an integer int max = int.parse(ageValidation['max']); // Parsing the string to an integer - print(min); - print(max); + logDebug(min); + logDebug(max); late DateTime minDate; late DateTime maxDate; final DateTime now = DateTime.now(); maxDate = DateTime(now.year - min, now.month, now.day); - print(maxDate); + logDebug(maxDate); minDate = DateTime(now.year - max, now.month, now.day); - print(minDate); + logDebug(minDate); // if (formType == 'child') { // // For 'child' form type, allow 0-25 age @@ -723,7 +724,7 @@ class _addOnsDetailsState extends State { } Future deleteItem(Map deletedItem) async { - print(deletedItem); + logDebug(deletedItem); try { var id = deletedItem['employee_id']; final response = await apiService.deleteItemToApi(id); @@ -743,23 +744,23 @@ class _addOnsDetailsState extends State { getGmcSiParentTopUp(); getGmcDependentAddOns(); ToastHelper.showSuccessToast(context, 'Item deleted successfully'); - print('Item deleted successfully'); + logDebug('Item deleted successfully'); } else { // Handle errors ToastHelper.showErrorToast(context, 'Failed to delete item'); } } catch (error) { // Handle network errors - print('Error deleting item: $error'); + logDebug('Error deleting item: $error'); } } void saveAddOnsDetails(Map formData, Map floatedData, action) async { // Construct the array of objects - print(formData); - print(floatedData); - print(action); + logDebug(formData); + logDebug(floatedData); + logDebug(action); formDataList.add({ 'relationship': formData['relationship'], 'name': formData['memberName'], @@ -796,11 +797,11 @@ class _addOnsDetailsState extends State { getGmcSiParentTopUp(); getGmcDependentAddOns(); ToastHelper.showSuccessToast(context, 'Saved Successfully...'); - print('Form data sent successfully.'); + logDebug('Form data sent successfully.'); } else { // Request failed, handle error ToastHelper.showErrorToast(context, 'Failed'); - print('Failed to send form data. Error: ${response}'); + logDebug('Failed to send form data. Error: ${response}'); } } @@ -813,31 +814,31 @@ class _addOnsDetailsState extends State { } void sendAddonsGmcDependentToAPI() async { - print(_addOnsDependentSwitcher); - print('continue'); - print(addOnsSelectedDependent); + logDebug(_addOnsDependentSwitcher); + logDebug('continue'); + logDebug(addOnsSelectedDependent); if (_addOnsDependentSwitcher == true) { if (addOnsSelectedDependent == null || addOnsSelectedDependent.isEmpty) { return; // Return if addOnsSelectedDependent is null or empty } else { - print('createOrUpdateEmployeePolicySiAmount'); + logDebug('createOrUpdateEmployeePolicySiAmount'); try { dynamic getTrueObjects = addOnsDependentMappedFamilyFloatersDependent .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); List> getTrueDataObjects = getTrueObjects .map>( (element) => element['data'] as Map) .toList(); - print(getTrueDataObjects); + logDebug(getTrueDataObjects); List> selectedValues = []; // try { - print('fff'); + logDebug('fff'); if (getTrueDataObjects != null || getTrueDataObjects.isNotEmpty) { for (var floater in getTrueDataObjects) { String employee_id = floater['employee_id']; @@ -856,7 +857,7 @@ class _addOnsDetailsState extends State { // Add the map to the list selectedValues.add(floaterData); } - print(selectedValues); + logDebug(selectedValues); } // Iterate through familyMembers list and send each member's data to the API @@ -872,15 +873,15 @@ class _addOnsDetailsState extends State { _dobController.clear(); // Navigator.pushNamed(context, 'empReviewDetails'); // ToastHelper.showSuccessToast(context, 'Saved successfully!'); - print('Saved successfully!'); + logDebug('Saved successfully!'); } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); ToastHelper.showErrorToast(context, 'Failed to save'); - print('Operation Failed!'); + logDebug('Operation Failed!'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } @@ -890,32 +891,32 @@ class _addOnsDetailsState extends State { } void sendAddonsGmcSiToAPI() async { - print(_topUpSiSwitcher); - print('continue'); - print(topUpSiSelectedSI); + logDebug(_topUpSiSwitcher); + logDebug('continue'); + logDebug(topUpSiSelectedSI); if (_topUpSiSwitcher == true) { if (topUpSiSelectedSI == null || topUpSiSelectedSI.isEmpty) { - print('topUpSiSelectedSI'); + logDebug('topUpSiSelectedSI'); return; // Return if addOnsSelectedDependent is null or empty } else { - print('createOrUpdateEmployeePolicySiAmount'); + logDebug('createOrUpdateEmployeePolicySiAmount'); try { dynamic getTrueObjects = topUpMappedFamilyFloatersSi .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); List> getTrueDataObjects = getTrueObjects .map>( (element) => element['data'] as Map) .toList(); - print(getTrueDataObjects); + logDebug(getTrueDataObjects); List> selectedValues = []; // try { - print('fff'); + logDebug('fff'); if (getTrueDataObjects != null || getTrueDataObjects.isNotEmpty) { for (var floater in getTrueDataObjects) { String employee_id = floater['employee_id']; @@ -934,7 +935,7 @@ class _addOnsDetailsState extends State { // Add the map to the list selectedValues.add(floaterData); } - print(selectedValues); + logDebug(selectedValues); } final response = @@ -949,15 +950,15 @@ class _addOnsDetailsState extends State { _dobController.clear(); // Navigator.pushNamed(context, 'empReviewDetails'); // ToastHelper.showSuccessToast(context, 'Saved successfully!'); - print('Saved successfully!'); + logDebug('Saved successfully!'); } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); // ToastHelper.showSuccessToast(context, 'Failed to Save...'); - print('Failed to Save...'); + logDebug('Failed to Save...'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } @@ -967,32 +968,32 @@ class _addOnsDetailsState extends State { } void sendAddonsGmcParentSiToAPI() async { - print(_topUpParentSiSwitcher); - print('continue'); - print(topUpParentSiSelectedSI); + logDebug(_topUpParentSiSwitcher); + logDebug('continue'); + logDebug(topUpParentSiSelectedSI); if (_topUpParentSiSwitcher == true) { if (topUpParentSiSelectedSI == null || topUpParentSiSelectedSI.isEmpty) { - print('topUpSiSelectedSI'); + logDebug('topUpSiSelectedSI'); return; // Return if addOnsSelectedDependent is null or empty } else { - print('createOrUpdateEmployeePolicySiAmount'); + logDebug('createOrUpdateEmployeePolicySiAmount'); try { dynamic getTrueObjects = topUpParentMappedFamilyFloatersSi .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); List> getTrueDataObjects = getTrueObjects .map>( (element) => element['data'] as Map) .toList(); - print(getTrueDataObjects); + logDebug(getTrueDataObjects); List> selectedValues = []; // try { - print('fff'); + logDebug('fff'); if (getTrueDataObjects != null || getTrueDataObjects.isNotEmpty) { for (var floater in getTrueDataObjects) { String employee_id = floater['employee_id']; @@ -1011,7 +1012,7 @@ class _addOnsDetailsState extends State { // Add the map to the list selectedValues.add(floaterData); } - print(selectedValues); + logDebug(selectedValues); } final response = @@ -1026,15 +1027,15 @@ class _addOnsDetailsState extends State { _dobController.clear(); // Navigator.pushNamed(context, 'empReviewDetails'); // ToastHelper.showSuccessToast(context, 'Saved successfully!'); - print('Saved successfully!'); + logDebug('Saved successfully!'); } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); // ToastHelper.showSuccessToast(context, 'Failed to Save...'); - print('Failed to Save...'); + logDebug('Failed to Save...'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } @@ -1051,16 +1052,16 @@ class _addOnsDetailsState extends State { final response = await apiService.removeAddonsGmcDependentToAPI( empCodeString!, addOnsDependentClientPolicyId!); if (response['status'] == 'success') { - print(response['data']); + logDebug(response['data']); } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -1072,16 +1073,16 @@ class _addOnsDetailsState extends State { final response = await apiService.removeAddonsGmcSiToAPI( empCodeString!, topUpClientPolicyId!); if (response['status'] == 'success') { - print(response['data']); + logDebug(response['data']); } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -1093,16 +1094,16 @@ class _addOnsDetailsState extends State { final response = await apiService.removeAddonsGmcParentSiToAPI( empCodeString!, topUpParentClientPolicyId!); if (response['status'] == 'success') { - print(response['data']); + logDebug(response['data']); } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -1132,7 +1133,7 @@ class _addOnsDetailsState extends State { void topUpSiCalculation(choosedSiValue) async { try { - print(choosedSiValue); + logDebug(choosedSiValue); var calculation = { 'client_policy_id': topUpClientPolicyId, @@ -1141,13 +1142,13 @@ class _addOnsDetailsState extends State { 'client_branch_id': empClientBranchId }; - print(calculation); + logDebug(calculation); // Iterate through familyMembers list and send each member's data to the API final response = await apiService.topUpSiCalculationToAPI(calculation); if (response['status'] == 'success') { - print(response); + logDebug(response); List? topUpEmpArray; for (var item in response['data']) { if (item.containsKey(empCodeString)) { @@ -1157,8 +1158,8 @@ class _addOnsDetailsState extends State { } if (topUpEmpArray != null) { - print('Array for emp_code $empCodeString:'); - print(topUpEmpArray); + logDebug('Array for emp_code $empCodeString:'); + logDebug(topUpEmpArray); double topUpRataPremimumSum = 0; for (var item in topUpEmpArray) { var topUpRataPremimum = item['policy_details']['rata_premimum']; @@ -1166,7 +1167,7 @@ class _addOnsDetailsState extends State { topUpRataPremimumSum += topUpRataPremimum; } } - print('Sum of rata_premimum: $topUpRataPremimumSum'); + logDebug('Sum of rata_premimum: $topUpRataPremimumSum'); double topUpGstSum = 0; for (var item in topUpEmpArray) { @@ -1175,32 +1176,32 @@ class _addOnsDetailsState extends State { topUpGstSum += topUpGst; } } - print('Sum of gst: $topUpGstSum'); + logDebug('Sum of gst: $topUpGstSum'); setState(() { topUpSiPremiumValue = (topUpRataPremimumSum as double).toInt(); - print(topUpSiPremiumValue); + logDebug(topUpSiPremiumValue); topUpSiPremiumGst = (topUpGstSum as double).toInt(); - print(topUpSiPremiumGst); + logDebug(topUpSiPremiumGst); topUpSiTotalAmt = topUpSiPremiumValue + topUpSiPremiumGst; - print(topUpSiTotalAmt); + logDebug(topUpSiTotalAmt); }); sendAddonsGmcSiToAPI(); } else { - print('Array not found for emp_code $empCodeString'); + logDebug('Array not found for emp_code $empCodeString'); } } else { - print('Operation Failed!'); + logDebug('Operation Failed!'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } void topUpParentSiCalculation(choosedSiValue) async { try { - print(choosedSiValue); + logDebug(choosedSiValue); var calculation = { 'client_policy_id': topUpParentClientPolicyId, @@ -1209,14 +1210,14 @@ class _addOnsDetailsState extends State { 'client_branch_id': empClientBranchId }; - print(calculation); + logDebug(calculation); // Iterate through familyMembers list and send each member's data to the API final response = await apiService.topUpParentSiCalculationToAPI(calculation); if (response['status'] == 'success') { - print(response['data']); + logDebug(response['data']); List? topUpEmpArray; for (var item in response['data']) { if (item.containsKey(empCodeString)) { @@ -1226,8 +1227,8 @@ class _addOnsDetailsState extends State { } if (topUpEmpArray != null) { - print('Array for emp_code $empCodeString:'); - print(topUpEmpArray); + logDebug('Array for emp_code $empCodeString:'); + logDebug(topUpEmpArray); double topUpRataPremimumSum = 0; for (var item in topUpEmpArray) { var topUpRataPremimum = item['policy_details']['rata_premimum']; @@ -1235,7 +1236,7 @@ class _addOnsDetailsState extends State { topUpRataPremimumSum += topUpRataPremimum; } } - print('Sum of rata_premimum: $topUpRataPremimumSum'); + logDebug('Sum of rata_premimum: $topUpRataPremimumSum'); double topUpGstSum = 0; for (var item in topUpEmpArray) { @@ -1244,33 +1245,33 @@ class _addOnsDetailsState extends State { topUpGstSum += topUpGst; } } - print('Sum of gst: $topUpGstSum'); + logDebug('Sum of gst: $topUpGstSum'); setState(() { topUpParentSiPremiumValue = (topUpRataPremimumSum as double).toInt(); - print(topUpParentSiPremiumValue); + logDebug(topUpParentSiPremiumValue); topUpParentSiPremiumGst = (topUpGstSum as double).toInt(); - print(topUpSiPremiumGst); + logDebug(topUpSiPremiumGst); topUpParentSiTotalAmt = topUpParentSiPremiumValue + topUpParentSiPremiumGst; - print(topUpParentSiTotalAmt); + logDebug(topUpParentSiTotalAmt); }); sendAddonsGmcParentSiToAPI(); } else { - print('Array not found for emp_code $empCodeString'); + logDebug('Array not found for emp_code $empCodeString'); } } else { - print('Operation Failed!'); + logDebug('Operation Failed!'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } void addOnsDependentCalculation(choosedDependentValue) async { try { - print(choosedDependentValue); + logDebug(choosedDependentValue); var calculation = { 'client_policy_id': addOnsDependentClientPolicyId, @@ -1279,14 +1280,14 @@ class _addOnsDetailsState extends State { 'client_branch_id': empClientBranchId }; - print(calculation); + logDebug(calculation); // Iterate through familyMembers list and send each member's data to the API final response = await apiService.addOnsDependentCalculationToAPI(calculation); if (response['status'] == 'success') { - print(response['data']); + logDebug(response['data']); List? addOnsEmpArray; for (var item in response['data']) { if (item.containsKey(empCodeString)) { @@ -1296,8 +1297,8 @@ class _addOnsDetailsState extends State { } if (addOnsEmpArray != null) { - print('Array for emp_code $empCodeString:'); - print(addOnsEmpArray); + logDebug('Array for emp_code $empCodeString:'); + logDebug(addOnsEmpArray); double addOnsRataPremimumSum = 0; for (var item in addOnsEmpArray) { var addOnsRataPremimum = item['policy_details']['rata_premimum']; @@ -1305,7 +1306,7 @@ class _addOnsDetailsState extends State { addOnsRataPremimumSum += addOnsRataPremimum; } } - print('Sum of rata_premimum: $addOnsRataPremimumSum'); + logDebug('Sum of rata_premimum: $addOnsRataPremimumSum'); double addOnsGstSum = 0; for (var item in addOnsEmpArray) { @@ -1314,25 +1315,25 @@ class _addOnsDetailsState extends State { addOnsGstSum += addOnsGst; } } - print('Sum of gst: $addOnsGstSum'); + logDebug('Sum of gst: $addOnsGstSum'); setState(() { addOnDependentPremiumValue = (addOnsRataPremimumSum as double).toInt(); - print(addOnDependentPremiumValue); + logDebug(addOnDependentPremiumValue); addOnsDependentPremiumGst = (addOnsGstSum as double).toInt(); - print(addOnsDependentPremiumGst); + logDebug(addOnsDependentPremiumGst); addOnsDependentTotalAmt = addOnDependentPremiumValue + addOnsDependentPremiumGst; - print(topUpSiTotalAmt); + logDebug(topUpSiTotalAmt); }); } else { - print('Array not found for emp_code $empCodeString'); + logDebug('Array not found for emp_code $empCodeString'); } } else { - print('Operation Failed!'); + logDebug('Operation Failed!'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } @@ -1341,12 +1342,12 @@ class _addOnsDetailsState extends State { setState(() { isLoading = true; }); - print('sendAddOnAPI'); + logDebug('sendAddOnAPI'); if (gpaDataIsEmpty != 0) { - print('gpaDataIsEmpty : $gpaDataIsEmpty'); + logDebug('gpaDataIsEmpty : $gpaDataIsEmpty'); for (var item in gpaPolicies) { - print('ClientPolicyId'); + logDebug('ClientPolicyId'); // Extract ClientPolicyId value from each object String clientPolicyId = item['ClientPolicyId']; // Convert to integer and add to iAgreeForAddOn list @@ -1363,9 +1364,9 @@ class _addOnsDetailsState extends State { } } - print('iAgreeForAddOn'); + logDebug('iAgreeForAddOn'); iAgreeForAddOn = iAgreeForAddOn.toSet().toList(); - print(iAgreeForAddOn); // Output: [90, 92, 88, 89] + logDebug(iAgreeForAddOn); // Output: [90, 92, 88, 89] Map apiParams = { 'emp_code': empCodeString, @@ -1385,7 +1386,7 @@ class _addOnsDetailsState extends State { isChecked = false; }); - print('response.statusCode == 200'); + logDebug('response.statusCode == 200'); ToastHelper.showSuccessToast(context, 'Saved Successfully...'); } else { setState(() { @@ -1393,14 +1394,14 @@ class _addOnsDetailsState extends State { }); // Handle other status codes ToastHelper.showErrorToast(context, 'failed to save'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -1408,8 +1409,8 @@ class _addOnsDetailsState extends State { final SharedPreferences prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('hrtoken')) { String? mobileNo = prefs.getString('fromHrLoginMobileNo'); - print('mobileNo'); - print(mobileNo); + logDebug('mobileNo'); + logDebug(mobileNo); Navigator.pushNamed(context, 'empDetails', arguments: {'mobile': mobileNo}); } else { @@ -1418,7 +1419,7 @@ class _addOnsDetailsState extends State { } void checkSiTopUp() async { - print('checkSiTopUp'); + logDebug('checkSiTopUp'); List> siData = [ { 'topUpSiPremiumValue': topUpSiPremiumValue, @@ -1431,7 +1432,7 @@ class _addOnsDetailsState extends State { } void checkSiParentTopUp() async { - print('checkSiParentTopUp'); + logDebug('checkSiParentTopUp'); List> siParentData = [ { 'topUpParentSiPremiumValue': topUpParentSiPremiumValue, @@ -1444,7 +1445,7 @@ class _addOnsDetailsState extends State { } void checkDependentTopUp() async { - print('checkDependentTopUp'); + logDebug('checkDependentTopUp'); List> dependentData = [ { 'addOnDependentPremiumValue': addOnDependentPremiumValue, @@ -1458,10 +1459,10 @@ class _addOnsDetailsState extends State { @override Widget build(BuildContext context) { - print('CVC'); - print('Check1: $topUpSiPolicies'); - print('CVC'); - print('Check2: $addOnsDependentPolicies'); + logDebug('CVC'); + logDebug('Check1: $topUpSiPolicies'); + logDebug('CVC'); + logDebug('Check2: $addOnsDependentPolicies'); if (gpaDataIsEmpty == 0 && gmcDataIsEmpty == 0) { return Scaffold( appBar: CustomAppBar(), @@ -3974,7 +3975,7 @@ class _addOnsDetailsState extends State { if (_topUpSiSwitcher == false) { removeAddonsGmcSiToAPI(); } else { - print('checkSiTopUp'); + logDebug('checkSiTopUp'); checkSiTopUp(); } @@ -3982,7 +3983,7 @@ class _addOnsDetailsState extends State { false) { removeAddonsGmcParentSiToAPI(); } else { - print('checkSiParentTopUp'); + logDebug('checkSiParentTopUp'); checkSiParentTopUp(); } @@ -3990,7 +3991,7 @@ class _addOnsDetailsState extends State { false) { removeAddonsGmcDependentToAPI(); } else { - print('checkDependentTopUp'); + logDebug('checkDependentTopUp'); checkDependentTopUp(); sendAddonsGmcDependentToAPI(); } @@ -4045,24 +4046,24 @@ class _addOnsDetailsState extends State { Future _launchURL(String url) async { final Uri uri = Uri.parse(url); // Parse the URL properly - print('_launchURL $uri'); + logDebug('_launchURL $uri'); if (uri != null) { - print('If $uri'); + logDebug('If $uri'); await launchUrl(uri, mode: LaunchMode.externalApplication); } else { - print('else $uri'); + logDebug('else $uri'); throw 'Could not launch $url'; } } void openForm(Map floaterData, action) { - print(action); - print(floaterData); - print(relationshipOptions); - print('test'); - print(_relationShipController); - print(_memberNameController); - print(_dobController); + logDebug(action); + logDebug(floaterData); + logDebug(relationshipOptions); + logDebug('test'); + logDebug(_relationShipController); + logDebug(_memberNameController); + logDebug(_dobController); dynamic popupName = floaterData['button_name']; // Check if the action is 'Edit' @@ -4072,32 +4073,32 @@ class _addOnsDetailsState extends State { ) .toList(); - print(selectedRelationships); - print(addOnsDependentMappedFamilyFloatersDependent); + logDebug(selectedRelationships); + logDebug(addOnsDependentMappedFamilyFloatersDependent); if (action == 'Add') { if (floaterData['form_type'] == 'parent_in_law' || floaterData['form_type'] == 'parent') { - print('Add'); + logDebug('Add'); // Filter the addOnsDependentMappedFamilyFloatersDependent list to get only the objects where is_value_exist is true dynamic getTrueObjects = addOnsDependentMappedFamilyFloatersDependent .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); List> getTrueDataObjects = getTrueObjects .map>( (element) => element['data'] as Map) .toList(); - print(getTrueDataObjects); + logDebug(getTrueDataObjects); selectedRelationships.removeWhere((relationship) => getTrueDataObjects.any((dataObject) => dataObject['relationship'] == relationship['relationship_name'])); - print(selectedRelationships); + logDebug(selectedRelationships); } } @@ -4376,24 +4377,24 @@ class _addOnsDetailsState extends State { dynamic getTrueObjects = gmcMappedFamilyFloaters .where((element) => element['is_value_exist'] == true) .toList(); - print('getTrueObjects'); - print(getTrueObjects); + logDebug('getTrueObjects'); + logDebug(getTrueObjects); if (getTrueObjects.length > 0) { - print('true'); + logDebug('true'); gmcSumInsured = gmcMappedFamilyFloaters[0]["data"]["basic_cover_si"]; } else { - print('false'); + logDebug('false'); gmcSumInsured = item['Policy_Terms']['sum_insured']; } gmcTypeName = item['type']; }); - print('forEach Card'); - print(gmcMappedFamilyFloaters); + logDebug('forEach Card'); + logDebug(gmcMappedFamilyFloaters); dynamic getTrueObjects = gmcMappedFamilyFloaters .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); Widget card = getTrueObjects.length > 0 ? Card( @@ -4559,8 +4560,8 @@ class _addOnsDetailsState extends State { List cards = []; for (var item in data) { - print('item'); - print(item); + logDebug('item'); + logDebug(item); String? gpaPolicyName = item['Policy_Name']; String? gpaECardDownload = item['eCardDownload']; diff --git a/lib/branch/branch_card_widget.dart b/lib/branch/branch_card_widget.dart index 1b3342f..7093659 100755 --- a/lib/branch/branch_card_widget.dart +++ b/lib/branch/branch_card_widget.dart @@ -26,7 +26,8 @@ class BranchCard extends StatelessWidget { child: Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: isSelected ? const Color(0xFF00999E) : const Color(0xFFF0F9F9), + color: + isSelected ? const Color(0xFF00999E) : const Color(0xFFF0F9F9), borderRadius: BorderRadius.circular(8), border: Border.all( color: const Color(0xFF00999E), @@ -44,8 +45,7 @@ class BranchCard extends StatelessWidget { style: GoogleFonts.poppins( fontSize: 13, fontWeight: FontWeight.w500, - color: - isSelected ? Colors.white : const Color(0xFF00999E), + color: isSelected ? Colors.white : const Color(0xFF00999E), ), ), const SizedBox(height: 4), @@ -55,8 +55,7 @@ class BranchCard extends StatelessWidget { overflow: TextOverflow.ellipsis, style: GoogleFonts.poppins( fontSize: 11, - color: - isSelected ? Colors.white70 : Colors.black87, + color: isSelected ? Colors.white70 : Colors.black87, ), ), ], diff --git a/lib/branch/branch_selection_page.dart b/lib/branch/branch_selection_page.dart index e1745e8..396b724 100755 --- a/lib/branch/branch_selection_page.dart +++ b/lib/branch/branch_selection_page.dart @@ -33,7 +33,7 @@ class _BranchSelectionPageState extends State { Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', - (route) => false, + (route) => false, ); } else { // Push state back to prevent browser navigation @@ -83,23 +83,23 @@ class _BranchSelectionPageState extends State { Future _showLogoutDialog() async { return await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => AlertDialog( - title: Text("Confirm Logout"), - content: Text("Do you want to logout?"), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: Text("Cancel"), + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + title: Text("Confirm Logout"), + content: Text("Do you want to logout?"), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text("Logout"), + ), + ], ), - TextButton( - onPressed: () => Navigator.of(context).pop(true), - child: Text("Logout"), - ), - ], - ), - ) ?? + ) ?? false; } @@ -112,7 +112,7 @@ class _BranchSelectionPageState extends State { ); } - Widget _buildContent(BuildContext context) { + Widget _buildContent(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFFF5F7F7), body: LayoutBuilder( @@ -164,8 +164,7 @@ class _BranchSelectionPageState extends State { shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: branches.length, - gridDelegate: - SliverGridDelegateWithFixedCrossAxisCount( + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: crossAxisCount, mainAxisExtent: 90, // 🔥 FIXED HEIGHT mainAxisSpacing: 15, @@ -176,8 +175,7 @@ class _BranchSelectionPageState extends State { return BranchCard( clientName: branch['client_name'] ?? 'Unknown Client kjbgjsk jsdhbjbf sdjfjbds fdjsgjdbs gdsjbgjds', - branchName: - branch['branch_name'] ?? 'Unknown Branch', + branchName: branch['branch_name'] ?? 'Unknown Branch', isSelected: selectedIndex == index, onTap: () => _selectBranch(index), ); @@ -218,5 +216,5 @@ class _BranchSelectionPageState extends State { }, ), ); - } + } } diff --git a/lib/config/environment.dart b/lib/config/environment.dart index a0fb58b..576671b 100755 --- a/lib/config/environment.dart +++ b/lib/config/environment.dart @@ -1,5 +1,5 @@ // lib/environment.dart -enum Flavor { dev, uat, prod, prod1} +enum Flavor { dev, uat, prod, prod1 } class Environment { static Flavor flavor = Flavor.dev; // overwritten by each main_*.dart @@ -44,6 +44,7 @@ class Environment { return "/"; } } + static String getPageTitle(String? routeName) { String base = "Nhance HR"; if (isProd) base = "Nhance HR"; // You can differentiate names if needed @@ -71,4 +72,4 @@ class Environment { return base; } } -} \ No newline at end of file +} diff --git a/lib/config/main_dev.dart b/lib/config/main_dev.dart index 19e2474..d0e58bf 100755 --- a/lib/config/main_dev.dart +++ b/lib/config/main_dev.dart @@ -1,4 +1,3 @@ - import '../main.dart'; import 'environment.dart'; @@ -6,4 +5,3 @@ Future main() async { Environment.flavor = Flavor.dev; await startApp(); } - diff --git a/lib/config/main_prod.dart b/lib/config/main_prod.dart index 44580d0..a4a6dac 100755 --- a/lib/config/main_prod.dart +++ b/lib/config/main_prod.dart @@ -1,5 +1,3 @@ - - import '../main.dart'; import 'environment.dart'; @@ -7,4 +5,3 @@ Future main() async { Environment.flavor = Flavor.prod; await startApp(); } - diff --git a/lib/config/main_prod1.dart b/lib/config/main_prod1.dart index f2eae0f..0409013 100755 --- a/lib/config/main_prod1.dart +++ b/lib/config/main_prod1.dart @@ -1,5 +1,3 @@ - - import '../main.dart'; import 'environment.dart'; @@ -7,4 +5,3 @@ Future main() async { Environment.flavor = Flavor.prod1; await startApp(); } - diff --git a/lib/config/main_uat.dart b/lib/config/main_uat.dart index 1d0484a..ff41fbb 100755 --- a/lib/config/main_uat.dart +++ b/lib/config/main_uat.dart @@ -1,5 +1,3 @@ - - import '../main.dart'; import 'environment.dart'; @@ -7,4 +5,3 @@ Future main() async { Environment.flavor = Flavor.uat; await startApp(); } - diff --git a/lib/customAppBar/base_layout.dart b/lib/customAppBar/base_layout.dart index 6143d21..8df45d8 100644 --- a/lib/customAppBar/base_layout.dart +++ b/lib/customAppBar/base_layout.dart @@ -15,23 +15,22 @@ class BaseLayout extends StatelessWidget { // 2. Use the Title widget to communicate with the browser's tab return Title( - title: Environment.getPageTitle(routeName), - color: const Color(0xFF00999E), // Required, usually matches your theme - child: Scaffold( - appBar: const NhanceTopBar(), - body: Row( - children: [ - const NhanceSideBar(), - Expanded( - child: Container( - color: const Color(0xFFF5F7F7), - padding: const EdgeInsets.all(16), - child: child, - ), + title: Environment.getPageTitle(routeName), + color: const Color(0xFF00999E), // Required, usually matches your theme + child: Scaffold( + appBar: const NhanceTopBar(), + body: Row( + children: [ + const NhanceSideBar(), + Expanded( + child: Container( + color: const Color(0xFFF5F7F7), + padding: const EdgeInsets.all(16), + child: child, + ), + ), + ], ), - ], - ), - ) ); + )); } } - diff --git a/lib/customAppBar/customAppBar.dart b/lib/customAppBar/customAppBar.dart index dab3841..c1848e6 100755 --- a/lib/customAppBar/customAppBar.dart +++ b/lib/customAppBar/customAppBar.dart @@ -7,6 +7,7 @@ import 'package:nhancepolicy/responsive.dart'; import '../service/api_service.dart'; import '../service/token_storage_service.dart'; +import 'package:nhancepolicy/logger.dart'; class CustomAppBar extends StatefulWidget implements PreferredSizeWidget { @override @@ -37,12 +38,11 @@ class _CustomAppBarState extends State { // final String? hrtoken = prefs.getString('_postToken'); // final String? token = prefs.getString('enrollToken'); // prefs.clear(); - print('LocalStorage Cleared'); + logDebug('LocalStorage Cleared'); apiService.logout(); // Navigator.pushNamed(context, 'hrLogin'); } - @override Widget build(BuildContext context) { final sw = MediaQuery.of(context).size.width; @@ -100,7 +100,7 @@ class _CustomAppBarState extends State { Navigator.pushNamedAndRemoveUntil( context, 'branchSelection', - (route) => false, + (route) => false, ); }, ), diff --git a/lib/customAppBar/enrollmentAppBar.dart b/lib/customAppBar/enrollmentAppBar.dart index b86df68..5f38747 100755 --- a/lib/customAppBar/enrollmentAppBar.dart +++ b/lib/customAppBar/enrollmentAppBar.dart @@ -4,6 +4,7 @@ import 'package:nhancepolicy/customAppBar/toastHelper.dart'; import 'package:nhancepolicy/responsive.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:nhancepolicy/responsive.dart'; +import 'package:nhancepolicy/logger.dart'; class CustomAppBar extends StatefulWidget implements PreferredSizeWidget { @override @@ -35,9 +36,9 @@ class _CustomAppBarState extends State { showBackToHR = prefs.getBool('showBackToHR')!; // showBackToHR = (hrtoken != null && hrtoken.isNotEmpty) && // (token != null && token.isNotEmpty); - // print((hrtoken != null && hrtoken.isNotEmpty)); - // print((token != null && token.isNotEmpty)); - // print('showBackToHR $showBackToHR'); + // logDebug((hrtoken != null && hrtoken.isNotEmpty)); + // logDebug((token != null && token.isNotEmpty)); + // logDebug('showBackToHR $showBackToHR'); // hideInactiveStatus = token != null && token.isNotEmpty; }); diff --git a/lib/customAppBar/side_bar.dart b/lib/customAppBar/side_bar.dart index 4bbcd1a..9c24620 100644 --- a/lib/customAppBar/side_bar.dart +++ b/lib/customAppBar/side_bar.dart @@ -5,6 +5,7 @@ import 'package:flutter_svg/svg.dart'; import 'package:nhancepolicy/service/api_service.dart'; import 'package:nhancepolicy/service/svg_service.dart'; import 'package:nhancepolicy/service/token_storage_service.dart'; +import 'package:nhancepolicy/logger.dart'; class NhanceSideBar extends StatefulWidget { const NhanceSideBar({super.key}); @@ -26,7 +27,6 @@ class _NhanceSideBarState extends State { List postModules = []; List enrollmentModules = []; - @override void initState() { super.initState(); @@ -35,31 +35,26 @@ class _NhanceSideBarState extends State { // _checkTokens(); } - - - Future _buildSideMenu() async { final enrollmentRaw = - await tokenService.readValue('enrollmentAllowed_modules'); // "[1]" + await tokenService.readValue('enrollmentAllowed_modules'); // "[1]" final postRaw = - await tokenService.readValue('empAllowed_modules'); // "[2,3,4]" + await tokenService.readValue('empAllowed_modules'); // "[2,3,4]" - print('enrollmentRaw $enrollmentRaw'); - print('postRaw $postRaw'); + logDebug('enrollmentRaw $enrollmentRaw'); + logDebug('postRaw $postRaw'); // ✅ Decode safely - enrollmentModules = - enrollmentRaw != null && enrollmentRaw.isNotEmpty + enrollmentModules = enrollmentRaw != null && enrollmentRaw.isNotEmpty ? List.from(jsonDecode(enrollmentRaw)) : []; - postModules = - postRaw != null && postRaw.isNotEmpty + postModules = postRaw != null && postRaw.isNotEmpty ? List.from(jsonDecode(postRaw)) : []; - print('enrollmentModules $enrollmentModules'); - print('postModules $postModules'); + logDebug('enrollmentModules $enrollmentModules'); + logDebug('postModules $postModules'); final List> items = []; @@ -95,13 +90,12 @@ class _NhanceSideBarState extends State { }); } - Future logout(BuildContext context) async { // final prefs = await SharedPreferences.getInstance(); // final String? hrtoken = prefs.getString('_postToken'); // final String? token = prefs.getString('enrollToken'); // prefs.clear(); - print('LocalStorage Cleared'); + logDebug('LocalStorage Cleared'); apiService.logout(); // Navigator.pushNamed(context, 'hrLogin'); } @@ -220,22 +214,22 @@ class _NhanceSideBarState extends State { ); }).toList(), - if(postModules.isNotEmpty && postModules.contains(5)) - _SideItem( - // icon: Icons.dashboard, - icon: SvgPicture.string( - SvgService.getSvg('dashboard'), - width: 35, - height: 35, - colorFilter: const ColorFilter.mode( - Colors.white, - BlendMode.srcIn, + if (postModules.isNotEmpty && postModules.contains(5)) + _SideItem( + // icon: Icons.dashboard, + icon: SvgPicture.string( + SvgService.getSvg('dashboard'), + width: 35, + height: 35, + colorFilter: const ColorFilter.mode( + Colors.white, + BlendMode.srcIn, + ), ), + label: "Insights", + isActive: activeRoute == 'hrDashboard', + onTap: () => _navigate('hrDashboard'), ), - label: "Insights", - isActive: activeRoute == 'hrDashboard', - onTap: () => _navigate('hrDashboard'), - ), const Spacer(), @@ -260,7 +254,6 @@ class _NhanceSideBarState extends State { } } - class _SideItem extends StatelessWidget { // final IconData icon; final Widget icon; // 👈 changed @@ -308,5 +301,3 @@ class _SideItem extends StatelessWidget { ); } } - - diff --git a/lib/customAppBar/toastHelper.dart b/lib/customAppBar/toastHelper.dart index 09accc7..1867a34 100755 --- a/lib/customAppBar/toastHelper.dart +++ b/lib/customAppBar/toastHelper.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; // import 'package:fluttertoast/fluttertoast.dart'; import 'package:toastification/toastification.dart'; +import 'package:nhancepolicy/logger.dart'; class ToastHelper { static void showSuccessToast(BuildContext context, String message) { @@ -10,8 +11,8 @@ class ToastHelper { style: ToastificationStyle.flatColored, autoCloseDuration: const Duration(seconds: 2), title: Text( - message, - maxLines: 3, // ✅ allow wrapping + message, + maxLines: 3, // ✅ allow wrapping overflow: TextOverflow.visible, softWrap: true, ), @@ -49,12 +50,12 @@ class ToastHelper { dragToClose: true, applyBlurEffect: true, callbacks: ToastificationCallbacks( - onTap: (toastItem) => print('Toast ${toastItem.id} tapped'), + onTap: (toastItem) => logDebug('Toast ${toastItem.id} tapped'), onCloseButtonTap: (toastItem) => - print('Toast ${toastItem.id} close button tapped'), + logDebug('Toast ${toastItem.id} close button tapped'), onAutoCompleteCompleted: (toastItem) => - print('Toast ${toastItem.id} auto complete completed'), - onDismissed: (toastItem) => print('Toast ${toastItem.id} dismissed'), + logDebug('Toast ${toastItem.id} auto complete completed'), + onDismissed: (toastItem) => logDebug('Toast ${toastItem.id} dismissed'), ), ); } @@ -100,12 +101,12 @@ class ToastHelper { dragToClose: true, applyBlurEffect: true, callbacks: ToastificationCallbacks( - onTap: (toastItem) => print('Toast ${toastItem.id} tapped'), + onTap: (toastItem) => logDebug('Toast ${toastItem.id} tapped'), onCloseButtonTap: (toastItem) => - print('Toast ${toastItem.id} close button tapped'), + logDebug('Toast ${toastItem.id} close button tapped'), onAutoCompleteCompleted: (toastItem) => - print('Toast ${toastItem.id} auto complete completed'), - onDismissed: (toastItem) => print('Toast ${toastItem.id} dismissed'), + logDebug('Toast ${toastItem.id} auto complete completed'), + onDismissed: (toastItem) => logDebug('Toast ${toastItem.id} dismissed'), ), ); } @@ -118,7 +119,7 @@ class ToastHelper { autoCloseDuration: const Duration(seconds: 2), title: Text( message, - maxLines: 3, // ✅ allow wrapping + maxLines: 3, // ✅ allow wrapping overflow: TextOverflow.visible, softWrap: true, ), @@ -156,18 +157,19 @@ class ToastHelper { dragToClose: true, applyBlurEffect: true, callbacks: ToastificationCallbacks( - onTap: (toastItem) => print('Toast ${toastItem.id} tapped'), + onTap: (toastItem) => logDebug('Toast ${toastItem.id} tapped'), onCloseButtonTap: (toastItem) => - print('Toast ${toastItem.id} close button tapped'), + logDebug('Toast ${toastItem.id} close button tapped'), onAutoCompleteCompleted: (toastItem) => - print('Toast ${toastItem.id} auto complete completed'), - onDismissed: (toastItem) => print('Toast ${toastItem.id} dismissed'), + logDebug('Toast ${toastItem.id} auto complete completed'), + onDismissed: (toastItem) => logDebug('Toast ${toastItem.id} dismissed'), ), ); // _showToast(context, message, Colors.red); } - static void showErrorToast2(BuildContext context, String message,String decmessage) { + static void showErrorToast2( + BuildContext context, String message, String decmessage) { toastification.show( context: context, type: ToastificationType.error, @@ -175,8 +177,7 @@ class ToastHelper { autoCloseDuration: const Duration(seconds: 2), title: Text(message), // you can also use RichText widget for title and description parameters - description: RichText( - text: TextSpan(text: decmessage)), + description: RichText(text: TextSpan(text: decmessage)), alignment: Alignment.topRight, direction: TextDirection.ltr, animationDuration: const Duration(milliseconds: 100), @@ -208,12 +209,12 @@ class ToastHelper { dragToClose: true, applyBlurEffect: true, callbacks: ToastificationCallbacks( - onTap: (toastItem) => print('Toast ${toastItem.id} tapped'), + onTap: (toastItem) => logDebug('Toast ${toastItem.id} tapped'), onCloseButtonTap: (toastItem) => - print('Toast ${toastItem.id} close button tapped'), + logDebug('Toast ${toastItem.id} close button tapped'), onAutoCompleteCompleted: (toastItem) => - print('Toast ${toastItem.id} auto complete completed'), - onDismissed: (toastItem) => print('Toast ${toastItem.id} dismissed'), + logDebug('Toast ${toastItem.id} auto complete completed'), + onDismissed: (toastItem) => logDebug('Toast ${toastItem.id} dismissed'), ), ); // _showToast(context, message, Colors.red); @@ -260,12 +261,12 @@ class ToastHelper { dragToClose: true, applyBlurEffect: true, callbacks: ToastificationCallbacks( - onTap: (toastItem) => print('Toast ${toastItem.id} tapped'), + onTap: (toastItem) => logDebug('Toast ${toastItem.id} tapped'), onCloseButtonTap: (toastItem) => - print('Toast ${toastItem.id} close button tapped'), + logDebug('Toast ${toastItem.id} close button tapped'), onAutoCompleteCompleted: (toastItem) => - print('Toast ${toastItem.id} auto complete completed'), - onDismissed: (toastItem) => print('Toast ${toastItem.id} dismissed'), + logDebug('Toast ${toastItem.id} auto complete completed'), + onDismissed: (toastItem) => logDebug('Toast ${toastItem.id} dismissed'), ), ); // _showToast(context, message, Colors.red); diff --git a/lib/customAppBar/top_app_bar.dart b/lib/customAppBar/top_app_bar.dart index cb57038..0ae9ec0 100644 --- a/lib/customAppBar/top_app_bar.dart +++ b/lib/customAppBar/top_app_bar.dart @@ -42,7 +42,6 @@ class _NhanceTopBarState extends State { Navigator.pushReplacementNamed(context, route); } - @override Widget build(BuildContext context) { return AppBar( @@ -53,7 +52,6 @@ class _NhanceTopBarState extends State { children: [ Image.asset('assets/nhance_client_logo.png', height: 36), const Spacer(), - if (selectedBranch != null) _BranchPopup( clientName: selectedBranch!['client_name'], @@ -66,6 +64,7 @@ class _NhanceTopBarState extends State { ); } } + class _BranchPopup extends StatelessWidget { final String clientName; final String branchName; @@ -85,7 +84,6 @@ class _BranchPopup extends StatelessWidget { tooltip: '', offset: const Offset(0, 48), onSelected: onSelected, - itemBuilder: (context) { return branches.map((branch) { return PopupMenuItem>( @@ -114,7 +112,6 @@ class _BranchPopup extends StatelessWidget { ); }).toList(); }, - child: Container( height: 40, padding: const EdgeInsets.symmetric(horizontal: 16), @@ -130,48 +127,48 @@ class _BranchPopup extends StatelessWidget { ], ), child: Row( - children: [ - // CLIENT NAME - Text( - clientName, - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.w500, + children: [ + // CLIENT NAME + Text( + clientName, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + ), + ), + + const SizedBox(width: 8), + + // 📍 BRANCH NAME (SELECTED) + Row( + children: [ + const Icon( + Icons.location_on, + size: 14, + color: Colors.grey, + ), + const SizedBox(width: 4), + Text( + branchName, + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + ], + ), + + const SizedBox(width: 6), + + // DROPDOWN ARROW + const Icon( + Icons.keyboard_arrow_down, + size: 20, + color: Colors.orange, + ), + ], ), ), - - const SizedBox(width: 8), - - // 📍 BRANCH NAME (SELECTED) - Row( - children: [ - const Icon( - Icons.location_on, - size: 14, - color: Colors.grey, - ), - const SizedBox(width: 4), - Text( - branchName, - style: const TextStyle( - fontSize: 12, - color: Colors.grey, - ), - ), - ], - ), - - const SizedBox(width: 6), - - // DROPDOWN ARROW - const Icon( - Icons.keyboard_arrow_down, - size: 20, - color: Colors.orange, - ), - ], - ), - ), ); } } diff --git a/lib/email_verify.dart b/lib/email_verify.dart index 812a16f..b8d68b5 100755 --- a/lib/email_verify.dart +++ b/lib/email_verify.dart @@ -19,6 +19,7 @@ import '../models/platform_helper_mobile.dart' if (dart.library.html) '../models/platform_helper_other.dart'; import 'branch/branch_selection_page.dart'; import 'config/environment.dart'; +import 'package:nhancepolicy/logger.dart'; // import 'dart:html' as html; @@ -101,13 +102,14 @@ class _MyEmailVerifyState extends State { void verifyOTP(String otp) async { try { final Map payload = (widget.type == 'mobile') - ? {'otp': _otpController.text,'mobile_no': widget.value} + ? {'otp': _otpController.text, 'mobile_no': widget.value} : {'otp': _otpController.text, 'email': widget.value}; final response = await http.post( Uri.parse(Environment.apiUrl + 'getVerifiedHrData'), body: json.encode(payload), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); @@ -117,14 +119,13 @@ class _MyEmailVerifyState extends State { _isLoading = false; }); Map data = json.decode(response.body); - print('Response data: $data'); + logDebug('Response data: $data'); final String mainStatus = data['status'] ?? 'failed'; final Map postEnrollment1 = data['post_enrollment'] ?? {}; - final String postStatus = - postEnrollment1['status'] ?? 'failed'; + final String postStatus = postEnrollment1['status'] ?? 'failed'; /// ❌ BLOCK if BOTH failed if (mainStatus != 'success' && postStatus != 'success') { @@ -197,13 +198,13 @@ class _MyEmailVerifyState extends State { ), ); } - // print('data: $data'); + // logDebug('data: $data'); // _token = data['data']; // String status = data['status']; // // // Directly access the post_enrollment data // Map post = data['post_enrollment']; - // print('post: $post'); + // logDebug('post: $post'); // // _postToken = post['data']; // String postStatus = post['status']; @@ -224,7 +225,7 @@ class _MyEmailVerifyState extends State { // }); // ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again'); // // Show a Snackbar if the OTP is invalid - // print('Invalid OTP. Please try again'); + // logDebug('Invalid OTP. Please try again'); // } } else if (response.statusCode == 401) { setState(() { @@ -237,9 +238,8 @@ class _MyEmailVerifyState extends State { Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', - (route) => false, + (route) => false, ); - } else if (response.statusCode == 403) { setState(() { _isLoading = false; @@ -251,21 +251,20 @@ class _MyEmailVerifyState extends State { Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', - (route) => false, + (route) => false, ); - } else if (response.statusCode == 451) { setState(() { _isLoading = false; }); - final body = jsonDecode(response.body); + final body = jsonDecode(response.body); final message = body['message']; ToastHelper.showWarningToast(context, message); } else if (response.statusCode == 429) { setState(() { _isLoading = false; }); - final body = jsonDecode(response.body); + final body = jsonDecode(response.body); final message = body['message']; ToastHelper.showWarningToast(context, message); } else { @@ -278,10 +277,10 @@ class _MyEmailVerifyState extends State { setState(() { _isLoading = false; }); - print('Error: $e'); + logDebug('Error: $e'); ToastHelper.showWarningToast(context, 'Something went wrong'); // Show a Snackbar if there's an error while verifying OTP - print('Failed to verify OTP. Please try again.'); + logDebug('Failed to verify OTP. Please try again.'); } } @@ -295,7 +294,7 @@ class _MyEmailVerifyState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(post['data']); - print('postdecodedToken : $decodedToken'); + logDebug('postdecodedToken : $decodedToken'); empClientBranchId = decodedToken['ref_id']; prefs.setString('empClientBranchId', empClientBranchId); empCodeString = decodedToken['emp_code'].toString(); @@ -314,7 +313,7 @@ class _MyEmailVerifyState extends State { // prefs.setString('emp_status', emp_status); // getClientLogoAndDetails(); - print('Successfully Login'); + logDebug('Successfully Login'); // Redirect to another page } @@ -325,7 +324,7 @@ class _MyEmailVerifyState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(data['data']); - print('postenrolldecodedToken : $decodedToken'); + logDebug('postenrolldecodedToken : $decodedToken'); enrollmentEmpClientBranchId = decodedToken['ref_id']; prefs.setString( 'enrollmentEmpClientBranchId', enrollmentEmpClientBranchId); @@ -346,7 +345,8 @@ class _MyEmailVerifyState extends State { // prefs.setString('enrollmentEmp_status', enrollmentEmp_status); } - getClientLogoAndDetails(empClientId, empClientBranchId,enrollmentClient_id,enrollmentEmpClientBranchId, post['data']); + getClientLogoAndDetails(empClientId, empClientBranchId, enrollmentClient_id, + enrollmentEmpClientBranchId, post['data']); final SharedPreferences prefs = await SharedPreferences.getInstance(); final _postToken = prefs.getString('_postToken'); @@ -367,7 +367,7 @@ class _MyEmailVerifyState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(data['data']); - print('enrolldecodedToken : $decodedToken'); + logDebug('enrolldecodedToken : $decodedToken'); enrollmentEmpClientBranchId = decodedToken['ref_id']; prefs.setString('enrollmentEmpClientBranchId', enrollmentEmpClientBranchId); enrollmentEmpCodeString = decodedToken['emp_code'].toString(); @@ -379,15 +379,16 @@ class _MyEmailVerifyState extends State { enrollmentClient_id = decodedToken['client_id']; prefs.setString('enrollmentClient_id', enrollmentClient_id); enrollmentHrId = decodedToken['id']; - print("enrollmentHrId- $enrollmentHrId"); + logDebug("enrollmentHrId- $enrollmentHrId"); prefs.setString('enrollmentHrId', enrollmentHrId); enrollmentAllowed_modules = decodedToken['allowed_modules']; prefs.setString( 'enrollmentAllowed_modules', jsonEncode(enrollmentAllowed_modules)); // enrollmentEmp_status = decodedToken['emp_status']; // prefs.setString('enrollmentEmp_status', enrollmentEmp_status); - getClientLogoAndDetails(empClientId,empClientBranchId,enrollmentClient_id, enrollmentEmpClientBranchId, data['data']); - print('Successfully Login'); + getClientLogoAndDetails(empClientId, empClientBranchId, enrollmentClient_id, + enrollmentEmpClientBranchId, data['data']); + logDebug('Successfully Login'); // Redirect to another page final enrollToken = prefs.getString('enrollToken'); @@ -426,7 +427,8 @@ class _MyEmailVerifyState extends State { Uri.parse(apiEndpoint), body: json.encode(payload), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); @@ -440,7 +442,7 @@ class _MyEmailVerifyState extends State { context, 'Verification code sent to ${widget.value}'); } else { ToastHelper.showErrorToast(context, message); - print('Invalid mobile number'); + logDebug('Invalid mobile number'); } } else { ToastHelper.showErrorToast(context, 'Something went wrong'); @@ -448,26 +450,28 @@ class _MyEmailVerifyState extends State { } } catch (e) { ToastHelper.showErrorToast(context, 'Something went wrong'); - print('Error: $e'); + logDebug('Error: $e'); } } - Future getClientLogoAndDetails(empClientId,empClientBranchId,enrollmentClientId, enrollmentClientBranchId, token) async { + Future getClientLogoAndDetails(empClientId, empClientBranchId, + enrollmentClientId, enrollmentClientBranchId, token) async { var url = Uri.parse(Environment.apiUrl + 'getClientDetails?post_client_id=$empClientId&post_branch_id=$empClientBranchId&pre_client_id=$enrollmentClientId&pre_branch_id=$enrollmentClientBranchId'); try { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $token', // Add token to the Authorization header }, ); if (response.statusCode == 200) { - // print('response.statusCode == 200'); + // logDebug('response.statusCode == 200'); Map data = json.decode(response.body); - // print(data); + // logDebug(data); if (data.containsKey('data')) { dynamic clientDetails = data['data']; @@ -476,27 +480,27 @@ class _MyEmailVerifyState extends State { prefs.setString('clientName', clientDetails['client']['client_name']); setState(() { // dynamic clientDetails = data['data']; - // print(clientDetails); + // logDebug(clientDetails); clientName = clientDetails['client']['client_name']; - print(clientName); + logDebug(clientName); clientLogo = clientDetails['client']['client_logo']; - print(clientLogo); + logDebug(clientLogo); }); } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -543,14 +547,13 @@ class _MyEmailVerifyState extends State { ], ), ), - child: Center( child: Container( - width: double.infinity, // ✅ fixed web width - height: _size.height, // ✅ fixed web height (IMPORTANT) + width: double.infinity, // ✅ fixed web width + height: _size.height, // ✅ fixed web height (IMPORTANT) margin: const EdgeInsets.all(60), clipBehavior: Clip.hardEdge, - decoration: BoxDecoration( + decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(40)), ), @@ -591,13 +594,10 @@ class _MyEmailVerifyState extends State { SizedBox(height: 15), Container( margin: Responsive.isDesktop(context) - ? EdgeInsets.symmetric( - horizontal: 150) - : EdgeInsets.symmetric( - horizontal: 0), + ? EdgeInsets.symmetric(horizontal: 150) + : EdgeInsets.symmetric(horizontal: 0), child: Row( - mainAxisAlignment: - MainAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Welcome to Nhance", @@ -612,36 +612,36 @@ class _MyEmailVerifyState extends State { SizedBox(height: 15), Container( margin: Responsive.isDesktop(context) - ? EdgeInsets.symmetric( - horizontal: 150) - : EdgeInsets.symmetric( - horizontal: 0), + ? EdgeInsets.symmetric(horizontal: 150) + : EdgeInsets.symmetric(horizontal: 0), child: RichText( textAlign: TextAlign.center, text: TextSpan( text: - "Please enter the one-time usage code sent to your ", + "Please enter the one-time usage code sent to your ", style: TextStyle( fontSize: 12, height: 1.5, color: Color(0xFF000000)), children: [ TextSpan( - text: widget.type == 'mobile' ? 'mobile number ${widget.value}' : 'Email Id ${widget.value}', + text: widget.type == 'mobile' + ? 'mobile number ${widget.value}' + : 'Email Id ${widget.value}', ), TextSpan( - text: widget.type == 'mobile' ? ' (Change Mobile)' : ' (Change Email)', + text: widget.type == 'mobile' + ? ' (Change Mobile)' + : ' (Change Email)', style: TextStyle( fontSize: 12, color: Color( 0xFFE26728)), // Change color as desired - recognizer: - TapGestureRecognizer() + recognizer: TapGestureRecognizer() ..onTap = () { // Navigate to the page where the user can change the phone number Navigator.pushNamed( - context, - 'hrLogin'); + context, 'hrLogin'); }, ), ], @@ -651,10 +651,8 @@ class _MyEmailVerifyState extends State { SizedBox(height: 15), Container( margin: Responsive.isDesktop(context) - ? EdgeInsets.symmetric( - horizontal: 150) - : EdgeInsets.symmetric( - horizontal: 0), + ? EdgeInsets.symmetric(horizontal: 150) + : EdgeInsets.symmetric(horizontal: 0), child: Pinput( length: 6, // defaultPinTheme: defaultPinTheme, @@ -667,63 +665,51 @@ class _MyEmailVerifyState extends State { SizedBox(height: 15), Container( margin: Responsive.isDesktop(context) - ? EdgeInsets.symmetric( - horizontal: 150) - : EdgeInsets.symmetric( - horizontal: 0), + ? EdgeInsets.symmetric(horizontal: 150) + : EdgeInsets.symmetric(horizontal: 0), child: Row( mainAxisAlignment: MainAxisAlignment .end, // Align text to the right children: [ _isTimerRunning ? Text( - "Resend OTP in $_secondsRemaining seconds", - style: - GoogleFonts.poppins( - color: - Colors.black), - ) + "Resend OTP in $_secondsRemaining seconds", + style: GoogleFonts.poppins( + color: Colors.black), + ) : InkWell( - onTap: () { - _resendOTP(); - }, - child: Text( - "Resend OTP", - style: - GoogleFonts.poppins( - color: Colors - .blue), - ), - ), + onTap: () { + _resendOTP(); + }, + child: Text( + "Resend OTP", + style: GoogleFonts.poppins( + color: Colors.blue), + ), + ), ], ), ), SizedBox(height: 15), Container( margin: Responsive.isDesktop(context) - ? EdgeInsets.symmetric( - horizontal: 150) - : EdgeInsets.symmetric( - horizontal: 0), + ? EdgeInsets.symmetric(horizontal: 150) + : EdgeInsets.symmetric(horizontal: 0), child: SizedBox( width: double.infinity, height: 45, child: ElevatedButton( style: ElevatedButton.styleFrom( - backgroundColor: - Color(0xFF00989E), + backgroundColor: Color(0xFF00989E), shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.circular(10), + borderRadius: BorderRadius.circular(10), ), ), onPressed: () { - if (_formKey.currentState! - .validate()) { + if (_formKey.currentState!.validate()) { _formKey.currentState! .save(); // Save form fields before calling verifyOTP - verifyOTP( - _otpController.text); + verifyOTP(_otpController.text); } }, child: Text( @@ -737,13 +723,11 @@ class _MyEmailVerifyState extends State { SizedBox(height: 15), Container( alignment: Alignment.bottomCenter, - padding: - EdgeInsets.symmetric(vertical: 8), + padding: EdgeInsets.symmetric(vertical: 8), child: RichText( textAlign: TextAlign.center, text: TextSpan( - text: - 'By continuing, you agree with our ', + text: 'By continuing, you agree with our ', style: GoogleFonts.poppins( color: Colors.black, fontSize: 9, @@ -782,9 +766,6 @@ class _MyEmailVerifyState extends State { ], ), ), - ) - - ) - ); + ))); } } diff --git a/lib/empDetails.dart b/lib/empDetails.dart index 5957079..5151712 100755 --- a/lib/empDetails.dart +++ b/lib/empDetails.dart @@ -19,6 +19,7 @@ import 'package:url_launcher/url_launcher.dart'; import 'config/environment.dart'; import 'customAppBar/customFooter.dart'; +import 'package:nhancepolicy/logger.dart'; class empDetails extends StatefulWidget { const empDetails({Key? key}) : super(key: key); @@ -131,10 +132,10 @@ class _empDetailsState extends State { String? getHrToken = prefs.getString('hrtoken'); String? empID = prefs.getString('employee_id'); Map? decodedToken = Jwt.parseJwt(getHrToken!); - print(decodedToken); + logDebug(decodedToken); hrPrimaryId = decodedToken['id']; - print('hrPrimaryId'); - print(hrPrimaryId); + logDebug('hrPrimaryId'); + logDebug(hrPrimaryId); _hrLoadToken(empID); } else { _loadToken(); @@ -142,7 +143,7 @@ class _empDetailsState extends State { } Future _hrLoadToken(empID) async { - print('_hrLoadToken'); + logDebug('_hrLoadToken'); final SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('fromHrLoginMobileNo', mobileNumber); @@ -161,19 +162,20 @@ class _empDetailsState extends State { 'employee_id': empID }), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); if (response.statusCode == 200) { - print('API Success'); + logDebug('API Success'); Map data = json.decode(response.body); - print(data); + logDebug(data); String status = data['status']; if (status == 'success') { - print(status); + logDebug(status); // final SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { prefs.setString('token', data['data']); @@ -181,10 +183,10 @@ class _empDetailsState extends State { // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(data['data']); - print('decodedTokenssss $decodedToken'); + logDebug('decodedTokenssss $decodedToken'); empClientBranchId = decodedToken['client_branch_id']; prefs.setString('empClientBranchId', empClientBranchId); - print(empClientBranchId); + logDebug(empClientBranchId); empCodeString = decodedToken['emp_code']; prefs.setString('empCode', empCodeString); empPrimaryId = decodedToken['id']; @@ -194,11 +196,11 @@ class _empDetailsState extends State { client_id = decodedToken['client_id']; prefs.setString('client_id', client_id); - print('Successfully Login'); + logDebug('Successfully Login'); // Redirect to another page token = prefs.getString('token'); - print('final $token'); + logDebug('final $token'); if (token != null && token.isNotEmpty) { // ToastHelper.showSuccessToast(context, 'Successfully Login'); await getTokenLoad(token); @@ -224,24 +226,24 @@ class _empDetailsState extends State { // ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again'); // Show a Snackbar if the OTP is invalid // ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again'); - print('Invalid OTP. Please try again'); + logDebug('Invalid OTP. Please try again'); } } else { // ToastHelper.showErrorToast(context, 'Failed to verify OTP'); throw Exception('Failed to verify OTP'); } } catch (e) { - print('Error: $e'); + logDebug('Error: $e'); ToastHelper.showErrorToast(context, 'Something went wrong'); // Show a Snackbar if there's an error while verifying OTP // ToastHelper.showErrorToast( // context, 'Failed to verify OTP. Please try again.'); - print('Failed to verify OTP. Please try again.'); + logDebug('Failed to verify OTP. Please try again.'); } } Future _loadToken() async { - print('_loadToken'); + logDebug('_loadToken'); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? token = prefs.getString('token'); if (token != null && token.isNotEmpty) { @@ -250,16 +252,16 @@ class _empDetailsState extends State { }); // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); - print(decodedToken); + logDebug(decodedToken); empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); - print(empCodeString); // Check if emp_code is correct + logDebug(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); gpaEmpName = prefs.getString('gpaEmpName'); client_id = prefs.getString('client_id'); - print(client_id); + logDebug(client_id); - // print(empPrimaryId); + // logDebug(empPrimaryId); // Call the API when the page enters // getSelfEmployeeProfile(''); if (prefs.containsKey('clientLogo') && prefs.containsKey('clientName')) { @@ -288,7 +290,7 @@ class _empDetailsState extends State { } final response = await apiService.getClientLogoAndDetailsToApi( client_id!, empCodeString!, empClientBranchId!); - print('check 1'); + logDebug('check 1'); if (response['status'] == 'success') { if (response.containsKey('data')) { @@ -298,27 +300,27 @@ class _empDetailsState extends State { prefs.setString('clientName', clientDetails['client']['client_name']); setState(() { // dynamic clientDetails = data['data']; - // print(clientDetails); + // logDebug(clientDetails); clientName = clientDetails['client']['client_name']; - print(clientName); + logDebug(clientName); clientLogo = clientDetails['client']['client_logo']; - print(clientLogo); + logDebug(clientLogo); }); } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -327,7 +329,7 @@ class _empDetailsState extends State { final response = await apiService.getTokenLoadAPI(token); } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -345,7 +347,7 @@ class _empDetailsState extends State { if (response.containsKey('data')) { setState(() { dynamic selfDetails = response['data']; - print(selfDetails); + logDebug(selfDetails); mobileNumber = selfDetails['relationship']; selfRelationship = selfDetails['relationship']; selfName = selfDetails['name']; @@ -359,7 +361,7 @@ class _empDetailsState extends State { selfEmailPersonal = selfDetails['email_personal']; selfEmpCode = selfDetails['emp_code']; selfFamilyFloaterKey = selfDetails['family_floater_key']; - // print(clientDetails); + // logDebug(clientDetails); selfEmpStatus = selfDetails['emp_status']; selfUnit = selfDetails['unit']; }); @@ -369,17 +371,17 @@ 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: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -416,7 +418,7 @@ class _empDetailsState extends State { if (response['status'] == 'success') { setState(() { gpaPolicies = response['data']; - print('gpaPolicies'); + logDebug('gpaPolicies'); }); } else { setState(() { @@ -424,11 +426,11 @@ class _empDetailsState extends State { }); // Handle other status codes ToastHelper.showWarningToast(context, 'Something went wrong'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -450,10 +452,10 @@ class _empDetailsState extends State { if (response['status'] == 'success') { setState(() { gmcPolicies = response['data']; - print('gmcPolicies'); + logDebug('gmcPolicies'); }); // Assuming data is a List - print(gmcPolicies); + logDebug(gmcPolicies); } else { setState(() { gmcDataIsEmpty = 0; @@ -461,11 +463,11 @@ 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: ${response['status']}'); + logDebug('API request failed with status: ${response['status']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -494,15 +496,15 @@ class _empDetailsState extends State { } catch (error) { // ToastHelper.showErrorToast( // context, 'Error fetching relationship list: $error'); - print('Error fetching relationship list: $error'); + logDebug('Error fetching relationship list: $error'); // Handle error accordingly, e.g., show a snackbar with an error message } } Future _selectDate(BuildContext context, formType) async { - print(formType); + logDebug(formType); var ageValidation = formType['age_validation']; - print(ageValidation); + logDebug(ageValidation); // Ensure ageValidation is a Map and contains the expected values if (ageValidation is Map) { int min = ageValidation.containsKey('min') @@ -512,17 +514,17 @@ class _empDetailsState extends State { ? int.tryParse(ageValidation['max'].toString()) ?? 100 : 100; - print('Min age: $min'); - print('Max age: $max'); + logDebug('Min age: $min'); + logDebug('Max age: $max'); late DateTime minDate; late DateTime maxDate; final DateTime now = DateTime.now(); maxDate = DateTime(now.year - min, now.month, now.day); - print(maxDate); + logDebug(maxDate); minDate = DateTime(now.year - max, now.month, now.day); - print(minDate); + logDebug(minDate); // if (formType['form_type'] == 'child') { // // For 'child' form type, allow 0-25 age @@ -576,12 +578,12 @@ class _empDetailsState extends State { }); } } else { - print('Invalid age validation data'); + logDebug('Invalid age validation data'); } } Future deleteItem(Map deletedItem) async { - print(deletedItem); + logDebug(deletedItem); try { var id = deletedItem['employee_id']; final response = await apiService.deleteItemToApi(id); @@ -598,25 +600,25 @@ class _empDetailsState extends State { getGmcEmpPolicyDetails(empPrimaryId); fetchRelationshipList(); ToastHelper.showSuccessToast(context, 'Item deleted successfully'); - print('Item deleted successfully'); + logDebug('Item deleted successfully'); } else { // Handle errors ToastHelper.showErrorToast(context, 'Failed to delete item'); - print('Failed to delete item. Status code: ${response['code']}'); - print('Response body: ${response}'); + logDebug('Failed to delete item. Status code: ${response['code']}'); + logDebug('Response body: ${response}'); } } catch (error) { // Handle network errors - print('Error deleting item: $error'); + logDebug('Error deleting item: $error'); } } void saveFamilyMemberDetails(Map formData, Map floatedData, action, gmcSumInsured) async { // Construct the array of objects - print(formData); - print('floatedData $floatedData'); - print(action); + logDebug(formData); + logDebug('floatedData $floatedData'); + logDebug(action); final SharedPreferences prefs = await SharedPreferences.getInstance(); dynamic primaryId; @@ -665,11 +667,11 @@ class _empDetailsState extends State { getGmcEmpPolicyDetails(empPrimaryId); fetchRelationshipList(); ToastHelper.showSuccessToast(context, 'Saved Successfully.'); - print('Form data sent successfully.'); + logDebug('Form data sent successfully.'); } else { // Request failed, handle error ToastHelper.showErrorToast(context, 'Failed'); - print('Failed to send form data. Error: ${response}'); + logDebug('Failed to send form data. Error: ${response}'); } } @@ -693,20 +695,20 @@ class _empDetailsState extends State { final String? detailsString = prefs.getString('hrSelectArgumentsData'); if (detailsString != null) { final dynamic details = jsonDecode(detailsString); - print('Decoded details:'); - print(details); + logDebug('Decoded details:'); + logDebug(details); // Ensure that details is a Map before passing it if (details is Map) { Navigator.pushNamed(context, 'hrPolicyDetails', arguments: details); } else { - print('Error: Decoded details is not a Map.'); + logDebug('Error: Decoded details is not a Map.'); } } else { - print('hrSelectArgumentsData is null.'); + logDebug('hrSelectArgumentsData is null.'); } } else { - print('hrtoken is null or empty.'); + logDebug('hrtoken is null or empty.'); } } @@ -718,18 +720,18 @@ class _empDetailsState extends State { if (arguments.containsKey('mobile')) { mobileNumber = arguments["mobile"]; // Call your tokenAPI or _loadToken function here - print("_hrLoadToken"); - print(mobileNumber); + logDebug("_hrLoadToken"); + logDebug(mobileNumber); // _hrLoadToken(); } } else { - print("Arguments are null or not in the expected format"); + logDebug("Arguments are null or not in the expected format"); // _loadToken(); mobileNumber = ''; } if (gpaDataIsEmpty == 0 && gmcDataIsEmpty == 0) { - print('body if'); - print(gpaPolicies); + logDebug('body if'); + logDebug(gpaPolicies); return Scaffold( appBar: CustomAppBar(), body: SingleChildScrollView( @@ -1051,10 +1053,10 @@ class _empDetailsState extends State { } void openForm(Map floaterData, action, gmcSumInsured) { - print(action); - print(floaterData); - print(relationshipOptions); - print('test'); + logDebug(action); + logDebug(floaterData); + logDebug(relationshipOptions); + logDebug('test'); // Check if the action is 'Edit' dynamic popupName = floaterData['button_name']; @@ -1071,32 +1073,32 @@ class _empDetailsState extends State { _relationShipController.text = 'Spouse'; } - print(selectedRelationships); - print(gmcMappedFamilyFloaters); + logDebug(selectedRelationships); + logDebug(gmcMappedFamilyFloaters); if (action == 'Add') { if (floaterData['form_type'] == 'parent_in_law' || floaterData['form_type'] == 'parent') { - print('Add'); + logDebug('Add'); // Filter the addOnsDependentMappedFamilyFloatersDependent list to get only the objects where is_value_exist is true dynamic getTrueObjects = gmcMappedFamilyFloaters .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); List> getTrueDataObjects = getTrueObjects .map>( (element) => element['data'] as Map) .toList(); - print(getTrueDataObjects); + logDebug(getTrueDataObjects); selectedRelationships.removeWhere((relationship) => getTrueDataObjects.any((dataObject) => dataObject['relationship'] == relationship['relationship_name'])); - print(selectedRelationships); + logDebug(selectedRelationships); } } else { // Set values to all fields @@ -1367,12 +1369,12 @@ class _empDetailsState extends State { Future _launchURL(String url) async { final Uri uri = Uri.parse(url); // Parse the URL properly - print('_launchURL $uri'); + logDebug('_launchURL $uri'); if (uri != null) { - print('If $uri'); + logDebug('If $uri'); await launchUrl(uri, mode: LaunchMode.externalApplication); } else { - print('else $uri'); + logDebug('else $uri'); throw 'Could not launch $url'; } } @@ -1738,8 +1740,8 @@ class _empDetailsState extends State { List cards = []; for (var item in data) { - print('item'); - print(item); + logDebug('item'); + logDebug(item); String? gpaPolicyName = item['Policy_Name']; String? gpaECardDownload = item['eCardDownload']; @@ -1991,8 +1993,8 @@ class _empDetailsState extends State { List cards = []; for (var item in data) { - print('item'); - print(item); + logDebug('item'); + logDebug(item); setState(() { gmcPolicyName = item['Policy_Name']; gmc_client_policy_id = item['ClientPolicyId']; @@ -2005,13 +2007,13 @@ class _empDetailsState extends State { dynamic getTrueObjects = gmcMappedFamilyFloaters .where((element) => element['is_value_exist'] == true) .toList(); - print('getTrueObjects'); - print(getTrueObjects); + logDebug('getTrueObjects'); + logDebug(getTrueObjects); if (getTrueObjects.length > 0) { - print('true'); + logDebug('true'); gmcSumInsured = gmcMappedFamilyFloaters[0]["data"]["basic_cover_si"]; } else { - print('false'); + logDebug('false'); gmcSumInsured = item['Policy_Terms']['sum_insured']; } String intOpenForEnrollment = item['OpenForEnrollment']; diff --git a/lib/empReview.dart b/lib/empReview.dart index 7640e97..865d282 100755 --- a/lib/empReview.dart +++ b/lib/empReview.dart @@ -15,6 +15,7 @@ import 'dart:convert'; import 'package:url_launcher/url_launcher.dart'; import 'customAppBar/customFooter.dart'; +import 'package:nhancepolicy/logger.dart'; class empReviewDetails extends StatefulWidget { const empReviewDetails({Key? key}) : super(key: key); @@ -171,13 +172,13 @@ class _empReviewDetailsState extends State { selfEmpStatus = prefs.getString('selfEmpStatus'); empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); - print(empCodeString); // Check if emp_code is correct + logDebug(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); gpaEmpName = prefs.getString('gpaEmpName'); client_id = prefs.getString('client_id'); - print(client_id); + logDebug(client_id); - // print(empPrimaryId); + // logDebug(empPrimaryId); // Call the API when the page enters if (prefs.containsKey('clientLogo') && prefs.containsKey('clientName')) { clientLogo = prefs.getString('clientLogo'); @@ -205,8 +206,8 @@ class _empReviewDetailsState extends State { if (prefs.containsKey('siData')) { activeSiData = 1; String? siDataJson = prefs.getString('siData'); - print('siDataJson'); - print(siDataJson); + logDebug('siDataJson'); + logDebug(siDataJson); List siDataList = jsonDecode(siDataJson!); if (siDataList.isNotEmpty) { @@ -221,8 +222,8 @@ class _empReviewDetailsState extends State { if (prefs.containsKey('siParentData')) { activeSiParentData = 1; String? siParentDataJson = prefs.getString('siParentData'); - print('siParentDataJson'); - print(siParentDataJson); + logDebug('siParentDataJson'); + logDebug(siParentDataJson); List siParentDataList = jsonDecode(siParentDataJson!); if (siParentDataList.isNotEmpty) { @@ -238,8 +239,8 @@ class _empReviewDetailsState extends State { if (prefs.containsKey('dependentData')) { activeDependentData = 1; String? dependentDataJson = prefs.getString('dependentData'); - print('dependentDataJson'); - print(dependentDataJson); + logDebug('dependentDataJson'); + logDebug(dependentDataJson); List dependentDataList = jsonDecode(dependentDataJson!); if (dependentDataList.isNotEmpty) { @@ -269,7 +270,7 @@ class _empReviewDetailsState extends State { totalPayableAmt += addOnsDependentTotalAmt; // Print or use the totalAmtSum value - print('Sum of Total Amounts: $totalPayableAmt'); + logDebug('Sum of Total Amounts: $totalPayableAmt'); } Future getClientLogoAndDetails() async { @@ -284,22 +285,22 @@ class _empReviewDetailsState extends State { if (response['status'] == 'success') { if (response.containsKey('data')) { dynamic clientDetails = response['data']; - print(clientDetails); + logDebug(clientDetails); clientName = clientDetails['client']['client_name']; - print(clientName); + logDebug(clientName); clientLogo = clientDetails['client']['client_logo']; - print(clientLogo); + logDebug(clientLogo); } else { // Handle other status messages if needed - print('API request failed with status: ${response['status']}'); + logDebug('API request failed with status: ${response['status']}'); } } else { // Handle other status codes - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -327,7 +328,7 @@ class _empReviewDetailsState extends State { if (response['status'] == 'success') { setState(() { gpaPolicies = response['data']; - print('gpaPolicies'); + logDebug('gpaPolicies'); }); } else { setState(() { @@ -335,11 +336,11 @@ class _empReviewDetailsState extends State { }); // Handle other status codes ToastHelper.showWarningToast(context, 'Something went wrong'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -366,10 +367,10 @@ class _empReviewDetailsState extends State { if (response['status'] == 'success') { setState(() { gmcPolicies = response['data']; - print('gmcPolicies'); + logDebug('gmcPolicies'); }); // Assuming data is a List - print(gmcPolicies); + logDebug(gmcPolicies); } else { setState(() { gmcDataIsEmpty = 0; @@ -377,11 +378,11 @@ class _empReviewDetailsState extends State { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -397,7 +398,7 @@ class _empReviewDetailsState extends State { if (response['status'] == 'success') { if (response.containsKey('data')) { dynamic topUpSiPolicies = response['data']; - print(topUpSiPolicies); + logDebug(topUpSiPolicies); if (topUpSiPolicies.isNotEmpty) { // setState(() { topUpClientPolicyId = @@ -405,7 +406,7 @@ class _empReviewDetailsState extends State { topUpSumInsured = topUpSiPolicies['gmc_si_topup'] ['family_floaters_of_only_si_value']; - print(topUpSumInsured); + logDebug(topUpSumInsured); if (topUpSumInsured == 0) { showHideTopUpCard = 0; @@ -420,8 +421,8 @@ class _empReviewDetailsState extends State { topUpMappedFamilyFloatersSiArray = topUpSiPolicies['gmc_si_topup'] ['family_floaters_of_only_si_array']; - print('topUpMappedFamilyFloatersSiArray'); - print(topUpMappedFamilyFloatersSiArray); + logDebug('topUpMappedFamilyFloatersSiArray'); + logDebug(topUpMappedFamilyFloatersSiArray); topUpTypeName = topUpSiPolicies['gmc_si_topup']['type']; @@ -437,23 +438,23 @@ class _empReviewDetailsState extends State { } else { // ToastHelper.showErrorToast( // context, 'No data found in the response'); - print('No data found in the response'); + logDebug('No data found in the response'); } } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -470,8 +471,8 @@ class _empReviewDetailsState extends State { if (response.containsKey('data')) { setState(() { topUpSiParentPolicies = response['data']; - print('topUpSiParentPolicies'); - print(topUpSiParentPolicies); + logDebug('topUpSiParentPolicies'); + logDebug(topUpSiParentPolicies); }); if (topUpSiParentPolicies.isNotEmpty) { // setState(() { @@ -481,8 +482,8 @@ class _empReviewDetailsState extends State { topUpParentSlabRates = await topUpSiParentPolicies['gmc_si_parent_topup']['SlabRates']; - print('topUpParentSlabRates'); - print(topUpParentSlabRates); + logDebug('topUpParentSlabRates'); + logDebug(topUpParentSlabRates); topUpParentPolicyName = await topUpSiParentPolicies['gmc_si_parent_topup'] @@ -494,24 +495,24 @@ class _empReviewDetailsState extends State { topUpParentFamilyFloater = await topUpSiParentPolicies['gmc_si_parent_topup'] ['policy_terms']['family_floater']; - print('topUpParentFamilyFloater'); - print(topUpParentFamilyFloater); + logDebug('topUpParentFamilyFloater'); + logDebug(topUpParentFamilyFloater); topUpParentMappedFamilyFloatersSi = await topUpSiParentPolicies['gmc_si_parent_topup'] ['family_floaters_of_only_si_array']; - print('topUpParentMappedFamilyFloatersSi'); - print(topUpParentMappedFamilyFloatersSi); + logDebug('topUpParentMappedFamilyFloatersSi'); + logDebug(topUpParentMappedFamilyFloatersSi); - print('topUpECardDownload'); + logDebug('topUpECardDownload'); topUpParentECardDownload = topUpSiParentPolicies['gmc_si_parent_topup']['eCardDownload']; - print(topUpParentECardDownload); + logDebug(topUpParentECardDownload); String intOpenForEnrollment = topUpSiParentPolicies['gmc_si_parent_topup'] ['OpenForEnrollment']; topUpParentOpenForEnrollment = int.parse(intOpenForEnrollment); - print(topUpParentOpenForEnrollment); + logDebug(topUpParentOpenForEnrollment); topUpParentTypeName = topUpSiParentPolicies['gmc_si_parent_topup']['type']; @@ -537,23 +538,23 @@ class _empReviewDetailsState extends State { } else { // ToastHelper.showErrorToast( // context, 'No data found in the response'); - print('No data found in the response'); + logDebug('No data found in the response'); } } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -569,19 +570,19 @@ class _empReviewDetailsState extends State { if (response['status'] == 'success') { if (response.containsKey('data')) { dynamic addOnsDependentPolicies = response['data']; - print('addOnsDependentPolicies'); - print(addOnsDependentPolicies); + logDebug('addOnsDependentPolicies'); + logDebug(addOnsDependentPolicies); if (addOnsDependentPolicies.isNotEmpty) { // setState(() { addOnsDependentClientPolicyId = addOnsDependentPolicies['gmc_dependent_addon'] ['client_policy_id']; - print(addOnsDependentClientPolicyId); + logDebug(addOnsDependentClientPolicyId); addOnsDependentSumInsured = addOnsDependentPolicies['gmc_dependent_addon'] ['family_floaters_of_dependent_and_si_value']; - print(addOnsDependentSumInsured); + logDebug(addOnsDependentSumInsured); if (addOnsDependentSumInsured == 0) { showHideAddOnsCard = 0; @@ -591,17 +592,17 @@ class _empReviewDetailsState extends State { addOnsDependentPolicyName = addOnsDependentPolicies['gmc_dependent_addon']['policy_name']; - print(addOnsDependentPolicyName); + logDebug(addOnsDependentPolicyName); addOnsDependentPolicyType = addOnsDependentPolicies['gmc_dependent_addon']['type']; - print(addOnsDependentPolicyType); + logDebug(addOnsDependentPolicyType); addOnsDependentMappedFamilyFloatersArray = await addOnsDependentPolicies['gmc_dependent_addon'] ['family_floaters_of_dependent_and_si_array']; - print('addOnsDependentMappedFamilyFloatersArray'); - print(addOnsDependentMappedFamilyFloatersArray); + logDebug('addOnsDependentMappedFamilyFloatersArray'); + logDebug(addOnsDependentMappedFamilyFloatersArray); addOnsFloaterTextHeading = addOnsDependentPolicies['gmc_dependent_addon'] @@ -616,23 +617,23 @@ class _empReviewDetailsState extends State { } else { // ToastHelper.showErrorToast( // context, 'No data found in the response'); - print('No data found in the response'); + logDebug('No data found in the response'); } } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${response['status']}'); + logDebug('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['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -645,7 +646,7 @@ class _empReviewDetailsState extends State { .where((element) => element['is_value_exist'] == true) .toList(); - print(getDependentTrueObjects); + logDebug(getDependentTrueObjects); if (getDependentTrueObjects.isNotEmpty) { iAgreeForAddOn.add(int.parse(addOnsDependentClientPolicyId)); @@ -657,7 +658,7 @@ class _empReviewDetailsState extends State { .where((element) => element['is_value_exist'] == true) .toList(); - print(getSiTrueObjects); + logDebug(getSiTrueObjects); if (getSiTrueObjects.isNotEmpty) { iAgreeForAddOn.add(int.parse(topUpClientPolicyId)); @@ -669,22 +670,22 @@ class _empReviewDetailsState extends State { .where((element) => element['is_value_exist'] == true) .toList(); - print(getSiTrueObjects); + logDebug(getSiTrueObjects); if (getSiTrueObjects.isNotEmpty) { iAgreeForAddOn.add(int.parse(topUpParentClientPolicyId)); } } - print('gpaPolicies'); - print(gpaPolicies); - print('gmcPolicies'); - print(gmcPolicies); + logDebug('gpaPolicies'); + logDebug(gpaPolicies); + logDebug('gmcPolicies'); + logDebug(gmcPolicies); if (gpaDataIsEmpty != 0) { - print('gpaDataIsEmpty : $gpaDataIsEmpty'); + logDebug('gpaDataIsEmpty : $gpaDataIsEmpty'); for (var item in gpaPolicies) { - print('ClientPolicyId'); + logDebug('ClientPolicyId'); // Extract ClientPolicyId value from each object String clientPolicyId = item['ClientPolicyId']; // Convert to integer and add to iAgreeForAddOn list @@ -700,16 +701,16 @@ class _empReviewDetailsState extends State { iAgreeForAddOn.add(int.parse(clientPolicyId)); } } - print('iAgreeForAddOn'); + logDebug('iAgreeForAddOn'); iAgreeForAddOn = iAgreeForAddOn.toSet().toList(); - print(iAgreeForAddOn); // Output: [90, 92, 88, 89] + logDebug(iAgreeForAddOn); // Output: [90, 92, 88, 89] Map apiParams = { 'emp_code': empCodeString, 'client_policy_id': iAgreeForAddOn, 'client_id': client_id, }; - print(apiParams); + logDebug(apiParams); // Convert the list of objects to JSON String formDataJson = jsonEncode(apiParams); @@ -725,7 +726,7 @@ class _empReviewDetailsState extends State { topUpParentIsChecked = false; addOnsDependentIsChecked = false; }); - print('response.statusCode == 200'); + logDebug('response.statusCode == 200'); _showSuccessDialog(); ToastHelper.showSuccessToast(context, 'Saved Successfully...'); } else { @@ -735,14 +736,14 @@ class _empReviewDetailsState extends State { // Handle other status codes _showErrorDialog(); ToastHelper.showErrorToast(context, 'Failed to Save'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -819,12 +820,12 @@ class _empReviewDetailsState extends State { Future _launchURL(String url) async { final Uri uri = Uri.parse(url); // Parse the URL properly - print('_launchURL $uri'); + logDebug('_launchURL $uri'); if (uri != null) { - print('If $uri'); + logDebug('If $uri'); await launchUrl(uri, mode: LaunchMode.externalApplication); } else { - print('else $uri'); + logDebug('else $uri'); throw 'Could not launch $url'; } } @@ -2570,8 +2571,8 @@ class _empReviewDetailsState extends State { List cards = []; for (var item in data) { - print('item'); - print(item); + logDebug('item'); + logDebug(item); String? gpaPolicyName = item['Policy_Name']; String? gpaPolicyType = item['type']; @@ -2770,24 +2771,24 @@ class _empReviewDetailsState extends State { dynamic getTrueObjects = gmcMappedFamilyFloaters .where((element) => element['is_value_exist'] == true) .toList(); - print('getTrueObjects'); - print(getTrueObjects); + logDebug('getTrueObjects'); + logDebug(getTrueObjects); if (getTrueObjects.length > 0) { - print('true'); + logDebug('true'); gmcSumInsured = gmcMappedFamilyFloaters[0]["data"]["basic_cover_si"]; } else { - print('false'); + logDebug('false'); gmcSumInsured = item['Policy_Terms']['sum_insured']; } gmcTypeName = item['type']; }); - print('forEach Card'); - print(gmcMappedFamilyFloaters); + logDebug('forEach Card'); + logDebug(gmcMappedFamilyFloaters); dynamic getTrueObjects = gmcMappedFamilyFloaters .where((element) => element['is_value_exist'] == true) .toList(); - print(getTrueObjects); + logDebug(getTrueObjects); Widget card = getTrueObjects.length > 0 ? Card( diff --git a/lib/home.dart b/lib/home.dart index 85a58a1..001e5ea 100755 --- a/lib/home.dart +++ b/lib/home.dart @@ -13,6 +13,7 @@ import 'package:jwt_decode/jwt_decode.dart'; import 'package:nhancepolicy/customAppBar/toastHelper.dart'; import 'config/environment.dart'; +import 'package:nhancepolicy/logger.dart'; // void main() { // runApp(MaterialApp( @@ -108,15 +109,15 @@ class _MyAppState extends State { }); // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); - print(decodedToken); + logDebug(decodedToken); empCodeString = decodedToken['emp_code'].toString(); // Ensure it's a string - print(empCodeString); // Check if emp_code is correct + logDebug(empCodeString); // Check if emp_code is correct empPrimaryId = decodedToken['id'].toString(); gpaEmpName = decodedToken['name'].toString(); client_id = decodedToken['client_id'].toString(); - print(client_id); - // print(empPrimaryId); + logDebug(client_id); + // logDebug(empPrimaryId); // Call the API when the page enters getEmpDetails(empCodeString); fetchRelationshipList(); @@ -136,7 +137,8 @@ class _MyAppState extends State { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', // Add token to the Authorization header }, @@ -153,7 +155,7 @@ class _MyAppState extends State { .where((obj) => obj['relationship'] != 'Self') .toList(); nonSelfObjectsArrayDetails = nonSelfObjects; - print(nonSelfObjectsArrayDetails); + logDebug(nonSelfObjectsArrayDetails); List familyMembersFromDetails = nonSelfObjects.map((detail) { return FamilyMember( @@ -174,7 +176,7 @@ class _MyAppState extends State { personalDetails = selfObject; // Assuming the first item contains the desired details - print(personalDetails); + logDebug(personalDetails); _empCodeController.text = personalDetails != null ? personalDetails['emp_code'] ?? '' @@ -191,18 +193,18 @@ class _MyAppState extends State { _mobileController.text = personalDetails != null ? personalDetails['mobile'] ?? '' : ''; } else { - print('Empty or invalid data received'); + logDebug('Empty or invalid data received'); } } else { - print('Invalid response format: missing "data" key'); + logDebug('Invalid response format: missing "data" key'); } } else { // Handle other status codes - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -213,7 +215,8 @@ class _MyAppState extends State { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', // Add token to the Authorization header }, @@ -247,7 +250,7 @@ class _MyAppState extends State { if (gpaPolicies.isNotEmpty) { // You can use gpaPolicies as needed - print('GPA Policies found: $gpaPolicies'); + logDebug('GPA Policies found: $gpaPolicies'); gpaPolicyName = await gpaPolicies[0]['Policy_Name']; gpaGridMaster = await gpaPolicies[0]['GridMaster']; gpaSlabRates = await gpaPolicies[0]['SlabRates']; @@ -259,18 +262,18 @@ class _MyAppState extends State { gpaSelectedSI = gpaMappedFamilyFloaters['basic_cover_si'].toString(); - print(gpasumInsured); + logDebug(gpasumInsured); //find the premium amount that match sumInsured amount from policyTerm Map? findGpasumInsuredObject = gpaSlabRates.firstWhere( (rate) => rate['si'] == gpasumInsured.toString(), orElse: () => null, ); - print('test'); + logDebug('test'); if (findGpasumInsuredObject != null) { gpasumInsuredPermium = findGpasumInsuredObject['premium'].toString(); - // print(test); + // logDebug(test); } else { gpasumInsuredPermium = 0; } @@ -289,23 +292,23 @@ class _MyAppState extends State { gpaAssignSelectedSI = 0; } - print(gpaSelectedSlabRateObject); + logDebug(gpaSelectedSlabRateObject); if (gpaSelectedSlabRateObject != null) { gpaPermiumValue = gpaSelectedSlabRateObject['premium'].toString(); } else { gpaPermiumValue = 0; } - print(gpaAssignSelectedSI); + logDebug(gpaAssignSelectedSI); String stringValue = gpaSelectedSI.toString(); // Extract the string from the list int intValue1 = int.parse(stringValue); int? intValue = int.tryParse(gpasumInsured); - print('policy_trem_amound'); - print(intValue); - print("selected si"); - print(intValue1); + logDebug('policy_trem_amound'); + logDebug(intValue); + logDebug("selected si"); + logDebug(intValue1); if (intValue != null && intValue1 != null) { if (intValue < intValue1) { gpaAdditionalText = 1; @@ -314,7 +317,7 @@ class _MyAppState extends State { (rate) => rate['si'] == gpaAssignSelectedSI.toString(), orElse: () => null, ); - print(findObject); + logDebug(findObject); // setState(() { gpaAPISIDetails = findObject; @@ -327,84 +330,84 @@ class _MyAppState extends State { } else { gpaPermiumValueChanged = 0; } - print(gpaPermiumValueChanged); - print(gpaPermiumValue); + logDebug(gpaPermiumValueChanged); + logDebug(gpaPermiumValue); // Convert string values to integers int gpaSelectedPermium = int.tryParse(gpasumInsuredPermium) ?? 0; int gpaChangedPermium = int.tryParse(gpaPermiumValueChanged) ?? 0; - print('gpasumInsuredPermium'); - print(gpaSelectedPermium); - print("gpaChangedPermium"); - print(gpaChangedPermium); + logDebug('gpasumInsuredPermium'); + logDebug(gpaSelectedPermium); + logDebug("gpaChangedPermium"); + logDebug(gpaChangedPermium); // Calculate the result int? result = gpaSelectedPermium != null && gpaChangedPermium != null ? gpaChangedPermium - gpaSelectedPermium : null; - print(result); + logDebug(result); gpaAdditionalTextAmount = result; - print(gpaAdditionalText); + logDebug(gpaAdditionalText); }); } else { setState(() { gpaAdditionalText = 0; - print(gpaAdditionalText); + logDebug(gpaAdditionalText); }); } } } else { - print('GPA Policies not found'); + logDebug('GPA Policies not found'); } if (gmcPolicies.isNotEmpty) { // You can use gmcPolicies as needed - print('GMC Policies found: $gmcPolicies'); + logDebug('GMC Policies found: $gmcPolicies'); gmcPolicyName = await gmcPolicies[0]['Policy_Name']; gmcGridMaster = await gmcPolicies[0]['GridMaster']; gmcSlabRates = await gmcPolicies[0]['SlabRates']; // relationshipOptions = // await await gmcPolicies[0]['Policy_Terms']['family_floaters']; - // print(relationshipOptions); + // logDebug(relationshipOptions); gmcfamily_floaters = await gmcPolicies[0]['mapped_family_floaters']; - print(gmcfamily_floaters); + logDebug(gmcfamily_floaters); setState(() { gmcFamily_floater_Status = gmcPolicies[0]['Policy_Terms']['family_floater']; - print(gmcFamily_floater_Status); + logDebug(gmcFamily_floater_Status); }); } else { - print('GMC Policies not found'); + logDebug('GMC Policies not found'); } } else { // Handle other status messages if needed - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { // Handle other status codes - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } checkGpaSumInsured() { - print(gpaAssignSelectedSI); - // print(gpaPermiumValue); - // print(gpaSelectedSlabRateObject); + logDebug(gpaAssignSelectedSI); + // logDebug(gpaPermiumValue); + // logDebug(gpaSelectedSlabRateObject); String stringValue = gpaSelectedSI.toString(); // Extract the string from the list int intValue1 = int.parse(stringValue); int? intValue = int.tryParse(gpasumInsured); - print('policy_trem_amound'); - print(intValue); - print("selected si"); - print(intValue1); + logDebug('policy_trem_amound'); + logDebug(intValue); + logDebug("selected si"); + logDebug(intValue1); if (intValue != null && intValue1 != null) { if (intValue < intValue1) { gpaAdditionalText = 1; @@ -413,7 +416,7 @@ class _MyAppState extends State { (rate) => rate['si'] == gpaSelectedSI.toString(), orElse: () => null, ); - print(findObject); + logDebug(findObject); // setState(() { gpaAPISIDetails = findObject; @@ -425,29 +428,29 @@ class _MyAppState extends State { } else { gpaPermiumValueChanged = 0; } - print(gpaPermiumValueChanged); - print(gpaPermiumValue); + logDebug(gpaPermiumValueChanged); + logDebug(gpaPermiumValue); // Convert string values to integers int gpaSelectedPermium = int.tryParse(gpasumInsuredPermium) ?? 0; int gpaChangedPermium = int.tryParse(gpaPermiumValueChanged) ?? 0; - print('gpasumInsuredPermium'); - print(gpaSelectedPermium); - print("gpaChangedPermium"); - print(gpaChangedPermium); + logDebug('gpasumInsuredPermium'); + logDebug(gpaSelectedPermium); + logDebug("gpaChangedPermium"); + logDebug(gpaChangedPermium); // Calculate the result int? result = gpaSelectedPermium != null && gpaChangedPermium != null ? gpaChangedPermium - gpaSelectedPermium : null; - print(result); + logDebug(result); gpaAdditionalTextAmount = result; - print(gpaAdditionalText); + logDebug(gpaAdditionalText); }); } else { setState(() { gpaAdditionalText = 0; - print(gpaAdditionalText); + logDebug(gpaAdditionalText); }); } } @@ -477,7 +480,8 @@ class _MyAppState extends State { url, body: jsonEncode(requestBody), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', // Add authorization header if needed 'Authorization': 'Bearer $_token', @@ -491,11 +495,11 @@ class _MyAppState extends State { } else { // Handle other status codes // ToastHelper.showErrorToast(context, 'Failed to update user details'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); // ToastHelper.showErrorToast(context, 'Exception occurred: $e'); } } @@ -508,7 +512,8 @@ class _MyAppState extends State { final response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', // Add token to the Authorization header }, @@ -526,7 +531,7 @@ class _MyAppState extends State { } catch (error) { // ToastHelper.showErrorToast( // context, 'Error fetching relationship list: $error'); - print('Error fetching relationship list: $error'); + logDebug('Error fetching relationship list: $error'); // Handle error accordingly, e.g., show a snackbar with an error message } } @@ -538,20 +543,20 @@ class _MyAppState extends State { } // void removeFamilyMember(int index) { - // print(index); + // logDebug(index); // setState(() { // familyMembers.removeAt(index); // }); - // print(familyMembers.toString()); + // logDebug(familyMembers.toString()); // } void removeFamilyMember(int index) async { - print(index); - // print(nonSelfObjectsArrayDetails[index]); + logDebug(index); + // logDebug(nonSelfObjectsArrayDetails[index]); // return; try { if (index >= 0 && index < nonSelfObjectsArrayDetails.length) { var removeObject = nonSelfObjectsArrayDetails[index] ?? false; - print(removeObject); + logDebug(removeObject); if (removeObject != false) { final id = nonSelfObjectsArrayDetails[index]['id']; // If the family member has an ID, it means it's an existing record, so make an API call to delete it @@ -560,7 +565,8 @@ class _MyAppState extends State { final response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', 'Authorization': 'Bearer $_token', // Add token to the Authorization header // Add your authorization token here @@ -573,10 +579,10 @@ class _MyAppState extends State { familyMembers.removeAt(index); nonSelfObjectsArrayDetails.removeAt(index); }); - print('Family member removed successfully'); + logDebug('Family member removed successfully'); } else { // If API call fails, print error message - print('Failed to remove family member: ${response.statusCode}'); + logDebug('Failed to remove family member: ${response.statusCode}'); } } else { // If the family member doesn't have an ID, it's a new record, so simply remove it from the list locally @@ -591,20 +597,20 @@ class _MyAppState extends State { } } catch (error) { // Handle any errors that occur during the API call - // print('Error removing family member: $error'); + // logDebug('Error removing family member: $error'); // ToastHelper.showErrorToast( // context, 'Error removing family member: $error'); } } void saveFamilyMemberDetails() async { - print(nonSelfObjectsArrayDetails); + logDebug(nonSelfObjectsArrayDetails); try { // Convert familyMembers list to a list of JSON objects // Convert familyMembers list to a list of JSON objects final List> membersData = familyMembers.map((member) { - print(member); + logDebug(member); // Include additional fields from personalDetails return { 'relationship': member.relationship, @@ -614,7 +620,7 @@ class _MyAppState extends State { 'client_id': personalDetails['client_id'], }; }).toList(); - print(membersData); + logDebug(membersData); List> updatedNewData = List>.generate(membersData.length, (index) { @@ -625,7 +631,7 @@ class _MyAppState extends State { } return updatedEntry; }); - print(updatedNewData); + logDebug(updatedNewData); // Iterate through familyMembers list and send each member's data to the API final url = Uri.parse(Environment.apiUrl + 'addEmployeeAndDependence'); @@ -633,7 +639,8 @@ class _MyAppState extends State { url, body: jsonEncode(updatedNewData), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', 'Authorization': 'Bearer $_token', // Add token to the Authorization header @@ -660,7 +667,7 @@ class _MyAppState extends State { void sendGpaDataToAPI() async { // Create a list to store the selected values for each floater - print(gpaAPISIDetails); + logDebug(gpaAPISIDetails); String si = gpaSelectedSI ?? ''; // String premium = gpaAPISIDetails['premium']; String ClientPolicyId = gpaClintPolicyId; @@ -679,11 +686,11 @@ class _MyAppState extends State { gpaApiData = floaterData; - print(gpaApiData); + logDebug(gpaApiData); try { final jsonData = gpaApiData; - print(jsonData); + logDebug(jsonData); // return; // Iterate through familyMembers list and send each member's data to the API @@ -693,7 +700,8 @@ class _MyAppState extends State { url, body: jsonEncode(jsonData), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', 'Authorization': 'Bearer $_token', // Add token to the Authorization header @@ -710,15 +718,15 @@ class _MyAppState extends State { }); floaterData = []; // ToastHelper.showSuccessToast(context, "Saved successfully!"); - print('Saved successfully!'); + logDebug('Saved successfully!'); } } else { // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); - print('Operation Failed!'); + logDebug('Operation Failed!'); } } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); } } @@ -727,7 +735,7 @@ class _MyAppState extends State { // Create a list to store the selected values for each floater List> selectedValues = []; // try { - print('fff'); + logDebug('fff'); // Iterate through each floater and get its selected value // Iterate through each floater and get its selected value for (var floater in gmcfamily_floaters) { @@ -750,7 +758,7 @@ class _MyAppState extends State { } final jsonData = selectedValues; - print(jsonData); + logDebug(jsonData); // return; // Iterate through each object in apidata for (var data in jsonData) { @@ -766,8 +774,8 @@ class _MyAppState extends State { } } } - print("gwm"); - print(jsonData); + logDebug("gwm"); + logDebug(jsonData); // return; // Iterate through familyMembers list and send each member's data to the API final url = @@ -776,7 +784,8 @@ class _MyAppState extends State { url, body: jsonEncode(jsonData), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', 'Authorization': 'Bearer $_token', // Add token to the Authorization header @@ -791,15 +800,15 @@ class _MyAppState extends State { getEmpDetails(empCodeString); }); // ToastHelper.showSuccessToast(context, "Saved successfully!"); - print('Saved successfully!'); + logDebug('Saved successfully!'); } } else { - print('Operation Failed!'); + logDebug('Operation Failed!'); // Failed to save member // ToastHelper.showErrorToast(context, "Operation Failed!"); } // } catch (error) { - print('Error saving family members'); + logDebug('Error saving family members'); // ToastHelper.showErrorToast(context, "Error saving family members"); // } } diff --git a/lib/hrHome.dart b/lib/hrHome.dart index 8465391..7cc2bc0 100755 --- a/lib/hrHome.dart +++ b/lib/hrHome.dart @@ -18,6 +18,7 @@ import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart' as path; import 'config/environment.dart'; +import 'package:nhancepolicy/logger.dart'; class MyHrHome extends StatefulWidget { const MyHrHome({Key? key}) : super(key: key); @@ -95,30 +96,31 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', }, ); if (response.statusCode == 200) { Map data = json.decode(response.body); if (data['status'] == 'success') { - print(data); + logDebug(data); setState(() { dataPolicy = List>.from(data['data']); - print(dataPolicy); + logDebug(dataPolicy); // reversedDataPolicy = dataPolicy.reversed.toList(); // getPolicyNameDetails0 = dataPolicy[0]['policy_name']; - // print(getPolicyNameDetails0); + // logDebug(getPolicyNameDetails0); // getPolicyNameDetails1 = dataPolicy[1]['policy_name']; - // print(getPolicyNameDetails1); + // logDebug(getPolicyNameDetails1); // getPolicyNameDetails2 = dataPolicy[2]['policy_name']; - // print(getPolicyNameDetails2); + // logDebug(getPolicyNameDetails2); // getPolicyNo0 = dataPolicy[0]['client_policy_id']; - // print(getPolicyNameDetails1); + // logDebug(getPolicyNameDetails1); // getPolicyNo1 = dataPolicy[1]['client_policy_id']; - // print(getPolicyNameDetails1); + // logDebug(getPolicyNameDetails1); // getPolicyNo2 = dataPolicy[2]['client_policy_id']; - // print(getPolicyNameDetails2); + // logDebug(getPolicyNameDetails2); }); // Code to execute periodically every 2 seconds dataPolicy.forEach((policy) { @@ -147,15 +149,15 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { } else { ToastHelper.showWarningToast( context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { ToastHelper.showWarningToast( context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -173,7 +175,8 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', }, ); @@ -185,21 +188,21 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { List>.from(data['data']); originalDataGpa = getEmpDependenceByClintIdGPA; filteredDataGpa = List.from(originalDataGpa); - print('filteredDataGpa'); - print(filteredDataGpa); + logDebug('filteredDataGpa'); + logDebug(filteredDataGpa); }); } else { ToastHelper.showWarningToast( context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { ToastHelper.showWarningToast( context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -217,7 +220,8 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', }, ); @@ -233,15 +237,15 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { } else { ToastHelper.showErrorToast( context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { ToastHelper.showErrorToast( context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -259,7 +263,8 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', }, ); @@ -275,15 +280,15 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { } else { ToastHelper.showErrorToast( context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { ToastHelper.showErrorToast( context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -303,7 +308,8 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { url, headers: { 'Authorization': 'Bearer $_token', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }, ); if (response.statusCode == 200) { @@ -320,15 +326,15 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { } else { ToastHelper.showErrorToast( context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { ToastHelper.showErrorToast( context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -443,7 +449,8 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', }, ); @@ -467,7 +474,7 @@ class _MyHrHomeState extends State with TickerProviderStateMixin { html.Url.revokeObjectUrl(url); } else { // Handle error - print('Failed to download Excel file: ${response.statusCode}'); + logDebug('Failed to download Excel file: ${response.statusCode}'); } } @@ -1306,7 +1313,7 @@ class _DependenceDataSource0 extends DataTableSource { int get selectedRowCount => 0; void _navigateToAnotherPage(row) { - print(row['mobile']); + logDebug(row['mobile']); // Navigation logic here Navigator.pushNamed(context, 'empDetails', arguments: {'mobile': row['mobile']}); @@ -1369,7 +1376,7 @@ class _DependenceDataSource1 extends DataTableSource { int get selectedRowCount => 0; void _navigateToAnotherPage(row) { - print(row); + logDebug(row); Navigator.pushNamed(context, 'empDetails', arguments: {'mobile': row['mobile']}); } @@ -1432,7 +1439,7 @@ class _DependenceDataSource2 extends DataTableSource { int get selectedRowCount => 0; void _navigateToAnotherPage(row) { - print(row); + logDebug(row); Navigator.pushNamed(context, 'empDetails', arguments: {'mobile': row['mobile']}); } @@ -1495,7 +1502,7 @@ class _DependenceDataSource3 extends DataTableSource { int get selectedRowCount => 0; void _navigateToAnotherPage(row) { - print(row); + logDebug(row); Navigator.pushNamed(context, 'empDetails', arguments: {'mobile': row['mobile']}); } diff --git a/lib/hrLogin.dart b/lib/hrLogin.dart index 9ba9013..2347a16 100755 --- a/lib/hrLogin.dart +++ b/lib/hrLogin.dart @@ -17,6 +17,7 @@ import 'package:url_launcher/url_launcher.dart'; import 'config/environment.dart'; import 'email_verify.dart'; +import 'package:nhancepolicy/logger.dart'; class MyHrLogin extends StatefulWidget { const MyHrLogin({Key? key}); @@ -45,24 +46,21 @@ class _MyPhoneState extends State { @override void initState() { - print('vndbbcbdskbvkjs1'); + logDebug('vndbbcbdskbvkjs1'); // countryController.text = "+91"; super.initState(); clearLocalStorageWhenStarts('initState'); } - clearLocalStorageWhenStarts(fromData) async { - print(fromData); - print('Clearing secure storage on app start'); + logDebug(fromData); + logDebug('Clearing secure storage on app start'); await tokenService.clearAll(); - print('Secure Storage Cleared'); + logDebug('Secure Storage Cleared'); } - - void toggleField() { setState(() { isEmailFieldVisible = !isEmailFieldVisible; @@ -71,7 +69,7 @@ class _MyPhoneState extends State { Future verifyMobileAndEmailNumber() async { await tokenService.clearAll(); - print('verifyMobileAndEmailNumber :- Local Storage Clear'); + logDebug('verifyMobileAndEmailNumber :- Local Storage Clear'); try { if (_formKey.currentState!.validate()) { setState(() { @@ -87,13 +85,12 @@ class _MyPhoneState extends State { setState(() { isEmailFieldVisible = true; }); - print("User entered Email: $input"); + logDebug("User entered Email: $input"); } else if (isMobile) { isEmailFieldVisible = false; - print("User entered Mobile: $input"); + logDebug("User entered Mobile: $input"); } - // Determine the API and the payload based on the visible field String apiEndpoint = isEmailFieldVisible ? Environment.apiUrl + 'verifyHrWithEmail' @@ -108,7 +105,8 @@ class _MyPhoneState extends State { Uri.parse(apiEndpoint), body: json.encode(payload), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); @@ -119,33 +117,37 @@ class _MyPhoneState extends State { String message = data['data']['message']; if (userVerification) { if (isEmailFieldVisible) { - print('isEmailFieldVisible $isEmailFieldVisible'); + logDebug('isEmailFieldVisible $isEmailFieldVisible'); await tokenService.writeValue( 'empEmail', emailMobileController.text, ); - // print('${emailMobileController.text}'); + // logDebug('${emailMobileController.text}'); // final message = 'Verification code sent to ${emailMobileController.text}'; - ToastHelper.showSuccessToast(context, 'Verification code sent to ${emailMobileController.text}'); + ToastHelper.showSuccessToast(context, + 'Verification code sent to ${emailMobileController.text}'); Navigator.push( context, MaterialPageRoute( builder: (context) => MyEmailVerify( type: 'email', - value: emailMobileController.text.trim(), // Pass the phone number + value: emailMobileController.text + .trim(), // Pass the phone number ), ), ); } else { // final message = 'Verification code sent to ${emailMobileController.text}'; - ToastHelper.showSuccessToast(context, 'Verification code sent to ${emailMobileController.text}'); + ToastHelper.showSuccessToast(context, + 'Verification code sent to ${emailMobileController.text}'); Navigator.push( context, MaterialPageRoute( builder: (context) => MyEmailVerify( type: 'mobile', - value: emailMobileController.text.trim(), // Pass the phone number + value: emailMobileController.text + .trim(), // Pass the phone number ), ), ); @@ -157,7 +159,7 @@ class _MyPhoneState extends State { _isLoading = false; }); ToastHelper.showErrorToast(context, message); - print('Invalid mobile number'); + logDebug('Invalid mobile number'); } } else if (response.statusCode == 429) { setState(() { @@ -181,14 +183,14 @@ class _MyPhoneState extends State { _isLoading = false; }); ToastHelper.showErrorToast(context, 'Something went wrong'); - print('Error: $e'); + logDebug('Error: $e'); } } // Future _verifyPhoneNumber() async { // var enteredMobileNumber = mobileController.text; // var countryCode = countryController.text; - // print('${countryCode + enteredMobileNumber}'); + // logDebug('${countryCode + enteredMobileNumber}'); // await _auth.verifyPhoneNumber( // phoneNumber: '${countryCode + enteredMobileNumber}', // timeout: const Duration(seconds: 60), @@ -200,7 +202,7 @@ class _MyPhoneState extends State { // // }); // }, // verificationFailed: (FirebaseAuthException e) { - // print('Verification Failed: ${e.code} - ${e.message}'); + // logDebug('Verification Failed: ${e.code} - ${e.message}'); // String errorMessage; // if (e.code == 'invalid-app-credential') { // errorMessage = 'Invalid Credential. Please try again.'; @@ -275,7 +277,7 @@ class _MyPhoneState extends State { // }, // verificationFailed: (FirebaseAuthException e) { // if (e.code == 'invalid-phone-number') { - // print('The provided phone number is not valid.'); + // logDebug('The provided phone number is not valid.'); // } // }, // codeSent: (String verificationId, int? resendToken) async { @@ -328,14 +330,13 @@ class _MyPhoneState extends State { ], ), ), - child: Center( child: Container( - width: double.infinity, // ✅ fixed web width - height: _size.height, // ✅ fixed web height (IMPORTANT) + width: double.infinity, // ✅ fixed web width + height: _size.height, // ✅ fixed web height (IMPORTANT) margin: const EdgeInsets.all(60), clipBehavior: Clip.hardEdge, - decoration: BoxDecoration( + decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(40)), ), @@ -375,11 +376,9 @@ class _MyPhoneState extends State { ), SizedBox(height: 25), Container( - margin: EdgeInsets.symmetric( - horizontal: 150), + margin: EdgeInsets.symmetric(horizontal: 150), child: Row( - mainAxisAlignment: - MainAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( @@ -396,9 +395,11 @@ class _MyPhoneState extends State { SizedBox(height: 20), Container( height: 55, - margin: const EdgeInsets.symmetric(horizontal: 150) , + margin: + const EdgeInsets.symmetric(horizontal: 150), decoration: BoxDecoration( - border: Border.all(width: 1, color: Colors.grey), + border: + Border.all(width: 1, color: Colors.grey), borderRadius: BorderRadius.circular(10), ), child: TextFormField( @@ -407,10 +408,12 @@ class _MyPhoneState extends State { decoration: const InputDecoration( border: InputBorder.none, hintText: "Email / Mobile Number ", - contentPadding: EdgeInsets.symmetric(horizontal: 10), + contentPadding: + EdgeInsets.symmetric(horizontal: 10), ), validator: (value) { - if (value == null || value.trim().isEmpty) { + if (value == null || + value.trim().isEmpty) { return "Please enter email or mobile number"; } @@ -421,11 +424,15 @@ class _MyPhoneState extends State { return "No spaces allowed"; } - final emailRegex = RegExp(r'^[^@]+@[^@]+\.[^@]+$'); - final mobileRegex = RegExp(r'^[0-9]{10}$'); + final emailRegex = + RegExp(r'^[^@]+@[^@]+\.[^@]+$'); + final mobileRegex = + RegExp(r'^[0-9]{10}$'); - bool isEmailFormat = emailRegex.hasMatch(input); - bool isMobileFormat = mobileRegex.hasMatch(input); + bool isEmailFormat = + emailRegex.hasMatch(input); + bool isMobileFormat = + mobileRegex.hasMatch(input); // --------------------------- // 🛑 MOBILE VALIDATION @@ -441,27 +448,33 @@ class _MyPhoneState extends State { // --------------------------- // Reject anything that has '@' but is NOT a valid email format - if (input.contains('@') && !isEmailFormat) { + if (input.contains('@') && + !isEmailFormat) { return "Enter a valid email address"; } // Reject email with extra digits at the end - if (input.contains('@') && RegExp(r'\d+$').hasMatch(input)) { + if (input.contains('@') && + RegExp(r'\d+$').hasMatch(input)) { return "Email cannot contain extra numbers"; } // Reject email+mobile combination - if (input.contains('@') && RegExp(r'\d{10}$').hasMatch(input)) { + if (input.contains('@') && + RegExp(r'\d{10}$').hasMatch(input)) { return "Enter only email OR mobile number"; } // --------------------------- // 🛑 MIXED CONTENT (letters + digits but NOT email) // --------------------------- - bool hasLetters = RegExp(r'[A-Za-z]').hasMatch(input); - bool hasDigits = RegExp(r'[0-9]').hasMatch(input); + bool hasLetters = + RegExp(r'[A-Za-z]').hasMatch(input); + bool hasDigits = + RegExp(r'[0-9]').hasMatch(input); - if ((hasLetters && hasDigits) && !input.contains('@')) { + if ((hasLetters && hasDigits) && + !input.contains('@')) { return "Enter only email OR 10-digit mobile number"; } @@ -473,27 +486,19 @@ class _MyPhoneState extends State { } return null; - } - - ), + }), ), SizedBox(height: 20), Container( - margin: EdgeInsets.symmetric( - horizontal: 150), + margin: EdgeInsets.symmetric(horizontal: 150), child: SizedBox( width: double.infinity, height: 45, child: ElevatedButton( - style: ElevatedButton - .styleFrom( - backgroundColor: - Color(0xFF00989E), - shape: - RoundedRectangleBorder( - borderRadius: - BorderRadius - .circular(10), + style: ElevatedButton.styleFrom( + backgroundColor: Color(0xFF00989E), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), ), ), onPressed: _isLoading @@ -501,19 +506,17 @@ class _MyPhoneState extends State { : verifyMobileAndEmailNumber, child: _isLoading ? const CircularProgressIndicator( - valueColor: - AlwaysStoppedAnimation< - Color>( - Color(0xFF00989E), - ), - ) - : Text( "Login with Email / Mobile OTP", - style: GoogleFonts - .poppins( - color: const Color( - 0xFFFFFFFF), - ), - ), + valueColor: + AlwaysStoppedAnimation( + Color(0xFF00989E), + ), + ) + : Text( + "Login with Email / Mobile OTP", + style: GoogleFonts.poppins( + color: const Color(0xFFFFFFFF), + ), + ), ), ), ), @@ -521,7 +524,8 @@ class _MyPhoneState extends State { Container( width: double.infinity, alignment: Alignment.bottomCenter, - padding: const EdgeInsets.symmetric(vertical: 8), + padding: + const EdgeInsets.symmetric(vertical: 8), child: RichText( textAlign: TextAlign.center, text: TextSpan( @@ -544,7 +548,8 @@ class _MyPhoneState extends State { 'https://nhanceindia.in/privacy-policy/'); if (await canLaunchUrl(url)) { await launchUrl(url, - mode: LaunchMode.externalApplication); + mode: LaunchMode + .externalApplication); } }, ), @@ -568,7 +573,8 @@ class _MyPhoneState extends State { 'https://nhanceindia.in/privacy-policy/'); if (await canLaunchUrl(url)) { await launchUrl(url, - mode: LaunchMode.externalApplication); + mode: LaunchMode + .externalApplication); } }, ), @@ -627,9 +633,6 @@ class _MyPhoneState extends State { ], ), ), - ) - - ) - ); + ))); } } diff --git a/lib/hrVerify.dart b/lib/hrVerify.dart index 6ac8865..6d987e0 100755 --- a/lib/hrVerify.dart +++ b/lib/hrVerify.dart @@ -85,8 +85,8 @@ // // checkTokenAvailability(); // verificationId = widget.verificationId; // mobileNumber = widget.mobileNumber; -// print('Received verificationId: $verificationId'); -// print('Received mobileNumber: $mobileNumber'); +// logDebug('Received verificationId: $verificationId'); +// logDebug('Received mobileNumber: $mobileNumber'); // if (verificationId.isEmpty) { // // Handle the case where verificationId is not provided // Navigator.pop(context); @@ -103,7 +103,7 @@ // // void logOutFirebase() async { // await _auth.signOut(); -// print('User signed out'); +// logDebug('User signed out'); // } // // @override @@ -143,7 +143,7 @@ // }); // Map data = json.decode(response.body); // -// print('Response data: $data'); +// logDebug('Response data: $data'); // // // Extract enrollment data // List preEnrollmentData = data['data'] ?? []; @@ -165,13 +165,13 @@ // ), // ); // -// // print('data: $data'); +// // logDebug('data: $data'); // // _token = data['data']; // // String status = data['status']; // // // // // Directly access the post_enrollment data // // Map post = data['post_enrollment']; -// // print('post: $post'); +// // logDebug('post: $post'); // // // // _postToken = post['data']; // // String postStatus = post['status']; @@ -192,7 +192,7 @@ // // }); // // ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again'); // // // Show a Snackbar if the OTP is invalid -// // print('Invalid OTP. Please try again'); +// // logDebug('Invalid OTP. Please try again'); // // } // } else { // setState(() { @@ -205,10 +205,10 @@ // setState(() { // _isLoading = false; // }); -// print('Error: $e'); +// logDebug('Error: $e'); // ToastHelper.showWarningToast(context, 'Something went wrong'); // // Show a Snackbar if there's an error while verifying OTP -// print('Failed to verify OTP. Please try again.'); +// logDebug('Failed to verify OTP. Please try again.'); // } // } // @@ -222,7 +222,7 @@ // // // Decode the JWT token received from the API response // Map? decodedToken = Jwt.parseJwt(post['data']); -// print('postdecodedToken : $decodedToken'); +// logDebug('postdecodedToken : $decodedToken'); // empClientBranchId = decodedToken['ref_id']; // prefs.setString('empClientBranchId', empClientBranchId); // empCodeString = decodedToken['emp_code'].toString(); @@ -247,7 +247,7 @@ // // // Decode the JWT token received from the API response // Map? decodedToken = Jwt.parseJwt(data['data']); -// print('decodedToken : $decodedToken'); +// logDebug('decodedToken : $decodedToken'); // enrollmentEmpClientBranchId = decodedToken['ref_id']; // prefs.setString( // 'enrollmentEmpClientBranchId', enrollmentEmpClientBranchId); @@ -288,7 +288,7 @@ // // // Decode the JWT token received from the API response // Map? decodedToken = Jwt.parseJwt(data['data']); -// print('enrolldecodedToken : $decodedToken'); +// logDebug('enrolldecodedToken : $decodedToken'); // enrollmentEmpClientBranchId = decodedToken['ref_id']; // prefs.setString('enrollmentEmpClientBranchId', enrollmentEmpClientBranchId); // enrollmentEmpCodeString = decodedToken['emp_code'].toString(); @@ -308,7 +308,7 @@ // // enrollmentEmp_status = decodedToken['emp_status']; // // prefs.setString('enrollmentEmp_status', enrollmentEmp_status); // -// print('Successfully Login'); +// logDebug('Successfully Login'); // // // Redirect to another page // final enrollToken = prefs.getString('enrollToken'); @@ -399,7 +399,7 @@ // // setState(() { // // _isLoading = false; // // }); -// print('Error: $e'); +// logDebug('Error: $e'); // ToastHelper.showErrorToast( // context, 'Failed to verify OTP. Please try again.'); // } diff --git a/lib/logger.dart b/lib/logger.dart new file mode 100644 index 0000000..d3ca92e --- /dev/null +++ b/lib/logger.dart @@ -0,0 +1,111 @@ +import 'dart:developer' as developer; + +import 'package:flutter/foundation.dart'; +import 'package:nhancepolicy/config/environment.dart'; + +String _formatMessage( + String message, { + String? className, + String? methodName, +}) { + final timestamp = DateTime.now().toIso8601String(); + final contextParts = []; + if (className != null && className.isNotEmpty) { + contextParts.add(className); + } + if (methodName != null && methodName.isNotEmpty) { + contextParts.add(methodName); + } + final context = contextParts.isEmpty ? '' : '[${contextParts.join('.')}] '; + return '[$timestamp] $context$message'; +} + +void _log( + String level, + String message, { + String tag = 'APP', + Object? error, + StackTrace? stackTrace, + String? className, + String? methodName, +}) { + final shouldLog = kDebugMode || Environment.flavor == Flavor.dev; + if (!shouldLog) { + return; + } + final formatted = + _formatMessage(message, className: className, methodName: methodName); + final channel = '$tag:$level'; + + developer.log( + formatted, + name: channel, + error: error, + stackTrace: stackTrace, + ); + debugPrint('[$channel] $formatted'); +} + +void logDebug( + Object? message, { + String tag = 'APP', + String? className, + String? methodName, +}) { + _log( + 'DEBUG', + '${message ?? 'null'}', + tag: tag, + className: className, + methodName: methodName, + ); +} + +void logInfo( + Object? message, { + String tag = 'APP', + String? className, + String? methodName, +}) { + _log( + 'INFO', + '${message ?? 'null'}', + tag: tag, + className: className, + methodName: methodName, + ); +} + +void logWarning( + Object? message, { + String tag = 'APP', + String? className, + String? methodName, +}) { + _log( + 'WARN', + '${message ?? 'null'}', + tag: tag, + className: className, + methodName: methodName, + ); +} + +void logError( + Object? message, { + String tag = 'APP', + Object? error, + StackTrace? stackTrace, + String? className, + String? methodName, +}) { + _log( + 'ERROR', + '${message ?? 'null'}', + tag: tag, + error: error, + stackTrace: stackTrace, + className: className, + methodName: methodName, + ); +} diff --git a/lib/main.dart b/lib/main.dart index 9047dc4..325caa8 100755 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:nhancepolicy/addons.dart'; @@ -28,10 +27,11 @@ import 'package:firebase_core/firebase_core.dart'; import 'presentation/cdTransactionDetails.dart'; import 'config/environment.dart'; import 'email_verify.dart'; +import 'package:nhancepolicy/logger.dart'; Future startApp() async { // html.window.onBeforeUnload.listen((event) { - // print('Local Storage cleared by window'); + // logDebug('Local Storage cleared by window'); // html.window.localStorage.clear(); // }); // Ask confirmation (browser may or may not show it again) @@ -216,16 +216,15 @@ class MyApp extends StatelessWidget { final Map appRoutes = { 'phone': (context) => MyPhone(), 'mailVerify': (context) => MyEmailVerify( - type: '', - value: '', - - ), + type: '', + value: '', + ), 'verify': (context) => MyVerify( - verificationId: '', - mobileNumber: '', - resendToken: null, - onResendCode: (String, int) {}, - ), + verificationId: '', + mobileNumber: '', + resendToken: null, + onResendCode: (String, int) {}, + ), 'home': (context) => MyApp(), 'hrLogin': (context) => MyHrLogin(), // 'hrVerify': (context) => MyHrVerify( @@ -236,33 +235,33 @@ final Map appRoutes = { // ), 'hrHome': (context) => MyHrHome(), 'preFileUpload': (context) => const preFileUpload( - ClientId: '', - policyTypeId: '', - ClientPoliyId: '', - clientBranchId: '', - Token: '', - TokenType: '', - cardType: '', - cardPolicyNo: '', - cardInsurer_name: '', - cardPolicy_name: '', - cardPolicy_ExpDate: '', - total_premium: '', - ), + ClientId: '', + policyTypeId: '', + ClientPoliyId: '', + clientBranchId: '', + Token: '', + TokenType: '', + cardType: '', + cardPolicyNo: '', + cardInsurer_name: '', + cardPolicy_name: '', + cardPolicy_ExpDate: '', + total_premium: '', + ), 'postFileUpload': (context) => const postFileUpload( - ClientId: '', - policyTypeId: '', - ClientPoliyId: '', - clientBranchId: '', - Token: '', - TokenType: '', - cardType: '', - cardPolicyNo: '', - cardInsurer_name: '', - cardPolicy_name: '', - cardPolicy_ExpDate: '', - total_premium: '', - ), + ClientId: '', + policyTypeId: '', + ClientPoliyId: '', + clientBranchId: '', + Token: '', + TokenType: '', + cardType: '', + cardPolicyNo: '', + cardInsurer_name: '', + cardPolicy_name: '', + cardPolicy_ExpDate: '', + total_premium: '', + ), 'excelErrorScreen': (context) => const excelErrorScreen( ClientId: '', policy_no: '', @@ -271,41 +270,40 @@ final Map appRoutes = { clientBranchId: '', Token: '', TokenType: '', - id: '' - ), + id: ''), 'empDetails': (context) => empDetails(), 'addOnsDetails': (context) => addOnsDetails(), 'empReviewDetails': (context) => empReviewDetails(), 'hrDashboard': (context) => hrDashboard(), 'hrPolicyDetails': (context) => hrPolicyDetails( - ClientId: '', - policyTypeId: '', - ClientPoliyId: '', - clientBranchId: '', - Token: '', - TokenType: '', - cardType: '', - cardPolicyNo: '', - cardInsurer_name: '', - cardPolicy_name: '', - cardPolicy_ExpDate: '', - total_premium: '', - is_ecard_bulk_download_for_employee: 0, - ), + ClientId: '', + policyTypeId: '', + ClientPoliyId: '', + clientBranchId: '', + Token: '', + TokenType: '', + cardType: '', + cardPolicyNo: '', + cardInsurer_name: '', + cardPolicy_name: '', + cardPolicy_ExpDate: '', + total_premium: '', + is_ecard_bulk_download_for_employee: 0, + ), 'oldPolicy': (context) => oldPolicy(), 'branchSelection': (context) => BranchSelectionPage(), 'policies': (context) => policies(), 'CdPoliciesList': (context) => CdPoliciesList(), 'ClaimsPolicies': (context) => ClaimsPolicies( - empCode:'', - ), + empCode: '', + ), 'cdTransactionDetails': (context) => cdTransactionDetails( - insurerName: '', - cdMasterAccountNo: '', - insurerId: '', - cd_ac_pk: '', - empClientId: '', - ), + insurerName: '', + cdMasterAccountNo: '', + insurerId: '', + cd_ac_pk: '', + empClientId: '', + ), }; /// 🔐 Global Auth Wrapper (Protects All Pages) @@ -330,8 +328,7 @@ class _AuthWrapperState extends State { if (token == null || token.isEmpty) { WidgetsBinding.instance.addPostFrameCallback((_) { - Navigator.pushNamedAndRemoveUntil( - context, 'hrLogin', (route) => false); + Navigator.pushNamedAndRemoveUntil(context, 'hrLogin', (route) => false); }); } } diff --git a/lib/oldPolicy.dart b/lib/oldPolicy.dart index 87e41ba..d4a099c 100755 --- a/lib/oldPolicy.dart +++ b/lib/oldPolicy.dart @@ -11,6 +11,7 @@ import 'package:http/http.dart' as http; import 'config/environment.dart'; import 'customAppBar/customAppBar.dart'; import 'customAppBar/toastHelper.dart'; +import 'package:nhancepolicy/logger.dart'; class oldPolicy extends StatefulWidget { const oldPolicy({Key? key}) : super(key: key); @@ -53,7 +54,7 @@ class _oldPolicyState extends State { } Future _loadToken() async { - print('_loadToken'); + logDebug('_loadToken'); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? token = prefs.getString('token'); if (token != null && token.isNotEmpty) { @@ -62,14 +63,14 @@ class _oldPolicyState extends State { }); // Decode the JWT token received from the API response Map? decodedToken = Jwt.parseJwt(token); - print(decodedToken); + logDebug(decodedToken); empClientBranchId = prefs.getString('empClientBranchId'); empCodeString = prefs.getString('empCode'); - print(empCodeString); // Check if emp_code is correct + logDebug(empCodeString); // Check if emp_code is correct empPrimaryId = prefs.getString('empPrimaryId'); gpaEmpName = prefs.getString('gpaEmpName'); client_id = prefs.getString('client_id'); - print(client_id); + logDebug(client_id); getOldPolicyDetails(); } else { // Token is empty or null, handle accordingly (e.g., navigate to login screen) @@ -95,10 +96,10 @@ class _oldPolicyState extends State { if (data['status'] == 'success') { setState(() { oldPolicyList = data['data']; - print('gmcPolicies'); + logDebug('gmcPolicies'); }); // Assuming data is a List - print(oldPolicyList); + logDebug(oldPolicyList); } else { setState(() { oldPolicyDataIsEmpty = 0; @@ -106,7 +107,7 @@ class _oldPolicyState 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']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { setState(() { @@ -115,11 +116,11 @@ class _oldPolicyState extends State { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -185,8 +186,8 @@ class _oldPolicyState extends State { List generateGmcCards(List data) { List cards = []; - print('data'); - print(data); + logDebug('data'); + logDebug(data); for (var item in data) { setState(() { diff --git a/lib/phone.dart b/lib/phone.dart index fb8a2d3..c9fbf2f 100755 --- a/lib/phone.dart +++ b/lib/phone.dart @@ -13,6 +13,7 @@ import 'package:flutter_animated_button/flutter_animated_button.dart'; import 'package:google_fonts/google_fonts.dart'; import 'config/environment.dart'; +import 'package:nhancepolicy/logger.dart'; class MyPhone extends StatefulWidget { const MyPhone({Key? key}); @@ -62,7 +63,8 @@ class _MyPhoneState extends State { Uri.parse(Environment.apiUrl + 'verifyEmployeeNumber'), body: json.encode({'mobile_number': enteredMobileNumber}), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); @@ -78,7 +80,7 @@ class _MyPhoneState extends State { // arguments: enteredMobileNumber); } else { ToastHelper.showErrorToast(context, message); - print('Invalid mobile number'); + logDebug('Invalid mobile number'); } } else { ToastHelper.showErrorToast(context, 'Something went wrong'); @@ -87,14 +89,14 @@ class _MyPhoneState extends State { } } catch (e) { ToastHelper.showErrorToast(context, 'Something went wrong'); - print('Error: $e'); + logDebug('Error: $e'); } } Future _verifyPhoneNumber() async { var enteredMobileNumber = mobileController.text; var countryCode = countryController.text; - print('${countryCode + enteredMobileNumber}'); + logDebug('${countryCode + enteredMobileNumber}'); await _auth.verifyPhoneNumber( phoneNumber: '${countryCode + enteredMobileNumber}', timeout: const Duration(seconds: 60), @@ -108,7 +110,7 @@ class _MyPhoneState extends State { verificationFailed: (FirebaseAuthException e) { ToastHelper.showSuccessToast(context, 'Verification Failed!'); if (e.code == 'invalid-phone-number') { - print('The provided phone number is not valid.'); + logDebug('The provided phone number is not valid.'); } setState(() { _isLoading = false; @@ -158,7 +160,7 @@ class _MyPhoneState extends State { }, verificationFailed: (FirebaseAuthException e) { if (e.code == 'invalid-phone-number') { - print('The provided phone number is not valid.'); + logDebug('The provided phone number is not valid.'); } }, codeSent: (String verificationId, int? resendToken) { diff --git a/lib/presentation/RaiseClaimForm.dart b/lib/presentation/RaiseClaimForm.dart index fa41f61..19316e8 100644 --- a/lib/presentation/RaiseClaimForm.dart +++ b/lib/presentation/RaiseClaimForm.dart @@ -18,6 +18,7 @@ import 'package:file_picker/file_picker.dart'; import '../service/multi_file_upload_widget.dart'; import '../service/token_storage_service.dart'; import 'package:pdf/widgets.dart' as pw; +import 'package:nhancepolicy/logger.dart'; class RaiseClaimDialog extends StatefulWidget { final BuildContext parentContext; @@ -215,13 +216,14 @@ class _RaiseClaimDialogState extends State { } Future getClaimsPoliciesDetails() async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); - final response = await apiService.getClaimPoliciesToApi(_postPreToken!,empClientId); + logDebug('10'); + final response = + await apiService.getClaimPoliciesToApi(_postPreToken!, empClientId); if (response['status'] == 'success') { setState(() { isLoading = false; @@ -235,8 +237,9 @@ class _RaiseClaimDialogState extends State { }) .toList(); - claimTypeMap = Map.from(getClaimPoliciesApi['claim_type']); - print('claimTypeMap $claimTypeMap'); + claimTypeMap = + Map.from(getClaimPoliciesApi['claim_type']); + logDebug('claimTypeMap $claimTypeMap'); }); } else { setState(() { @@ -245,13 +248,13 @@ class _RaiseClaimDialogState extends State { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { // isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { // _isLoading = false; @@ -261,11 +264,11 @@ class _RaiseClaimDialogState extends State { Future getPostCashDepositDetails( empClientBranchId, empClientId, empHrId, _postPreToken) async { - print('IN'); - print("clintBranchId -$empClientBranchId"); - print("clintID -$empClientId"); - print("hr_id -$empHrId"); - print("token -$_postPreToken"); + logDebug('IN'); + logDebug("clintBranchId -$empClientBranchId"); + logDebug("clintID -$empClientId"); + logDebug("hr_id -$empHrId"); + logDebug("token -$_postPreToken"); isLoading = true; // setState(() { @@ -280,30 +283,30 @@ class _RaiseClaimDialogState extends State { // final response = await apiService.getCashDepositDetailsToApi( // clintID!, clintBranchId!, hr_id, token); - print('IN1'); + logDebug('IN1'); if (response['status'] == 'success') { isLoading = false; setState(() { - print('response'); - print(response['data']); + logDebug('response'); + logDebug(response['data']); getPostCardArrays = List>.from(response['data']); - print('getPostCardArrays'); - print(getPostCardArrays); + logDebug('getPostCardArrays'); + logDebug(getPostCardArrays); activePoliciesList = getPostCardArrays; }); - print('IN2'); + logDebug('IN2'); } else { isLoading = false; - print('API request failed with status'); + logDebug('API request failed with status'); setState(() { activePoliciesList = []; }); - print('API request failed with status'); + logDebug('API request failed with status'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -338,7 +341,7 @@ class _RaiseClaimDialogState extends State { } void loadClaimTypes() { - print('serviceId $serviceId'); + logDebug('serviceId $serviceId'); if (serviceId == null) return; String key = serviceId.toString(); @@ -353,13 +356,12 @@ class _RaiseClaimDialogState extends State { }; }).toList(); - print('claimTypeList $claimTypeList'); + logDebug('claimTypeList $claimTypeList'); // // ✅ AUTO SELECT FIRST CLAIM TYPE // if (claimTypeList.isNotEmpty) { // claimTypeId = claimTypeList.first['id']; // } - } else { claimTypeList = []; claimTypeId = null; @@ -368,12 +370,12 @@ class _RaiseClaimDialogState extends State { } Future getCDPoliciesDetails() async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); + logDebug('10'); final response = await apiService.getEmployeeAndDependenceToApi( empClientId, @@ -408,7 +410,7 @@ class _RaiseClaimDialogState extends State { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { isLoading = false; @@ -422,7 +424,8 @@ class _RaiseClaimDialogState extends State { isServiceValid = serviceId != null; isPolicyValid = selectedClientPolicyId != null; isMemberValid = selectedMemberId != null; - MultiFileUploadWidget.showValidation = serviceId != null && FileUploadService().files.isEmpty; + MultiFileUploadWidget.showValidation = + serviceId != null && FileUploadService().files.isEmpty; // MultiFileUploadWidget.showValidation = FileUploadService().files.isEmpty; // isClaimTypeValid = claimTypeId != null; // isSubjectValid = subjectController.text.trim().isNotEmpty; @@ -445,8 +448,7 @@ class _RaiseClaimDialogState extends State { // isHospitalPhoneNoValid = !isGmc || (RegExp(r'^\d{10}$').hasMatch(phone)); isHospitalPhoneNoValid = !isGmc || phone.isNotEmpty; - - isAdmitDateValid = !isGmc || admitDate != null; + isAdmitDateValid = !isGmc || admitDate != null; isDischargeDateValid = !isGmc || dischargeDate != null; isClaimTypeValid = !isGmc || claimTypeId != null; @@ -463,17 +465,17 @@ class _RaiseClaimDialogState extends State { // 🎯 GPA / GTLI / EDLI validation // 🎯 GPA / GTLI / EDLI dynamic validation // if (serviceId == 2) { - // print('serviceId == 2'); + // logDebug('serviceId == 2'); // isAccidentDateValid = accidentDate != null; // isDeathDateValid = true; // } // else if (serviceId == 3 || serviceId == 4) { - // print('serviceId == 3 || serviceId == 4'); + // logDebug('serviceId == 3 || serviceId == 4'); // isDeathDateValid = deathDate != null; // isAccidentDateValid = true; // } // else { - // print('ELSE'); + // logDebug('ELSE'); // isAccidentDateValid = true; // isDeathDateValid = true; // } @@ -482,20 +484,17 @@ class _RaiseClaimDialogState extends State { isAccidentDateValid = accidentDate != null; isDeathDateValid = true; isIntimationDateValid = true; - } - else if (serviceId == 3) { + } else if (serviceId == 3) { // GTLI isDeathDateValid = deathDate != null; isAccidentDateValid = true; isIntimationDateValid = true; - } - else if (serviceId == 4) { + } else if (serviceId == 4) { // EDLI isDeathDateValid = deathDate != null; isAccidentDateValid = true; isIntimationDateValid = true; - } - else { + } else { isAccidentDateValid = true; isDeathDateValid = true; isIntimationDateValid = true; @@ -529,12 +528,12 @@ class _RaiseClaimDialogState extends State { isAccidentDateValid && isDeathDateValid && isIntimationDateValid) { - // ✅ Phone validation AFTER all required fields pass // ✅ Exact 10 digit validation AFTER all required fields filled if ((serviceId == 1 || serviceId == 72) && hospitalPhoneNoController.text.trim().isNotEmpty && - !RegExp(r'^\d{10}$').hasMatch(hospitalPhoneNoController.text.trim())) { + !RegExp(r'^\d{10}$') + .hasMatch(hospitalPhoneNoController.text.trim())) { ToastHelper.showErrorToast( context, 'Hospital phone number must be exactly 10 digits', @@ -549,7 +548,6 @@ class _RaiseClaimDialogState extends State { ); return; } - } else { ToastHelper.showErrorToast( context, @@ -563,7 +561,7 @@ class _RaiseClaimDialogState extends State { }); try { - print('Check One'); + logDebug('Check One'); Map fields = { 'client_policy_id': selectedClientPolicyId, // 'policy_type_id': selectedPolicyTypeId, @@ -609,13 +607,11 @@ class _RaiseClaimDialogState extends State { } if (deathDate != null) { - fields['date_of_death'] = - DateFormat('yyyy-MM-dd').format(deathDate!); + fields['date_of_death'] = DateFormat('yyyy-MM-dd').format(deathDate!); } if (birthDate != null) { - fields['dob'] = - DateFormat('yyyy-MM-dd').format(birthDate!); + fields['dob'] = DateFormat('yyyy-MM-dd').format(birthDate!); } if (intimationDate != null) { @@ -635,18 +631,18 @@ class _RaiseClaimDialogState extends State { 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final stringFields = fields.map((key, value) => MapEntry(key, value?.toString() ?? '')); - print("📁 stringFields: ${stringFields}"); + logDebug("📁 stringFields: ${stringFields}"); request.fields.addAll(stringFields); // get uploaded files final uploadedFiles = FileUploadService().files; - print("📁 Total uploaded files: ${uploadedFiles.length}"); - print( + logDebug("📁 Total uploaded files: ${uploadedFiles.length}"); + logDebug( "📂 File list (original names): ${uploadedFiles.map((f) => f.file.name).toList()}"); // Validate all labels present (optional but recommended) for (final uf in uploadedFiles) { - print( + logDebug( "📝 Checking label for file: ${uf.file.name}, current label: '${uf.label}'"); if ((uf.label ?? '').trim().isEmpty) { ToastHelper.showErrorToast( @@ -706,7 +702,7 @@ class _RaiseClaimDialogState extends State { // replace file name with .pdf extension final pdfFileName = pf.name.replaceAll(RegExp(r'\.\w+$'), '.pdf'); - print('📄 Converted image ${pf.name} → PDF ($pdfFileName)'); + logDebug('📄 Converted image ${pf.name} → PDF ($pdfFileName)'); request.files.add(http.MultipartFile.fromBytes( 'claim_docs[]', fileBytes, @@ -729,9 +725,9 @@ class _RaiseClaimDialogState extends State { request.fields['claim_doc_names'] = encodedNames; // ✅ Debug print - print("Payload being sent:"); - print("Files: ${uploadedFiles.map((f) => f.file.name).toList()}"); - print("Names (JSON): $encodedNames"); + logDebug("Payload being sent:"); + logDebug("Files: ${uploadedFiles.map((f) => f.file.name).toList()}"); + logDebug("Names (JSON): $encodedNames"); final response = await request.send(); final responseBody = await response.stream.bytesToString(); @@ -752,7 +748,7 @@ class _RaiseClaimDialogState extends State { isLoading = false; }); // context.go('/claims', extra: 2); - print('Form data submitted successfully'); + logDebug('Form data submitted successfully'); fileService.clearAll(); } else { setState(() { @@ -765,7 +761,7 @@ class _RaiseClaimDialogState extends State { setState(() { isLoading = false; }); - print('Error submitting form data: $e'); + logDebug('Error submitting form data: $e'); } finally { setState(() => isSubmitting = false); // 🔥 stop loader } @@ -919,351 +915,368 @@ class _RaiseClaimDialogState extends State { return true; }, child: Dialog( - backgroundColor: Colors.white, // ✅ PURE WHITE popup - insetPadding: const EdgeInsets.all(20), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(16), - child: SizedBox( - width: - MediaQuery.of(context).size.width * 0.75, // Desktop popup width - // height: MediaQuery.of(context).size.height * 0.85, - child: Stack( - children: [ - /// MAIN CONTENT (YOUR EXISTING UI) - SingleChildScrollView( - child: Container( - padding: EdgeInsets.all(20), - color: Colors.white, - child: Column( - children: [ - /// 🔹 HEADER ROW (Title + Close) - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + backgroundColor: Colors.white, // ✅ PURE WHITE popup + insetPadding: const EdgeInsets.all(20), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: SizedBox( + width: MediaQuery.of(context).size.width * + 0.75, // Desktop popup width + // height: MediaQuery.of(context).size.height * 0.85, + child: Stack( + children: [ + /// MAIN CONTENT (YOUR EXISTING UI) + SingleChildScrollView( + child: Container( + padding: EdgeInsets.all(20), + color: Colors.white, + child: Column( children: [ - Text( - "Raise Insurance Claim", - style: GoogleFonts.poppins( - fontSize: 20, - fontWeight: FontWeight.w600, - ), + /// 🔹 HEADER ROW (Title + Close) + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Raise Insurance Claim", + style: GoogleFonts.poppins( + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => { + setState(() { + resetFormOnServiceChange(); + }), + Navigator.pop(context) + }, + ), + ], ), - IconButton( - icon: const Icon(Icons.close), - onPressed: () => { - setState(() { - resetFormOnServiceChange(); - }), - Navigator.pop(context) - }, + + const SizedBox(height: 16), + + Form( + key: formKey, + child: Column( + children: [ + _row([ + buildDropdownField( + 'Service', + (value) { + final selectedItem = + departmentList.firstWhere( + (item) => item['id'] == value, + orElse: () => {}, + ); + setState(() { + resetFormOnServiceChange(); + serviceId = value; + serviceName = selectedItem['name']; + policyNumberId = null; + isServiceValid = true; + }); + logDebug( + '🔥 serviceId set to $serviceId'); + filterPoliciesByService(value!); + loadClaimTypes(); + }, + departmentList, + 'name', + serviceId, + required: true, + isValid: isServiceValid, + ), + buildDropdownField( + 'Select Policy', + (value) { + final selectedPolicy = + policyNumberList.firstWhere( + (p) => p['id'] == value); + + setState(() { + // ✅ THIS is what you send to API + selectedClientPolicyId = + selectedPolicy['id']; + + // optional + selectedPolicyTypeId = + selectedPolicy['policy_type_id']; + policyNumberId = value; + + isPolicyValid = true; + }); + + getCDPoliciesDetails(); + }, + policyNumberList, + 'label', // 👈 DISPLAY FIELD + policyNumberId, + required: true, + isValid: isPolicyValid, + ), + if (serviceId == 1 || serviceId == 72) + buildDropdownField( + 'Select Claim Type', + (value) { + setState(() { + claimTypeId = value; + isClaimTypeValid = true; + }); + }, + claimTypeList, + 'name', + claimTypeId, + required: true, + isValid: isClaimTypeValid, + ), + buildDropdownFieldSearch( + 'Member Name', + (value) { + final member = + employeePolicyList.firstWhere( + (m) => m['id'] == value, + ); + + setState(() { + selectedMemberId = value; + selectedMemberObject = + member; // ✅ FULL OBJECT + selectedMemberName = member['name']; + isMemberValid = true; + logDebug( + 'selectedMemberObject $selectedMemberObject'); + }); + }, + employeePolicyList, + 'name', + selectedMemberId, + required: true, + isValid: isMemberValid, + ), + ]), + _row([ + buildTextField( + 'Message', messageController), + if (serviceId == 1 || serviceId == 72) ...[ + buildTextField('Hospital Name', + hospitalNameController, + required: true, + isValid: isHospitalNameValid), + buildTextField('Hospital Address', + hospitalAddressController, + required: true, + isValid: isHospitalAddressValid), + ] + ]), + if (serviceId == 1 || serviceId == 72) + _row([ + buildTextField('Hospital City', + hospitalCityController, + required: true, + isValid: isHospitalCityValid, + inputFormatters: [ + FilteringTextInputFormatter.allow( + RegExp(r"[a-zA-Z\s]")), + ]), + buildTextField('Hospital State', + hospitalStateController, + required: true, + isValid: isHospitalStateValid, + inputFormatters: [ + FilteringTextInputFormatter.allow( + RegExp(r"[a-zA-Z\s]")), + ]), + buildTextField('Hospital Pincode', + hospitalPinCodeController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter + .digitsOnly, + LengthLimitingTextInputFormatter(6), + ], + required: true, + isValid: isHospitalPincodeValid), + ]), + if (serviceId == 1 || serviceId == 72) + _row([ + buildTextField( + 'Hospital Phone No', + hospitalPhoneNoController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter + .digitsOnly, + LengthLimitingTextInputFormatter(10), + ], + required: true, + isValid: !hasSubmitted || + serviceId == null || + (serviceId != 1 && + serviceId != 72) || + RegExp(r'^\d{10}$').hasMatch( + hospitalPhoneNoController.text + .trim()), + ), + buildDatePickerField( + label: 'Admit Date', + selectedDate: admitDate, + allowFuture: false, + onDateSelected: (d) { + setState(() { + admitDate = d; + dischargeDate = null; + }); + }, + required: true, + isValid: isAdmitDateValid), + buildDatePickerField( + label: 'Discharge Date', + selectedDate: dischargeDate, + allowFuture: true, + minDate: admitDate + ?.add(const Duration(days: 1)), + onDateSelected: (d) => + setState(() => dischargeDate = d), + required: true, + isValid: isDischargeDateValid), + buildTextField('Claims Amount', + claimAmountController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter + .digitsOnly + ], + required: true, + isValid: isClaimAmountValid), + ]), + if ([2, 3, 4].contains(serviceId)) + _row([ + buildDatePickerField( + label: 'Date of Birth', + selectedDate: birthDate, + allowFuture: false, + onDateSelected: (d) => + setState(() => birthDate = d), + ), + buildDatePickerField( + label: 'Accident Date', + selectedDate: accidentDate, + allowFuture: false, + onDateSelected: (d) { + setState(() { + accidentDate = d; + deathDate = null; + intimationDate = null; + }); + }, + required: serviceId == 2, + isValid: isAccidentDateValid), + buildDatePickerField( + label: 'Date of Death', + selectedDate: deathDate, + allowFuture: false, + onDateSelected: (d) => + setState(() => deathDate = d), + required: + (serviceId == 3 || serviceId == 4) + ? true + : false, // 🔥 GTLI & EDLI + isValid: isDeathDateValid, + ), + ]), + if ([2, 3, 4].contains(serviceId)) + _row([ + buildDatePickerField( + label: 'Date of Intimation', + selectedDate: intimationDate, + allowFuture: false, + onDateSelected: (d) => setState( + () => intimationDate = d)), + buildTextField( + 'Sum Insured', + sumInsuredController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly + ], + ), + const SizedBox(), + ]), + _row([ + MultiFileUploadWidget(), + ]), + Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 120, + height: 42, + child: ElevatedButton( + onPressed: + (isSubmitting || serviceId == null) + ? null + : sendFormDataToApi, + style: ElevatedButton.styleFrom( + backgroundColor: + const Color(0xFFE26728), + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.circular(10), + ), + ), + child: isSubmitting + ? const SizedBox( + height: 18, + width: 18, + child: + CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Text( + 'Send', + style: TextStyle( + color: Colors.white, + fontWeight: + FontWeight.w600), + ), + ), + ), + ), + ], + ), ), ], ), + ), + ), - const SizedBox(height: 16), - - Form( - key: formKey, - child: Column( - children: [ - _row([ - buildDropdownField( - 'Service', - (value) { - final selectedItem = - departmentList.firstWhere( - (item) => item['id'] == value, - orElse: () => {}, - ); - setState(() { - resetFormOnServiceChange(); - serviceId = value; - serviceName = selectedItem['name']; - policyNumberId = null; - isServiceValid = true; - }); - print('🔥 serviceId set to $serviceId'); - filterPoliciesByService(value!); - loadClaimTypes(); - }, - departmentList, - 'name', - serviceId, - required: true, - isValid: isServiceValid, - ), - buildDropdownField( - 'Select Policy', - (value) { - final selectedPolicy = policyNumberList - .firstWhere((p) => p['id'] == value); - - setState(() { - // ✅ THIS is what you send to API - selectedClientPolicyId = - selectedPolicy['id']; - - // optional - selectedPolicyTypeId = - selectedPolicy['policy_type_id']; - policyNumberId = value; - - isPolicyValid = true; - }); - - getCDPoliciesDetails(); - }, - policyNumberList, - 'label', // 👈 DISPLAY FIELD - policyNumberId, - required: true, - isValid: isPolicyValid, - ), - if (serviceId == 1 || serviceId == 72) - buildDropdownField( - 'Select Claim Type', - (value) { - setState(() { - claimTypeId = value; - isClaimTypeValid = true; - }); - }, - claimTypeList, - 'name', - claimTypeId, - required: true, - isValid: isClaimTypeValid, - ), - buildDropdownFieldSearch( - 'Member Name', - (value) { - final member = - employeePolicyList.firstWhere( - (m) => m['id'] == value, - ); - - setState(() { - selectedMemberId = value; - selectedMemberObject = - member; // ✅ FULL OBJECT - selectedMemberName = member['name']; - isMemberValid = true; - print( - 'selectedMemberObject $selectedMemberObject'); - }); - }, - employeePolicyList, - 'name', - selectedMemberId, - required: true, - isValid: isMemberValid, - ), - ]), - _row([ - buildTextField('Message', messageController), - - if (serviceId == 1 || serviceId == 72) ...[ - buildTextField( - 'Hospital Name', hospitalNameController, - required: true, - isValid: isHospitalNameValid), - buildTextField('Hospital Address', - hospitalAddressController, - required: true, - isValid: isHospitalAddressValid), - ] - ]), - if (serviceId == 1 || serviceId == 72) - _row([ - buildTextField( - 'Hospital City', hospitalCityController, - required: true, - isValid: isHospitalCityValid, - inputFormatters: [ - FilteringTextInputFormatter.allow( - RegExp(r"[a-zA-Z\s]")), - ]), - buildTextField( - 'Hospital State', hospitalStateController, - required: true, - isValid: isHospitalStateValid, - inputFormatters: [ - FilteringTextInputFormatter.allow( - RegExp(r"[a-zA-Z\s]")), - ]), - buildTextField('Hospital Pincode', - hospitalPinCodeController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - LengthLimitingTextInputFormatter(6), - ], - required: true, - isValid: isHospitalPincodeValid), - ]), - if (serviceId == 1 || serviceId == 72) - _row([ - buildTextField('Hospital Phone No', - hospitalPhoneNoController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - LengthLimitingTextInputFormatter(10), - ], - required: true, - isValid: !hasSubmitted || - serviceId == null || - (serviceId != 1 && serviceId != 72) || - RegExp(r'^\d{10}$').hasMatch(hospitalPhoneNoController.text.trim()), - ), - buildDatePickerField( - label: 'Admit Date', - selectedDate: admitDate, - allowFuture: false, - onDateSelected: (d) { - setState(() { - admitDate = d; - dischargeDate = null; - }); - }, - required: true, - isValid: isAdmitDateValid), - buildDatePickerField( - label: 'Discharge Date', - selectedDate: dischargeDate, - allowFuture: true, - minDate: admitDate - ?.add(const Duration(days: 1)), - onDateSelected: (d) => - setState(() => dischargeDate = d), - required: true, - isValid: isDischargeDateValid), - buildTextField( - 'Claims Amount', claimAmountController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly - ], - required: true, - isValid: isClaimAmountValid), - ]), - if ([2, 3, 4].contains(serviceId)) - _row([ - buildDatePickerField( - label: 'Date of Birth', - selectedDate: birthDate, - allowFuture: false, - onDateSelected: (d) => - setState(() => birthDate = d), - ), - buildDatePickerField( - label: 'Accident Date', - selectedDate: accidentDate, - allowFuture: false, - onDateSelected: (d) { - setState(() { - accidentDate = d; - deathDate = null; - intimationDate = null; - }); - }, - required: serviceId == 2, - isValid: isAccidentDateValid), - buildDatePickerField( - label: 'Date of Death', - selectedDate: deathDate, - allowFuture: false, - onDateSelected: (d) => - setState(() => deathDate = d), - required: (serviceId == 3 || serviceId == 4) ? true : false, // 🔥 GTLI & EDLI - isValid: isDeathDateValid, - ), - ]), - if ([2, 3, 4].contains(serviceId)) - _row([ - buildDatePickerField( - label: 'Date of Intimation', - selectedDate: intimationDate, - allowFuture: false, - onDateSelected: (d) => - setState(() => intimationDate = d)), - buildTextField( - 'Sum Insured', - sumInsuredController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly - ], - ), - const SizedBox(), - ]), - _row([ - MultiFileUploadWidget(), - ]), - Align( - alignment: Alignment.centerRight, - child: SizedBox( - width: 120, - height: 42, - child: ElevatedButton( - onPressed: (isSubmitting || serviceId == null) - ? null - : sendFormDataToApi, - style: ElevatedButton.styleFrom( - backgroundColor: const Color(0xFFE26728), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - ), - child: isSubmitting - ? const SizedBox( - height: 18, - width: 18, - child: CircularProgressIndicator( - strokeWidth: 2, - color: Colors.white, - ), - ) - : const Text( - 'Send', - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.w600), - ), - ), - ), - ), - ], + /// 🔥 LOADER OVERLAY + if (isLoading) + Positioned.fill( + child: Container( + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.6), + borderRadius: BorderRadius.circular(20), + ), + child: Center( + child: Image.asset( + 'assets/nhance-loader.gif', + height: 60, + width: 60, + ), ), ), - ], - ), - ), + ), + ], ), - - /// 🔥 LOADER OVERLAY - if (isLoading) - Positioned.fill( - child: Container( - decoration: BoxDecoration( - color: Colors.white.withOpacity(0.6), - borderRadius: BorderRadius.circular(20), - ), - child: Center( - child: Image.asset( - 'assets/nhance-loader.gif', - height: 60, - width: 60, - ), - ), - ), - ), - ], - ), - ), - ))); + ), + ))); } /// ---------- HELPERS ---------- diff --git a/lib/presentation/cdList.dart b/lib/presentation/cdList.dart index b056b64..fe92413 100644 --- a/lib/presentation/cdList.dart +++ b/lib/presentation/cdList.dart @@ -17,7 +17,7 @@ import 'package:collection/collection.dart'; import '../customAppBar/base_layout.dart'; import '../service/api_service.dart'; import '../service/token_storage_service.dart'; - +import 'package:nhancepolicy/logger.dart'; class CdPoliciesList extends StatefulWidget { const CdPoliciesList({Key? key}) : super(key: key); @@ -26,7 +26,6 @@ class CdPoliciesList extends StatefulWidget { State createState() => _CdPoliciesListState(); } - class _CdPoliciesListState extends State { final tokenService = TokenStorageService(); Uint8List? fileBytes; @@ -55,11 +54,10 @@ class _CdPoliciesListState extends State { List get _paginatedData { final startIndex = (_currentPage - 1) * _rowsPerPage; final endIndex = - (_currentPage * _rowsPerPage).clamp(0, filteredData.length); + (_currentPage * _rowsPerPage).clamp(0, filteredData.length); return filteredData.sublist(startIndex, endIndex); } - @override void initState() { super.initState(); @@ -73,23 +71,24 @@ class _CdPoliciesListState extends State { } Future checkIds() async { - print('checkIds'); + logDebug('checkIds'); _postPreToken = await tokenService.getCurrentToken(); empClientId = await tokenService.readValue('empClientId'); // empClientBranchId = await tokenService.readValue('empClientBranchId'); empHrId = await tokenService.readValue('empHrId'); - print('$_postPreToken - $empClientId - $empHrId'); + logDebug('$_postPreToken - $empClientId - $empHrId'); await getCDPoliciesDetails(empClientId, empHrId, _postPreToken); } Future getCDPoliciesDetails(empClientId, empHrId, _postPreToken) async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); - final response = await apiService.getCDPoliciesToApi(empClientId, empHrId, _postPreToken); + logDebug('10'); + final response = await apiService.getCDPoliciesToApi( + empClientId, empHrId, _postPreToken); if (response['status'] == 'success') { setState(() { isLoading = false; @@ -98,8 +97,8 @@ class _CdPoliciesListState extends State { getCDPolicies = List>.from(response['data']); originalData = getCDPolicies; filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { setState(() { @@ -108,13 +107,13 @@ class _CdPoliciesListState extends State { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -123,7 +122,7 @@ class _CdPoliciesListState extends State { } void search(String query) { - print(query); + logDebug(query); // Check if the query is empty if (query.isEmpty) { // If search query is empty, show all data @@ -138,9 +137,9 @@ class _CdPoliciesListState extends State { // For example, check if any field in the row contains the query // Adjust this logic based on your data structure return row['insurer_name'] - .toString() - .toLowerCase() - .contains(query.toLowerCase()) || + .toString() + .toLowerCase() + .contains(query.toLowerCase()) || row['cd_master_account_no'] .toString() .toLowerCase() @@ -152,7 +151,7 @@ class _CdPoliciesListState extends State { }).toList(); }); } - print(filteredData.length); + logDebug(filteredData.length); } void exportToCsv(List> data) { @@ -185,51 +184,51 @@ class _CdPoliciesListState extends State { } Future handleExportAction() async { - print('handleExportAction'); + logDebug('handleExportAction'); _postPreToken = await tokenService.getCurrentToken(); final postId = await tokenService.readValue('empHrId'); final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); var activity = "export_cddata"; - print('postId - $postId'); - print('preId - $preId'); - print('activity - $activity'); + logDebug('postId - $postId'); + logDebug('preId - $preId'); + logDebug('activity - $activity'); try { - print('10'); + logDebug('10'); final response = await apiService.getPostLogHrActivity( postId!, preId!, _postPreToken!, activity); if (response['status'] == 'success') { - print('Request success'); + logDebug('Request success'); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } Future _showLogoutDialog() async { return await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => AlertDialog( - title: Text("Confirm Logout"), - content: Text("Do you want to logout?"), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: Text("Cancel"), + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + title: Text("Confirm Logout"), + content: Text("Do you want to logout?"), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text("Logout"), + ), + ], ), - TextButton( - onPressed: () => Navigator.of(context).pop(true), - child: Text("Logout"), - ), - ], - ), - ) ?? + ) ?? false; } @@ -300,7 +299,7 @@ class _CdPoliciesListState extends State { prefixIcon: Icon(Icons.search, size: 18), border: InputBorder.none, contentPadding: - EdgeInsets.symmetric(horizontal: 12, vertical: 8), + EdgeInsets.symmetric(horizontal: 12, vertical: 8), ), ), ), @@ -336,25 +335,23 @@ class _CdPoliciesListState extends State { SizedBox(height: 20), isLoading ? Expanded( - // color: Color(0x98FFFCE5), // semi-transparent overlay - child: Center( - child: Image.asset( - 'assets/nhance-loader.gif', - height: 60, - width: 60, - ), - ), - ) + // color: Color(0x98FFFCE5), // semi-transparent overlay + child: Center( + child: Image.asset( + 'assets/nhance-loader.gif', + height: 60, + width: 60, + ), + ), + ) : Expanded( - child: _buildCDGrid(), - ) + child: _buildCDGrid(), + ) ], ), ); } - - Widget _buildCDGrid() { if (filteredData.isEmpty) { return const Center( @@ -362,9 +359,9 @@ class _CdPoliciesListState extends State { ); } ResponsiveGridConfig _getGridConfig( - BuildContext context, - bool isEnrollment, - ) { + BuildContext context, + bool isEnrollment, + ) { final width = MediaQuery.of(context).size.width; if (width < 600) { @@ -377,8 +374,8 @@ class _CdPoliciesListState extends State { return ResponsiveGridConfig(4, 3.8); } } - final config = _getGridConfig(context, true); + final config = _getGridConfig(context, true); return GridView.builder( itemCount: filteredData.length, @@ -425,7 +422,8 @@ class _CdPoliciesListState extends State { settings: const RouteSettings(name: 'cdTransactionDetails'), builder: (_) => cdTransactionDetails( insurerName: filteredData[index]['insurer_name'], - cdMasterAccountNo: filteredData[index]['cd_master_account_no'], + cdMasterAccountNo: filteredData[index] + ['cd_master_account_no'], insurerId: filteredData[index]['insurer_id'], cd_ac_pk: filteredData[index]['cd_ac_pk'], empClientId: empClientId, @@ -435,12 +433,9 @@ class _CdPoliciesListState extends State { }, child: _CDPolicyCard(data: filteredData[index]), ); - }, ); } - - } class _CDPolicyCard extends StatelessWidget { @@ -455,8 +450,8 @@ class _CDPolicyCard extends StatelessWidget { final Color amountColor = balance < 0 ? Colors.red : balance < 50000 - ? Colors.orange - : Colors.green; + ? Colors.orange + : Colors.green; return Container( padding: const EdgeInsets.all(14), @@ -473,16 +468,15 @@ class _CDPolicyCard extends StatelessWidget { children: [ Expanded( flex: 7, - child: Text( - data['insurer_name'] ?? '', - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: GoogleFonts.poppins( + child: Text( + data['insurer_name'] ?? '', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w500, - color: Color(0xFF000000) - ), - ), + color: Color(0xFF000000)), + ), ), Expanded( flex: 3, @@ -506,7 +500,7 @@ class _CDPolicyCard extends StatelessWidget { children: [ /// Account number Expanded( - flex: 8, + flex: 8, child: Text( 'CD No: ${data['cd_master_account_no']}', maxLines: 1, @@ -538,4 +532,3 @@ class _CDPolicyCard extends StatelessWidget { ); } } - diff --git a/lib/presentation/cdTransactionDetails.dart b/lib/presentation/cdTransactionDetails.dart index f218fa5..14a6b69 100755 --- a/lib/presentation/cdTransactionDetails.dart +++ b/lib/presentation/cdTransactionDetails.dart @@ -18,6 +18,7 @@ import '../config/environment.dart'; import '../customAppBar/base_layout.dart'; import 'cdList.dart'; import 'claims.dart'; +import 'package:nhancepolicy/logger.dart'; class cdTransactionDetails extends StatefulWidget { final String insurerName; @@ -26,29 +27,27 @@ class cdTransactionDetails extends StatefulWidget { final String cd_ac_pk; final String empClientId; // final String postToken; - const cdTransactionDetails( - {Key? key, - required this.insurerName, - required this.cdMasterAccountNo, - required this.insurerId, - required this.cd_ac_pk, - required this.empClientId, - // required this.postToken - }); + const cdTransactionDetails({ + Key? key, + required this.insurerName, + required this.cdMasterAccountNo, + required this.insurerId, + required this.cd_ac_pk, + required this.empClientId, + // required this.postToken + }); @override State createState() => _cdTransactionDetailsState(); } class _cdTransactionDetailsState extends State { - String? localInsurerId; String? localCdAcPk; String? localEmpClientId; String? localInsurerName; String? localCdMasterAccountNo; - final tokenService = TokenStorageService(); Uint8List? fileBytes; List> getCDTransData = []; @@ -60,9 +59,11 @@ class _cdTransactionDetailsState extends State { // List dataPolicy = []; List reversedDataPolicy = []; List> originalData = []; // Original data source - List> originalEndorsementData = []; // Original data source + List> originalEndorsementData = + []; // Original data source List> filteredData = []; // Filtered data source - List> filteredEndorsementData = []; // Filtered data source + List> filteredEndorsementData = + []; // Filtered data source List> getCDTransDataAmount = []; // Filtered data source dynamic argumentsData; dynamic policyType; @@ -94,7 +95,6 @@ class _cdTransactionDetailsState extends State { apiService = ApiService(context); // Initialize ApiService here restoreTransactionData(); - } @override @@ -102,8 +102,6 @@ class _cdTransactionDetailsState extends State { super.dispose(); } - - // downloadPolicyFiles?file_id=13 // getPolicyAndEndorsementFiles?cd_ac_pk=12 @@ -128,9 +126,9 @@ class _cdTransactionDetailsState extends State { ? widget.cdMasterAccountNo : await tokenService.readValue('hr_cd_master_account_no'); - print('restore localInsurerId = $localInsurerId'); - print('restore localCdAcPk = $localCdAcPk'); - print('restore localEmpClientId = $localEmpClientId'); + logDebug('restore localInsurerId = $localInsurerId'); + logDebug('restore localCdAcPk = $localCdAcPk'); + logDebug('restore localEmpClientId = $localEmpClientId'); if (localInsurerId != null && localCdAcPk != null && @@ -148,15 +146,15 @@ class _cdTransactionDetailsState extends State { } Future getCdTransactionDetails() async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); + logDebug('10'); final _postPreToken = await tokenService.getCurrentToken(); - final response = await apiService.getCdTransactionData(localEmpClientId!, - localInsurerId!, localCdAcPk!, _postPreToken!); + final response = await apiService.getCdTransactionData( + localEmpClientId!, localInsurerId!, localCdAcPk!, _postPreToken!); if (response['status'] == 'success') { setState(() { isLoading = false; @@ -176,8 +174,8 @@ class _cdTransactionDetailsState extends State { // currect_balance = formatAmount(response['data']['currect_balance']); insurer_short_name = response['data']['insurer_short_name']; // insurer_short_name = formatAmount(response['data']['insurer_short_name']); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { setState(() { @@ -186,13 +184,13 @@ class _cdTransactionDetailsState extends State { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -203,7 +201,7 @@ class _cdTransactionDetailsState extends State { Future _openEndorsementFile(id, file_name) async { // final http.Response response = await apiService.getHrFileDownloadToApi(id, widget.Token); final _postPreToken = await tokenService.getCurrentToken(); - print("**********-------*****"); + logDebug("**********-------*****"); final apiurl = Environment.apiUrlPost; final String url = '$apiurl/downloadPolicyFiles?file_id=$id'; @@ -211,7 +209,7 @@ class _cdTransactionDetailsState extends State { Uri.parse(url), headers: { 'APP-SIGNATURE': - 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_postPreToken', 'Content-Type': 'application/json', // 'app-signature': 'ts-traveltool-2025-signature-123456', @@ -220,7 +218,7 @@ class _cdTransactionDetailsState extends State { if (response.statusCode == 200) { try { - print("PDF Downloaded"); + logDebug("PDF Downloaded"); // ✅ Create a blob from the response body bytes final blob = html.Blob([response.bodyBytes]); @@ -242,51 +240,56 @@ class _cdTransactionDetailsState extends State { } } else { ToastHelper.showErrorToast(context, 'Failed to download'); - print("Download failed with status: ${response.statusCode}"); + logDebug("Download failed with status: ${response.statusCode}"); } } - Future getCdEndorsementDetails(id) async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); + logDebug('10'); final _postPreToken = await tokenService.getCurrentToken(); - final response = await apiService.getCdEndorsementData(id, _postPreToken!); + final response = + await apiService.getCdEndorsementData(id, _postPreToken!); if (response['status'] == true) { setState(() { isLoading = false; }); setState(() { - getCDEndorsementData = List>.from(response['data']); + getCDEndorsementData = + List>.from(response['data']); originalEndorsementData = getCDEndorsementData; filteredEndorsementData = List.from(originalEndorsementData); _showFileListPopup(filteredEndorsementData); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { setState(() { isLoading = false; }); - getCDEndorsementData = List>.from(response['data']); - if (getCDEndorsementData == null || getCDEndorsementData.isEmpty || getCDEndorsementData == null || (getCDEndorsementData as List).isEmpty) { + getCDEndorsementData = + List>.from(response['data']); + if (getCDEndorsementData == null || + getCDEndorsementData.isEmpty || + getCDEndorsementData == null || + (getCDEndorsementData as List).isEmpty) { _showEmptyPopup(response['message']); return; } // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -327,7 +330,7 @@ class _cdTransactionDetailsState extends State { ), onTap: () { // Navigator.pop(context); // close popup - _openEndorsementFile(file['id'],file['file_name']); + _openEndorsementFile(file['id'], file['file_name']); }, ); }, @@ -369,9 +372,8 @@ class _cdTransactionDetailsState extends State { ); } - void search(String query) { - print(query); + logDebug(query); // Check if the query is empty if (query.isEmpty) { // If search query is empty, show all data @@ -436,7 +438,7 @@ class _cdTransactionDetailsState extends State { }).toList(); }); } - print(filteredData.length); + logDebug(filteredData.length); } void exportToCsv(List> data) { @@ -497,31 +499,31 @@ class _cdTransactionDetailsState extends State { } Future handleExportAction() async { - print('handleExportAction'); + logDebug('handleExportAction'); final postId = await tokenService.readValue('empHrId'); final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); var activity = "export_cdsummary"; - print('postId - $postId'); - print('preId - $preId'); - print('activity - $activity'); + logDebug('postId - $postId'); + logDebug('preId - $preId'); + logDebug('activity - $activity'); try { - print('10'); + logDebug('10'); final _postPreToken = await tokenService.getCurrentToken(); final response = await apiService.getPostLogHrActivity( postId!, preId!, _postPreToken!, activity); if (response['status'] == 'success') { - print('Request success'); + logDebug('Request success'); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -551,36 +553,36 @@ class _cdTransactionDetailsState extends State { Future _launchURL(String url) async { final Uri uri = Uri.parse(url); // Parse the URL properly - print('_launchURL $uri'); + logDebug('_launchURL $uri'); if (uri != null) { - print('If $uri'); + logDebug('If $uri'); await launchUrl(uri, mode: LaunchMode.externalApplication); } else { ToastHelper.showWarningToast(context, 'File not generated'); - print('else $uri'); + logDebug('else $uri'); throw 'Could not launch $url'; } } Future _showLogoutDialog() async { return await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => AlertDialog( - title: Text("Confirm Logout"), - content: Text("Do you want to logout?"), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: Text("Cancel"), + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + title: Text("Confirm Logout"), + content: Text("Do you want to logout?"), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text("Logout"), + ), + ], ), - TextButton( - onPressed: () => Navigator.of(context).pop(true), - child: Text("Logout"), - ), - ], - ), - ) ?? + ) ?? false; } @@ -591,7 +593,6 @@ class _cdTransactionDetailsState extends State { return amount.round().toString(); } - @override Widget build(BuildContext context) { return BaseLayout( @@ -607,141 +608,140 @@ class _cdTransactionDetailsState extends State { } Widget _buildContent(BuildContext context) { - return isLoading ? Container( - color: Colors.transparent, // Semi-transparent background - child: Center( - child: // Your GIF loader widget - Image.asset( - height: 60, - width: 60, - 'assets/nhance-loader.gif'), // Adjust path to your GIF loader - ), - ) : Container( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - /// 🔙 Back + Title (LEFT) - Row( - children: [ - IconButton( - tooltip: 'Previous Page', - onPressed: () async { - await clearPolicyStorage(); + return isLoading + ? Container( + color: Colors.transparent, // Semi-transparent background + child: Center( + child: // Your GIF loader widget + Image.asset( + height: 60, + width: 60, + 'assets/nhance-loader.gif'), // Adjust path to your GIF loader + ), + ) + : Container( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + /// 🔙 Back + Title (LEFT) + Row( + children: [ + IconButton( + tooltip: 'Previous Page', + onPressed: () async { + await clearPolicyStorage(); - if (Navigator.canPop(context)) { - Navigator.pop(context); - } else { - Navigator.pushReplacement( - context, - MaterialPageRoute( - settings: const RouteSettings(name: 'cdPoliciesList'), - builder: (_) => CdPoliciesList(), - ), - ); - } - }, - icon: const Icon( - Icons.arrow_back_ios, - size: 18, - color: Colors.black, + if (Navigator.canPop(context)) { + Navigator.pop(context); + } else { + Navigator.pushReplacement( + context, + MaterialPageRoute( + settings: + const RouteSettings(name: 'cdPoliciesList'), + builder: (_) => CdPoliciesList(), + ), + ); + } + }, + icon: const Icon( + Icons.arrow_back_ios, + size: 18, + color: Colors.black, + ), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), ), - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - ), - const SizedBox(width: 6), - Text( - 'Transaction Details - ${insurer_short_name} (${localCdMasterAccountNo ?? widget.cdMasterAccountNo})', - style: GoogleFonts.poppins( - fontSize: 18, - fontWeight: FontWeight.w500, - color: Colors.black, + const SizedBox(width: 6), + Text( + 'Transaction Details - ${insurer_short_name} (${localCdMasterAccountNo ?? widget.cdMasterAccountNo})', + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w500, + color: Colors.black, + ), ), - ), - ], - ), - - /// Push right content to end - const Spacer(), - - /// 🔍 Search Box - Container( - width: 380, - height: 37, - decoration: BoxDecoration( - color: const Color(0xFFF0F0F0), - borderRadius: BorderRadius.circular(8), + ], ), - child: TextField( - controller: searchController, - onChanged: search, - style: GoogleFonts.poppins(fontSize: 14), - decoration: const InputDecoration( - hintText: 'Search', - prefixIcon: Icon(Icons.search, size: 18), - border: InputBorder.none, - contentPadding: - EdgeInsets.symmetric(horizontal: 12, vertical: 8), - ), - ), - ), - const SizedBox(width: 12), + /// Push right content to end + const Spacer(), - /// ⬇️ Export Button - SizedBox( - width: 116, - height: 37, - child: ElevatedButton( - onPressed: () => exportToCsv(filteredData), - style: ElevatedButton.styleFrom( - backgroundColor: const Color(0xFFE26728), - elevation: 0, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), + /// 🔍 Search Box + Container( + width: 380, + height: 37, + decoration: BoxDecoration( + color: const Color(0xFFF0F0F0), + borderRadius: BorderRadius.circular(8), ), - child: Text( - 'Export', - style: GoogleFonts.poppins( - fontSize: 16, - fontWeight: FontWeight.w700, - color: Colors.white, - letterSpacing: 1, + child: TextField( + controller: searchController, + onChanged: search, + style: GoogleFonts.poppins(fontSize: 14), + decoration: const InputDecoration( + hintText: 'Search', + prefixIcon: Icon(Icons.search, size: 18), + border: InputBorder.none, + contentPadding: + EdgeInsets.symmetric(horizontal: 12, vertical: 8), ), ), ), - ), - ], - ), - SizedBox(height: 10), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - _buildInfoCard('Deposits', '₹$total_deposit', - Color(0xFF39D45B), Icons.arrow_upward), - _buildInfoCard('Consumed', '₹$total_consumed', - Color(0xFFED1D24), Icons.arrow_downward), - _buildInfoCard('Refund', '₹$total_refund', - Color(0xFF39D45B), Icons.arrow_upward), - _buildInfoCard('Current Balance', '₹$currect_balance', - Colors.black, null), - ], - ), - SizedBox(height: 16), - Expanded( - child: _buildCDDataTable(context), - ), - ], - ) - ); + const SizedBox(width: 12), + + /// ⬇️ Export Button + SizedBox( + width: 116, + height: 37, + child: ElevatedButton( + onPressed: () => exportToCsv(filteredData), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFFE26728), + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: Text( + 'Export', + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w700, + color: Colors.white, + letterSpacing: 1, + ), + ), + ), + ), + ], + ), + SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _buildInfoCard('Deposits', '₹$total_deposit', + Color(0xFF39D45B), Icons.arrow_upward), + _buildInfoCard('Consumed', '₹$total_consumed', + Color(0xFFED1D24), Icons.arrow_downward), + _buildInfoCard('Refund', '₹$total_refund', Color(0xFF39D45B), + Icons.arrow_upward), + _buildInfoCard('Current Balance', '₹$currect_balance', + Colors.black, null), + ], + ), + SizedBox(height: 16), + Expanded( + child: _buildCDDataTable(context), + ), + ], + )); } - - Widget _buildInfoCard( String label, String value, Color iconColor, IconData? icon) { return Expanded( @@ -811,7 +811,7 @@ class _cdTransactionDetailsState extends State { /// 📄 TABLE ROWS SliverList( delegate: SliverChildBuilderDelegate( - (context, index) { + (context, index) { final item = _paginatedData[index]; return _buildCDRow(item); }, @@ -831,9 +831,8 @@ class _cdTransactionDetailsState extends State { final bool isAllowedSubType = item['sub_type'] == '3' || item['sub_type'] == '4'; - final bool hasSplitUpFile = - item['split_up_url'] != null && - item['split_up_url'].toString().trim().isNotEmpty; + final bool hasSplitUpFile = item['split_up_url'] != null && + item['split_up_url'].toString().trim().isNotEmpty; return Container( padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), @@ -862,9 +861,7 @@ class _cdTransactionDetailsState extends State { _cell(item['sub_type_text'], 2), SizedBox(width: 10), _cell( - item['transaction_type'] == 'Credit' - ? item['amount'] - : '-', + item['transaction_type'] == 'Credit' ? item['amount'] : '-', 2, alignRight: true, ), @@ -877,9 +874,7 @@ class _cdTransactionDetailsState extends State { // ), SizedBox(width: 10), _cell( - item['transaction_type'] == 'Debit' - ? item['amount'] - : '-', + item['transaction_type'] == 'Debit' ? item['amount'] : '-', 2, alignRight: true, ), @@ -905,7 +900,6 @@ class _cdTransactionDetailsState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - /// --- PDF ICON SLOT --- SizedBox( width: 36, @@ -987,7 +981,8 @@ class _cdTransactionDetailsState extends State { final totalItems = filteredData.length; // Calculate entries range - final int startEntry = totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; + final int startEntry = + totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; int endEntry = _currentPage * _rowsPerPage; if (endEntry > totalItems) endEntry = totalItems; @@ -1026,7 +1021,8 @@ class _cdTransactionDetailsState extends State { return Padding( padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, // Standard Table Footer Layout + mainAxisAlignment: + MainAxisAlignment.spaceBetween, // Standard Table Footer Layout children: [ /// --- LEFT SIDE: ENTRY DETAILS --- Text( @@ -1041,7 +1037,6 @@ class _cdTransactionDetailsState extends State { /// --- RIGHT SIDE: CONTROLS --- Row( children: [ - DropdownButton( value: _rowsPerPage, items: [5, 10, 15, 20, 50].map((int value) { @@ -1211,7 +1206,7 @@ class _cdTransactionDetailsState extends State { child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: - _currentPage == page ? const Color(0xFF00A6A6) : Colors.grey[300], + _currentPage == page ? const Color(0xFF00A6A6) : Colors.grey[300], foregroundColor: _currentPage == page ? Colors.white : Colors.black, minimumSize: const Size(36, 36), padding: EdgeInsets.zero, @@ -1225,10 +1220,8 @@ class _cdTransactionDetailsState extends State { ), ); } - } - class _CDTableHeaderDelegate extends SliverPersistentHeaderDelegate { @override double get minExtent => 52; @@ -1289,11 +1282,11 @@ class _HeaderCell extends StatelessWidget { final bool center; const _HeaderCell( - this.text, - this.flex, { - this.alignRight = false, - this.center = false, - }); + this.text, + this.flex, { + this.alignRight = false, + this.center = false, + }); @override Widget build(BuildContext context) { @@ -1301,8 +1294,9 @@ class _HeaderCell extends StatelessWidget { flex: flex, child: Text( text, - textAlign: - center ? TextAlign.center : (alignRight ? TextAlign.right : TextAlign.left), + textAlign: center + ? TextAlign.center + : (alignRight ? TextAlign.right : TextAlign.left), style: GoogleFonts.poppins( fontSize: 12, fontWeight: FontWeight.w500, @@ -1313,7 +1307,6 @@ class _HeaderCell extends StatelessWidget { } } - class _ActionIconButton extends StatelessWidget { final IconData icon; final VoidCallback onTap; @@ -1323,7 +1316,7 @@ class _ActionIconButton extends StatelessWidget { const _ActionIconButton({ required this.icon, required this.onTap, - this.toolTip, // 2. Added to constructor + this.toolTip, // 2. Added to constructor this.enabled = true, }); @@ -1334,9 +1327,7 @@ class _ActionIconButton extends StatelessWidget { width: 36, height: 36, child: Material( - color: enabled - ? const Color(0xFFDFF4F5) - : Colors.transparent, + color: enabled ? const Color(0xFFDFF4F5) : Colors.transparent, borderRadius: BorderRadius.circular(10), child: InkWell( borderRadius: BorderRadius.circular(10), @@ -1363,8 +1354,6 @@ class _ActionIconButton extends StatelessWidget { } } - - // Sample Data class representing each element in the array class Data { final dynamic value; diff --git a/lib/presentation/claims.dart b/lib/presentation/claims.dart index b25d8fe..fc36f5d 100755 --- a/lib/presentation/claims.dart +++ b/lib/presentation/claims.dart @@ -19,22 +19,28 @@ import '../customAppBar/base_layout.dart'; import '../service/api_service.dart'; import '../service/token_storage_service.dart'; import 'RaiseClaimForm.dart'; +import 'package:nhancepolicy/logger.dart'; class ClaimsPolicies extends StatefulWidget { - final String empCode; - const ClaimsPolicies( - {Key? key, - required this.empCode, - }); + const ClaimsPolicies({ + Key? key, + required this.empCode, + }); @override State createState() => _ClaimsPolicieState(); } - class _ClaimsPolicieState extends State { - List tabHeader = ['name', 'empCode', 'from', 'to', 'claimNum','policyNumber']; + List tabHeader = [ + 'name', + 'empCode', + 'from', + 'to', + 'claimNum', + 'policyNumber' + ]; final tokenService = TokenStorageService(); List> filteredData = []; // Filtered data source dynamic empClientId; @@ -91,7 +97,6 @@ class _ClaimsPolicieState extends State { } } - Map claim_Detials() { final data = { "client_id": empClientId ?? '', @@ -116,15 +121,14 @@ class _ClaimsPolicieState extends State { controllers[field] = TextEditingController(); } - // if (_postPreToken != null && _postPreToken!.isNotEmpty) { // // claim_Detials(); // - // print("Empcoed1- ${widget.empCodeHrPolicy}"); - // print("EmpisHrcode- ${empHrId}"); + // logDebug("Empcoed1- ${widget.empCodeHrPolicy}"); + // logDebug("EmpisHrcode- ${empHrId}"); // if (widget.empCodeHrPolicy != '') { - // print("Empcoedbool- ${widget.isHrcode}"); + // logDebug("Empcoedbool- ${widget.isHrcode}"); // controllers['empCode']!.text = widget.empCodeHrPolicy; // // if (widget.isHrcode == 0) { // // controllers['empCode']?.clear(); @@ -132,19 +136,18 @@ class _ClaimsPolicieState extends State { // // controllers['empCode']!.text = widget.empCodeHrPolicy; // // } // - // print("Empcoed- ${widget.empCodeHrPolicy}"); + // logDebug("Empcoed- ${widget.empCodeHrPolicy}"); // } // // // if (widget.empCodeHrPolicy != '' && widget.isHrcode) { - // // print("Empcoedbool- ${widget.isHrcode}"); + // // logDebug("Empcoedbool- ${widget.isHrcode}"); // // controllers['empCode']!.text = widget.empCodeHrPolicy; - // // print("Empcoed- ${widget.empCodeHrPolicy}"); + // // logDebug("Empcoed- ${widget.empCodeHrPolicy}"); // // } // // getClaimList(); // } - // getApiData(); _loadIds(); } @@ -178,13 +181,14 @@ class _ClaimsPolicieState extends State { } Future getClaimsPoliciesDetails() async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); - final response = await apiService.getClaimPoliciesToApi(_postPreToken!,''); + logDebug('10'); + final response = + await apiService.getClaimPoliciesToApi(_postPreToken!, ''); if (response['status'] == 'success') { setState(() { isLoading = false; @@ -199,13 +203,13 @@ class _ClaimsPolicieState extends State { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { // isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { // _isLoading = false; @@ -214,7 +218,7 @@ class _ClaimsPolicieState extends State { } Future getClaimList() async { - print('getClaimList called'); + logDebug('getClaimList called'); setState(() { isLoading = true; }); @@ -224,7 +228,7 @@ class _ClaimsPolicieState extends State { empClientBranchId ??= await tokenService.readValue('empClientBranchId'); final requestData = claim_Detials(); - print("Request Body: $requestData"); + logDebug("Request Body: $requestData"); try { final response = await apiService.getClaimPoliciesListDataToApi( @@ -235,21 +239,21 @@ class _ClaimsPolicieState extends State { if (response['status'] == 'success') { setState(() { getClaimPolicies = List>.from(response['data']); - print('API Data - $getClaimPolicies'); + logDebug('API Data - $getClaimPolicies'); originalData = getClaimPolicies; filteredData = List.from(originalData); - print('originalData - $getClaimPolicies'); + logDebug('originalData - $getClaimPolicies'); }); } else { getClaimPolicies = []; originalData = getClaimPolicies; filteredData = List.from(originalData); - print('originalData - $getClaimPolicies'); - print('Request failed: ${response['code']}'); + logDebug('originalData - $getClaimPolicies'); + logDebug('Request failed: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { isLoading = false; @@ -260,19 +264,19 @@ class _ClaimsPolicieState extends State { int getStatusCount(String status) { return filteredData .where((item) => - (item['status'] ?? '').toString().toLowerCase() == - status.toLowerCase()) + (item['status'] ?? '').toString().toLowerCase() == + status.toLowerCase()) .length; } - Future applyFilter() async { - print("Filtersss"); + logDebug("Filtersss"); + /// ✅ Resolve futures FIRST empClientId ??= await tokenService.readValue('empClientId'); empClientBranchId ??= await tokenService.readValue('empClientBranchId'); final data = claim_Detials(); - print("data -- $data"); + logDebug("data -- $data"); getClaimList(); setState(() { appliedClaimStatus = selectedClaimStatus; // ✅ apply only after API call @@ -300,14 +304,25 @@ class _ClaimsPolicieState extends State { empClientBranchId ??= await tokenService.readValue('empClientBranchId'); final data = claim_Detials(); - print("restdata -- $data"); + logDebug("restdata -- $data"); } void exportToCsv(List> data) { List> rows = []; // Header - rows.add(['Emp Name', 'Emp Code','Insured Name', 'Policy Type','Client Policy No','Claim Number','Claim Type','Status','Claim Amount','Record Date']); + rows.add([ + 'Emp Name', + 'Emp Code', + 'Insured Name', + 'Policy Type', + 'Client Policy No', + 'Claim Number', + 'Claim Type', + 'Status', + 'Claim Amount', + 'Record Date' + ]); // Data rows for (var item in data) { @@ -340,34 +355,34 @@ class _ClaimsPolicieState extends State { } Future handleExportAction() async { - print('handleExportAction'); + logDebug('handleExportAction'); _postPreToken = await tokenService.getCurrentToken(); final postId = await tokenService.readValue('empHrId'); final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); var activity = "export_cddata"; - print('postId - $postId'); - print('preId - $preId'); - print('activity - $activity'); + logDebug('postId - $postId'); + logDebug('preId - $preId'); + logDebug('activity - $activity'); try { - print('10'); + logDebug('10'); final response = await apiService.getPostLogHrActivity( postId!, preId!, _postPreToken!, activity); if (response['status'] == 'success') { - print('Request success'); + logDebug('Request success'); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } void search(String query) { - print(query); + logDebug(query); // Check if the query is empty if (query.isEmpty) { // If search query is empty, show all data @@ -382,9 +397,9 @@ class _ClaimsPolicieState extends State { // For example, check if any field in the row contains the query // Adjust this logic based on your data structure return row['emp_name'] - .toString() - .toLowerCase() - .contains(query.toLowerCase()) || + .toString() + .toLowerCase() + .contains(query.toLowerCase()) || row['emp_code'] .toString() .toLowerCase() @@ -424,28 +439,28 @@ class _ClaimsPolicieState extends State { }).toList(); }); } - print(filteredData.length); + logDebug(filteredData.length); } Future _showLogoutDialog() async { return await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => AlertDialog( - title: Text("Confirm Logout"), - content: Text("Do you want to logout?"), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: Text("Cancel"), + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + title: Text("Confirm Logout"), + content: Text("Do you want to logout?"), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text("Logout"), + ), + ], ), - TextButton( - onPressed: () => Navigator.of(context).pop(true), - child: Text("Logout"), - ), - ], - ), - ) ?? + ) ?? false; } @@ -457,9 +472,9 @@ class _ClaimsPolicieState extends State { return list .map>((e) => { - 'id': int.parse(e['id'].toString()), - 'name': e['claim_status'].toString(), - }) + 'id': int.parse(e['id'].toString()), + 'name': e['claim_status'].toString(), + }) .toList(); } @@ -488,19 +503,19 @@ class _ClaimsPolicieState extends State { /// 🔙 Back + Title (LEFT) Row( children: [ - if(widget.empCode.isNotEmpty) - IconButton( - onPressed: () => { - Navigator.of(context).pop(), - }, - icon: const Icon( - Icons.arrow_back_ios, - size: 18, - color: Colors.black, + if (widget.empCode.isNotEmpty) + IconButton( + onPressed: () => { + Navigator.of(context).pop(), + }, + icon: const Icon( + Icons.arrow_back_ios, + size: 18, + color: Colors.black, + ), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), ), - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - ), const SizedBox(width: 6), Text( 'Claims', @@ -533,7 +548,7 @@ class _ClaimsPolicieState extends State { prefixIcon: Icon(Icons.search, size: 18), border: InputBorder.none, contentPadding: - EdgeInsets.symmetric(horizontal: 12, vertical: 8), + EdgeInsets.symmetric(horizontal: 12, vertical: 8), ), ), ), @@ -546,7 +561,7 @@ class _ClaimsPolicieState extends State { height: 37, child: ElevatedButton( onPressed: () { - exportToCsv(filteredData); + exportToCsv(filteredData); }, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFE26728), @@ -567,6 +582,7 @@ class _ClaimsPolicieState extends State { ), ), const SizedBox(width: 12), + /// ⬇️ Add Button SizedBox( width: 100, @@ -612,18 +628,18 @@ class _ClaimsPolicieState extends State { isLoading ? Expanded( - // color: Color(0x98FFFCE5), // Semi-transparent background - child: Center( - child: // Your GIF loader widget - Image.asset( - height: 60, - width: 60, - 'assets/nhance-loader.gif'), // Adjust path to your GIF loader - ), - ) + // color: Color(0x98FFFCE5), // Semi-transparent background + child: Center( + child: // Your GIF loader widget + Image.asset( + height: 60, + width: 60, + 'assets/nhance-loader.gif'), // Adjust path to your GIF loader + ), + ) : Expanded( - child: _buildClaimsDataTable(context), // ✅ THIS IS REQUIRED - ), + child: _buildClaimsDataTable(context), // ✅ THIS IS REQUIRED + ), // Expanded( // child: Container( // child: Column( @@ -643,8 +659,6 @@ class _ClaimsPolicieState extends State { ); } - - Widget _buildInputFields(BuildContext context) { return SizedBox( height: 70, // 🔥 controls total height like image @@ -670,11 +684,11 @@ class _ClaimsPolicieState extends State { width: MediaQuery.of(context).size.width * 0.15, child: buildDropdownFieldSearch( 'Claim Status', - (int? value) { + (int? value) { setState(() { selectedClaimStatus = value; }); - print('Selected Claim Status ID: $selectedClaimStatus'); + logDebug('Selected Claim Status ID: $selectedClaimStatus'); }, claimStatusList, 'name', @@ -683,7 +697,6 @@ class _ClaimsPolicieState extends State { ); } - Widget _buildClaimsDataTable(BuildContext context) { if (filteredData.isEmpty) { return const Center(child: Text('No available data')); @@ -700,7 +713,7 @@ class _ClaimsPolicieState extends State { /// 📄 TABLE ROWS SliverList( delegate: SliverChildBuilderDelegate( - (context, index) { + (context, index) { final item = _paginatedData[index]; return _buildDataRow(item); }, @@ -802,19 +815,19 @@ class _ClaimsPolicieState extends State { Tooltip( message: 'View Claim History', child: - // 2. MouseRegion for the hand pointer - MouseRegion( + // 2. MouseRegion for the hand pointer + MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { - // print('id ${item['id']}'); - // print('emp_name ${item['emp_name']}'); - // print('emp_code ${item['emp_code']}'); - // print('policy_type ${item['policy_type']}'); - // print('client_policy_no ${item['client_policy_no']}'); - // print('claim_amount ${item['claim_amount']}'); - // print('claim_no ${item['claim_no']}'); - // print(widget.postToken); + // logDebug('id ${item['id']}'); + // logDebug('emp_name ${item['emp_name']}'); + // logDebug('emp_code ${item['emp_code']}'); + // logDebug('policy_type ${item['policy_type']}'); + // logDebug('client_policy_no ${item['client_policy_no']}'); + // logDebug('claim_amount ${item['claim_amount']}'); + // logDebug('claim_no ${item['claim_no']}'); + // logDebug(widget.postToken); // return; showDialog( context: context, @@ -829,7 +842,8 @@ class _ClaimsPolicieState extends State { empCode: item['emp_code'] ?? '', // example policyType: item['policy_type'] ?? '', clientPolicyNo: item['client_policy_no'] ?? '', - claimAmount: item['claim_amount']?.toString() ?? '', + claimAmount: + item['claim_amount']?.toString() ?? '', claimNo: item['claim_no'] ?? '', postToken: _postPreToken ?? '', ), @@ -845,7 +859,8 @@ class _ClaimsPolicieState extends State { borderRadius: BorderRadius.circular(8), ), child: Padding( - padding: EdgeInsets.all(10), // You can adjust this value + padding: + EdgeInsets.all(10), // You can adjust this value child: Image.asset( 'assets/claimHistory.png', fit: BoxFit.contain, @@ -871,9 +886,10 @@ class _ClaimsPolicieState extends State { if (statusMaster.isEmpty) return const SizedBox(); final List displayStatuses = appliedClaimStatus != null - ? statusMaster.where((status) => - int.parse(status['id'].toString()) == appliedClaimStatus) - .toList() + ? statusMaster + .where((status) => + int.parse(status['id'].toString()) == appliedClaimStatus) + .toList() : statusMaster; return SizedBox( @@ -890,8 +906,7 @@ class _ClaimsPolicieState extends State { final color = getStatusColor(statusName); return Container( - padding: - const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(6), @@ -910,7 +925,6 @@ class _ClaimsPolicieState extends State { ); } - static final _dataBold = GoogleFonts.poppins( fontSize: 12, fontWeight: FontWeight.w400, @@ -943,7 +957,8 @@ class _ClaimsPolicieState extends State { Widget _buildPagination(BuildContext context) { // 1. Calculate the range of entries being shown final totalItems = filteredData.length; - final int startEntry = totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; + final int startEntry = + totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; int endEntry = _currentPage * _rowsPerPage; if (endEntry > totalItems) endEntry = totalItems; @@ -974,7 +989,6 @@ class _ClaimsPolicieState extends State { _currentPage + 1, _currentPage + 2, ]; - } List visiblePages = getVisiblePages(); @@ -983,7 +997,8 @@ class _ClaimsPolicieState extends State { // Match this horizontal padding (16) to your Table Header padding for perfect alignment padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, // Pushes text to left, buttons to right + mainAxisAlignment: MainAxisAlignment + .spaceBetween, // Pushes text to left, buttons to right children: [ // --- LEFT SIDE: Showing Text --- Text( @@ -1196,23 +1211,23 @@ class _ClaimsPolicieState extends State { // Get id from type_name int? getIdByTypeName(String? typeName) { - print("getIdByTypeName"); - print("getIdByTypeName - $typeName"); + logDebug("getIdByTypeName"); + logDebug("getIdByTypeName - $typeName"); final match = ticketTypeList.firstWhere( (e) => e['type_name'] == typeName, orElse: () => null, ); - print("match - $match"); + logDebug("match - $match"); if (match != null && match is Map) { final map = match as Map; final id = map['ticket_type']; - print("Returning ticket_type: $id"); + logDebug("Returning ticket_type: $id"); return id is int ? id : int.tryParse(id.toString()); } - print("no match or invalid map"); + logDebug("no match or invalid map"); return null; } @@ -1248,9 +1263,9 @@ class _ClaimsPolicieState extends State { selectedPolicyType = getIdByTypeName(value); }); - print( + logDebug( "Selected selectedPolicyTypeName: $selectedPolicyTypeName"); - print("Selected selectedPolicyType: $selectedPolicyType"); + logDebug("Selected selectedPolicyType: $selectedPolicyType"); }, decoratorProps: DropDownDecoratorProps( decoration: InputDecoration( @@ -1309,72 +1324,72 @@ class _ClaimsPolicieState extends State { height: 3, ), SizedBox( - height: 40, - child: Container( - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.08), // soft shadow - blurRadius: 8, - offset: const Offset(0, 2), // downward shadow + height: 40, + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), // soft shadow + blurRadius: 8, + offset: const Offset(0, 2), // downward shadow + ), + ], + ), + child: TextField( + controller: controllers['from'], + readOnly: true, + onTap: () async { + FocusScope.of(context) + .requestFocus(FocusNode()); // hide keyboard + DateTime? pickedDate = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(2000), + lastDate: DateTime.now(), + ); + + if (pickedDate != null) { + String formattedDate = + "${pickedDate.day.toString().padLeft(2, '0')}-${pickedDate.month.toString().padLeft(2, '0')}-${pickedDate.year}"; + + logDebug("FomatedFromDAta - $formattedDate"); + setState(() { + controllers['from']?.text = formattedDate; + controllers['to'] + ?.clear(); // 🔥 prevent invalid To date + }); + } + }, + style: const TextStyle( + fontSize: 12, ), - ], - ), - child: TextField( - controller: controllers['from'], - readOnly: true, - onTap: () async { - FocusScope.of(context) - .requestFocus(FocusNode()); // hide keyboard - DateTime? pickedDate = await showDatePicker( - context: context, - initialDate: DateTime.now(), - firstDate: DateTime(2000), - lastDate: DateTime.now(), - ); + decoration: InputDecoration( + floatingLabelBehavior: FloatingLabelBehavior.never, - if (pickedDate != null) { - String formattedDate = - "${pickedDate.day.toString().padLeft(2, '0')}-${pickedDate.month.toString().padLeft(2, '0')}-${pickedDate.year}"; + hintText: 'Select', + filled: true, + fillColor: Colors.white, - print("FomatedFromDAta - $formattedDate"); - setState(() { - controllers['from']?.text = formattedDate; - controllers['to']?.clear(); // 🔥 prevent invalid To date - }); - } - }, - style: const TextStyle( - fontSize: 12, - ), - decoration: InputDecoration( - floatingLabelBehavior: FloatingLabelBehavior.never, - - hintText: 'Select', - filled: true, - fillColor: Colors.white, - - border: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.circular(8.0), + border: OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + borderRadius: BorderRadius.circular(8.0), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + borderRadius: BorderRadius.circular(8.0), + ), + focusedBorder: OutlineInputBorder( + borderSide: BorderSide(color: Colors.teal, width: 2.0), + borderRadius: BorderRadius.circular(8.0), + ), + // contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), + contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 10), + suffixIcon: const Icon(Icons.calendar_today, size: 16), + ), ), - enabledBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.circular(8.0), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.teal, width: 2.0), - borderRadius: BorderRadius.circular(8.0), - ), - // contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), - contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 10), - suffixIcon: const Icon(Icons.calendar_today, size: 16), - ), - ), - ) - ), + )), ], ), ); @@ -1394,88 +1409,87 @@ class _ClaimsPolicieState extends State { height: 3, ), SizedBox( - height: 40, - child: Container( - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.08), // soft shadow - blurRadius: 8, - offset: const Offset(0, 2), // downward shadow + height: 40, + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), // soft shadow + blurRadius: 8, + offset: const Offset(0, 2), // downward shadow + ), + ], + ), + child: TextField( + controller: controllers['to'], + readOnly: true, + onTap: () async { + FocusScope.of(context).requestFocus(FocusNode()); + + final fromDate = _parseDate(controllers['from']?.text); + + DateTime? pickedDate = await showDatePicker( + context: context, + initialDate: fromDate ?? DateTime.now(), + firstDate: fromDate ?? + DateTime(2000), // ✅ cannot be before From date + lastDate: DateTime.now(), // ✅ no future dates + ); + + if (pickedDate != null) { + String formattedDate = + "${pickedDate.day.toString().padLeft(2, '0')}-" + "${pickedDate.month.toString().padLeft(2, '0')}-" + "${pickedDate.year}"; + + setState(() { + controllers['to']?.text = formattedDate; + }); + } + }, + style: const TextStyle( + fontSize: 12, ), - ], - ), - child: TextField( - controller: controllers['to'], - readOnly: true, - onTap: () async { - FocusScope.of(context).requestFocus(FocusNode()); + decoration: InputDecoration( + floatingLabelBehavior: FloatingLabelBehavior.never, - final fromDate = _parseDate(controllers['from']?.text); + hintText: 'Select', - DateTime? pickedDate = await showDatePicker( - context: context, - initialDate: fromDate ?? DateTime.now(), - firstDate: fromDate ?? DateTime(2000), // ✅ cannot be before From date - lastDate: DateTime.now(), // ✅ no future dates - ); + filled: true, + fillColor: Colors.white, - if (pickedDate != null) { - String formattedDate = - "${pickedDate.day.toString().padLeft(2, '0')}-" - "${pickedDate.month.toString().padLeft(2, '0')}-" - "${pickedDate.year}"; - - setState(() { - controllers['to']?.text = formattedDate; - }); - } - }, - style: const TextStyle( - fontSize: 12, - ), - decoration: InputDecoration( - floatingLabelBehavior: FloatingLabelBehavior.never, - - hintText: 'Select', - - filled: true, - fillColor: Colors.white, - - border: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.circular(8.0), + border: OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + borderRadius: BorderRadius.circular(8.0), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + borderRadius: BorderRadius.circular(8.0), + ), + focusedBorder: OutlineInputBorder( + borderSide: BorderSide(color: Colors.teal, width: 2.0), + borderRadius: BorderRadius.circular(8.0), + ), + // contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), + contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 10), + suffixIcon: const Icon(Icons.calendar_today, size: 16), + ), ), - enabledBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.circular(8.0), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.teal, width: 2.0), - borderRadius: BorderRadius.circular(8.0), - ), - // contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), - contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 10), - suffixIcon: const Icon(Icons.calendar_today, size: 16), - ), - ), - ) - ), + )), ], ), ); } Widget buildDropdownFieldSearch( - String label, - void Function(int?) onChanged, - List> itemsList, - String displayField, - int? selectedValue, - ) { - + String label, + void Function(int?) onChanged, + List> itemsList, + String displayField, + int? selectedValue, + ) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -1539,11 +1553,12 @@ class _ClaimsPolicieState extends State { ), searchMatchFn: (item, searchValue) { final matchedItem = itemsList.firstWhere( - (e) => e['id'] == item.value, + (e) => e['id'] == item.value, orElse: () => {}, ); - final text = matchedItem['name']?.toString().toLowerCase() ?? ''; + final text = + matchedItem['name']?.toString().toLowerCase() ?? ''; return text.contains(searchValue.toLowerCase()); }, ), @@ -1583,9 +1598,6 @@ class _ClaimsPolicieState extends State { ); } - - - Widget _buildPolicyNumber(BuildContext context) { return Container( width: MediaQuery.of(context).size.width * 0.15, @@ -1600,50 +1612,49 @@ class _ClaimsPolicieState extends State { height: 3, ), SizedBox( - height: 40, - child: Container( - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.08), // soft shadow - blurRadius: 8, - offset: const Offset(0, 2), // downward shadow + height: 40, + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), // soft shadow + blurRadius: 8, + offset: const Offset(0, 2), // downward shadow + ), + ], + ), + child: TextField( + controller: controllers['policyNumber'], + style: const TextStyle( + fontSize: 12, ), - ], - ), - child: TextField( - controller: controllers['policyNumber'], - style: const TextStyle( - fontSize: 12, - ), - decoration: InputDecoration( - floatingLabelBehavior: FloatingLabelBehavior.never, + decoration: InputDecoration( + floatingLabelBehavior: FloatingLabelBehavior.never, - hintText: 'Policy Number', + hintText: 'Policy Number', - filled: true, - fillColor: Colors.white, + filled: true, + fillColor: Colors.white, - border: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.circular(8.0), + border: OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + borderRadius: BorderRadius.circular(8.0), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + borderRadius: BorderRadius.circular(8.0), + ), + focusedBorder: OutlineInputBorder( + borderSide: BorderSide(color: Colors.teal, width: 2.0), + borderRadius: BorderRadius.circular(8.0), + ), + // contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), + contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 10), + ), ), - enabledBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.circular(8.0), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.teal, width: 2.0), - borderRadius: BorderRadius.circular(8.0), - ), - // contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), - contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 10), - ), - ), - ) - ), + )), ], ), ); @@ -1668,16 +1679,14 @@ class _ClaimsPolicieState extends State { mainAxisAlignment: MainAxisAlignment.start, children: [ _IconActionButton( - icon: Icons.filter_alt_outlined, - onTap: applyFilter, - tooltip:"Filter" - ), + icon: Icons.filter_alt_outlined, + onTap: applyFilter, + tooltip: "Filter"), const SizedBox(width: 12), _IconActionButton( - icon: Icons.refresh_outlined, - onTap: reset, - tooltip:"Reset" - ), + icon: Icons.refresh_outlined, + onTap: reset, + tooltip: "Reset"), ], ), ), @@ -1685,7 +1694,6 @@ class _ClaimsPolicieState extends State { ), ); } - } class _ClaimsHeaderDelegate extends SliverPersistentHeaderDelegate { @@ -1749,20 +1757,21 @@ class _IconActionButton extends StatelessWidget { @override Widget build(BuildContext context) { return Tooltip( - message: tooltip, - preferBelow: false, // Optional: Shows tooltip above the button - child: SizedBox( - width: 40, - height: 40, - child: Material( - color: const Color(0xFF00999E), - borderRadius: BorderRadius.circular(10), - child: InkWell( + message: tooltip, + preferBelow: false, // Optional: Shows tooltip above the button + child: SizedBox( + width: 40, + height: 40, + child: Material( + color: const Color(0xFF00999E), borderRadius: BorderRadius.circular(10), - onTap: onTap, - child: Icon(icon, color: Colors.white, size: 20), + child: InkWell( + borderRadius: BorderRadius.circular(10), + onTap: onTap, + child: Icon(icon, color: Colors.white, size: 20), + ), ), ), - ),); + ); } } diff --git a/lib/presentation/claimshistory.dart b/lib/presentation/claimshistory.dart index cad4feb..c3f600f 100755 --- a/lib/presentation/claimshistory.dart +++ b/lib/presentation/claimshistory.dart @@ -13,6 +13,7 @@ import 'package:file_picker/file_picker.dart'; import 'package:pdf/widgets.dart' as pw; import '../../../config/environment.dart'; import '../../../customAppBar/toastHelper.dart'; +import 'package:nhancepolicy/logger.dart'; class ClaimHistoryPopup extends StatefulWidget { final String ticket_id; @@ -77,13 +78,13 @@ class _ClaimHistoryPopupState extends State apiService = ApiService(context); // debug prints kept - print("CLAIMHISTORY"); - print(widget.claimAmount); - print(widget.claimNo); - print(widget.clientPolicyNo); - print(widget.empCode); - print(widget.policyType); - print(widget.ticket_id); + logDebug("CLAIMHISTORY"); + logDebug(widget.claimAmount); + logDebug(widget.claimNo); + logDebug(widget.clientPolicyNo); + logDebug(widget.empCode); + logDebug(widget.policyType); + logDebug(widget.ticket_id); getClaimsHistoryDetails(); } @@ -144,7 +145,7 @@ class _ClaimHistoryPopupState extends State setState(() => isSubmitting = true); // 🔥 start loader try { - print('enter'); + logDebug('enter'); // STEP 1: Must select at least one document type final selectedDocs = requiredDocsList @@ -235,9 +236,9 @@ class _ClaimHistoryPopupState extends State request.fields['claim_doc_names'] = jsonEncode(labels); // Debug - print( + logDebug( "Files uploaded: ${fileService.files.map((e) => e.file.name).toList()}"); - print("Labels: $labels"); + logDebug("Labels: $labels"); // STEP 7: Send the request final response = await request.send(); @@ -299,8 +300,8 @@ class _ClaimHistoryPopupState extends State }) .toList(); - print(isActionFreeze); - print('requiredDocsList $requiredDocsList'); + logDebug(isActionFreeze); + logDebug('requiredDocsList $requiredDocsList'); for (var d in requiredDocsList) { _assignedFiles[d['document_name']] = null; @@ -308,11 +309,11 @@ class _ClaimHistoryPopupState extends State }); } else { setState(() => isLoading = false); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() => isLoading = false); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -321,7 +322,7 @@ class _ClaimHistoryPopupState extends State try { await launchUrl(uri, mode: LaunchMode.externalApplication); } catch (e) { - print('Could not launch URL: $e'); + logDebug('Could not launch URL: $e'); } } @@ -477,13 +478,17 @@ class _ClaimHistoryPopupState extends State isDesktop: false, key: ValueKey('mobile_ir'), ) - : _buildMainLeftContent(key: ValueKey('main_left'),showIRDocs: showIRDocs), + : _buildMainLeftContent( + key: ValueKey('main_left'), + showIRDocs: showIRDocs), ) : Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // LEFT: main content - scrollable - Expanded(child: _buildMainLeftContent(showIRDocs: showIRDocs)), + Expanded( + child: + _buildMainLeftContent(showIRDocs: showIRDocs)), // RIGHT: IR panel - desktop inline (only visible on wide screens) AnimatedContainer( @@ -510,7 +515,10 @@ class _ClaimHistoryPopupState extends State // ------------------------- // Main left content extracted to keep code tidy // ------------------------- - Widget _buildMainLeftContent({Key? key,required bool showIRDocs,}) { + Widget _buildMainLeftContent({ + Key? key, + required bool showIRDocs, + }) { return SingleChildScrollView( key: key, child: Column( @@ -738,9 +746,9 @@ class _ClaimHistoryPopupState extends State shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: claimFiles.length, - gridDelegate: - SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: showIRDocs ? 2 : 3, // ✅ desktop: 3 per row + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: + showIRDocs ? 2 : 3, // ✅ desktop: 3 per row crossAxisSpacing: 16, mainAxisSpacing: 16, childAspectRatio: 5.9, // controls height @@ -799,22 +807,23 @@ class _ClaimHistoryPopupState extends State Tooltip( message: 'Download', // Added tooltip name child: InkWell( - borderRadius: BorderRadius.circular(6), - onTap: () => _launchURL(file['url']), - child: Container( - padding: const EdgeInsets.all(6), - decoration: BoxDecoration( - color: const Color(0xFFE6E6E6), - borderRadius: BorderRadius.circular(6), - ), - child: const Icon( - Icons.download, - size: 18, - color: Colors.black, + borderRadius: BorderRadius.circular(6), + onTap: () => _launchURL(file['url']), + child: Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: const Color(0xFFE6E6E6), + borderRadius: + BorderRadius.circular(6), + ), + child: const Icon( + Icons.download, + size: 18, + color: Colors.black, + ), ), ), ), - ), ], ), ), diff --git a/lib/presentation/excelVerification.dart b/lib/presentation/excelVerification.dart index 6911202..1c755f4 100644 --- a/lib/presentation/excelVerification.dart +++ b/lib/presentation/excelVerification.dart @@ -16,6 +16,7 @@ import 'dart:typed_data'; import 'package:collection/collection.dart'; import 'package:url_launcher/url_launcher.dart'; import '../customAppBar/base_layout.dart'; +import 'package:nhancepolicy/logger.dart'; class excelErrorScreen extends StatefulWidget { final String ClientId; @@ -73,14 +74,13 @@ class _activePolicyExcelErrorState extends State List>> get _paginatedExcelData { final start = (_currentPage - 1) * _rowsPerPage; final end = - (_currentPage * _rowsPerPage).clamp(0, filteredExcelData.length); + (_currentPage * _rowsPerPage).clamp(0, filteredExcelData.length); return filteredExcelData.sublist(start, end); } final ScrollController _verticalController = ScrollController(); final ScrollController _horizontalController = ScrollController(); - @override void initState() { super.initState(); @@ -95,7 +95,6 @@ class _activePolicyExcelErrorState extends State super.dispose(); } - Future getCDPoliciesDetails() async { setState(() { isLoading = true; @@ -103,7 +102,7 @@ class _activePolicyExcelErrorState extends State try { final response = - await apiService.getExcelFileErrorsApi(widget.id, widget.TokenType); + await apiService.getExcelFileErrorsApi(widget.id, widget.TokenType); // 🔴 CASE 1: Empty data → popup + back if (response['data'] is List && response['data'].isEmpty) { @@ -117,27 +116,24 @@ class _activePolicyExcelErrorState extends State if (response['message'] == "Error data feteched successfully") { // This runs if the message matches EXACTLY (including the typo 'feteched') ToastHelper.showErrorToast(context, response['message']); - }else { + } else { ToastHelper.showSuccessToast(context, response['message']); } - - setState(() { isLoading = false; isSuccess = false; excelValidationStaus = 1; - excelHeader = - List.from(response['data']['excel_header']); + excelHeader = List.from(response['data']['excel_header']); excelData = (response['data']['excel_data'] as List) .map>>( (row) => row - .map>( - (cell) => Map.from(cell)) - .toList(), - ) + .map>( + (cell) => Map.from(cell)) + .toList(), + ) .toList(); filteredExcelData = List.from(excelData); @@ -148,15 +144,13 @@ class _activePolicyExcelErrorState extends State setState(() => isLoading = false); _showEmptyDataDialog(response['message']); } - } catch (e) { setState(() => isLoading = false); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); _showEmptyDataDialog('Something went wrong. Please try again.'); } } - void _showEmptyDataDialog(String message) { showDialog( context: context, @@ -185,7 +179,6 @@ class _activePolicyExcelErrorState extends State ); } - void search(String query) { if (query.isEmpty) { setState(() { @@ -246,9 +239,8 @@ class _activePolicyExcelErrorState extends State html.Url.revokeObjectUrl(url); } - // Future handleExportAction() async { - // print('handleExportAction'); + // logDebug('handleExportAction'); // // final postId = await tokenService.readValue('empHrId'); // final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); @@ -258,12 +250,12 @@ class _activePolicyExcelErrorState extends State // var activityPre = "export_preempdata"; // dynamic response; // - // print('postId - $postId'); - // print('preId - $preId'); - // print('activity - $activity'); + // logDebug('postId - $postId'); + // logDebug('preId - $preId'); + // logDebug('activity - $activity'); // // try { - // print('10'); + // logDebug('10'); // // if (widget.TokenType == 'pre') { // response = await apiService.getPreLogHrActivity( @@ -274,14 +266,14 @@ class _activePolicyExcelErrorState extends State // } // // if (response['status'] == 'success') { - // print('Request success'); + // logDebug('Request success'); // } else { // // ToastHelper.showWarningToast( // // context, 'Request failed with status: ${response.statusCode}'); - // print('Request failed with status: ${response['code']}'); + // logDebug('Request failed with status: ${response['code']}'); // } // } catch (e) { - // print('Exception occurred: $e'); + // logDebug('Exception occurred: $e'); // } // } @@ -295,7 +287,6 @@ class _activePolicyExcelErrorState extends State return DateFormat('dd-MM-yyyy hh:mm a').format(parsedDate); } - @override Widget build(BuildContext context) { return BaseLayout( @@ -420,7 +411,6 @@ class _activePolicyExcelErrorState extends State excelHeader: excelHeader, excelData: filteredExcelData, // or excelData ); - }, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFE26728), @@ -446,7 +436,6 @@ class _activePolicyExcelErrorState extends State Expanded( child: _buildCDDataTable(context), ), - ], ), ); @@ -499,8 +488,7 @@ class _activePolicyExcelErrorState extends State return SizedBox( width: columnWidth, child: Padding( - padding: - const EdgeInsets.symmetric(horizontal: 12), + padding: const EdgeInsets.symmetric(horizontal: 12), child: Text( header, style: GoogleFonts.poppins( @@ -535,150 +523,198 @@ class _activePolicyExcelErrorState extends State return SizedBox( width: columnWidth, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), + padding: + const EdgeInsets.symmetric(horizontal: 12), child: hasError ? Row( - children: [ - Expanded( - child: Text( + children: [ + Expanded( + child: Text( + cell['value']?.toString() ?? '-', + style: GoogleFonts.poppins( + fontSize: 12, + ), + ), + ), + const SizedBox(width: 6), + IconButton( + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + icon: const Icon( + Icons.error_outline, + color: Colors.red, + size: 16, + ), + onPressed: () { + showDialog( + context: context, + barrierDismissible: true, + builder: (_) { + final List errors = + cell['error'] as List; + + return Dialog( + backgroundColor: + Colors.transparent, + child: Container( + width: 420, + padding: const EdgeInsets + .symmetric( + horizontal: 24, + vertical: 28), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius.circular( + 20), + ), + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + /// ERROR TITLE + Text( + 'Error!', + style: GoogleFonts + .poppins( + fontSize: 32, + fontWeight: + FontWeight.bold, + color: Colors.black, + ), + ), + + const SizedBox( + height: 16), + + /// RED ICON + Container( + width: 64, + height: 64, + decoration: + const BoxDecoration( + color: Color( + 0xFFE0002A), + shape: + BoxShape.circle, + ), + child: const Center( + child: Text( + '!', + style: TextStyle( + color: Colors + .white, + fontSize: 36, + fontWeight: + FontWeight + .bold, + ), + ), + ), + ), + + const SizedBox( + height: 20), + + /// ERROR HEADING (optional – first error) + Text( + errors.isNotEmpty + ? errors.first + .toString() + : 'Validation Error', + textAlign: + TextAlign.center, + style: GoogleFonts + .poppins( + fontSize: 18, + fontWeight: + FontWeight.w600, + color: Colors.black, + ), + ), + + const SizedBox( + height: 12), + + /// ERROR DETAILS + ...errors.skip(1).map( + (e) => Padding( + padding: + const EdgeInsets + .only( + top: 6), + child: Text( + e.toString(), + textAlign: + TextAlign + .center, + style: GoogleFonts + .poppins( + fontSize: + 14, + color: const Color( + 0xFFE09B2D), // orange text + ), + ), + ), + ), + + const SizedBox( + height: 20), + + /// OK BUTTON + SizedBox( + width: 120, + height: 30, + child: ElevatedButton( + onPressed: () => + Navigator.pop( + context), + style: + ElevatedButton + .styleFrom( + backgroundColor: + const Color( + 0xFFE0002A), + shape: + RoundedRectangleBorder( + borderRadius: + BorderRadius + .circular( + 20), + ), + elevation: 0, + ), + child: Text( + 'OK', + style: GoogleFonts + .poppins( + fontSize: 14, + fontWeight: + FontWeight + .w600, + color: Colors + .white, + ), + ), + ), + ), + ], + ), + ), + ); + }, + ); + }, + ), + ], + ) + : Text( cell['value']?.toString() ?? '-', style: GoogleFonts.poppins( fontSize: 12, ), ), - ), - const SizedBox(width: 6), - IconButton( - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - icon: const Icon( - Icons.error_outline, - color: Colors.red, - size: 16, - ), - onPressed: () { - showDialog( - context: context, - barrierDismissible: true, - builder: (_) { - final List errors = cell['error'] as List; - - return Dialog( - backgroundColor: Colors.transparent, - child: Container( - width: 420, - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 28), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(20), - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - /// ERROR TITLE - Text( - 'Error!', - style: GoogleFonts.poppins( - fontSize: 32, - fontWeight: FontWeight.bold, - color: Colors.black, - ), - ), - - const SizedBox(height: 16), - - /// RED ICON - Container( - width: 64, - height: 64, - decoration: const BoxDecoration( - color: Color(0xFFE0002A), - shape: BoxShape.circle, - ), - child: const Center( - child: Text( - '!', - style: TextStyle( - color: Colors.white, - fontSize: 36, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - - const SizedBox(height: 20), - - /// ERROR HEADING (optional – first error) - Text( - errors.isNotEmpty ? errors.first.toString() : 'Validation Error', - textAlign: TextAlign.center, - style: GoogleFonts.poppins( - fontSize: 18, - fontWeight: FontWeight.w600, - color: Colors.black, - ), - ), - - const SizedBox(height: 12), - - /// ERROR DETAILS - ...errors.skip(1).map( - (e) => Padding( - padding: const EdgeInsets.only(top: 6), - child: Text( - e.toString(), - textAlign: TextAlign.center, - style: GoogleFonts.poppins( - fontSize: 14, - color: const Color(0xFFE09B2D), // orange text - ), - ), - ), - ), - - const SizedBox(height: 20), - - /// OK BUTTON - SizedBox( - width: 120, - height: 30, - child: ElevatedButton( - onPressed: () => Navigator.pop(context), - style: ElevatedButton.styleFrom( - backgroundColor: const Color(0xFFE0002A), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20), - ), - elevation: 0, - ), - child: Text( - 'OK', - style: GoogleFonts.poppins( - fontSize: 14, - fontWeight: FontWeight.w600, - color: Colors.white, - ), - ), - ), - ), - ], - ), - ), - ); - }, - ); - - }, - ), - ], - ) - : Text( - cell['value']?.toString() ?? '-', - style: GoogleFonts.poppins( - fontSize: 12, - ), - ), ), ); }).toList(), @@ -700,10 +736,8 @@ class _activePolicyExcelErrorState extends State ); } - Widget _buildPagination(BuildContext context) { - final totalPages = - (filteredExcelData.length / _rowsPerPage).ceil(); + final totalPages = (filteredExcelData.length / _rowsPerPage).ceil(); if (totalPages <= 1) { return const SizedBox.shrink(); // 👈 hide if only one page @@ -730,14 +764,11 @@ class _activePolicyExcelErrorState extends State }); }, ), - IconButton( icon: const Icon(Icons.chevron_left), - onPressed: _currentPage > 1 - ? () => setState(() => _currentPage--) - : null, + onPressed: + _currentPage > 1 ? () => setState(() => _currentPage--) : null, ), - for (int i = 1; i <= totalPages; i++) Padding( padding: const EdgeInsets.symmetric(horizontal: 4), @@ -747,7 +778,7 @@ class _activePolicyExcelErrorState extends State ? const Color(0xFF00A6A6) : Colors.grey[300], foregroundColor: - _currentPage == i ? Colors.white : Colors.black, + _currentPage == i ? Colors.white : Colors.black, minimumSize: const Size(36, 36), padding: EdgeInsets.zero, ), @@ -759,7 +790,6 @@ class _activePolicyExcelErrorState extends State child: Text(i.toString()), ), ), - IconButton( icon: const Icon(Icons.chevron_right), onPressed: _currentPage < totalPages @@ -769,6 +799,4 @@ class _activePolicyExcelErrorState extends State ], ); } - - } diff --git a/lib/presentation/hrDashboard.dart b/lib/presentation/hrDashboard.dart index 84fb0ac..81b1716 100755 --- a/lib/presentation/hrDashboard.dart +++ b/lib/presentation/hrDashboard.dart @@ -18,7 +18,8 @@ class hrDashboard extends StatefulWidget { State createState() => _hrDashboardState(); } -class _hrDashboardState extends State with SingleTickerProviderStateMixin { +class _hrDashboardState extends State + with SingleTickerProviderStateMixin { late ApiService apiService; bool isLoading = false; String? selectedPolicyId; @@ -67,7 +68,9 @@ class _hrDashboardState extends State with SingleTickerProviderStat ? List.from(jsonDecode(postRaw)) : []; - if (!(postModules.contains(2) || postModules.contains(3) || postModules.contains(4))) { + if (!(postModules.contains(2) || + postModules.contains(3) || + postModules.contains(4))) { setState(() => hasDashboardError = true); return; } @@ -76,10 +79,12 @@ class _hrDashboardState extends State with SingleTickerProviderStat empClientBranchId = await tokenService.readValue('empClientBranchId'); empHrId = await tokenService.readValue('empHrId'); - await getPostCashDepositDetails(empClientBranchId, empClientId, empHrId, _postPreToken); + await getPostCashDepositDetails( + empClientBranchId, empClientId, empHrId, _postPreToken); } - Future getPostCashDepositDetails(branchId, clientId, hrId, token) async { + Future getPostCashDepositDetails( + branchId, clientId, hrId, token) async { setState(() => isLoading = true); try { if (branchId == null || clientId == null) return; @@ -89,7 +94,8 @@ class _hrDashboardState extends State with SingleTickerProviderStat if (response['status'] == 'success') { final list = List>.from(response['data']); final List> filteredList = list.where((item) { - final int policyTypeId = int.tryParse(item['policy_type_id'].toString()) ?? 0; + final int policyTypeId = + int.tryParse(item['policy_type_id'].toString()) ?? 0; return policyTypeId == 2 || policyTypeId == 3 || policyTypeId == 4 || @@ -137,7 +143,6 @@ class _hrDashboardState extends State with SingleTickerProviderStat isTpaSelected = false; }); - _registerMetabaseIframe( token: response['data']['metabaseToken'], url: response['data']['metabaseUrl'], @@ -173,9 +178,9 @@ class _hrDashboardState extends State with SingleTickerProviderStat }, _postPreToken); if (response['status'] == 'success') { -setState(() { - isTpaSelected = true; -}); + setState(() { + isTpaSelected = true; + }); _registerMetabaseIframe( token: response['data']['metabaseToken'], @@ -184,7 +189,6 @@ setState(() { ); setState(() => _metabaseLoaded = true); - } else { ToastHelper.showErrorToast(context, response['message']); } @@ -206,8 +210,7 @@ setState(() { _dashboardViewType = viewType; - final embedUrl = - "$url/embed/dashboard/$token" + final embedUrl = "$url/embed/dashboard/$token" "#theme=light&bordered=true&titled=true" "&v=${DateTime.now().millisecondsSinceEpoch}"; // 🔥 cache buster @@ -222,7 +225,7 @@ setState(() { ui.platformViewRegistry.registerViewFactory( viewType, - (int viewId) => iframe, + (int viewId) => iframe, ); _registeredViewTypes.add(viewType); @@ -243,8 +246,8 @@ setState(() { child: isDashboardLoading ? _buildLoader() : _metabaseLoaded - ? _buildDashboardView() - : _buildEmptyState(), + ? _buildDashboardView() + : _buildEmptyState(), ), ), ); @@ -406,7 +409,7 @@ setState(() { color: Colors.white, child: Row( children: [ - if (!isTpaSelected)...[ + if (!isTpaSelected) ...[ const Text( 'Select Policy', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13), @@ -418,17 +421,18 @@ setState(() { child: SearchAnchor( viewBackgroundColor: Colors.white, viewConstraints: const BoxConstraints(maxHeight: 220), - builder: (BuildContext context, SearchController controller) { String displayText = "Select Policy"; if (selectedPolicyId != null) { final policy = activePoliciesList.firstWhere( - (p) => p['client_policy_id'].toString() == selectedPolicyId, + (p) => + p['client_policy_id'].toString() == selectedPolicyId, orElse: () => {}, ); if (policy.isNotEmpty) { - displayText = "${policy['type']} - ${policy['policy_no']}"; + displayText = + "${policy['type']} - ${policy['policy_no']}"; } } @@ -459,24 +463,22 @@ setState(() { ), ); }, - suggestionsBuilder: (BuildContext context, SearchController controller) { final input = controller.text.toLowerCase(); return activePoliciesList .where((policy) => - policy['type'] - .toString() - .toLowerCase() - .contains(input) || - policy['policy_no'] - .toString() - .toLowerCase() - .contains(input)) + policy['type'] + .toString() + .toLowerCase() + .contains(input) || + policy['policy_no'] + .toString() + .toLowerCase() + .contains(input)) .map((policy) { - final label = - "${policy['type']} - ${policy['policy_no']}"; + final label = "${policy['type']} - ${policy['policy_no']}"; return ListTile( dense: true, @@ -497,18 +499,13 @@ setState(() { ), ), ], - - const Spacer(), - if (isTpaDashboardEnabled) ElevatedButton( style: ElevatedButton.styleFrom( - backgroundColor: isTpaSelected - ? Colors.teal - : Colors.grey.shade300, - foregroundColor: - isTpaSelected ? Colors.white : Colors.black, + backgroundColor: + isTpaSelected ? Colors.teal : Colors.grey.shade300, + foregroundColor: isTpaSelected ? Colors.white : Colors.black, ), onPressed: () { if (selectedPolicyId == null) return; @@ -522,9 +519,7 @@ setState(() { } }, child: Text( - isTpaSelected - ? "Insights from Nhance" - : "Insights from TPA ", + isTpaSelected ? "Insights from Nhance" : "Insights from TPA ", ), ), ], @@ -532,27 +527,31 @@ setState(() { ); } - Widget _buildLoader() => Center( - child: Image.asset('assets/nhance-loader.gif', height: 60, width: 60), - ); + child: Image.asset('assets/nhance-loader.gif', height: 60, width: 60), + ); Widget _buildEmptyState() => const Center( - child: Text('No dashboard data available', style: TextStyle(color: Colors.grey)), - ); + child: Text('No dashboard data available', + style: TextStyle(color: Colors.grey)), + ); Future _showLogoutDialog() async { return await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text("Confirm Logout"), - content: const Text("Do you want to logout?"), - actions: [ - TextButton(onPressed: () => Navigator.pop(context, false), child: const Text("Cancel")), - TextButton(onPressed: () => Navigator.pop(context, true), child: const Text("Logout")), - ], - ), - ) ?? + context: context, + builder: (context) => AlertDialog( + title: const Text("Confirm Logout"), + content: const Text("Do you want to logout?"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text("Cancel")), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text("Logout")), + ], + ), + ) ?? false; } -} \ No newline at end of file +} diff --git a/lib/presentation/hrPolicyDetails.dart b/lib/presentation/hrPolicyDetails.dart index c702f11..4638705 100755 --- a/lib/presentation/hrPolicyDetails.dart +++ b/lib/presentation/hrPolicyDetails.dart @@ -27,6 +27,7 @@ import '../customAppBar/base_layout.dart'; import '../customAppBar/customFooter.dart'; import '../service/secure_pop_scope.dart'; import 'hrDashboard.dart'; +import 'package:nhancepolicy/logger.dart'; class hrPolicyDetails extends StatefulWidget { final String ClientId; @@ -68,7 +69,6 @@ class hrPolicyDetails extends StatefulWidget { class _HrPolicyDetailsState extends State with TickerProviderStateMixin { - String? localClientId; String? localPolicyTypeId; String? localClientPolicyId; @@ -146,11 +146,11 @@ class _HrPolicyDetailsState extends State case 'total': return const Color(0xFFE2FBCB); case 'under process': - return Color(0xFFBDF9D9); + return Color(0xFFBDF9D9); case 'active': - return Colors.green; + return Colors.green; case 'inactive': - return Colors.red; + return Colors.red; default: return const Color(0xFFB0BEC5); } @@ -162,9 +162,9 @@ class _HrPolicyDetailsState extends State // super.initState(); // apiService = ApiService(context); // Initialize ApiService here // - // print("_PreEnrollmentState 1"); + // logDebug("_PreEnrollmentState 1"); // getCDPoliciesDetails(); - // print('allowed_modules'); + // logDebug('allowed_modules'); // } @override void initState() { @@ -224,11 +224,10 @@ class _HrPolicyDetailsState extends State ? widget.total_premium : await tokenService.readValue('hr_total_premium'); - final savedBulk = await tokenService.readValue( - 'hr_is_ecard_bulk_download_for_employee'); + final savedBulk = + await tokenService.readValue('hr_is_ecard_bulk_download_for_employee'); - localIsEcardBulkDownload = - widget.is_ecard_bulk_download_for_employee != 0 + localIsEcardBulkDownload = widget.is_ecard_bulk_download_for_employee != 0 ? widget.is_ecard_bulk_download_for_employee : int.tryParse(savedBulk ?? '0') ?? 0; @@ -268,17 +267,17 @@ class _HrPolicyDetailsState extends State // } Future getCDPoliciesDetails_06FEB() async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); + logDebug('10'); modulesString = await tokenService.readValue('empAllowed_modules'); // modulesString = "[2,3]"; - print("empmodulesString - $modulesString"); + logDebug("empmodulesString - $modulesString"); if (modulesString != null && modulesString!.trim().isNotEmpty) { final List? moduleList = modulesString @@ -293,10 +292,16 @@ class _HrPolicyDetailsState extends State } final response = localTokenType == "post" - ? await apiService.getEmployeeAndDependenceToApi(localClientId ?? widget.ClientId, - localClientPolicyId ?? widget.ClientPoliyId, localClientBranchId ?? widget.clientBranchId, localToken ?? widget.Token) - : await apiService.getEmployeeAndDependenceToApiPre(localClientId ?? widget.ClientId, - localClientPolicyId ?? widget.ClientPoliyId, localClientBranchId ?? widget.clientBranchId, localToken ?? widget.Token!); + ? await apiService.getEmployeeAndDependenceToApi( + localClientId ?? widget.ClientId, + localClientPolicyId ?? widget.ClientPoliyId, + localClientBranchId ?? widget.clientBranchId, + localToken ?? widget.Token) + : await apiService.getEmployeeAndDependenceToApiPre( + localClientId ?? widget.ClientId, + localClientPolicyId ?? widget.ClientPoliyId, + localClientBranchId ?? widget.clientBranchId, + localToken ?? widget.Token!); if (response['status'] == 'success') { setState(() { @@ -306,8 +311,8 @@ class _HrPolicyDetailsState extends State getCDPolicies = List>.from(response['data']); originalData = getCDPolicies; filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { setState(() { @@ -316,13 +321,13 @@ class _HrPolicyDetailsState extends State // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - // print('Request failed with status: ${response['code']}'); + // logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -331,15 +336,15 @@ class _HrPolicyDetailsState extends State } Future getCDPoliciesDetails() async { - print('getCDPoliciesDetails started'); + logDebug('getCDPoliciesDetails started'); setState(() { isLoading = true; }); try { - print('Fetching modules...'); + logDebug('Fetching modules...'); modulesString = await tokenService.readValue('empAllowed_modules'); - print("empmodulesString - $modulesString"); + logDebug("empmodulesString - $modulesString"); if (modulesString != null && modulesString!.trim().isNotEmpty) { final List? moduleList = modulesString @@ -353,36 +358,41 @@ class _HrPolicyDetailsState extends State hasModule = moduleList?.contains(storeModuleId) ?? false; } - print('Calling API with TokenType: ${localTokenType}'); - print( + logDebug('Calling API with TokenType: ${localTokenType}'); + logDebug( 'ClientId: ${localClientId}, ClientPoliyId: ${localClientPolicyId}'); final response = localTokenType == "post" - ? await apiService.getEmployeeAndDependenceToApi(localClientId ?? widget.ClientId, - localClientPolicyId ?? widget.ClientPoliyId, localClientBranchId ?? widget.clientBranchId, localToken ?? widget.Token) - : await apiService.getEmployeeAndDependenceToApiPre(localClientId ?? widget.ClientId, - localClientPolicyId ?? widget.ClientPoliyId, localClientBranchId ?? widget.clientBranchId, localToken ?? widget.Token!); + ? await apiService.getEmployeeAndDependenceToApi( + localClientId ?? widget.ClientId, + localClientPolicyId ?? widget.ClientPoliyId, + localClientBranchId ?? widget.clientBranchId, + localToken ?? widget.Token) + : await apiService.getEmployeeAndDependenceToApiPre( + localClientId ?? widget.ClientId, + localClientPolicyId ?? widget.ClientPoliyId, + localClientBranchId ?? widget.clientBranchId, + localToken ?? widget.Token!); - print('API Response: ${response.toString()}'); + logDebug('API Response: ${response.toString()}'); if (response != null && response['status'] == 'success') { - final data = response['data']; - if (data != null && data is List) { - // Check if it's actually a list - setState(() { - getCDPolicies = List>.from(data); - originalData = getCDPolicies; - filteredData = List.from(originalData); - isLoading = false; - }); - } else { - setState(() => isLoading = false); - } - + final data = response['data']; + if (data != null && data is List) { + // Check if it's actually a list + setState(() { + getCDPolicies = List>.from(data); + originalData = getCDPolicies; + filteredData = List.from(originalData); + isLoading = false; + }); + } else { + setState(() => isLoading = false); + } } else { final errorCode = response?['code'] ?? 'Unknown'; // final errorMessage = response?['message'] ?? 'Request failed'; - // print('❌ Request failed - Code: $errorCode, Message: $errorMessage'); + // logDebug('❌ Request failed - Code: $errorCode, Message: $errorMessage'); setState(() { isLoading = false; @@ -393,8 +403,8 @@ class _HrPolicyDetailsState extends State } } } catch (e, stackTrace) { - print('❌ Exception occurred: $e'); - print('Stack trace: $stackTrace'); + logDebug('❌ Exception occurred: $e'); + logDebug('Stack trace: $stackTrace'); setState(() { isLoading = false; @@ -415,29 +425,28 @@ class _HrPolicyDetailsState extends State 'client_policy_id': clientPolicyId, 'policy_no': policyNo }; - final response = - await apiService.getEcardRequest(eCarDParams, localToken!); - print('check 1'); + final response = await apiService.getEcardRequest(eCarDParams, localToken!); + logDebug('check 1'); final ecardDownloadUrl = response['data']['eCardDownload']; final message = response['data']['message']; if (ecardDownloadUrl != null) { - print('✅ Link: $ecardDownloadUrl'); + logDebug('✅ Link: $ecardDownloadUrl'); await _launchURL(ecardDownloadUrl); // Only launch if status is success // ToastHelper.showSuccessToast(context, message); } else { - print('❌ Error: $message'); + logDebug('❌ Error: $message'); ToastHelper.showErrorToast(context, message); } } Future _launchURL(String url) async { final Uri uri = Uri.parse(url); // Parse the URL properly - print('_launchURL $uri'); + logDebug('_launchURL $uri'); if (uri != null) { - print('If $uri'); + logDebug('If $uri'); await launchUrl(uri, mode: LaunchMode.externalApplication); } else { - print('else $uri'); + logDebug('else $uri'); throw 'Could not launch $url'; } } @@ -452,9 +461,7 @@ class _HrPolicyDetailsState extends State } else { setState(() { filteredData = originalData.where((row) { - - final status = - row['status']?.toString().toLowerCase().trim() ?? ''; + final status = row['status']?.toString().toLowerCase().trim() ?? ''; bool statusMatch; @@ -466,35 +473,30 @@ class _HrPolicyDetailsState extends State statusMatch = status.contains(lowerQuery); } - return row['name'] - ?.toString() - .toLowerCase() - .contains(lowerQuery) == true || - row['uhid'] - ?.toString() - .toLowerCase() - .contains(lowerQuery) == true || + return row['name']?.toString().toLowerCase().contains(lowerQuery) == + true || + row['uhid']?.toString().toLowerCase().contains(lowerQuery) == + true || row['relationship'] - ?.toString() - .toLowerCase() - .contains(lowerQuery) == true || + ?.toString() + .toLowerCase() + .contains(lowerQuery) == + true || row['formatted_dob'] - ?.toString() - .replaceAll("/", "-") - .toLowerCase() - .contains(lowerQuery) == true || - row['gender'] - ?.toString() - .toLowerCase() - .contains(lowerQuery) == true || - row['mobile'] - ?.toString() - .toLowerCase() - .contains(lowerQuery) == true || + ?.toString() + .replaceAll("/", "-") + .toLowerCase() + .contains(lowerQuery) == + true || + row['gender']?.toString().toLowerCase().contains(lowerQuery) == + true || + row['mobile']?.toString().toLowerCase().contains(lowerQuery) == + true || row['email_corporate'] - ?.toString() - .toLowerCase() - .contains(lowerQuery) == true || + ?.toString() + .toLowerCase() + .contains(lowerQuery) == + true || statusMatch; }).toList(); }); @@ -547,7 +549,7 @@ class _HrPolicyDetailsState extends State } Future handleExportAction() async { - print('handleExportAction'); + logDebug('handleExportAction'); final postId = await tokenService.readValue('empHrId'); final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); @@ -557,12 +559,12 @@ class _HrPolicyDetailsState extends State var activityPre = "export_preempdata"; dynamic response; - print('postId - $postId'); - print('preId - $preId'); - print('activity - $activity'); + logDebug('postId - $postId'); + logDebug('preId - $preId'); + logDebug('activity - $activity'); try { - print('10'); + logDebug('10'); if (localTokenType == 'pre') { response = await apiService.getPreLogHrActivity( @@ -573,14 +575,14 @@ class _HrPolicyDetailsState extends State } if (response['status'] == 'success') { - print('Request success'); + logDebug('Request success'); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -592,19 +594,19 @@ class _HrPolicyDetailsState extends State Future getEcardBulkDownload() async { try { final emp_policy_ids = selectedEmployeeIds.toList(); - print('10 $emp_policy_ids'); + logDebug('10 $emp_policy_ids'); empHrId = await tokenService.readValue('empHrId'); final response = await apiService.getEcardBulkDownloadApi( '', empHrId, emp_policy_ids, localToken!); if (response['status'] == true) { - print('Request success'); + logDebug('Request success'); _showBulkDownloadSuccessPopup(response['message']); } else { ToastHelper.showErrorToast(context, response['message']); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -766,8 +768,7 @@ class _HrPolicyDetailsState extends State ), ), - if (localIsEcardBulkDownload == - 1) ...[ + if (localIsEcardBulkDownload == 1) ...[ const SizedBox(width: 12), SizedBox( width: 40, @@ -800,23 +801,44 @@ class _HrPolicyDetailsState extends State height: 37, child: ElevatedButton( onPressed: () async { - - await tokenService.writeValue('upload_ClientId', widget.ClientId.toString()); - await tokenService.writeValue('upload_policyTypeId', widget.policyTypeId.toString()); - await tokenService.writeValue('upload_ClientPoliyId', widget.ClientPoliyId.toString()); - await tokenService.writeValue('upload_clientBranchId', widget.clientBranchId.toString()); - await tokenService.writeValue('upload_Token', widget.Token.toString()); - await tokenService.writeValue('upload_TokenType', widget.TokenType.toString()); - await tokenService.writeValue('upload_cardType', widget.cardType.toString()); - await tokenService.writeValue('upload_cardPolicyNo', widget.cardPolicyNo.toString()); - await tokenService.writeValue('upload_cardInsurer_name', widget.cardInsurer_name.toString()); - await tokenService.writeValue('upload_cardPolicy_name', widget.cardPolicy_name.toString()); - await tokenService.writeValue('upload_cardPolicy_ExpDate', widget.cardPolicy_ExpDate.toString()); - await tokenService.writeValue('upload_total_premium', widget.total_premium.toString()); + await tokenService.writeValue('upload_ClientId', + widget.ClientId.toString()); + await tokenService.writeValue( + 'upload_policyTypeId', + widget.policyTypeId.toString()); + await tokenService.writeValue( + 'upload_ClientPoliyId', + widget.ClientPoliyId.toString()); + await tokenService.writeValue( + 'upload_clientBranchId', + widget.clientBranchId.toString()); + await tokenService.writeValue( + 'upload_Token', widget.Token.toString()); + await tokenService.writeValue('upload_TokenType', + widget.TokenType.toString()); + await tokenService.writeValue('upload_cardType', + widget.cardType.toString()); + await tokenService.writeValue( + 'upload_cardPolicyNo', + widget.cardPolicyNo.toString()); + await tokenService.writeValue( + 'upload_cardInsurer_name', + widget.cardInsurer_name.toString()); + await tokenService.writeValue( + 'upload_cardPolicy_name', + widget.cardPolicy_name.toString()); + await tokenService.writeValue( + 'upload_cardPolicy_ExpDate', + widget.cardPolicy_ExpDate.toString()); + await tokenService.writeValue( + 'upload_total_premium', + widget.total_premium.toString()); Navigator.push( context, MaterialPageRoute( - settings: localTokenType != "post" ? RouteSettings(name: 'preFileUpload') : RouteSettings(name: 'postFileUpload'), + settings: localTokenType != "post" + ? RouteSettings(name: 'preFileUpload') + : RouteSettings(name: 'postFileUpload'), builder: (context) => localTokenType != "post" ? preFileUpload( @@ -973,25 +995,25 @@ class _HrPolicyDetailsState extends State // ---------------- TABLE (SCROLLABLE) ---------------- Expanded( child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: isLoading - ? Container( - color: Colors - .transparent, // Semi-transparent background - child: Center( - child: // Your GIF loader widget - Image.asset( - height: 60, - width: 60, - 'assets/nhance-loader.gif'), // Adjust path to your GIF loader - ), - ) - : Column( - children: [ - _buildCDDataTable(context), // ← DO NOT wrap again in Expanded - ], - ) - ), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: isLoading + ? Container( + color: Colors + .transparent, // Semi-transparent background + child: Center( + child: // Your GIF loader widget + Image.asset( + height: 60, + width: 60, + 'assets/nhance-loader.gif'), // Adjust path to your GIF loader + ), + ) + : Column( + children: [ + _buildCDDataTable( + context), // ← DO NOT wrap again in Expanded + ], + )), ), const SizedBox(height: 48), @@ -1367,26 +1389,24 @@ class _HrPolicyDetailsState extends State return const Center(child: Text('No data available')); } - return Expanded( // ✅ VERY IMPORTANT + return Expanded( + // ✅ VERY IMPORTANT child: CustomScrollView( slivers: [ - /// 🔒 Sticky Header SliverPersistentHeader( pinned: true, delegate: _CDHeaderDelegate( - showUHID: localPolicyTypeId != '6' && - localPolicyTypeId != '7', + showUHID: localPolicyTypeId != '6' && localPolicyTypeId != '7', showAction: - localTokenType != "pre" && - (hasAnyEcardLink || hasModule), + localTokenType != "pre" && (hasAnyEcardLink || hasModule), ), ), /// 📄 Rows SliverList( delegate: SliverChildBuilderDelegate( - (context, index) { + (context, index) { final item = _paginatedData[index]; return _buildCDRow(item); }, @@ -1414,7 +1434,6 @@ class _HrPolicyDetailsState extends State ), child: Row( children: [ - /// NAME Expanded( flex: 3, @@ -1428,8 +1447,7 @@ class _HrPolicyDetailsState extends State ), /// UHID - if (localPolicyTypeId != '6' && - localPolicyTypeId != '7') + if (localPolicyTypeId != '6' && localPolicyTypeId != '7') Expanded( flex: 2, child: Text(item['uhid'] ?? '-', style: _dataBold), @@ -1442,8 +1460,7 @@ class _HrPolicyDetailsState extends State Expanded( flex: 2, - child: Text( - item['formatted_dob']?.replaceAll("/", "-") ?? '-', + child: Text(item['formatted_dob']?.replaceAll("/", "-") ?? '-', style: _dataBold), ), @@ -1466,8 +1483,7 @@ class _HrPolicyDetailsState extends State Expanded( flex: 2, child: Container( - padding: - const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( color: getStatusColor(item['status'] ?? ''), borderRadius: BorderRadius.circular(10), @@ -1482,115 +1498,113 @@ class _HrPolicyDetailsState extends State /// ACTION - if (localTokenType != "pre" && - (hasAnyEcardLink || hasModule)) - Expanded( - flex: 3, - child: Builder( - builder: (context) { - final isSelf = item['relationship'] == 'Self'; - final hasEcard = item['ecard_download_link'] != null; - final showEcard = isSelf && hasEcard; - final showClaim = localTokenType == "post" && hasModule; + if (localTokenType != "pre" && (hasAnyEcardLink || hasModule)) + Expanded( + flex: 3, + child: Builder( + builder: (context) { + final isSelf = item['relationship'] == 'Self'; + final hasEcard = item['ecard_download_link'] != null; + final showEcard = isSelf && hasEcard; + final showClaim = localTokenType == "post" && hasModule; - if (!showEcard && !showClaim) { - return SizedBox(); // No icon to show - } + if (!showEcard && !showClaim) { + return SizedBox(); // No icon to show + } - return SizedBox( - height: 40, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - - /// --- eCard Button (Fixed Space) --- - SizedBox( - width: 40, - height: 40, - child: Visibility( - visible: showEcard, - maintainSize: true, - maintainAnimation: true, - maintainState: true, - child: Tooltip( - message: 'Download e-Card', - child: MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: () { - getEcardDownload( - item['emp_code'], - item['employee_id'], - item['client_policy_id'], - item['policy_no'], - ); - }, - child: Container( - decoration: BoxDecoration( - color: const Color(0xFFE6F5F6), - borderRadius: BorderRadius.circular(8), - ), - padding: const EdgeInsets.all(6), - child: Image.asset( - 'assets/credit_card.png', - fit: BoxFit.contain, - ), - ), - ), - ), - ), - ), - ), - - const SizedBox(width: 8), - - /// --- Claim Button (Fixed Space) --- - SizedBox( - width: 40, - height: 40, - child: Visibility( - visible: showClaim, - maintainSize: true, - maintainAnimation: true, - maintainState: true, - child: Tooltip( - message: 'View Claims', - child: MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => ClaimsPolicies( - empCode: item['emp_code']!, - ), - ), - ); - }, - child: Container( - decoration: BoxDecoration( - color: const Color(0xFFE6F5F6), - borderRadius: BorderRadius.circular(8), - ), - padding: const EdgeInsets.all(6), - child: Image.asset( - 'assets/claim.png', - fit: BoxFit.contain, - ), - ), - ), - ), - ), - ), - ), - ], - ), - ); - }, + return SizedBox( + height: 40, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + /// --- eCard Button (Fixed Space) --- + SizedBox( + width: 40, + height: 40, + child: Visibility( + visible: showEcard, + maintainSize: true, + maintainAnimation: true, + maintainState: true, + child: Tooltip( + message: 'Download e-Card', + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () { + getEcardDownload( + item['emp_code'], + item['employee_id'], + item['client_policy_id'], + item['policy_no'], + ); + }, + child: Container( + decoration: BoxDecoration( + color: const Color(0xFFE6F5F6), + borderRadius: BorderRadius.circular(8), + ), + padding: const EdgeInsets.all(6), + child: Image.asset( + 'assets/credit_card.png', + fit: BoxFit.contain, + ), ), ), + ), + ), + ), + ), + + const SizedBox(width: 8), + + /// --- Claim Button (Fixed Space) --- + SizedBox( + width: 40, + height: 40, + child: Visibility( + visible: showClaim, + maintainSize: true, + maintainAnimation: true, + maintainState: true, + child: Tooltip( + message: 'View Claims', + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ClaimsPolicies( + empCode: item['emp_code']!, + ), + ), + ); + }, + child: Container( + decoration: BoxDecoration( + color: const Color(0xFFE6F5F6), + borderRadius: BorderRadius.circular(8), + ), + padding: const EdgeInsets.all(6), + child: Image.asset( + 'assets/claim.png', + fit: BoxFit.contain, + ), + ), + ), + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), ], ), ); @@ -1603,14 +1617,14 @@ class _HrPolicyDetailsState extends State // ); // // if (localTokenType == "post" && hasModule) { - // print("paginatTtt - $_paginatedData"); + // logDebug("paginatTtt - $_paginatedData"); // - // print("📥 Any e-card link present: $hasAnyEcardLink"); + // logDebug("📥 Any e-card link present: $hasAnyEcardLink"); // } // } // - // print('widgetpolicyTypeId'); - // print(localPolicyTypeId); + // logDebug('widgetpolicyTypeId'); + // logDebug(localPolicyTypeId); // // if (filteredData.isEmpty) { // return SizedBox( @@ -2062,7 +2076,7 @@ class _HrPolicyDetailsState extends State // // GestureDetector( // // onTap: () { // // setState(() { - // // print( + // // logDebug( // // "policytabdata - ${item['emp_code']!}"); // // Navigator.push( // // context, @@ -2189,7 +2203,8 @@ class _HrPolicyDetailsState extends State Widget _buildPagination(BuildContext context) { // 1. Calculate the range of entries being shown final totalItems = filteredData.length; - final int startEntry = totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; + final int startEntry = + totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; int endEntry = _currentPage * _rowsPerPage; if (endEntry > totalItems) endEntry = totalItems; @@ -2213,14 +2228,13 @@ class _HrPolicyDetailsState extends State totalPages ]; } - return [ - _currentPage - 2, - _currentPage - 1, - _currentPage, - _currentPage + 1, - _currentPage + 2, - ]; - + return [ + _currentPage - 2, + _currentPage - 1, + _currentPage, + _currentPage + 1, + _currentPage + 2, + ]; } List visiblePages = getVisiblePages(); @@ -2229,7 +2243,8 @@ class _HrPolicyDetailsState extends State // Match this horizontal padding (16) to your Table Header padding for perfect alignment padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, // Pushes text to left, buttons to right + mainAxisAlignment: MainAxisAlignment + .spaceBetween, // Pushes text to left, buttons to right children: [ // --- LEFT SIDE: Showing Text --- Text( @@ -2245,23 +2260,24 @@ class _HrPolicyDetailsState extends State Row( children: [ // Dropdown for rows per page - DropdownButton( - value: _rowsPerPage, - focusColor: Colors.transparent, // Fix: Removes the grey/blue highlight on change - items: [5, 10, 15, 20, 50].map((int value) { - return DropdownMenuItem( - value: value, - child: Text(' $value ', - style: GoogleFonts.poppins(fontSize: 15)), - ); - }).toList(), - onChanged: (newValue) { - setState(() { - _rowsPerPage = newValue!; - _currentPage = 1; - }); - }, - ), + DropdownButton( + value: _rowsPerPage, + focusColor: Colors + .transparent, // Fix: Removes the grey/blue highlight on change + items: [5, 10, 15, 20, 50].map((int value) { + return DropdownMenuItem( + value: value, + child: Text(' $value ', + style: GoogleFonts.poppins(fontSize: 15)), + ); + }).toList(), + onChanged: (newValue) { + setState(() { + _rowsPerPage = newValue!; + _currentPage = 1; + }); + }, + ), const SizedBox(width: 8), @@ -2357,7 +2373,6 @@ class _HrPolicyDetailsState extends State ); } - class _CDHeaderDelegate extends SliverPersistentHeaderDelegate { final bool showUHID; final bool showAction; @@ -2396,8 +2411,7 @@ class _CDHeaderDelegate extends SliverPersistentHeaderDelegate { ); } - Widget _headerCell(String text, int flex, - {bool center = false}) { + Widget _headerCell(String text, int flex, {bool center = false}) { return Expanded( flex: flex, child: Text( @@ -2413,4 +2427,4 @@ class _CDHeaderDelegate extends SliverPersistentHeaderDelegate { @override bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) => true; -} \ No newline at end of file +} diff --git a/lib/presentation/policies.dart b/lib/presentation/policies.dart index aa85ae0..249b1df 100644 --- a/lib/presentation/policies.dart +++ b/lib/presentation/policies.dart @@ -22,6 +22,7 @@ import '../customAppBar/base_layout.dart'; import '../customAppBar/toastHelper.dart'; import '../service/secure_pop_scope.dart'; import 'hrPolicyDetails.dart'; +import 'package:nhancepolicy/logger.dart'; class policies extends StatefulWidget { const policies({Key? key}) : super(key: key); @@ -30,7 +31,6 @@ class policies extends StatefulWidget { State createState() => _policiesState(); } - class _policiesState extends State with SingleTickerProviderStateMixin { late ApiService apiService; @@ -61,7 +61,6 @@ class _policiesState extends State List postModules = []; List enrollmentModules = []; - @override void initState() { super.initState(); @@ -93,14 +92,14 @@ class _policiesState extends State // Get the current token final token = await tokenService.getCurrentToken(); - print('token - $token'); + logDebug('token - $token'); - print('token check in'); + logDebug('token check in'); if ((token != null && token!.isNotEmpty)) { - print('token check done'); + logDebug('token check done'); _loadToken(); } else { - print('token check reject'); + logDebug('token check reject'); ToastHelper.showErrorToast(context, 'Session Out'); Navigator.pushReplacementNamed(context, 'hrLogin'); } @@ -119,11 +118,11 @@ class _policiesState extends State // ? List.from(jsonDecode(postRaw)) // : []; // - // print('enrollmentModules $enrollmentModules'); - // print('postModules $postModules'); + // logDebug('enrollmentModules $enrollmentModules'); + // logDebug('postModules $postModules'); // // _postPreToken = await tokenService.getCurrentToken(); - // print(_postPreToken); + // logDebug(_postPreToken); // // if (enrollmentModules.contains(1)) { // enrollmentClient_id = await tokenService.readValue('enrollmentClient_id'); @@ -147,14 +146,13 @@ class _policiesState extends State Future _loadToken() async { setState(() { - isLoading = true; // 🔥 START LOADER HERE + isLoading = true; // 🔥 START LOADER HERE }); try { final enrollmentRaw = - await tokenService.readValue('enrollmentAllowed_modules'); - final postRaw = - await tokenService.readValue('empAllowed_modules'); + await tokenService.readValue('enrollmentAllowed_modules'); + final postRaw = await tokenService.readValue('empAllowed_modules'); enrollmentModules = enrollmentRaw != null && enrollmentRaw.isNotEmpty ? List.from(jsonDecode(enrollmentRaw)) @@ -171,11 +169,10 @@ class _policiesState extends State /// 👇 Add APIs dynamically if (enrollmentModules.contains(1)) { enrollmentClient_id = - await tokenService.readValue('enrollmentClient_id'); + await tokenService.readValue('enrollmentClient_id'); enrollmentEmpClientBranchId = - await tokenService.readValue('enrollmentEmpClientBranchId'); - enrollmentHrId = - await tokenService.readValue('enrollmentHrId'); + await tokenService.readValue('enrollmentEmpClientBranchId'); + enrollmentHrId = await tokenService.readValue('enrollmentHrId'); apiCalls.add( getPreCashDepositDetails( @@ -189,8 +186,7 @@ class _policiesState extends State if (postModules.contains(2)) { empClientId = await tokenService.readValue('empClientId'); - empClientBranchId = - await tokenService.readValue('empClientBranchId'); + empClientBranchId = await tokenService.readValue('empClientBranchId'); empHrId = await tokenService.readValue('empHrId'); apiCalls.add( @@ -206,11 +202,11 @@ class _policiesState extends State /// 🔥 WAIT FOR ALL APIs await Future.wait(apiCalls); } catch (e) { - print("Error in _loadToken: $e"); + logDebug("Error in _loadToken: $e"); } finally { if (mounted) { setState(() { - isLoading = false; // 🔥 STOP LOADER ONLY ONCE + isLoading = false; // 🔥 STOP LOADER ONLY ONCE }); } } @@ -218,11 +214,11 @@ class _policiesState extends State Future getPreCashDepositDetails(enrollmentEmpClientBranchId, enrollmentClient_id, enrollmentHrId, _postPreToken) async { - print('IN'); - print("clintBranchId -$enrollmentEmpClientBranchId"); - print("clintID -$enrollmentClient_id"); - print("hr_id -$enrollmentHrId"); - print("token -$_postPreToken"); + logDebug('IN'); + logDebug("clintBranchId -$enrollmentEmpClientBranchId"); + logDebug("clintID -$enrollmentClient_id"); + logDebug("hr_id -$enrollmentHrId"); + logDebug("token -$_postPreToken"); // setState(() { // _isLoading = true; @@ -239,33 +235,33 @@ class _policiesState extends State // final response = await apiService.getCashDepositDetailsToApi( // clintID!, clintBranchId!, hr_id, token); - print('IN1'); + logDebug('IN1'); if (response['status'] == 'success') { setState(() { - print('response'); - print(response['data']); + logDebug('response'); + logDebug(response['data']); getPreCardArrays = List>.from(response['data']); - print('getPreCardArrays'); - print(getPreCardArrays); + logDebug('getPreCardArrays'); + logDebug(getPreCardArrays); openForEnrollmentList = getPreCardArrays; }); - print('IN2'); + logDebug('IN2'); } else { - print('API request failed with status'); + logDebug('API request failed with status'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } Future getPostCashDepositDetails( empClientBranchId, empClientId, empHrId, _postPreToken) async { - print('IN'); - print("clintBranchId -$empClientBranchId"); - print("clintID -$empClientId"); - print("hr_id -$empHrId"); - print("token -$_postPreToken"); + logDebug('IN'); + logDebug("clintBranchId -$empClientBranchId"); + logDebug("clintID -$empClientId"); + logDebug("hr_id -$empHrId"); + logDebug("token -$_postPreToken"); // setState(() { // _isLoading = true; @@ -279,28 +275,28 @@ class _policiesState extends State // final response = await apiService.getCashDepositDetailsToApi( // clintID!, clintBranchId!, hr_id, token); - print('IN1'); + logDebug('IN1'); if (response['status'] == 'success') { setState(() { - print('response'); - print(response['data']); + logDebug('response'); + logDebug(response['data']); getPostCardArrays = List>.from(response['data']); - print('getPostCardArrays'); - print(getPostCardArrays); + logDebug('getPostCardArrays'); + logDebug(getPostCardArrays); activePoliciesList = getPostCardArrays; }); - print('IN2'); + logDebug('IN2'); } else { - print('API request failed with status'); + logDebug('API request failed with status'); setState(() { activePoliciesList = []; }); - print('API request failed with status'); + logDebug('API request failed with status'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -326,22 +322,21 @@ class _policiesState extends State false; } - - Future getEcardBulkDownload(clientPolicyId) async { try { - print('10'); + logDebug('10'); empHrId = await tokenService.readValue('empHrId'); - final response = await apiService.getEcardBulkDownloadApi(clientPolicyId,empHrId,'',_postPreToken!); + final response = await apiService.getEcardBulkDownloadApi( + clientPolicyId, empHrId, '', _postPreToken!); if (response['status'] == true) { - print('Request success'); + logDebug('Request success'); _showBulkDownloadSuccessPopup(response['message']); } else { ToastHelper.showErrorToast(context, response['message']); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -382,9 +377,10 @@ class _policiesState extends State borderRadius: BorderRadius.circular(8), ), ), - child: Text('OK',style: GoogleFonts.poppins( - color: Colors.white - ),), + child: Text( + 'OK', + style: GoogleFonts.poppins(color: Colors.white), + ), ), ), ], @@ -394,7 +390,6 @@ class _policiesState extends State ); } - @override Widget build(BuildContext context) { return BaseLayout( @@ -411,157 +406,159 @@ class _policiesState extends State required List> openEnrollment, required List> activePolicies, }) { - return isLoading ? Container( - color: Colors.transparent, // Semi-transparent background - child: Center( - child: // Your GIF loader widget - Image.asset( - height: 60, - width: 60, - 'assets/nhance-loader.gif'), // Adjust path to your GIF loader - ), - ) : Scaffold( - body: SingleChildScrollView( - - // padding: const EdgeInsets.all(20), - child: Container( - color: const Color(0xFFF5F7F7), // 👈 same light grey as dashboard - // padding: const EdgeInsets.all(20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - // IconButton( - // onPressed: () { - // _showLogoutDialog(); - // }, - // icon: const Icon( - // Icons.arrow_back_ios, - // size: 20, - // color: Colors.black, - // ), - // padding: EdgeInsets.zero, - // constraints: const BoxConstraints(), - // ), - const SizedBox(width: 5), - Text( - 'Policies', - style: GoogleFonts.poppins( - fontSize: 22, - fontWeight: FontWeight.w500, - color: Colors.black, - ), - ), - ], + return isLoading + ? Container( + color: Colors.transparent, // Semi-transparent background + child: Center( + child: // Your GIF loader widget + Image.asset( + height: 60, + width: 60, + 'assets/nhance-loader.gif'), // Adjust path to your GIF loader ), - if(enrollmentModules.contains(1))...[ - SizedBox(height: 15), - Container( - width: double.infinity, - // constraints: const BoxConstraints( - // minHeight: 180, - // ), - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(6), - ), - child: IntrinsicHeight( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - 'Open for Enrollment', - style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600), - ), - SizedBox(height: 14), + ) + : Scaffold( + body: SingleChildScrollView( - /// ✅ SCROLLABLE AREA - openEnrollment.isEmpty - ? _EmptyBox('No policies open for enrollment') - : _PolicyGrid( - policies: openEnrollment, - isEnrollment: true, - ), - - ], - ), - ) - - ), - ], - if(postModules.contains(2))...[ - SizedBox(height: 20), - Container( - width: double.infinity, - // constraints: const BoxConstraints( - // minHeight: 180, - // ), - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(6), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - /// HEADER - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - 'Active Policies', - style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600), + // padding: const EdgeInsets.all(20), + child: Container( + color: const Color(0xFFF5F7F7), // 👈 same light grey as dashboard + // padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // IconButton( + // onPressed: () { + // _showLogoutDialog(); + // }, + // icon: const Icon( + // Icons.arrow_back_ios, + // size: 20, + // color: Colors.black, + // ), + // padding: EdgeInsets.zero, + // constraints: const BoxConstraints(), + // ), + const SizedBox(width: 5), + Text( + 'Policies', + style: GoogleFonts.poppins( + fontSize: 22, + fontWeight: FontWeight.w500, + color: Colors.black, ), - _ActiveExpiredToggle( - selectedIndex: selectedIndex, - onChange: (value) async { - setState(() { - selectedIndex = value; - stausVal = value == 1 ? 1 : 0; - }); - await getPostCashDepositDetails( - empClientBranchId, - empClientId, - empHrId, - _postPreToken, - ); - }, + ), + ], + ), + if (enrollmentModules.contains(1)) ...[ + SizedBox(height: 15), + Container( + width: double.infinity, + // constraints: const BoxConstraints( + // minHeight: 180, + // ), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(6), ), - ], - ), - const SizedBox(height: 14), + child: IntrinsicHeight( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Open for Enrollment', + style: GoogleFonts.poppins( + fontSize: 14, fontWeight: FontWeight.w600), + ), + SizedBox(height: 14), - /// ✅ SCROLLABLE GRID - activePolicies.isEmpty - ? stausVal == 0 ? _EmptyBox('You don’t have any expired policies at the moment.') : _EmptyBox('No active policies found') - : _PolicyGrid( - policies: activePolicies, - isEnrollment: false, - onBulkDownload: getEcardBulkDownload, - ), - - - const SizedBox(height: 8), - Align( - alignment: Alignment.bottomRight, - child: Text( - '* Premium may vary subject to claims', - style: GoogleFonts.poppins(fontSize: 10, color: Colors.red), - ), - ), + /// ✅ SCROLLABLE AREA + openEnrollment.isEmpty + ? _EmptyBox('No policies open for enrollment') + : _PolicyGrid( + policies: openEnrollment, + isEnrollment: true, + ), + ], + ), + )), ], - ), + if (postModules.contains(2)) ...[ + SizedBox(height: 20), + Container( + width: double.infinity, + // constraints: const BoxConstraints( + // minHeight: 180, + // ), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(6), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// HEADER + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Active Policies', + style: GoogleFonts.poppins( + fontSize: 14, fontWeight: FontWeight.w600), + ), + _ActiveExpiredToggle( + selectedIndex: selectedIndex, + onChange: (value) async { + setState(() { + selectedIndex = value; + stausVal = value == 1 ? 1 : 0; + }); + await getPostCashDepositDetails( + empClientBranchId, + empClientId, + empHrId, + _postPreToken, + ); + }, + ), + ], + ), + const SizedBox(height: 14), + + /// ✅ SCROLLABLE GRID + activePolicies.isEmpty + ? stausVal == 0 + ? _EmptyBox( + 'You don’t have any expired policies at the moment.') + : _EmptyBox('No active policies found') + : _PolicyGrid( + policies: activePolicies, + isEnrollment: false, + onBulkDownload: getEcardBulkDownload, + ), + + const SizedBox(height: 8), + Align( + alignment: Alignment.bottomRight, + child: Text( + '* Premium may vary subject to claims', + style: GoogleFonts.poppins( + fontSize: 10, color: Colors.red), + ), + ), + ], + ), + ), + ] + ], ), - - ] - - ], - ), - )), - ); + )), + ); } } @@ -570,9 +567,9 @@ class ResponsiveGridConfig { final double childAspectRatio; const ResponsiveGridConfig( - this.crossAxisCount, - this.childAspectRatio, - ); + this.crossAxisCount, + this.childAspectRatio, + ); } class _PolicyGrid extends StatelessWidget { @@ -588,9 +585,9 @@ class _PolicyGrid extends StatelessWidget { }); ResponsiveGridConfig _getGridConfig( - BuildContext context, - bool isEnrollment, - ) { + BuildContext context, + bool isEnrollment, + ) { final width = MediaQuery.of(context).size.width; // if (width < 600) { @@ -603,8 +600,6 @@ class _PolicyGrid extends StatelessWidget { // return ResponsiveGridConfig(4, isEnrollment ? 3.1 : 2.4); // } - - if (width >= 1400) { return const ResponsiveGridConfig(4, 2.6); // Big screen } else if (width >= 1000) { @@ -616,7 +611,6 @@ class _PolicyGrid extends StatelessWidget { } } - @override @override Widget build(BuildContext context) { @@ -633,9 +627,7 @@ class _PolicyGrid extends StatelessWidget { cardHeight = 170; } - final double totalHeight = - rowCount * cardHeight + ((rowCount - 1) * 16); - + final double totalHeight = rowCount * cardHeight + ((rowCount - 1) * 16); return SizedBox( height: totalHeight, @@ -656,100 +648,94 @@ class _PolicyGrid extends StatelessWidget { return isEnrollment ? _EnrollmentPolicyCardNew( - data: data, - onTap: () async { - final token = await tokenService.getCurrentToken(); - final clientId = - await tokenService.readValue('enrollmentClient_id'); - final branchId = await tokenService - .readValue('enrollmentEmpClientBranchId'); + data: data, + onTap: () async { + final token = await tokenService.getCurrentToken(); + final clientId = + await tokenService.readValue('enrollmentClient_id'); + final branchId = await tokenService + .readValue('enrollmentEmpClientBranchId'); - if (token == null || clientId == null || branchId == null) { - return; - } + if (token == null || clientId == null || branchId == null) { + return; + } - Navigator.push( - context, - MaterialPageRoute( - settings: const RouteSettings(name: 'hrPolicyDetails'), - builder: (_) => hrPolicyDetails( - ClientId: clientId, - policyTypeId: - data['policy_type_id'].toString(), - ClientPoliyId: - data['client_policy_id'].toString(), - clientBranchId: branchId, - Token: token, - TokenType: "pre", - cardType: data['type'].toString(), - cardPolicyNo: data['policy_no'].toString(), - cardInsurer_name: - data['insurer_short_name'].toString(), - cardPolicy_name: - data['policy_name'].toString(), - cardPolicy_ExpDate: - data['policy_expiry_date'].toString(), - total_premium: '', - is_ecard_bulk_download_for_employee: 0, - ), - ), - ); - }, - ) + Navigator.push( + context, + MaterialPageRoute( + settings: const RouteSettings(name: 'hrPolicyDetails'), + builder: (_) => hrPolicyDetails( + ClientId: clientId, + policyTypeId: data['policy_type_id'].toString(), + ClientPoliyId: data['client_policy_id'].toString(), + clientBranchId: branchId, + Token: token, + TokenType: "pre", + cardType: data['type'].toString(), + cardPolicyNo: data['policy_no'].toString(), + cardInsurer_name: + data['insurer_short_name'].toString(), + cardPolicy_name: data['policy_name'].toString(), + cardPolicy_ExpDate: + data['policy_expiry_date'].toString(), + total_premium: '', + is_ecard_bulk_download_for_employee: 0, + ), + ), + ); + }, + ) : _ActivePolicyCardNew( - data: data, - onBulkDownload: onBulkDownload, - onTap: () async { - final token = await tokenService.getCurrentToken(); - final clientId = await tokenService.readValue('empClientId'); - final branchId = await tokenService.readValue('empClientBranchId'); + data: data, + onBulkDownload: onBulkDownload, + onTap: () async { + final token = await tokenService.getCurrentToken(); + final clientId = + await tokenService.readValue('empClientId'); + final branchId = + await tokenService.readValue('empClientBranchId'); - print("token: $token"); - print("clientId: $clientId"); - print("branchId: $branchId"); + logDebug("token: $token"); + logDebug("clientId: $clientId"); + logDebug("branchId: $branchId"); - if (token == null || clientId == null || branchId == null) { - print("Missing required values"); - return; - } + if (token == null || clientId == null || branchId == null) { + logDebug("Missing required values"); + return; + } - Navigator.push( - context, - MaterialPageRoute( - settings: const RouteSettings(name: 'hrPolicyDetails'), - builder: (_) => hrPolicyDetails( - ClientId: clientId, - policyTypeId: - data['policy_type_id'].toString(), - ClientPoliyId: - data['client_policy_id'].toString(), - clientBranchId: branchId, - Token: token, - TokenType: 'post', - cardType: data['type'].toString(), - cardPolicyNo: data['policy_no'].toString(), - cardInsurer_name: - data['insurer_short_name'].toString(), - cardPolicy_name: - data['policy_name'].toString(), - cardPolicy_ExpDate: - data['policy_expiry_date'].toString(), - total_premium: - data['total_premium'].toString(), - is_ecard_bulk_download_for_employee: - data['is_ecard_bulk_download_for_employee'], - ), - ), - ); - }, - ); + Navigator.push( + context, + MaterialPageRoute( + settings: const RouteSettings(name: 'hrPolicyDetails'), + builder: (_) => hrPolicyDetails( + ClientId: clientId, + policyTypeId: data['policy_type_id'].toString(), + ClientPoliyId: data['client_policy_id'].toString(), + clientBranchId: branchId, + Token: token, + TokenType: 'post', + cardType: data['type'].toString(), + cardPolicyNo: data['policy_no'].toString(), + cardInsurer_name: + data['insurer_short_name'].toString(), + cardPolicy_name: data['policy_name'].toString(), + cardPolicy_ExpDate: + data['policy_expiry_date'].toString(), + total_premium: data['total_premium'].toString(), + is_ecard_bulk_download_for_employee: + data['is_ecard_bulk_download_for_employee'], + ), + ), + ); + }, + ); }, ), ); } } - // class _PolicyGrid extends StatelessWidget { // final List> policies; // final bool isEnrollment; @@ -832,8 +818,8 @@ class _PolicyGrid extends StatelessWidget { // return; // } // -// print('$token , $empClientId, $empBranchId'); -// print(data); +// logDebug('$token , $empClientId, $empBranchId'); +// logDebug(data); // // return; // // Navigator.push( @@ -889,20 +875,20 @@ class _EnrollmentPolicyCardNew extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ /// Policy Number - Tooltip( - message: '${data['type']} - ${data['policy_no']}', - waitDuration: const Duration(milliseconds: 300), - child: Text( - '${data['type']} - ${data['policy_no']}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - softWrap: false, - style: GoogleFonts.poppins( - fontSize: 14, - fontWeight: FontWeight.w500, - ), - ), - ), + Tooltip( + message: '${data['type']} - ${data['policy_no']}', + waitDuration: const Duration(milliseconds: 300), + child: Text( + '${data['type']} - ${data['policy_no']}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + softWrap: false, + style: GoogleFonts.poppins( + fontSize: 14, + fontWeight: FontWeight.w500, + ), + ), + ), // const SizedBox(height: 4), // @@ -969,7 +955,11 @@ class _ActivePolicyCardNew extends StatelessWidget { final VoidCallback? onTap; final Function(String clientPolicyId)? onBulkDownload; - const _ActivePolicyCardNew({required this.data, this.onTap,this.onBulkDownload,}); + const _ActivePolicyCardNew({ + required this.data, + this.onTap, + this.onBulkDownload, + }); @override Widget build(BuildContext context) { @@ -1008,7 +998,8 @@ class _ActivePolicyCardNew extends StatelessWidget { right: 10, child: GestureDetector( onTap: () { - print('ICON CLICKED ${data['client_policy_id']}'); + logDebug( + 'ICON CLICKED ${data['client_policy_id']}'); onBulkDownload?.call( data['client_policy_id'].toString(), ); @@ -1038,7 +1029,7 @@ class _ActivePolicyCardNew extends StatelessWidget { children: [ Expanded( child: Text( - '${data['type']} - ${data['policy_no']}', + '${data['type']} - ${data['policy_no']}', style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w500, @@ -1098,10 +1089,7 @@ class _ActivePolicyCardNew extends StatelessWidget { ), ], ), - ) - ) - - ); + ))); } } diff --git a/lib/presentation/postFileUpload.dart b/lib/presentation/postFileUpload.dart index c58cb74..6172634 100755 --- a/lib/presentation/postFileUpload.dart +++ b/lib/presentation/postFileUpload.dart @@ -24,6 +24,7 @@ import 'package:url_launcher/url_launcher.dart'; import '../config/environment.dart'; import '../customAppBar/base_layout.dart'; import '../customAppBar/customFooter.dart'; +import 'package:nhancepolicy/logger.dart'; class postFileUpload extends StatefulWidget { final String ClientId; @@ -61,7 +62,6 @@ class postFileUpload extends StatefulWidget { class _postFileUploadState extends State { final tokenService = TokenStorageService(); - String localClientId = ''; String localPolicyTypeId = ''; String localClientPolicyId = ''; @@ -75,8 +75,6 @@ class _postFileUploadState extends State { String localCardPolicyExpDate = ''; String localTotalPremium = ''; - - Uint8List? fileBytes; Uint8List? fileBytes2; late String _token; @@ -145,7 +143,6 @@ class _postFileUploadState extends State { getFileUploadMasterDetails(); getFileListDetails(); }); - } @override @@ -253,9 +250,9 @@ class _postFileUploadState extends State { // PlatformFile file = result.files.first; // Uint8List fileBytes = file.bytes!; // // Use the fileBytes as needed - // print('File name: ${file.name}'); - // print('File size: ${file.size}'); - // print('File bytes: $fileBytes'); + // logDebug('File name: ${file.name}'); + // logDebug('File size: ${file.size}'); + // logDebug('File bytes: $fileBytes'); // _processExcelData(fileBytes); // } else { // // User canceled the picker @@ -263,31 +260,31 @@ class _postFileUploadState extends State { // } Future getFileUploadMasterDetails() async { - print('9'); + logDebug('9'); try { final response = await apiService.getFileUploadMastersToApi(localToken); if (response['status'] == true) { - print('getFileUploadMasterList1'); + logDebug('getFileUploadMasterList1'); setState(() { final actions = Map.from(response['data']['actions']); setState(() { getFileUploadMasterList = actions.entries .map((e) => {"key": e.key, "value": e.value}) .toList(); - print('getFileUploadMasterList: $getFileUploadMasterList'); + logDebug('getFileUploadMasterList: $getFileUploadMasterList'); }); - print('getFileUploadMasterList'); - print(getFileUploadMasterList); + logDebug('getFileUploadMasterList'); + logDebug(getFileUploadMasterList); }); } else { - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { // _isLoading = false; @@ -299,28 +296,28 @@ class _postFileUploadState extends State { empPrimaryId = await tokenService.readValue('empPrimaryId'); empClientId = await tokenService.readValue('empClientId'); - print('9'); + logDebug('9'); try { final response = await apiService.getFileListToApi(empPrimaryId, localCardPolicyNo, empClientId, localToken, localTokenType); if (response['status'] == 'success') { - print('getThrFileList'); + logDebug('getThrFileList'); setState(() { getThrFileList = List>.from(response['data']); originalData = getThrFileList; filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { // _isLoading = false; @@ -330,9 +327,9 @@ class _postFileUploadState extends State { Future getHrFileDownload(id, file_name) async { // final http.Response response = await apiService.getHrFileDownloadToApi(id, localToken); - print("**********-------*****"); + logDebug("**********-------*****"); final encryptClientId = localClientId; - print(encryptClientId); + logDebug(encryptClientId); final apiurl = Environment.apiUrlPost; final String url = '$apiurl/hrFileDownload?id=$id&cliend_id=$encryptClientId'; @@ -351,7 +348,7 @@ class _postFileUploadState extends State { if (response.statusCode == 200) { try { - print("PDF Downloaded"); + logDebug("PDF Downloaded"); // ✅ Create a blob from the response body bytes final blob = html.Blob([response.bodyBytes]); @@ -373,15 +370,15 @@ class _postFileUploadState extends State { } } else { ToastHelper.showErrorToast(context, 'Failed to download'); - print("Download failed with status: ${response.statusCode}"); + logDebug("Download failed with status: ${response.statusCode}"); } } Future downloadPostSampleFile(String apiParam) async { - print("fun Sam f - in"); + logDebug("fun Sam f - in"); final post_file_name = apiParam + '_sample_file.xlsx'; - print("fun Sam f - name $post_file_name"); + logDebug("fun Sam f - name $post_file_name"); final apiurl = Environment.apiUrlPost; final String url = '$apiurl/downloadSampleExcel/$apiParam'; final token = localToken; @@ -399,7 +396,7 @@ class _postFileUploadState extends State { if (response.statusCode == 200) { try { - print("fun sam f - ${response.statusCode}"); + logDebug("fun sam f - ${response.statusCode}"); // ✅ Create a blob from the response body bytes final blob = html.Blob([response.bodyBytes]); @@ -417,19 +414,19 @@ class _postFileUploadState extends State { ToastHelper.showSuccessToast(context, 'File Downloaded Successfully'); } catch (e) { - print("fun sam f - fail"); + logDebug("fun sam f - fail"); throw Exception('Error parsing response: $e'); } } else { ToastHelper.showErrorToast(context, 'Failed to download'); - print("Download failed with status: ${response.statusCode}"); + logDebug("Download failed with status: ${response.statusCode}"); } } void _uploadFile() async { - print('Test'); + logDebug('Test'); if (kIsWeb) { - print('kIsWeb'); + logDebug('kIsWeb'); final input = html.FileUploadInputElement(); input.accept = '.xlsx,.xls'; input.click(); @@ -467,8 +464,8 @@ class _postFileUploadState extends State { // Save fileBytes to local storage final jsonString = json.encode(fileBytes); html.window.localStorage['fileBytes'] = jsonString; - print('File Name: $fileName'); - print('File Bytes: $fileBytes'); + logDebug('File Name: $fileName'); + logDebug('File Bytes: $fileBytes'); sendExcelFIleTOAPI(fileBytes, fileName); // Call the function to process Excel data here // _processExcelData(fileBytes, fileName); @@ -477,7 +474,7 @@ class _postFileUploadState extends State { }); } else { // Handle non-web platforms here (e.g., show an error message) - print('File upload is only supported on web platforms.'); + logDebug('File upload is only supported on web platforms.'); } } @@ -495,17 +492,17 @@ class _postFileUploadState extends State { // // Invalid DOB format, skip this entry // continue; // } - print(entry['Relation']); + logDebug(entry['Relation']); if ((entry['Relation'].toString() == 'Son' || entry['Relation'].toString() == 'Daughter')) { if (DateTime.now().difference(dob).inDays > 25 * 365) { - print('child $dob'); + logDebug('child $dob'); invalidCount++; } } else if ((entry['Relation'] != 'Son' && entry['Relation'] != 'Daughter')) { if (DateTime.now().difference(dob).inDays < 18 * 365) { - print('others $dob'); + logDebug('others $dob'); invalidCount++; } } @@ -515,8 +512,8 @@ class _postFileUploadState extends State { } void _dragAndDropFile(html.File file) async { - print('file'); - print(file); + logDebug('file'); + logDebug(file); // Prepare form data final formData = html.FormData(); formData.appendBlob('file', file); @@ -529,7 +526,7 @@ class _postFileUploadState extends State { ); // Handle response as needed - print(response.responseText); + logDebug(response.responseText); } Future sendExcelFIleTOAPI(Uint8List fileBytes, fileName) async { @@ -539,24 +536,24 @@ class _postFileUploadState extends State { isLoading = true; }); // }); - print('submit'); - print(fileBytes); + logDebug('submit'); + logDebug(fileBytes); if (fileBytes == null) { ToastHelper.showErrorToast(context, 'Please upload file'); - print('return'); + logDebug('return'); return; // No file selected } else { - print('else'); + logDebug('else'); // // Prepare form data // final formData = html.FormData(); // formData.appendBlob('file', html.Blob([fileBytes]), fileName); // URL of the API where you want to send the file final apiUrl = Environment.apiUrlPost + 'hrFileUpload'; - print('else'); + logDebug('else'); // Create a multipart request final request = http.MultipartRequest('POST', Uri.parse(apiUrl)); - print('else'); + logDebug('else'); // Attach the file to the request // Set authorization token in headers request.headers['APP-SIGNATURE'] = @@ -564,7 +561,7 @@ class _postFileUploadState extends State { request.headers['Authorization'] = 'Bearer $_token'; // request.files.add(http.MultipartFile.fromBytes('file', fileBytes, // filename: fileName)); - print('Filename: $fileName'); + logDebug('Filename: $fileName'); // request.files.add(http.MultipartFile.fromBytes( // 'file', // fileBytes, @@ -575,7 +572,7 @@ class _postFileUploadState extends State { fileBytes, filename: fileName ?? 'default_filename.xlsx', )); - print('clintID: $clintID'); + logDebug('clintID: $clintID'); request.fields['client_id'] = localClientId; request.fields['policy_no'] = localCardPolicyNo; @@ -591,16 +588,16 @@ class _postFileUploadState extends State { // "status": "inception", // "created_by": 10 - print('request : $request'); + logDebug('request : $request'); // Send the request final response = await request.send(); - print('else'); + logDebug('else'); // Read response stream as a string final responseString = await response.stream.bytesToString(); - print(responseString); + logDebug(responseString); Map data = json.decode(responseString); if (data['status'] == true) { - print('upload success'); + logDebug('upload success'); setState(() { isLoading = false; }); @@ -632,7 +629,7 @@ class _postFileUploadState extends State { } void search(String query) { - print(query); + logDebug(query); // Check if the query is empty if (query.isEmpty) { // If search query is empty, show all data @@ -661,7 +658,7 @@ class _postFileUploadState extends State { }).toList(); }); } - print(filteredData.length); + logDebug(filteredData.length); } @override @@ -696,24 +693,47 @@ class _postFileUploadState extends State { return; } - final clientId = await tokenService.readValue('hr_ClientId') ?? ''; - final policyTypeId = await tokenService.readValue('hr_policyTypeId') ?? ''; - final clientPolicyId = await tokenService.readValue('hr_ClientPoliyId') ?? ''; - final clientBranchId = await tokenService.readValue('hr_clientBranchId') ?? ''; - final token = await tokenService.readValue('hr_Token') ?? ''; - final tokenType = await tokenService.readValue('hr_TokenType') ?? ''; - final cardType = await tokenService.readValue('hr_cardType') ?? ''; - final policyNo = await tokenService.readValue('hr_cardPolicyNo') ?? ''; - final insurer = await tokenService.readValue('hr_cardInsurer_name') ?? ''; - final policyName = await tokenService.readValue('hr_cardPolicy_name') ?? ''; - final expDate = await tokenService.readValue('hr_cardPolicy_ExpDate') ?? ''; - final totalPremium = await tokenService.readValue('hr_total_premium') ?? ''; - final bulkDownload = await tokenService.readValue('hr_is_ecard_bulk_download_for_employee') ?? '0'; + final clientId = + await tokenService.readValue('hr_ClientId') ?? ''; + final policyTypeId = + await tokenService.readValue('hr_policyTypeId') ?? + ''; + final clientPolicyId = + await tokenService.readValue('hr_ClientPoliyId') ?? + ''; + final clientBranchId = + await tokenService.readValue('hr_clientBranchId') ?? + ''; + final token = + await tokenService.readValue('hr_Token') ?? ''; + final tokenType = + await tokenService.readValue('hr_TokenType') ?? ''; + final cardType = + await tokenService.readValue('hr_cardType') ?? ''; + final policyNo = + await tokenService.readValue('hr_cardPolicyNo') ?? + ''; + final insurer = await tokenService + .readValue('hr_cardInsurer_name') ?? + ''; + final policyName = await tokenService + .readValue('hr_cardPolicy_name') ?? + ''; + final expDate = await tokenService + .readValue('hr_cardPolicy_ExpDate') ?? + ''; + final totalPremium = + await tokenService.readValue('hr_total_premium') ?? + ''; + final bulkDownload = await tokenService.readValue( + 'hr_is_ecard_bulk_download_for_employee') ?? + '0'; Navigator.pushReplacement( context, MaterialPageRoute( - settings: const RouteSettings(name: 'hrPolicyDetails'), + settings: + const RouteSettings(name: 'hrPolicyDetails'), builder: (_) => hrPolicyDetails( ClientId: clientId, policyTypeId: policyTypeId, @@ -727,7 +747,8 @@ class _postFileUploadState extends State { cardPolicy_name: policyName, cardPolicy_ExpDate: expDate, total_premium: totalPremium, - is_ecard_bulk_download_for_employee: int.tryParse(bulkDownload) ?? 0, + is_ecard_bulk_download_for_employee: + int.tryParse(bulkDownload) ?? 0, ), ), ); @@ -745,8 +766,7 @@ class _postFileUploadState extends State { // mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "${localCardType} - ${localCardPolicyNo} " ?? - '', + "${localCardType} - ${localCardPolicyNo} " ?? '', style: GoogleFonts.poppins( color: Colors.black, fontSize: 14, @@ -801,134 +821,134 @@ class _postFileUploadState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - /// Select File Action - Expanded( - flex: 5, - child: buildStyledDropdown( - label: 'Select File Action', - value: selectedKey, - items: getFileUploadMasterList, - onChanged: (val) { - setState(() { - selectedKey = val; - final selectedItem = getFileUploadMasterList - .firstWhere((e) => e['key'] == val); - selectedValue = selectedItem['value']; - currentApiValue = selectedItem['key']; - showSampleButton = true; - }); - }, + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// Select File Action + Expanded( + flex: 5, + child: buildStyledDropdown( + label: 'Select File Action', + value: selectedKey, + items: getFileUploadMasterList, + onChanged: (val) { + setState(() { + selectedKey = val; + final selectedItem = getFileUploadMasterList + .firstWhere((e) => e['key'] == val); + selectedValue = selectedItem['value']; + currentApiValue = selectedItem['key']; + showSampleButton = true; + }); + }, + ), + ), + + const SizedBox(width: 16), + + /// Upload Box + Expanded( + flex: 5, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// ✅ LABEL + RichText( + text: TextSpan( + text: 'Upload File', + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w500, + color: Colors.black, ), + children: const [ + TextSpan( + text: '(Supported Formats: XLSX)', + style: TextStyle( + fontSize: 11, + color: Colors.grey, + fontWeight: FontWeight.w400, + ), + ), + ], ), + ), - const SizedBox(width: 16), + const SizedBox(height: 6), - /// Upload Box - Expanded( - flex: 5, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - /// ✅ LABEL - RichText( - text: TextSpan( - text: 'Upload File', - style: GoogleFonts.poppins( - fontSize: 12, - fontWeight: FontWeight.w500, - color: Colors.black, + /// ✅ DOTTED UPLOAD BOX + DragTarget( + onAccept: (html.File droppedFile) { + setState(() { + fileName = droppedFile.name; + }); + _dragAndDropFile(droppedFile); + }, + builder: + (context, candidateData, rejectedData) { + return GestureDetector( + onTap: () { + if (selectedValue != null) { + _uploadFile(); + } else { + ToastHelper.showErrorToast( + context, + 'Please select file action', + ); + } + }, + child: Container( + height: 40, + padding: const EdgeInsets.symmetric( + horizontal: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius.circular(8), + border: Border.all( + color: const Color(0xFF00A6A6), + width: 1, ), - children: const [ - TextSpan( - text: '(Supported Formats: XLSX)', - style: TextStyle( - fontSize: 11, - color: Colors.grey, - fontWeight: FontWeight.w400, + ), + child: Row( + children: [ + Expanded( + child: Text( + fileName ?? + 'Upload Your Documents', + overflow: + TextOverflow.ellipsis, + style: GoogleFonts.poppins( + fontSize: 13, + color: fileName == null + ? Colors.grey + : Colors.black, + ), ), ), + const Icon( + Icons.file_upload_outlined, + size: 18, + color: Colors.black, + ), ], ), - ), - - const SizedBox(height: 6), - - /// ✅ DOTTED UPLOAD BOX - DragTarget( - onAccept: (html.File droppedFile) { - setState(() { - fileName = droppedFile.name; - }); - _dragAndDropFile(droppedFile); - }, - builder: - (context, candidateData, rejectedData) { - return GestureDetector( - onTap: () { - if (selectedValue != null) { - _uploadFile(); - } else { - ToastHelper.showErrorToast( - context, - 'Please select file action', - ); - } - }, - child: Container( - height: 40, - padding: const EdgeInsets.symmetric( - horizontal: 12), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: - BorderRadius.circular(8), - border: Border.all( - color: const Color(0xFF00A6A6), - width: 1, - ), - ), - child: Row( - children: [ - Expanded( - child: Text( - fileName ?? - 'Upload Your Documents', - overflow: - TextOverflow.ellipsis, - style: GoogleFonts.poppins( - fontSize: 13, - color: fileName == null - ? Colors.grey - : Colors.black, - ), - ), - ), - const Icon( - Icons.file_upload_outlined, - size: 18, - color: Colors.black, - ), - ], - ), - )); - }, - ), - ], - ), - ), - ], - ), - SizedBox(height: 20), - Column( - children: [ - _buildFileUploadedGrid(), - const SizedBox(height: 16), - _buildPagination(context), - ], - ), + )); + }, + ), + ], + ), + ), + ], + ), + SizedBox(height: 20), + Column( + children: [ + _buildFileUploadedGrid(), + const SizedBox(height: 16), + _buildPagination(context), + ], + ), ]))) ], ), @@ -1052,19 +1072,17 @@ class _postFileUploadState extends State { physics: const NeverScrollableScrollPhysics(), // ✅ Disable inner scroll padding: const EdgeInsets.all(16), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - crossAxisSpacing: 16, - mainAxisSpacing: 16, - childAspectRatio: 10, - ), - itemCount: _paginatedData.length, - itemBuilder: (context, index) { - final item = _paginatedData[index]; - return _buildFileCard(item); - }, - ); - - + crossAxisCount: 2, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + childAspectRatio: 10, + ), + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final item = _paginatedData[index]; + return _buildFileCard(item); + }, + ); } Widget _buildFileCard(Map item) { @@ -1159,7 +1177,7 @@ class _postFileUploadState extends State { if (item['file_error_status'] == '1') InkWell( onTap: () async { - print(item); + logDebug(item); // return; final String? token = await tokenService.getCurrentToken(); @@ -1168,18 +1186,18 @@ class _postFileUploadState extends State { final String? empBranchId = await tokenService.readValue('empClientBranchId'); - print(item); - print(empClientId); - print(localPolicyTypeId); - print(empBranchId); - print(token); - print('post'); - print(localCardType); - print(localCardPolicyNo); - print(localCardInsurerName); - print(localCardPolicyName); - print(localCardPolicyExpDate); - print(item['id']); + logDebug(item); + logDebug(empClientId); + logDebug(localPolicyTypeId); + logDebug(empBranchId); + logDebug(token); + logDebug('post'); + logDebug(localCardType); + logDebug(localCardPolicyNo); + logDebug(localCardInsurerName); + logDebug(localCardPolicyName); + logDebug(localCardPolicyExpDate); + logDebug(item['id']); // ✅ SAFETY CHECK if (token == null || diff --git a/lib/presentation/preFileUpload.dart b/lib/presentation/preFileUpload.dart index c9cf4d7..97c0bbc 100755 --- a/lib/presentation/preFileUpload.dart +++ b/lib/presentation/preFileUpload.dart @@ -19,6 +19,7 @@ import '../config/environment.dart'; import '../customAppBar/base_layout.dart'; import 'excelVerification.dart'; import 'hrPolicyDetails.dart'; +import 'package:nhancepolicy/logger.dart'; class preFileUpload extends StatefulWidget { final String ClientId; @@ -229,9 +230,9 @@ class _excelVerifyState extends State { // PlatformFile file = result.files.first; // Uint8List fileBytes = file.bytes!; // // Use the fileBytes as needed - // print('File name: ${file.name}'); - // print('File size: ${file.size}'); - // print('File bytes: $fileBytes'); + // logDebug('File name: ${file.name}'); + // logDebug('File size: ${file.size}'); + // logDebug('File bytes: $fileBytes'); // _processExcelData(fileBytes); // } else { // // User canceled the picker @@ -239,9 +240,9 @@ class _excelVerifyState extends State { // } void _uploadFile(importPolicyName) async { - print('Test'); + logDebug('Test'); if (kIsWeb) { - print('kIsWeb'); + logDebug('kIsWeb'); final input = html.FileUploadInputElement(); input.accept = '.xlsx,.xls'; input.click(); @@ -274,8 +275,8 @@ class _excelVerifyState extends State { // Save fileBytes to local storage // final jsonString = json.encode(fileBytes); // html.window.localStorage['fileBytes'] = jsonString; - print('File Name: $fileName'); - print('File Bytes: $fileBytes'); + logDebug('File Name: $fileName'); + logDebug('File Bytes: $fileBytes'); sendExcelFIleTOAPI(fileBytes, fileName); // Call the function to process Excel data here // _processExcelData(fileBytes, fileName); @@ -284,7 +285,7 @@ class _excelVerifyState extends State { }); } else { // Handle non-web platforms here (e.g., show an error message) - print('File upload is only supported on web platforms.'); + logDebug('File upload is only supported on web platforms.'); } } @@ -304,20 +305,20 @@ class _excelVerifyState extends State { } else if (fileName.endsWith('.xls')) { dataArray = decodeXLSData(fileBytes); } else if (fileName.endsWith('.csv')) { - print('csv'); + logDebug('csv'); dataArray = decodeCSVData(fileBytes); } else { throw UnsupportedError('Unsupported file format: $fileName'); } - print('_processExcelData'); + logDebug('_processExcelData'); // Decode the Excel file and extract relevant data // Assuming dataArray is your array containing Excel data // List> dataArray = decodeExcelData(fileBytes); - print(dataArray); - // print(dataArray[0].toString()); + logDebug(dataArray); + // logDebug(dataArray[0].toString()); // Extract Name, Age, and City from the array - print(dataArray[0].length); + logDebug(dataArray[0].length); if (dataArray[0].length == 11) { for (int i = 0; i < dataArray.length; i++) { @@ -335,71 +336,71 @@ class _excelVerifyState extends State { "Grade": dataArray[i][10].value, }; if (i == 0) { - // print(dataMap); + // logDebug(dataMap); validationArray.add(dataMap); } else { - // print(dataMap); + // logDebug(dataMap); extractedData.add(dataMap); } } // Do something with extracted data (e.g., display in UI) originalData = extractedData; filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); - print(validationArray); + logDebug('filteredData'); + logDebug(filteredData); + logDebug(validationArray); validationArray[0].forEach((key, value) { - print(key); - print(value); + logDebug(key); + logDebug(value); if (key.toString().trim().toLowerCase() != value.toString().trim().toLowerCase()) { // If key and value are not equal, increment mismatch count columnIndexMismatchCount++; - print('columnIndexMismatchCount: $value'); + logDebug('columnIndexMismatchCount: $value'); } if (value.toString() == 'null') { // If value is null, increment missing count columnMissingCount++; - print('Value: $value'); + logDebug('Value: $value'); } }); - print('columnIndexMismatchCount: $columnIndexMismatchCount'); - print('columnMissingCount: $columnMissingCount'); + logDebug('columnIndexMismatchCount: $columnIndexMismatchCount'); + logDebug('columnMissingCount: $columnMissingCount'); nonExcelFilteredData = filteredData.where((item) { final relation = item['Relation']; return relation != null && relation.toString().trim().toLowerCase() != 'self'; }).toList(); - print('nonExcelFilteredData'); + logDebug('nonExcelFilteredData'); - print(nonExcelFilteredData); - print(nonExcelFilteredData.length); + logDebug(nonExcelFilteredData); + logDebug(nonExcelFilteredData.length); if (argumentsData['type'] == 'GPA') { if (nonExcelFilteredData.length > 0) { - print('nonSelf'); + logDebug('nonSelf'); invalidRelationships = nonExcelFilteredData.length; } else { - print('Self'); + logDebug('Self'); invalidRelationships = nonExcelFilteredData.length; } - print('invalidRelationships: $invalidRelationships'); + logDebug('invalidRelationships: $invalidRelationships'); } else { invalidRelationships = 0; } int invalidDobCount = countInvalidDobs(filteredData); - print('Number of invalid DOBs: $invalidDobCount'); + logDebug('Number of invalid DOBs: $invalidDobCount'); dobAgeCheckCount = invalidDobCount; } else { - print('Some Column is Missing'); + logDebug('Some Column is Missing'); var columnMissingCount = 11 - dataArray[0].length; missingColumnErrorMsg = columnMissingCount; - print(missingColumnErrorMsg); + logDebug(missingColumnErrorMsg); } } @@ -412,12 +413,12 @@ class _excelVerifyState extends State { // Placeholder function for decoding Excel data List> decodeExcelData(Uint8List fileBytes) { - print('decodeExcelData'); + logDebug('decodeExcelData'); // Create an Excel instance from the fileBytes final excel = Excel.decodeBytes(fileBytes); - print('decodeExcelData'); - print(excel); + logDebug('decodeExcelData'); + logDebug(excel); // Assuming there's only one sheet in the Excel file final sheet = excel.tables.keys.first; @@ -484,17 +485,17 @@ class _excelVerifyState extends State { // // Invalid DOB format, skip this entry // continue; // } - print(entry['Relation']); + logDebug(entry['Relation']); if ((entry['Relation'].toString() == 'Son' || entry['Relation'].toString() == 'Daughter')) { if (DateTime.now().difference(dob).inDays > 25 * 365) { - print('child $dob'); + logDebug('child $dob'); invalidCount++; } } else if ((entry['Relation'] != 'Son' && entry['Relation'] != 'Daughter')) { if (DateTime.now().difference(dob).inDays < 18 * 365) { - print('others $dob'); + logDebug('others $dob'); invalidCount++; } } @@ -504,8 +505,8 @@ class _excelVerifyState extends State { } void _dragAndDropFile(html.File file) async { - print('file'); - print(file); + logDebug('file'); + logDebug(file); // Prepare form data final formData = html.FormData(); formData.appendBlob('file', file); @@ -518,7 +519,7 @@ class _excelVerifyState extends State { ); // Handle response as needed - print(response.responseText); + logDebug(response.responseText); } void _retrieveAndUploadFile() { @@ -544,23 +545,23 @@ class _excelVerifyState extends State { isLoading = true; // }); // }); - print('submit'); - print(fileBytes); + logDebug('submit'); + logDebug(fileBytes); if (fileBytes == null) { - print('return'); + logDebug('return'); return; // No file selected } else { - print('else'); + logDebug('else'); // // Prepare form data // final formData = html.FormData(); // formData.appendBlob('file', html.Blob([fileBytes]), fileName); final enrollmentHrId = await tokenService.readValue('enrollmentHrId'); // URL of the API where you want to send the file final apiUrl = Environment.apiUrl + 'employeeUpload'; - print('else'); + logDebug('else'); // Create a multipart request final request = http.MultipartRequest('POST', Uri.parse(apiUrl)); - print('else'); + logDebug('else'); // Attach the file to the request // Set authorization token in headers request.headers['APP-SIGNATURE'] = @@ -568,7 +569,7 @@ class _excelVerifyState extends State { request.headers['Authorization'] = 'Bearer $_token'; // request.files.add(http.MultipartFile.fromBytes('file', fileBytes, // filename: fileName)); - print('Filename: $fileName'); + logDebug('Filename: $fileName'); request.files.add(http.MultipartFile.fromBytes( 'file', fileBytes, @@ -586,20 +587,20 @@ class _excelVerifyState extends State { // } else { // request.fields['policy_id'] = '3'; // } - print('request : $request'); + logDebug('request : $request'); // Send the request final response = await request.send(); - print('else'); + logDebug('else'); // Read response stream as a string final responseString = await response.stream.bytesToString(); - print('else'); + logDebug('else'); // Check the status code of the response if (response.statusCode == 200) { isLoading = false; Map data = json.decode(responseString); if (data['status'] == false) { ToastHelper.showErrorToast(context, data['message']); - print('Table'); + logDebug('Table'); setState(() { isSuccess = true; @@ -621,7 +622,7 @@ class _excelVerifyState extends State { getFileListDetails(); }); // ToastHelper.showErrorToast(context, data['message']); - print('Table'); + logDebug('Table'); } } else { setState(() { @@ -630,38 +631,38 @@ class _excelVerifyState extends State { // ToastHelper.showSuccessToast( // context, 'Failed to upload file: ${response.reasonPhrase}'); ToastHelper.showErrorToast(context, 'Something went wrong'); - print('Failed to upload file: ${response.reasonPhrase}'); + logDebug('Failed to upload file: ${response.reasonPhrase}'); } } } Future handleImportAction() async { - print('handleImportAction'); + logDebug('handleImportAction'); final postId = await tokenService.readValue('empHrId'); final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); var activity = "import_enrollempdata"; dynamic response; - print('postId - $postId'); - print('preId - $preId'); - print('activity - $activity'); + logDebug('postId - $postId'); + logDebug('preId - $preId'); + logDebug('activity - $activity'); try { - print('10'); + logDebug('10'); response = await apiService.getImportLogHrActivity( postId!, preId!, localToken, activity); if (response['status'] == 'success') { - print('Request success'); + logDebug('Request success'); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -671,28 +672,28 @@ class _excelVerifyState extends State { final enrollmentClientId = await tokenService.readValue('enrollmentClient_id'); - print('9'); + logDebug('9'); try { final response = await apiService.getFileListToApi(enrollmentPrimaryId, localCardPolicyNo, enrollmentClientId, localToken, localTokenType); if (response['status'] == true) { - print('getThrFileList'); + logDebug('getThrFileList'); setState(() { getThrFileList = List>.from(response['data']); originalData = getThrFileList; filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { // _isLoading = false; @@ -724,23 +725,23 @@ class _excelVerifyState extends State { // Future downloadSampleFile() async { // // final response = await apiService.getSampleFileDownload(localToken); - // print('check 1'); + // logDebug('check 1'); // if (response['status'] == 'success') { // final url = response['data']; // _launchURL(url); // } else { // ToastHelper.showErrorToast(context, '⚠️ Unknown response format'); - // print('⚠️ Unknown response format'); + // logDebug('⚠️ Unknown response format'); // } // } // // Future _launchURL(String url) async { - // print('url $url'); + // logDebug('url $url'); // try { // final Uri uri = Uri.parse(url); // await launchUrl(uri, mode: LaunchMode.externalApplication); // } catch (e) { - // print('Could not launch URL: $e'); + // logDebug('Could not launch URL: $e'); // } // } @@ -770,7 +771,7 @@ class _excelVerifyState extends State { if (response.statusCode == 200) { try { - print("PDF Downloaded"); + logDebug("PDF Downloaded"); // ✅ Create a blob from the response body bytes final blob = html.Blob([response.bodyBytes]); @@ -789,7 +790,7 @@ class _excelVerifyState extends State { throw Exception('Error parsing response: $e'); } } else { - print("Download failed with status: ${response.statusCode}"); + logDebug("Download failed with status: ${response.statusCode}"); } } @@ -827,24 +828,47 @@ class _excelVerifyState extends State { return; } - final clientId = await tokenService.readValue('hr_ClientId') ?? ''; - final policyTypeId = await tokenService.readValue('hr_policyTypeId') ?? ''; - final clientPolicyId = await tokenService.readValue('hr_ClientPoliyId') ?? ''; - final clientBranchId = await tokenService.readValue('hr_clientBranchId') ?? ''; - final token = await tokenService.readValue('hr_Token') ?? ''; - final tokenType = await tokenService.readValue('hr_TokenType') ?? ''; - final cardType = await tokenService.readValue('hr_cardType') ?? ''; - final policyNo = await tokenService.readValue('hr_cardPolicyNo') ?? ''; - final insurer = await tokenService.readValue('hr_cardInsurer_name') ?? ''; - final policyName = await tokenService.readValue('hr_cardPolicy_name') ?? ''; - final expDate = await tokenService.readValue('hr_cardPolicy_ExpDate') ?? ''; - final totalPremium = await tokenService.readValue('hr_total_premium') ?? ''; - final bulkDownload = await tokenService.readValue('hr_is_ecard_bulk_download_for_employee') ?? '0'; + final clientId = + await tokenService.readValue('hr_ClientId') ?? ''; + final policyTypeId = + await tokenService.readValue('hr_policyTypeId') ?? + ''; + final clientPolicyId = + await tokenService.readValue('hr_ClientPoliyId') ?? + ''; + final clientBranchId = + await tokenService.readValue('hr_clientBranchId') ?? + ''; + final token = + await tokenService.readValue('hr_Token') ?? ''; + final tokenType = + await tokenService.readValue('hr_TokenType') ?? ''; + final cardType = + await tokenService.readValue('hr_cardType') ?? ''; + final policyNo = + await tokenService.readValue('hr_cardPolicyNo') ?? + ''; + final insurer = await tokenService + .readValue('hr_cardInsurer_name') ?? + ''; + final policyName = await tokenService + .readValue('hr_cardPolicy_name') ?? + ''; + final expDate = await tokenService + .readValue('hr_cardPolicy_ExpDate') ?? + ''; + final totalPremium = + await tokenService.readValue('hr_total_premium') ?? + ''; + final bulkDownload = await tokenService.readValue( + 'hr_is_ecard_bulk_download_for_employee') ?? + '0'; Navigator.pushReplacement( context, MaterialPageRoute( - settings: const RouteSettings(name: 'hrPolicyDetails'), + settings: + const RouteSettings(name: 'hrPolicyDetails'), builder: (_) => hrPolicyDetails( ClientId: clientId, policyTypeId: policyTypeId, @@ -858,7 +882,8 @@ class _excelVerifyState extends State { cardPolicy_name: policyName, cardPolicy_ExpDate: expDate, total_premium: totalPremium, - is_ecard_bulk_download_for_employee: int.tryParse(bulkDownload) ?? 0, + is_ecard_bulk_download_for_employee: + int.tryParse(bulkDownload) ?? 0, ), ), ); @@ -1400,7 +1425,7 @@ class _excelVerifyState extends State { message: 'Info', // Added tooltip name child: InkWell( onTap: () async { - print(item); + logDebug(item); // return; final String? token = await tokenService.getCurrentToken(); @@ -1410,18 +1435,18 @@ class _excelVerifyState extends State { await tokenService .readValue('enrollmentEmpClientBranchId'); - print(item); - print(enrollmentClient_id); - print(localPolicyTypeId); - print(enrollmentEmpClientBranchId); - print(token); - print('post'); - print(localCardType); - print(localCardPolicyNo); - print(localCardInsurerName); - print(localCardPolicyName); - print(localCardPolicyExpDate); - print(item['id']); + logDebug(item); + logDebug(enrollmentClient_id); + logDebug(localPolicyTypeId); + logDebug(enrollmentEmpClientBranchId); + logDebug(token); + logDebug('post'); + logDebug(localCardType); + logDebug(localCardPolicyNo); + logDebug(localCardInsurerName); + logDebug(localCardPolicyName); + logDebug(localCardPolicyExpDate); + logDebug(item['id']); // ✅ SAFETY CHECK if (token == null || diff --git a/lib/service/_ResponsiveGridConfig.dart b/lib/service/_ResponsiveGridConfig.dart index 7a92603..3a1e669 100644 --- a/lib/service/_ResponsiveGridConfig.dart +++ b/lib/service/_ResponsiveGridConfig.dart @@ -8,9 +8,9 @@ class _ResponsiveGridConfig { } _ResponsiveGridConfig _getGridConfig( - BuildContext context, - bool isEnrollment, - ) { + BuildContext context, + bool isEnrollment, +) { final width = MediaQuery.of(context).size.width; if (width < 600) { diff --git a/lib/service/api_service.dart b/lib/service/api_service.dart index f198a7f..ca497d3 100755 --- a/lib/service/api_service.dart +++ b/lib/service/api_service.dart @@ -5,6 +5,7 @@ import 'dart:convert'; import '../config/environment.dart'; import '../customAppBar/toastHelper.dart'; +import 'package:nhancepolicy/logger.dart'; class ApiService { final BuildContext context; @@ -29,7 +30,7 @@ class ApiService { Future> getClientLogoAndDetailsToApi( String clientId, String empCode, String branchID) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -50,7 +51,8 @@ class ApiService { String? empCode, String? status, String? branchID, - String? mobileNo,String? emailId) async { + String? mobileNo, + String? emailId) async { if (_token == null) { await _initializeToken(); } @@ -69,7 +71,7 @@ class ApiService { String empCode, String branchID, String client_policy_id) async { - print(_token); + logDebug(_token); _token = await token; if (_token == null) { await _initializeToken(); @@ -84,7 +86,7 @@ class ApiService { } Future> fetchRelationshipListToApi() async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -103,7 +105,7 @@ class ApiService { String policy, String branchID, login_by_hr) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -123,7 +125,7 @@ class ApiService { String policy, String branchID, login_by_hr) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -138,7 +140,7 @@ class ApiService { Future> getGmcSiTopUpToApi( String client_id, String emp_code, String policy, String branchID) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -153,7 +155,7 @@ class ApiService { Future> getGmcSiParentTopUpToApi( String client_id, String emp_code, String policy, String branchID) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -168,7 +170,7 @@ class ApiService { Future> getGmcDependentAddOnsToApi( String client_id, String emp_code, String policy, String branchID) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -181,19 +183,18 @@ class ApiService { return response; } - Future> getExcelFileErrorsApi(id,type) async { - print(_token); + Future> getExcelFileErrorsApi(id, type) async { + logDebug(_token); if (_token == null) { await _initializeToken(); } final apiURL; - if(type == 'post'){ + if (type == 'post') { apiURL = Environment.apiUrlPost; } else { apiURL = Environment.apiUrl; } - final url = Uri.parse( - '${apiURL}getExcelFileErrors/${id}/api'); + final url = Uri.parse('${apiURL}getExcelFileErrors/${id}/api'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; @@ -203,7 +204,7 @@ class ApiService { Future> removeAddonsGmcDependentToAPI( String empCodeString, String addOnsDependentClientPolicyId) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -218,7 +219,7 @@ class ApiService { Future> removeAddonsGmcSiToAPI( String empCodeString, String topUpClientPolicyId) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -233,7 +234,7 @@ class ApiService { Future> removeAddonsGmcParentSiToAPI( String empCodeString, String topUpParentClientPolicyId) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -247,7 +248,7 @@ class ApiService { } Future> deleteItemToApi(id) async { - print(_token); + logDebug(_token); if (_token == null) { await _initializeToken(); } @@ -261,7 +262,7 @@ class ApiService { Future> saveFamilyMemberDetailsToApi( List> formDataList) async { - print('saveFamilyMemberDetailsToApi API SERVICE'); + logDebug('saveFamilyMemberDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -282,7 +283,7 @@ class ApiService { Future> saveAddOnsDetailsToApi( List> formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -303,7 +304,7 @@ class ApiService { Future> sendAddonsGmcDependentToAPI( List> formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -325,7 +326,7 @@ class ApiService { Future> sendAddonsGmcSiToAPI( List> formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -347,7 +348,7 @@ class ApiService { Future> sendAddonsGmcParentSiToAPI( List> formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -369,7 +370,7 @@ class ApiService { Future> sendAddOnToAPI( Map formData) async { - print('sendAddOnToAPI API SERVICE'); + logDebug('sendAddOnToAPI API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -389,7 +390,7 @@ class ApiService { } Future> topUpSiCalculationToAPI(formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -410,7 +411,7 @@ class ApiService { Future> topUpParentSiCalculationToAPI( formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -431,7 +432,7 @@ class ApiService { Future> addOnsDependentCalculationToAPI( formDataList) async { - print('saveAddOnsDetailsToApi API SERVICE'); + logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } @@ -454,8 +455,8 @@ class ApiService { Future> getCashDepositDetailsToApi( String clintID, String empRefId, String hr_id, String token) async { - print("getCashDepositDetailsToApi1"); - print("HRID- $hr_id"); + logDebug("getCashDepositDetailsToApi1"); + logDebug("HRID- $hr_id"); if (token == null) { await _initializeToken(); @@ -472,7 +473,7 @@ class ApiService { Future> getActiveCashDepositDetailsToApi(String clintID, String empRefId, String hr_id, String token, int emp_status) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); if (token == null) { await _initializeToken(); @@ -491,7 +492,7 @@ class ApiService { Future> getCDPoliciesToApi( String clintID, String hr_id, String token) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}cdSummaryData?client_id=$clintID&hr_id=$hr_id'); @@ -504,11 +505,11 @@ class ApiService { Future> getImportLogHrActivity( String? postId, String? preId, String token, String activity) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); - print('postId1 - $postId'); - print('preId1 - $preId'); - print('activity1 - $activity'); + logDebug('postId1 - $postId'); + logDebug('preId1 - $preId'); + logDebug('activity1 - $activity'); // final url = Uri.parse( // '${Environment.apiUrlPost}logHrActivity?user_id=$postId&pre_hr_id=$preId&user_type=hr&activity=$activity'); @@ -517,7 +518,8 @@ class ApiService { final headers = { 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { @@ -542,8 +544,8 @@ class ApiService { } } - Future> getEcardBulkDownloadApi(client_policy_id,empHrId,emp_policy_ids,String token) async { - + Future> getEcardBulkDownloadApi( + client_policy_id, empHrId, emp_policy_ids, String token) async { // final url = Uri.parse( // '${Environment.apiUrlPost}logHrActivity?user_id=$postId&pre_hr_id=$preId&user_type=hr&activity=$activity'); @@ -551,13 +553,14 @@ class ApiService { final headers = { 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'client_policy_id': client_policy_id, 'hr_id': empHrId, - 'emp_policy_ids':emp_policy_ids, + 'emp_policy_ids': emp_policy_ids, }; final response = await http.post( @@ -577,21 +580,22 @@ class ApiService { Future> getPostLogHrActivity( String? postId, String? preId, String token, String activity) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); - print('postId1 - $postId'); - print('preId1 - $preId'); - print('activity1 - $activity'); + logDebug('postId1 - $postId'); + logDebug('preId1 - $preId'); + logDebug('activity1 - $activity'); // final url = Uri.parse( // '${Environment.apiUrlPost}logHrActivity?user_id=$postId&pre_hr_id=$preId&user_type=hr&activity=$activity'); final url = Uri.parse('${Environment.apiUrlPost}logHrActivity'); - final headers = { - 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', - }; + final headers = { + 'Authorization': 'Bearer ${token ?? ''}', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + }; final body = { 'user_id': postId, @@ -617,17 +621,18 @@ class ApiService { Future> getPreLogHrActivity( String? postId, String? preId, String token, String activity) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); - print('postId1 - $postId'); - print('preId1 - $preId'); - print('activity1 - $activity'); + logDebug('postId1 - $postId'); + logDebug('preId1 - $preId'); + logDebug('activity1 - $activity'); final url = Uri.parse('${Environment.apiUrl}logHrActivity'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { @@ -652,13 +657,13 @@ class ApiService { } } - Future> postHrDashboard(params,token) async { - + Future> postHrDashboard(params, token) async { final url = Uri.parse('${Environment.apiUrlPost}getHrDashboad'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = params; @@ -679,12 +684,12 @@ class ApiService { } Future> postHrTpaDashboard(params, token) async { - final url = Uri.parse('${Environment.apiUrlPost}getHrTpaDashboard'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final response = await http.post( @@ -701,9 +706,11 @@ class ApiService { } } - Future> getClaimPoliciesToApi(String token,empClientId) async { - print("getgetClaimPoliciesToApii1"); - final url = Uri.parse('${Environment.apiUrlPost}claimsSearch?client_id=$empClientId'); + Future> getClaimPoliciesToApi( + String token, empClientId) async { + logDebug("getgetClaimPoliciesToApii1"); + final url = Uri.parse( + '${Environment.apiUrlPost}claimsSearch?client_id=$empClientId'); final headers = { 'Authorization': 'Bearer $token' ?? '', @@ -712,7 +719,8 @@ class ApiService { return response; } - Future> getClaimPoliciesFileDownload(id,String token) async { + Future> getClaimPoliciesFileDownload( + id, String token) async { final url = Uri.parse('${Environment.apiUrlPost}hrFileDownload?id=$id'); final headers = { @@ -724,11 +732,12 @@ class ApiService { Future> getClaimPoliciesListDataToApi( String token, Map body) async { - print("getgetClaimPoliciesToApii1"); + logDebug("getgetClaimPoliciesToApii1"); final url = Uri.parse('${Environment.apiUrlPost}claimsSearch'); final headers = { - 'APP-SIGNATURE' :'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', }; @@ -746,7 +755,7 @@ class ApiService { } } - Future> getEcardRequest(eCardParam,String token) async { + Future> getEcardRequest(eCardParam, String token) async { final url = Uri.parse('${Environment.apiUrlPost}ecardRequest'); final headers = { 'Authorization': 'Bearer $token' ?? '', @@ -754,13 +763,14 @@ class ApiService { }; final jsonBody = jsonEncode(eCardParam); // Send formDataJson as the body - final response = await _makePostRequestWithoutFormData(url,jsonBody, headers); + final response = + await _makePostRequestWithoutFormData(url, jsonBody, headers); return response; } Future> getCdTransactionData( String clintID, String insurerId, String cd_ac_pk, String token) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}cdTransactionData?client_id=$clintID&insurer_id=$insurerId&cd_ac_pk=$cd_ac_pk'); @@ -771,10 +781,11 @@ class ApiService { return response; } - Future> getOpenEndorsementFileData(id, String token) async { - print("getPolicyAndEndorsementFiles"); - final url = Uri.parse( - '${Environment.apiUrlPost}downloadPolicyFiles?file_id=$id'); + Future> getOpenEndorsementFileData( + id, String token) async { + logDebug("getPolicyAndEndorsementFiles"); + final url = + Uri.parse('${Environment.apiUrlPost}downloadPolicyFiles?file_id=$id'); final headers = { 'Authorization': 'Bearer $token' ?? '', @@ -784,7 +795,7 @@ class ApiService { } Future> getCdEndorsementData(id, String token) async { - print("getPolicyAndEndorsementFiles"); + logDebug("getPolicyAndEndorsementFiles"); final url = Uri.parse( '${Environment.apiUrlPost}getPolicyAndEndorsementFiles?cd_ac_pk=$id'); @@ -797,7 +808,7 @@ class ApiService { Future> getClaimsHistoryToApi( String ticket_type_id, String token) async { - print("getCashDepositDetailsToApi1"); + logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}claimView?ticket_id=$ticket_type_id'); @@ -809,8 +820,8 @@ class ApiService { } Future> getSampleFileDownload(String token) async { - final url = Uri.parse( - '${Environment.apiUrl}downloadSampleExcel/enrollment'); + final url = + Uri.parse('${Environment.apiUrl}downloadSampleExcel/enrollment'); final headers = { 'Authorization': 'Bearer $token' ?? '', @@ -821,7 +832,7 @@ class ApiService { Future> getEmployeeAndDependenceToApi( String clintID, getPolicyNo, String empRefId, String token) async { - print(_hrtoken); + logDebug(_hrtoken); if (token == null) { await _initializeToken(); } @@ -835,12 +846,11 @@ class ApiService { } Future> getFileUploadMastersToApi(String token) async { - print(_hrtoken); + logDebug(_hrtoken); if (token == null) { await _initializeToken(); } - final url = Uri.parse( - '${Environment.apiUrlPost}hrFileUploadMasters'); + final url = Uri.parse('${Environment.apiUrlPost}hrFileUploadMasters'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; @@ -848,13 +858,14 @@ class ApiService { return response; } - Future> getFileListToApi(empPrimaryId,cardPolicyNo,empClientId,String token,String type) async { - print(_hrtoken); + Future> getFileListToApi(empPrimaryId, cardPolicyNo, + empClientId, String token, String type) async { + logDebug(_hrtoken); if (token == null) { await _initializeToken(); } - final apiURL; - if(type == 'post'){ + final apiURL; + if (type == 'post') { apiURL = Environment.apiUrlPost; } else { apiURL = Environment.apiUrl; @@ -863,14 +874,15 @@ class ApiService { '${apiURL}hrFileList?created_by=$empPrimaryId&policy_no=$cardPolicyNo&client_id=$empClientId'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final response = await _makeGetRequest(url, headers); return response; } // Future> getHrFileDownloadToApi(id,String token) async { - // print(_hrtoken); + // logDebug(_hrtoken); // if (token == null) { // await _initializeToken(); // } @@ -885,7 +897,7 @@ class ApiService { Future> getEmployeeAndDependenceToApiPre( String clintID, String getPolicyNo, String empRefId, String token) async { - print(_hrtoken); + logDebug(_hrtoken); if (token == null) { await _initializeToken(); } @@ -981,38 +993,39 @@ class ApiService { // if (!isWeb) { await tokenService.clearAll(); - print('Secure Storage Cleared'); + logDebug('Secure Storage Cleared'); // } if (context.mounted) { - print('context.mounted'); + logDebug('context.mounted'); Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', - (route) => false, // remove all previous routes + (route) => false, // remove all previous routes ); } } - - Future> _makePostRequestWithoutFormData( Uri url, String body, Map headers) async { - headers['APP-SIGNATURE'] = 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; + headers['APP-SIGNATURE'] = + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final response = await http.post(url, headers: headers, body: body); return _handleResponse(response); } Future> _makeGetRequest( Uri url, Map headers) async { - headers['APP-SIGNATURE'] = 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; + headers['APP-SIGNATURE'] = + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final response = await http.get(url, headers: headers); return _handleResponse(response); } Future> _makePostRequest( Uri url, String body, Map headers) async { - headers['APP-SIGNATURE'] = 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; + headers['APP-SIGNATURE'] = + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final response = await http.post(url, headers: headers, body: body); return _handleResponse(response); } @@ -1036,13 +1049,13 @@ class ApiService { await _clearLocalStorageAndRedirect(); } return {}; - }else if (response.statusCode == 451) { - final body = jsonDecode(response.body); + } else if (response.statusCode == 451) { + final body = jsonDecode(response.body); final message = body['message']; ToastHelper.showWarningToast(context, message); return {}; } else if (response.statusCode == 429) { - final body = jsonDecode(response.body); + final body = jsonDecode(response.body); final message = body['message']; ToastHelper.showWarningToast(context, message); return {}; @@ -1059,8 +1072,7 @@ class ApiService { Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', - (route) => false, + (route) => false, ); } - } diff --git a/lib/service/file_upload_service.dart b/lib/service/file_upload_service.dart index 643d002..9269a7f 100755 --- a/lib/service/file_upload_service.dart +++ b/lib/service/file_upload_service.dart @@ -6,9 +6,9 @@ class UploadedFile { final TextEditingController controller; UploadedFile({required this.file}) : controller = TextEditingController( - text: file.extension != null - ? file.name.replaceAll('.${file.extension}', '') - : file.name); + text: file.extension != null + ? file.name.replaceAll('.${file.extension}', '') + : file.name); String get label => controller.text; void dispose() => controller.dispose(); diff --git a/lib/service/hrDashboardTabs/activePolicies.dart b/lib/service/hrDashboardTabs/activePolicies.dart index 133be4e..07a7e46 100755 --- a/lib/service/hrDashboardTabs/activePolicies.dart +++ b/lib/service/hrDashboardTabs/activePolicies.dart @@ -76,7 +76,7 @@ // apiService = ApiService(context); // _loadData(); // -// print("_PreEnrollmentState 1"); +// logDebug("_PreEnrollmentState 1"); // } // // Future _loadData() async { @@ -86,12 +86,12 @@ // // Future getCashDepositDetails( // clintBranchId, clintID, hr_id, token) async { -// print("_PreEnrollmentState 2"); -// print('IN'); -// print("clintBranchId -$clintBranchId"); -// print("clintID -$clintID"); -// print("hr_id -$hr_id"); -// print("token -$token"); +// logDebug("_PreEnrollmentState 2"); +// logDebug('IN'); +// logDebug("clintBranchId -$clintBranchId"); +// logDebug("clintID -$clintID"); +// logDebug("hr_id -$hr_id"); +// logDebug("token -$token"); // // isLoading = true; // // setState(() { @@ -107,33 +107,33 @@ // // // final response = await apiService.getCashDepositDetailsToApi( // // clintID!, clintBranchId!, hr_id, token); -// print('IN1'); +// logDebug('IN1'); // if (response['status'] == 'success') { // isLoading = false; // setState(() { -// print('response'); -// print(response['data']); +// logDebug('response'); +// logDebug(response['data']); // -// print("_PreEnrollmentState 3"); +// logDebug("_PreEnrollmentState 3"); // setState(() { // getCardArrays = List>.from(response['data']); // }); // -// print('getCardArrays'); -// print(getCardArrays); +// logDebug('getCardArrays'); +// logDebug(getCardArrays); // }); // -// print('IN2'); -// print("getCardArrays9 - $getCardArrays"); +// logDebug('IN2'); +// logDebug("getCardArrays9 - $getCardArrays"); // } else { // isLoading = false; -// print('API request failed with status'); +// logDebug('API request failed with status'); // setState(() { // getCardArrays = []; // }); // } // } catch (e) { -// print('Exception occurred: $e'); +// logDebug('Exception occurred: $e'); // } // } // @@ -153,7 +153,7 @@ // // Dynamic aspect ratio: // final aspectRatio = screenWidth / screenHeight; // -// print("_PreEnrollmentState 4"); +// logDebug("_PreEnrollmentState 4"); // // TODO: implement build // return Container( // // height: MediaQuery.of(context).size.height * 0.2, @@ -260,18 +260,18 @@ // } // // Widget buildPolicyCard(Map policy) { -// print("buildPolicyCard - $policy"); +// logDebug("buildPolicyCard - $policy"); // final mediaQuery = MediaQuery.of(context); // final devicePixelRatio = mediaQuery.devicePixelRatio; // final logicalWidth = 230 / devicePixelRatio; // final logicalHeight = 115 / devicePixelRatio; // -// print("logicalWidth - $logicalWidth"); -// print("logicalHeight - $logicalHeight"); +// logDebug("logicalWidth - $logicalWidth"); +// logDebug("logicalHeight - $logicalHeight"); // return InkWell( // onTap: () { // setState(() { -// print("policytab - $policy"); +// logDebug("policytab - $policy"); // Navigator.push( // context, // MaterialPageRoute( diff --git a/lib/service/hrDashboardTabs/cd.dart b/lib/service/hrDashboardTabs/cd.dart index 254d2ab..8124a95 100755 --- a/lib/service/hrDashboardTabs/cd.dart +++ b/lib/service/hrDashboardTabs/cd.dart @@ -14,6 +14,7 @@ import '../api_service.dart'; import 'package:collection/collection.dart'; import '../token_storage_service.dart'; +import 'package:nhancepolicy/logger.dart'; class CdPolicies extends StatefulWidget { final String empClientId; @@ -85,12 +86,12 @@ class _CdPolicieState extends State { } Future getCDPoliciesDetails() async { - print('9'); + logDebug('9'); setState(() { isLoading = true; }); try { - print('10'); + logDebug('10'); final response = await apiService.getCDPoliciesToApi( widget.empClientId, widget.empHrId, widget.postToken); if (response['status'] == 'success') { @@ -101,8 +102,8 @@ class _CdPolicieState extends State { getCDPolicies = List>.from(response['data']); originalData = getCDPolicies; filteredData = List.from(originalData); - print('filteredData'); - print(filteredData); + logDebug('filteredData'); + logDebug(filteredData); }); } else { setState(() { @@ -111,13 +112,13 @@ class _CdPolicieState extends State { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { setState(() { isLoading = false; }); - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } finally { setState(() { _isLoading = false; @@ -126,7 +127,7 @@ class _CdPolicieState extends State { } void search(String query) { - print(query); + logDebug(query); // Check if the query is empty if (query.isEmpty) { // If search query is empty, show all data @@ -155,7 +156,7 @@ class _CdPolicieState extends State { }).toList(); }); } - print(filteredData.length); + logDebug(filteredData.length); } void exportToCsv(List> data) { @@ -188,29 +189,29 @@ class _CdPolicieState extends State { } Future handleExportAction() async { - print('handleExportAction'); + logDebug('handleExportAction'); final postId = await tokenService.readValue('empHrId'); final preId = await tokenService.readValue('enrollmentEmpPrimaryId'); var activity = "export_cddata"; - print('postId - $postId'); - print('preId - $preId'); - print('activity - $activity'); + logDebug('postId - $postId'); + logDebug('preId - $preId'); + logDebug('activity - $activity'); try { - print('10'); + logDebug('10'); final response = await apiService.getPostLogHrActivity( postId!, preId!, widget.postToken, activity); if (response['status'] == 'success') { - print('Request success'); + logDebug('Request success'); } else { // ToastHelper.showWarningToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response['code']}'); + logDebug('Request failed with status: ${response['code']}'); } } catch (e) { - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } } @@ -555,7 +556,8 @@ class _CdPolicieState extends State { Widget _buildPagination(BuildContext context) { // 1. Calculate the range of entries being shown final totalItems = filteredData.length; - final int startEntry = totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; + final int startEntry = + totalItems == 0 ? 0 : ((_currentPage - 1) * _rowsPerPage) + 1; int endEntry = _currentPage * _rowsPerPage; if (endEntry > totalItems) endEntry = totalItems; @@ -586,7 +588,6 @@ class _CdPolicieState extends State { _currentPage + 1, _currentPage + 2, ]; - } List visiblePages = getVisiblePages(); @@ -595,7 +596,8 @@ class _CdPolicieState extends State { // Match this horizontal padding (16) to your Table Header padding for perfect alignment padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, // Pushes text to left, buttons to right + mainAxisAlignment: MainAxisAlignment + .spaceBetween, // Pushes text to left, buttons to right children: [ // --- LEFT SIDE: Showing Text --- Text( diff --git a/lib/service/hrDashboardTabs/preEnrollment.dart b/lib/service/hrDashboardTabs/preEnrollment.dart index ae3e18a..ba4a62a 100755 --- a/lib/service/hrDashboardTabs/preEnrollment.dart +++ b/lib/service/hrDashboardTabs/preEnrollment.dart @@ -75,7 +75,7 @@ // apiService = ApiService(context); // _loadData(); // -// print("_PreEnrollmentState 1"); +// logDebug("_PreEnrollmentState 1"); // } // // Future _loadData() async { @@ -85,12 +85,12 @@ // // Future getCashDepositDetails( // clintBranchId, clintID, hr_id, token) async { -// print("_PreEnrollmentState 2"); -// print('IN'); -// print("clintBranchId -$clintBranchId"); -// print("clintID -$clintID"); -// print("hr_id -$hr_id"); -// print("token -$token"); +// logDebug("_PreEnrollmentState 2"); +// logDebug('IN'); +// logDebug("clintBranchId -$clintBranchId"); +// logDebug("clintID -$clintID"); +// logDebug("hr_id -$hr_id"); +// logDebug("token -$token"); // // // isLoading = true; // setState(() { @@ -105,32 +105,32 @@ // // // final response = await apiService.getCashDepositDetailsToApi( // // clintID!, clintBranchId!, hr_id, token); -// print('IN1'); +// logDebug('IN1'); // if (response['status'] == 'success') { // // setState(() { // isLoading = false; -// print('response'); -// print(response['data']); +// logDebug('response'); +// logDebug(response['data']); // -// print("_PreEnrollmentState 3"); +// logDebug("_PreEnrollmentState 3"); // // getCardArrays = []; // getCardArrays = List>.from(response['data']); -// print('getCardArrays'); -// print(getCardArrays); +// logDebug('getCardArrays'); +// logDebug(getCardArrays); // }); // -// print('IN2'); -// print("getCardArrays9 - $getCardArrays"); +// logDebug('IN2'); +// logDebug("getCardArrays9 - $getCardArrays"); // } else { // setState(() { // isLoading = false; // }); // -// print('API request failed with status'); +// logDebug('API request failed with status'); // } // } catch (e) { -// print('Exception occurred: $e'); +// logDebug('Exception occurred: $e'); // } // } // @@ -150,7 +150,7 @@ // // Dynamic aspect ratio: // final aspectRatio = screenWidth / screenHeight; // -// print("_PreEnrollmentState 4"); +// logDebug("_PreEnrollmentState 4"); // // TODO: implement build // return Container( // // height: MediaQuery.of(context).size.height * 0.2, @@ -237,12 +237,12 @@ // final logicalWidth = 230 / devicePixelRatio; // final logicalHeight = 189 / devicePixelRatio; // -// print("logicalWidth - $logicalWidth"); -// print("logicalHeight - $logicalHeight"); +// logDebug("logicalWidth - $logicalWidth"); +// logDebug("logicalHeight - $logicalHeight"); // return InkWell( // onTap: () { // setState(() { -// print("policytab - $policy"); +// logDebug("policytab - $policy"); // Navigator.push( // context, // MaterialPageRoute( diff --git a/lib/service/multi_file_upload_widget.dart b/lib/service/multi_file_upload_widget.dart index c7defb4..b6416e6 100755 --- a/lib/service/multi_file_upload_widget.dart +++ b/lib/service/multi_file_upload_widget.dart @@ -19,7 +19,8 @@ class _MultiFileUploadWidgetState extends State { String? errorMessage; void _pickFiles() async { - final error = await fileService.pickFiles(maxFileSizeInMB: 10); // 5 MB limit + final error = + await fileService.pickFiles(maxFileSizeInMB: 10); // 5 MB limit if (error != null) { if (mounted) { setState(() { @@ -177,7 +178,6 @@ class _MultiFileUploadWidgetState extends State { // ), // ), ], - if (MultiFileUploadWidget.showValidation && fileService.files.isEmpty && errorMessage == null) ...[ @@ -187,7 +187,6 @@ class _MultiFileUploadWidgetState extends State { style: TextStyle(color: Colors.red, fontSize: 12), ), ], - if (errorMessage != null) ...[ const SizedBox(height: 4), Text( @@ -195,7 +194,6 @@ class _MultiFileUploadWidgetState extends State { style: const TextStyle(color: Colors.red, fontSize: 12), ), ], - const SizedBox(height: 8), ...fileService.files.asMap().entries.map((entry) { final index = entry.key; @@ -207,7 +205,8 @@ class _MultiFileUploadWidgetState extends State { ListTile( dense: true, contentPadding: EdgeInsets.zero, - title: Text(uploaded.file.name, style: const TextStyle(fontSize: 14)), + title: Text(uploaded.file.name, + style: const TextStyle(fontSize: 14)), trailing: IconButton( icon: const Icon(Icons.close, color: Colors.red), tooltip: 'Remove', // Built-in property @@ -215,7 +214,8 @@ class _MultiFileUploadWidgetState extends State { ), ), Padding( - padding: const EdgeInsets.only(left: 8.0, bottom: 8.0, right: 8.0), + padding: + const EdgeInsets.only(left: 8.0, bottom: 8.0, right: 8.0), child: TextField( controller: uploaded.controller, decoration: const InputDecoration( diff --git a/lib/service/secure_pop_scope.dart b/lib/service/secure_pop_scope.dart index 27b62cf..ac2e2aa 100644 --- a/lib/service/secure_pop_scope.dart +++ b/lib/service/secure_pop_scope.dart @@ -57,29 +57,29 @@ class _SecurePopScopeState extends State { Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', - (route) => false, + (route) => false, ); } Future _showLogoutDialog() async { return await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => AlertDialog( - title: const Text("Confirm Logout"), - content: const Text("Do you want to logout?"), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context, false), - child: const Text("Cancel"), + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + title: const Text("Confirm Logout"), + content: const Text("Do you want to logout?"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text("Logout"), + ), + ], ), - TextButton( - onPressed: () => Navigator.pop(context, true), - child: const Text("Logout"), - ), - ], - ), - ) ?? + ) ?? false; } diff --git a/lib/service/svg_service.dart b/lib/service/svg_service.dart index 2f07015..9dfa3fa 100644 --- a/lib/service/svg_service.dart +++ b/lib/service/svg_service.dart @@ -38,7 +38,6 @@ class SvgService { '''; - static String getSvg(String svgName) { switch (svgName) { case 'dashboard': diff --git a/lib/service/token_storage_service.dart b/lib/service/token_storage_service.dart index 30e2785..33203fc 100755 --- a/lib/service/token_storage_service.dart +++ b/lib/service/token_storage_service.dart @@ -1,16 +1,15 @@ import 'dart:convert'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:nhancepolicy/logger.dart'; class TokenStorageService { - static final TokenStorageService _instance = - TokenStorageService._internal(); + static final TokenStorageService _instance = TokenStorageService._internal(); factory TokenStorageService() => _instance; TokenStorageService._internal(); // 🔐 Secure storage instance - static const FlutterSecureStorage _secureStorage = - FlutterSecureStorage(); + static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); // Storage keys static const String _preEnrollmentKey = 'pre_enrollment_data'; @@ -37,14 +36,12 @@ class TokenStorageService { _postEnrollmentData = json.decode(postData); } - final branchData = - await _secureStorage.read(key: _selectedBranchKey); + final branchData = await _secureStorage.read(key: _selectedBranchKey); if (branchData != null) { _selectedBranch = json.decode(branchData); } - final tokenData = - await _secureStorage.read(key: _decodedTokenKey); + final tokenData = await _secureStorage.read(key: _decodedTokenKey); if (tokenData != null) { _decodedToken = json.decode(tokenData); } @@ -52,9 +49,9 @@ class TokenStorageService { // 💾 Save enrollment data Future saveEnrollmentData( - List preData, - List postData, - ) async { + List preData, + List postData, + ) async { _preEnrollmentData = preData; _postEnrollmentData = postData; @@ -71,8 +68,7 @@ class TokenStorageService { // Helper: check valid token bool hasValidToken(dynamic token) { - return token != null && - token.toString().trim().isNotEmpty; + return token != null && token.toString().trim().isNotEmpty; } // Add pre-enrollment data @@ -83,7 +79,8 @@ class TokenStorageService { // ❌ SKIP if token is empty or null if (!hasValidToken(token)) continue; - String uniqueId = '${item['id']}_${item['client_id']}_${item['client_branch_id']}'; + String uniqueId = + '${item['id']}_${item['client_id']}_${item['client_branch_id']}'; if (seenIds.contains(uniqueId)) continue; if (token.isNotEmpty && seenTokens.contains(token)) continue; @@ -103,7 +100,8 @@ class TokenStorageService { // ❌ SKIP if token is empty or null if (!hasValidToken(token)) continue; - String uniqueId = '${item['id']}_${item['client_id']}_${item['client_branch_id']}'; + String uniqueId = + '${item['id']}_${item['client_id']}_${item['client_branch_id']}'; if (seenIds.contains(uniqueId)) continue; if (token.isNotEmpty && seenTokens.contains(token)) continue; @@ -119,8 +117,7 @@ class TokenStorageService { } // 🌿 Save selected branch + decode JWT - Future saveSelectedBranch( - Map branch) async { + Future saveSelectedBranch(Map branch) async { _selectedBranch = branch; String token = branch['token']?.toString() ?? ''; @@ -131,8 +128,7 @@ class TokenStorageService { if (_decodedToken != null) { await _secureStorage.write( - key: _decodedTokenKey, - value: json.encode(_decodedToken)); + key: _decodedTokenKey, value: json.encode(_decodedToken)); } await _secureStorage.write( @@ -152,7 +148,7 @@ class TokenStorageService { return json.decode(decoded); } catch (e) { - print('JWT decode error: $e'); + logDebug('JWT decode error: $e'); return null; } } @@ -164,8 +160,8 @@ class TokenStorageService { bool isLoggedIn() => _selectedBranch != null && - _selectedBranch!['token'] != null && - _selectedBranch!['token'].toString().isNotEmpty; + _selectedBranch!['token'] != null && + _selectedBranch!['token'].toString().isNotEmpty; // 🚪 Logout (clear everything) Future clearAll() async { @@ -178,9 +174,9 @@ class TokenStorageService { } Future saveDecodedSessionData( - Map decodedToken, - String token, - ) async { + Map decodedToken, + String token, + ) async { // Handle allowed_modules safely dynamic allowedModules = decodedToken['allowed_modules']; if (allowedModules is String) { @@ -192,16 +188,13 @@ class TokenStorageService { value: decodedToken['post_branch_id']?.toString()); await _secureStorage.write( - key: 'empPrimaryId', - value: decodedToken['post_hr_id']?.toString()); + key: 'empPrimaryId', value: decodedToken['post_hr_id']?.toString()); await _secureStorage.write( - key: 'empClientId', - value: decodedToken['post_client_id']?.toString()); + key: 'empClientId', value: decodedToken['post_client_id']?.toString()); await _secureStorage.write( - key: 'empHrId', - value: decodedToken['post_hr_id']?.toString()); + key: 'empHrId', value: decodedToken['post_hr_id']?.toString()); await _secureStorage.write( key: 'empAllowed_modules', @@ -222,8 +215,7 @@ class TokenStorageService { value: decodedToken['pre_client_id']?.toString()); await _secureStorage.write( - key: 'enrollmentHrId', - value: decodedToken['pre_hr_id']?.toString()); + key: 'enrollmentHrId', value: decodedToken['pre_hr_id']?.toString()); await _secureStorage.write( key: 'enrollmentAllowed_modules', @@ -271,8 +263,8 @@ class TokenStorageService { } Future resetSessionAndSwitchBranch( - Map newBranch, - ) async { + Map newBranch, + ) async { // 1️⃣ Clear ONLY branch/session related keys await clearBranchSession(); @@ -291,5 +283,4 @@ class TokenStorageService { // 4️⃣ Update in-memory cache _selectedBranch = newBranch; } - } diff --git a/lib/verify.dart b/lib/verify.dart index 767f1ee..52cc60a 100755 --- a/lib/verify.dart +++ b/lib/verify.dart @@ -13,6 +13,7 @@ import 'package:jwt_decode/jwt_decode.dart'; import 'package:nhancepolicy/customAppBar/toastHelper.dart'; import 'config/environment.dart'; +import 'package:nhancepolicy/logger.dart'; class MyVerify extends StatefulWidget { final String verificationId; @@ -59,8 +60,8 @@ class _MyVerifyState extends State { // Start the timer when the widget is initialized verificationId = widget.verificationId; mobileNumber = widget.mobileNumber; - print('Received verificationId: $verificationId'); - print('Received mobileNumber: $mobileNumber'); + logDebug('Received verificationId: $verificationId'); + logDebug('Received mobileNumber: $mobileNumber'); if (verificationId.isEmpty) { // Handle the case where verificationId is not provided Navigator.pop(context); @@ -100,7 +101,7 @@ class _MyVerifyState extends State { } Future resendOTP(String mobileNumber) async { - print(mobileNumber); + logDebug(mobileNumber); // Update the UI as needed setState(() { _secondsRemaining = 30; @@ -112,7 +113,8 @@ class _MyVerifyState extends State { Uri.parse(Environment.apiUrl + 'verifyEmployeeNumber'), body: json.encode({'mobile_number': mobileNumber}), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); @@ -127,7 +129,7 @@ class _MyVerifyState extends State { } } catch (e) { // Handle API call errors - print('Error: $e'); + logDebug('Error: $e'); ToastHelper.showErrorToast( context, 'Failed to resend OTP. Please try again.'); } @@ -144,24 +146,25 @@ class _MyVerifyState extends State { 'otp_verification': otpVerifyStatus }), headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', HttpHeaders.contentTypeHeader: 'application/json', }, ); if (response.statusCode == 200) { Map data = json.decode(response.body); - print(data); + logDebug(data); _token = data['data']; String status = data['status']; - print(status); + logDebug(status); if (status == 'success') { 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); + logDebug(decodedToken); empClientBranchId = decodedToken['client_branch_id']; prefs.setString('empClientBranchId', empClientBranchId); empCodeString = decodedToken['emp_code'].toString(); @@ -175,7 +178,7 @@ class _MyVerifyState extends State { getClientLogoAndDetails(); - print('Successfully Login'); + logDebug('Successfully Login'); // Redirect to another page final token = prefs.getString('token'); @@ -193,19 +196,19 @@ class _MyVerifyState extends State { ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again'); // Show a Snackbar if the OTP is invalid // ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again'); - print('Invalid OTP. Please try again'); + logDebug('Invalid OTP. Please try again'); } } else { ToastHelper.showWarningToast(context, 'Something went wrong'); throw Exception('Failed to verify OTP'); } } catch (e) { - print('Error: $e'); + logDebug('Error: $e'); ToastHelper.showWarningToast(context, 'Something went wrong'); // Show a Snackbar if there's an error while verifying OTP // ToastHelper.showErrorToast( // context, 'Failed to verify OTP. Please try again.'); - print('Failed to verify OTP. Please try again.'); + logDebug('Failed to verify OTP. Please try again.'); } } @@ -238,7 +241,7 @@ class _MyVerifyState extends State { setState(() { _isLoading = false; }); - print('Error: $e'); + logDebug('Error: $e'); ToastHelper.showErrorToast( context, 'Failed to verify OTP. Please try again.'); } @@ -260,15 +263,16 @@ class _MyVerifyState extends State { var response = await http.get( url, headers: { - 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', + 'APP-SIGNATURE': + 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $_token', // Add token to the Authorization header }, ); if (response.statusCode == 200) { - // print('response.statusCode == 200'); + // logDebug('response.statusCode == 200'); Map data = json.decode(response.body); - // print(data); + // logDebug(data); if (data.containsKey('data')) { dynamic clientDetails = data['data']; @@ -277,27 +281,27 @@ class _MyVerifyState extends State { prefs.setString('clientName', clientDetails['client']['client_name']); setState(() { // dynamic clientDetails = data['data']; - // print(clientDetails); + // logDebug(clientDetails); clientName = clientDetails['client']['client_name']; - print(clientName); + logDebug(clientName); clientLogo = clientDetails['client']['client_logo']; - print(clientLogo); + logDebug(clientLogo); }); } else { // Handle other status messages if needed // ToastHelper.showErrorToast( // context, 'API request failed with status: ${data['status']}'); - print('API request failed with status: ${data['status']}'); + logDebug('API request failed with status: ${data['status']}'); } } else { // Handle other status codes // ToastHelper.showErrorToast( // context, 'Request failed with status: ${response.statusCode}'); - print('Request failed with status: ${response.statusCode}'); + logDebug('Request failed with status: ${response.statusCode}'); } } catch (e) { // Handle exceptions - print('Exception occurred: $e'); + logDebug('Exception occurred: $e'); } }