log clear

This commit is contained in:
Surendiran 2026-03-26 09:45:12 +05:30
parent 72b253918a
commit 9a3367e802
47 changed files with 3600 additions and 3416 deletions

File diff suppressed because it is too large Load Diff

View File

@ -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,
),
),
],

View File

@ -33,7 +33,7 @@ class _BranchSelectionPageState extends State<BranchSelectionPage> {
Navigator.pushNamedAndRemoveUntil(
context,
'hrLogin',
(route) => false,
(route) => false,
);
} else {
// Push state back to prevent browser navigation
@ -83,23 +83,23 @@ class _BranchSelectionPageState extends State<BranchSelectionPage> {
Future<bool> _showLogoutDialog() async {
return await showDialog<bool>(
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<BranchSelectionPage> {
);
}
Widget _buildContent(BuildContext context) {
Widget _buildContent(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF5F7F7),
body: LayoutBuilder(
@ -164,8 +164,7 @@ class _BranchSelectionPageState extends State<BranchSelectionPage> {
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<BranchSelectionPage> {
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<BranchSelectionPage> {
},
),
);
}
}
}

View File

@ -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;
}
}
}
}

View File

@ -1,4 +1,3 @@
import '../main.dart';
import 'environment.dart';
@ -6,4 +5,3 @@ Future<void> main() async {
Environment.flavor = Flavor.dev;
await startApp();
}

View File

@ -1,5 +1,3 @@
import '../main.dart';
import 'environment.dart';
@ -7,4 +5,3 @@ Future<void> main() async {
Environment.flavor = Flavor.prod;
await startApp();
}

View File

@ -1,5 +1,3 @@
import '../main.dart';
import 'environment.dart';
@ -7,4 +5,3 @@ Future<void> main() async {
Environment.flavor = Flavor.prod1;
await startApp();
}

View File

@ -1,5 +1,3 @@
import '../main.dart';
import 'environment.dart';
@ -7,4 +5,3 @@ Future<void> main() async {
Environment.flavor = Flavor.uat;
await startApp();
}

View File

@ -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,
),
),
],
),
],
),
) );
));
}
}

View File

@ -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<CustomAppBar> {
// 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<CustomAppBar> {
Navigator.pushNamedAndRemoveUntil(
context,
'branchSelection',
(route) => false,
(route) => false,
);
},
),

View File

@ -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<CustomAppBar> {
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;
});

View File

@ -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<NhanceSideBar> {
List<int> postModules = [];
List<int> enrollmentModules = [];
@override
void initState() {
super.initState();
@ -35,31 +35,26 @@ class _NhanceSideBarState extends State<NhanceSideBar> {
// _checkTokens();
}
Future<void> _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<int>.from(jsonDecode(enrollmentRaw))
: [];
postModules =
postRaw != null && postRaw.isNotEmpty
postModules = postRaw != null && postRaw.isNotEmpty
? List<int>.from(jsonDecode(postRaw))
: [];
print('enrollmentModules $enrollmentModules');
print('postModules $postModules');
logDebug('enrollmentModules $enrollmentModules');
logDebug('postModules $postModules');
final List<Map<String, dynamic>> items = [];
@ -95,13 +90,12 @@ class _NhanceSideBarState extends State<NhanceSideBar> {
});
}
Future<void> 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<NhanceSideBar> {
);
}).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<NhanceSideBar> {
}
}
class _SideItem extends StatelessWidget {
// final IconData icon;
final Widget icon; // 👈 changed
@ -308,5 +301,3 @@ class _SideItem extends StatelessWidget {
);
}
}

View File

@ -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);

View File

@ -42,7 +42,6 @@ class _NhanceTopBarState extends State<NhanceTopBar> {
Navigator.pushReplacementNamed(context, route);
}
@override
Widget build(BuildContext context) {
return AppBar(
@ -53,7 +52,6 @@ class _NhanceTopBarState extends State<NhanceTopBar> {
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<NhanceTopBar> {
);
}
}
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<Map<String, dynamic>>(
@ -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,
),
],
),
),
);
}
}

View File

@ -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<MyEmailVerify> {
void verifyOTP(String otp) async {
try {
final Map<String, dynamic> 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<MyEmailVerify> {
_isLoading = false;
});
Map<String, dynamic> data = json.decode(response.body);
print('Response data: $data');
logDebug('Response data: $data');
final String mainStatus = data['status'] ?? 'failed';
final Map<String, dynamic> 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<MyEmailVerify> {
),
);
}
// print('data: $data');
// logDebug('data: $data');
// _token = data['data'];
// String status = data['status'];
//
// // Directly access the post_enrollment data
// Map<String, dynamic> 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<MyEmailVerify> {
// });
// 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<MyEmailVerify> {
Navigator.pushNamedAndRemoveUntil(
context,
'hrLogin',
(route) => false,
(route) => false,
);
} else if (response.statusCode == 403) {
setState(() {
_isLoading = false;
@ -251,21 +251,20 @@ class _MyEmailVerifyState extends State<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<MyEmailVerify> {
// 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<MyEmailVerify> {
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<MyEmailVerify> {
// 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<MyEmailVerify> {
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
logDebug('Error: $e');
}
}
Future<void> getClientLogoAndDetails(empClientId,empClientBranchId,enrollmentClientId, enrollmentClientBranchId, token) async {
Future<void> 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<String, dynamic> 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<MyEmailVerify> {
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<MyEmailVerify> {
],
),
),
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<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
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<MyEmailVerify> {
],
),
),
)
)
);
)));
}
}

View File

@ -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<empDetails> {
String? getHrToken = prefs.getString('hrtoken');
String? empID = prefs.getString('employee_id');
Map<String, dynamic>? 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<empDetails> {
}
Future<void> _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<empDetails> {
'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<String, dynamic> 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<empDetails> {
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<empDetails> {
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<empDetails> {
// 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<void> _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<empDetails> {
});
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<empDetails> {
}
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<empDetails> {
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<empDetails> {
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<empDetails> {
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<empDetails> {
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<empDetails> {
// 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<empDetails> {
if (response['status'] == 'success') {
setState(() {
gpaPolicies = response['data'];
print('gpaPolicies');
logDebug('gpaPolicies');
});
} else {
setState(() {
@ -424,11 +426,11 @@ class _empDetailsState extends State<empDetails> {
});
// 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<empDetails> {
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<empDetails> {
// 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<empDetails> {
} 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<void> _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<String, dynamic>) {
int min = ageValidation.containsKey('min')
@ -512,17 +514,17 @@ class _empDetailsState extends State<empDetails> {
? 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<empDetails> {
});
}
} else {
print('Invalid age validation data');
logDebug('Invalid age validation data');
}
}
Future<void> deleteItem(Map<String, dynamic> 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<empDetails> {
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<String, dynamic> formData,
Map<String, dynamic> 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<empDetails> {
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<empDetails> {
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<String, dynamic> before passing it
if (details is Map<String, dynamic>) {
Navigator.pushNamed(context, 'hrPolicyDetails', arguments: details);
} else {
print('Error: Decoded details is not a Map<String, dynamic>.');
logDebug('Error: Decoded details is not a Map<String, dynamic>.');
}
} 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<empDetails> {
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<empDetails> {
}
void openForm(Map<String, dynamic> 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<empDetails> {
_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<Map<String, dynamic>> getTrueDataObjects = getTrueObjects
.map<Map<String, dynamic>>(
(element) => element['data'] as Map<String, dynamic>)
.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<empDetails> {
Future<void> _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<empDetails> {
List<Widget> 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<empDetails> {
List<Widget> 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<empDetails> {
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'];

View File

@ -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<empReviewDetails> {
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<empReviewDetails> {
if (prefs.containsKey('siData')) {
activeSiData = 1;
String? siDataJson = prefs.getString('siData');
print('siDataJson');
print(siDataJson);
logDebug('siDataJson');
logDebug(siDataJson);
List<dynamic> siDataList = jsonDecode(siDataJson!);
if (siDataList.isNotEmpty) {
@ -221,8 +222,8 @@ class _empReviewDetailsState extends State<empReviewDetails> {
if (prefs.containsKey('siParentData')) {
activeSiParentData = 1;
String? siParentDataJson = prefs.getString('siParentData');
print('siParentDataJson');
print(siParentDataJson);
logDebug('siParentDataJson');
logDebug(siParentDataJson);
List<dynamic> siParentDataList = jsonDecode(siParentDataJson!);
if (siParentDataList.isNotEmpty) {
@ -238,8 +239,8 @@ class _empReviewDetailsState extends State<empReviewDetails> {
if (prefs.containsKey('dependentData')) {
activeDependentData = 1;
String? dependentDataJson = prefs.getString('dependentData');
print('dependentDataJson');
print(dependentDataJson);
logDebug('dependentDataJson');
logDebug(dependentDataJson);
List<dynamic> dependentDataList = jsonDecode(dependentDataJson!);
if (dependentDataList.isNotEmpty) {
@ -269,7 +270,7 @@ class _empReviewDetailsState extends State<empReviewDetails> {
totalPayableAmt += addOnsDependentTotalAmt;
// Print or use the totalAmtSum value
print('Sum of Total Amounts: $totalPayableAmt');
logDebug('Sum of Total Amounts: $totalPayableAmt');
}
Future<void> getClientLogoAndDetails() async {
@ -284,22 +285,22 @@ class _empReviewDetailsState extends State<empReviewDetails> {
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<empReviewDetails> {
if (response['status'] == 'success') {
setState(() {
gpaPolicies = response['data'];
print('gpaPolicies');
logDebug('gpaPolicies');
});
} else {
setState(() {
@ -335,11 +336,11 @@ class _empReviewDetailsState extends State<empReviewDetails> {
});
// 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<empReviewDetails> {
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<empReviewDetails> {
// 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<empReviewDetails> {
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<empReviewDetails> {
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<empReviewDetails> {
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<empReviewDetails> {
} 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<empReviewDetails> {
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<empReviewDetails> {
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<empReviewDetails> {
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<empReviewDetails> {
} 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<empReviewDetails> {
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<empReviewDetails> {
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<empReviewDetails> {
} 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<empReviewDetails> {
.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<empReviewDetails> {
.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<empReviewDetails> {
.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<empReviewDetails> {
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<String, dynamic> 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<empReviewDetails> {
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<empReviewDetails> {
// 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<empReviewDetails> {
Future<void> _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<empReviewDetails> {
List<Widget> 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<empReviewDetails> {
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(

View File

@ -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<MyApp> {
});
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<MyApp> {
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<MyApp> {
.where((obj) => obj['relationship'] != 'Self')
.toList();
nonSelfObjectsArrayDetails = nonSelfObjects;
print(nonSelfObjectsArrayDetails);
logDebug(nonSelfObjectsArrayDetails);
List<FamilyMember> familyMembersFromDetails =
nonSelfObjects.map((detail) {
return FamilyMember(
@ -174,7 +176,7 @@ class _MyAppState extends State<MyApp> {
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<MyApp> {
_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<MyApp> {
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<MyApp> {
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<MyApp> {
gpaSelectedSI =
gpaMappedFamilyFloaters['basic_cover_si'].toString();
print(gpasumInsured);
logDebug(gpasumInsured);
//find the premium amount that match sumInsured amount from policyTerm
Map<String, dynamic>? 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<MyApp> {
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<MyApp> {
(rate) => rate['si'] == gpaAssignSelectedSI.toString(),
orElse: () => null,
);
print(findObject);
logDebug(findObject);
// setState(() {
gpaAPISIDetails = findObject;
@ -327,84 +330,84 @@ class _MyAppState extends State<MyApp> {
} 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<MyApp> {
(rate) => rate['si'] == gpaSelectedSI.toString(),
orElse: () => null,
);
print(findObject);
logDebug(findObject);
// setState(() {
gpaAPISIDetails = findObject;
@ -425,29 +428,29 @@ class _MyAppState extends State<MyApp> {
} 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<MyApp> {
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<MyApp> {
} 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<MyApp> {
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<MyApp> {
} 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<MyApp> {
}
// 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<MyApp> {
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<MyApp> {
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<MyApp> {
}
} 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<Map<String, dynamic>> 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<MyApp> {
'client_id': personalDetails['client_id'],
};
}).toList();
print(membersData);
logDebug(membersData);
List<Map<String, dynamic>> updatedNewData =
List<Map<String, dynamic>>.generate(membersData.length, (index) {
@ -625,7 +631,7 @@ class _MyAppState extends State<MyApp> {
}
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<MyApp> {
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<MyApp> {
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<MyApp> {
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<MyApp> {
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<MyApp> {
});
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<MyApp> {
// Create a list to store the selected values for each floater
List<Map<String, String>> 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<MyApp> {
}
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<MyApp> {
}
}
}
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<MyApp> {
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<MyApp> {
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");
// }
}

View File

@ -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<MyHrHome> 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<String, dynamic> data = json.decode(response.body);
if (data['status'] == 'success') {
print(data);
logDebug(data);
setState(() {
dataPolicy = List<Map<String, dynamic>>.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<MyHrHome> 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<MyHrHome> 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<MyHrHome> with TickerProviderStateMixin {
List<Map<String, dynamic>>.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<MyHrHome> 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<MyHrHome> 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<MyHrHome> 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<MyHrHome> 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<MyHrHome> 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<MyHrHome> 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<MyHrHome> 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<MyHrHome> 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']});
}

View File

@ -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<MyHrLogin> {
@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<MyHrLogin> {
Future<void> 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<MyHrLogin> {
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<MyHrLogin> {
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<MyHrLogin> {
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<MyHrLogin> {
_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<MyHrLogin> {
_isLoading = false;
});
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
logDebug('Error: $e');
}
}
// Future<void> _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<MyHrLogin> {
// // });
// },
// 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<MyHrLogin> {
// },
// 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<MyHrLogin> {
],
),
),
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<MyHrLogin> {
),
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<MyHrLogin> {
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<MyHrLogin> {
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<MyHrLogin> {
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<MyHrLogin> {
// ---------------------------
// 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<MyHrLogin> {
}
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<MyHrLogin> {
: 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>(
Color(0xFF00989E),
),
)
: Text(
"Login with Email / Mobile OTP",
style: GoogleFonts.poppins(
color: const Color(0xFFFFFFFF),
),
),
),
),
),
@ -521,7 +524,8 @@ class _MyPhoneState extends State<MyHrLogin> {
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<MyHrLogin> {
'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<MyHrLogin> {
'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<MyHrLogin> {
],
),
),
)
)
);
)));
}
}

View File

@ -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<String, dynamic> data = json.decode(response.body);
//
// print('Response data: $data');
// logDebug('Response data: $data');
//
// // Extract enrollment data
// List<dynamic> 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<String, dynamic> 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<String, dynamic>? 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<String, dynamic>? 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<String, dynamic>? 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.');
// }

111
lib/logger.dart Normal file
View File

@ -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 = <String>[];
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,
);
}

View File

@ -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<void> 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<String, WidgetBuilder> 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<String, WidgetBuilder> 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<String, WidgetBuilder> 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<AuthWrapper> {
if (token == null || token.isEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) {
Navigator.pushNamedAndRemoveUntil(
context, 'hrLogin', (route) => false);
Navigator.pushNamedAndRemoveUntil(context, 'hrLogin', (route) => false);
});
}
}

View File

@ -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<oldPolicy> {
}
Future<void> _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<oldPolicy> {
});
// Decode the JWT token received from the API response
Map<String, dynamic>? 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<oldPolicy> {
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<oldPolicy> {
// 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<oldPolicy> {
// 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<oldPolicy> {
List<Widget> generateGmcCards(List<dynamic> data) {
List<Widget> cards = [];
print('data');
print(data);
logDebug('data');
logDebug(data);
for (var item in data) {
setState(() {

View File

@ -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<MyPhone> {
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<MyPhone> {
// 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<MyPhone> {
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
logDebug('Error: $e');
}
}
Future<void> _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<MyPhone> {
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<MyPhone> {
},
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) {

File diff suppressed because it is too large Load Diff

View File

@ -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<CdPoliciesList> createState() => _CdPoliciesListState();
}
class _CdPoliciesListState extends State<CdPoliciesList> {
final tokenService = TokenStorageService();
Uint8List? fileBytes;
@ -55,11 +54,10 @@ class _CdPoliciesListState extends State<CdPoliciesList> {
List<dynamic> 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<CdPoliciesList> {
}
Future<void> 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<void> 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<CdPoliciesList> {
getCDPolicies = List<Map<String, dynamic>>.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<CdPoliciesList> {
// 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<CdPoliciesList> {
}
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<CdPoliciesList> {
// 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<CdPoliciesList> {
}).toList();
});
}
print(filteredData.length);
logDebug(filteredData.length);
}
void exportToCsv(List<Map<String, dynamic>> data) {
@ -185,51 +184,51 @@ class _CdPoliciesListState extends State<CdPoliciesList> {
}
Future<void> 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<bool> _showLogoutDialog() async {
return await showDialog<bool>(
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<CdPoliciesList> {
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<CdPoliciesList> {
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<CdPoliciesList> {
);
}
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<CdPoliciesList> {
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<CdPoliciesList> {
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<CdPoliciesList> {
},
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 {
);
}
}

View File

@ -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<cdTransactionDetails> createState() => _cdTransactionDetailsState();
}
class _cdTransactionDetailsState extends State<cdTransactionDetails> {
String? localInsurerId;
String? localCdAcPk;
String? localEmpClientId;
String? localInsurerName;
String? localCdMasterAccountNo;
final tokenService = TokenStorageService();
Uint8List? fileBytes;
List<Map<String, dynamic>> getCDTransData = [];
@ -60,9 +59,11 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
// List<dynamic> dataPolicy = [];
List<dynamic> reversedDataPolicy = [];
List<Map<String, dynamic>> originalData = []; // Original data source
List<Map<String, dynamic>> originalEndorsementData = []; // Original data source
List<Map<String, dynamic>> originalEndorsementData =
[]; // Original data source
List<Map<String, dynamic>> filteredData = []; // Filtered data source
List<Map<String, dynamic>> filteredEndorsementData = []; // Filtered data source
List<Map<String, dynamic>> filteredEndorsementData =
[]; // Filtered data source
List<Map<String, dynamic>> getCDTransDataAmount = []; // Filtered data source
dynamic argumentsData;
dynamic policyType;
@ -94,7 +95,6 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
apiService = ApiService(context); // Initialize ApiService here
restoreTransactionData();
}
@override
@ -102,8 +102,6 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
super.dispose();
}
// downloadPolicyFiles?file_id=13
// getPolicyAndEndorsementFiles?cd_ac_pk=12
@ -128,9 +126,9 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
? 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<cdTransactionDetails> {
}
Future<void> 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<cdTransactionDetails> {
// 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<cdTransactionDetails> {
// 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<cdTransactionDetails> {
Future<void> _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<cdTransactionDetails> {
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<cdTransactionDetails> {
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<cdTransactionDetails> {
}
} else {
ToastHelper.showErrorToast(context, 'Failed to download');
print("Download failed with status: ${response.statusCode}");
logDebug("Download failed with status: ${response.statusCode}");
}
}
Future<void> 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<Map<String, dynamic>>.from(response['data']);
getCDEndorsementData =
List<Map<String, dynamic>>.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<Map<String, dynamic>>.from(response['data']);
if (getCDEndorsementData == null || getCDEndorsementData.isEmpty || getCDEndorsementData == null || (getCDEndorsementData as List).isEmpty) {
getCDEndorsementData =
List<Map<String, dynamic>>.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<cdTransactionDetails> {
),
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<cdTransactionDetails> {
);
}
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<cdTransactionDetails> {
}).toList();
});
}
print(filteredData.length);
logDebug(filteredData.length);
}
void exportToCsv(List<Map<String, dynamic>> data) {
@ -497,31 +499,31 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
}
Future<void> 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<cdTransactionDetails> {
Future<void> _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<bool> _showLogoutDialog() async {
return await showDialog<bool>(
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<cdTransactionDetails> {
return amount.round().toString();
}
@override
Widget build(BuildContext context) {
return BaseLayout(
@ -607,141 +608,140 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
}
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<cdTransactionDetails> {
/// 📄 TABLE ROWS
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
(context, index) {
final item = _paginatedData[index];
return _buildCDRow(item);
},
@ -831,9 +831,8 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
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<cdTransactionDetails> {
_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<cdTransactionDetails> {
// ),
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<cdTransactionDetails> {
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
/// --- PDF ICON SLOT ---
SizedBox(
width: 36,
@ -987,7 +981,8 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
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<cdTransactionDetails> {
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<cdTransactionDetails> {
/// --- RIGHT SIDE: CONTROLS ---
Row(
children: [
DropdownButton<int>(
value: _rowsPerPage,
items: [5, 10, 15, 20, 50].map((int value) {
@ -1211,7 +1206,7 @@ class _cdTransactionDetailsState extends State<cdTransactionDetails> {
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<cdTransactionDetails> {
),
);
}
}
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;

File diff suppressed because it is too large Load Diff

View File

@ -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<ClaimHistoryPopup>
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<ClaimHistoryPopup>
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<ClaimHistoryPopup>
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<ClaimHistoryPopup>
})
.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<ClaimHistoryPopup>
});
} 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<ClaimHistoryPopup>
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<ClaimHistoryPopup>
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<ClaimHistoryPopup>
// -------------------------
// 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<ClaimHistoryPopup>
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<ClaimHistoryPopup>
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,
),
),
),
),
),
],
),
),

View File

@ -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<excelErrorScreen>
List<List<Map<String, dynamic>>> 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<excelErrorScreen>
super.dispose();
}
Future<void> getCDPoliciesDetails() async {
setState(() {
isLoading = true;
@ -103,7 +102,7 @@ class _activePolicyExcelErrorState extends State<excelErrorScreen>
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<excelErrorScreen>
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<String>.from(response['data']['excel_header']);
excelHeader = List<String>.from(response['data']['excel_header']);
excelData = (response['data']['excel_data'] as List)
.map<List<Map<String, dynamic>>>(
(row) => row
.map<Map<String, dynamic>>(
(cell) => Map<String, dynamic>.from(cell))
.toList(),
)
.map<Map<String, dynamic>>(
(cell) => Map<String, dynamic>.from(cell))
.toList(),
)
.toList();
filteredExcelData = List.from(excelData);
@ -148,15 +144,13 @@ class _activePolicyExcelErrorState extends State<excelErrorScreen>
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<excelErrorScreen>
);
}
void search(String query) {
if (query.isEmpty) {
setState(() {
@ -246,9 +239,8 @@ class _activePolicyExcelErrorState extends State<excelErrorScreen>
html.Url.revokeObjectUrl(url);
}
// Future<void> 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<excelErrorScreen>
// 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<excelErrorScreen>
// }
//
// 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<excelErrorScreen>
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<excelErrorScreen>
excelHeader: excelHeader,
excelData: filteredExcelData, // or excelData
);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFE26728),
@ -446,7 +436,6 @@ class _activePolicyExcelErrorState extends State<excelErrorScreen>
Expanded(
child: _buildCDDataTable(context),
),
],
),
);
@ -499,8 +488,7 @@ class _activePolicyExcelErrorState extends State<excelErrorScreen>
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<excelErrorScreen>
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<excelErrorScreen>
);
}
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<excelErrorScreen>
});
},
),
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<excelErrorScreen>
? 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<excelErrorScreen>
child: Text(i.toString()),
),
),
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: _currentPage < totalPages
@ -769,6 +799,4 @@ class _activePolicyExcelErrorState extends State<excelErrorScreen>
],
);
}
}

View File

@ -18,7 +18,8 @@ class hrDashboard extends StatefulWidget {
State<hrDashboard> createState() => _hrDashboardState();
}
class _hrDashboardState extends State<hrDashboard> with SingleTickerProviderStateMixin {
class _hrDashboardState extends State<hrDashboard>
with SingleTickerProviderStateMixin {
late ApiService apiService;
bool isLoading = false;
String? selectedPolicyId;
@ -67,7 +68,9 @@ class _hrDashboardState extends State<hrDashboard> with SingleTickerProviderStat
? List<int>.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<hrDashboard> 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<void> getPostCashDepositDetails(branchId, clientId, hrId, token) async {
Future<void> getPostCashDepositDetails(
branchId, clientId, hrId, token) async {
setState(() => isLoading = true);
try {
if (branchId == null || clientId == null) return;
@ -89,7 +94,8 @@ class _hrDashboardState extends State<hrDashboard> with SingleTickerProviderStat
if (response['status'] == 'success') {
final list = List<Map<String, dynamic>>.from(response['data']);
final List<Map<String, dynamic>> 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<hrDashboard> with SingleTickerProviderStat
isTpaSelected = false;
});
_registerMetabaseIframe(
token: response['data']['metabaseToken'],
url: response['data']['metabaseUrl'],
@ -173,9 +178,9 @@ class _hrDashboardState extends State<hrDashboard> 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<bool> _showLogoutDialog() async {
return await showDialog<bool>(
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;
}
}
}

View File

@ -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<hrPolicyDetails>
with TickerProviderStateMixin {
String? localClientId;
String? localPolicyTypeId;
String? localClientPolicyId;
@ -146,11 +146,11 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
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<hrPolicyDetails>
// 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<hrPolicyDetails>
? 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<hrPolicyDetails>
// }
Future<void> 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<int>? moduleList = modulesString
@ -293,10 +292,16 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
}
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<hrPolicyDetails>
getCDPolicies = List<Map<String, dynamic>>.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<hrPolicyDetails>
// 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<hrPolicyDetails>
}
Future<void> 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<int>? moduleList = modulesString
@ -353,36 +358,41 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
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<Map<String, dynamic>>.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<Map<String, dynamic>>.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<hrPolicyDetails>
}
}
} 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<hrPolicyDetails>
'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<void> _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<hrPolicyDetails>
} 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<hrPolicyDetails>
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<hrPolicyDetails>
}
Future<void> 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<hrPolicyDetails>
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<hrPolicyDetails>
}
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<hrPolicyDetails>
Future<void> 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<hrPolicyDetails>
),
),
if (localIsEcardBulkDownload ==
1) ...[
if (localIsEcardBulkDownload == 1) ...[
const SizedBox(width: 12),
SizedBox(
width: 40,
@ -800,23 +801,44 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
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<hrPolicyDetails>
// ---------------- 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<hrPolicyDetails>
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<hrPolicyDetails>
),
child: Row(
children: [
/// NAME
Expanded(
flex: 3,
@ -1428,8 +1447,7 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
),
/// 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<hrPolicyDetails>
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<hrPolicyDetails>
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<hrPolicyDetails>
/// 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<hrPolicyDetails>
// );
//
// 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<hrPolicyDetails>
// // GestureDetector(
// // onTap: () {
// // setState(() {
// // print(
// // logDebug(
// // "policytabdata - ${item['emp_code']!}");
// // Navigator.push(
// // context,
@ -2189,7 +2203,8 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
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<hrPolicyDetails>
totalPages
];
}
return [
_currentPage - 2,
_currentPage - 1,
_currentPage,
_currentPage + 1,
_currentPage + 2,
];
return [
_currentPage - 2,
_currentPage - 1,
_currentPage,
_currentPage + 1,
_currentPage + 2,
];
}
List<int> visiblePages = getVisiblePages();
@ -2229,7 +2243,8 @@ class _HrPolicyDetailsState extends State<hrPolicyDetails>
// 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<hrPolicyDetails>
Row(
children: [
// Dropdown for rows per page
DropdownButton<int>(
value: _rowsPerPage,
focusColor: Colors.transparent, // Fix: Removes the grey/blue highlight on change
items: [5, 10, 15, 20, 50].map((int value) {
return DropdownMenuItem<int>(
value: value,
child: Text(' $value ',
style: GoogleFonts.poppins(fontSize: 15)),
);
}).toList(),
onChanged: (newValue) {
setState(() {
_rowsPerPage = newValue!;
_currentPage = 1;
});
},
),
DropdownButton<int>(
value: _rowsPerPage,
focusColor: Colors
.transparent, // Fix: Removes the grey/blue highlight on change
items: [5, 10, 15, 20, 50].map((int value) {
return DropdownMenuItem<int>(
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<hrPolicyDetails>
);
}
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;
}
}

View File

@ -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<policies> createState() => _policiesState();
}
class _policiesState extends State<policies>
with SingleTickerProviderStateMixin {
late ApiService apiService;
@ -61,7 +61,6 @@ class _policiesState extends State<policies>
List<int> postModules = [];
List<int> enrollmentModules = [];
@override
void initState() {
super.initState();
@ -93,14 +92,14 @@ class _policiesState extends State<policies>
// 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<policies>
// ? List<int>.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<policies>
Future<void> _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<int>.from(jsonDecode(enrollmentRaw))
@ -171,11 +169,10 @@ class _policiesState extends State<policies>
/// 👇 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<policies>
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<policies>
/// 🔥 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<policies>
Future<void> 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<policies>
// 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<Map<String, dynamic>>.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<void> 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<policies>
// 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<Map<String, dynamic>>.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<policies>
false;
}
Future<void> 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<policies>
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<policies>
);
}
@override
Widget build(BuildContext context) {
return BaseLayout(
@ -411,157 +406,159 @@ class _policiesState extends State<policies>
required List<Map<String, dynamic>> openEnrollment,
required List<Map<String, dynamic>> 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 dont 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 dont 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<Map<String, dynamic>> 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 {
),
],
),
)
)
);
)));
}
}

View File

@ -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<postFileUpload> {
final tokenService = TokenStorageService();
String localClientId = '';
String localPolicyTypeId = '';
String localClientPolicyId = '';
@ -75,8 +75,6 @@ class _postFileUploadState extends State<postFileUpload> {
String localCardPolicyExpDate = '';
String localTotalPremium = '';
Uint8List? fileBytes;
Uint8List? fileBytes2;
late String _token;
@ -145,7 +143,6 @@ class _postFileUploadState extends State<postFileUpload> {
getFileUploadMasterDetails();
getFileListDetails();
});
}
@override
@ -253,9 +250,9 @@ class _postFileUploadState extends State<postFileUpload> {
// 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<postFileUpload> {
// }
Future<void> 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<String, String>.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<postFileUpload> {
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<Map<String, dynamic>>.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<postFileUpload> {
Future<void> 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<postFileUpload> {
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<postFileUpload> {
}
} else {
ToastHelper.showErrorToast(context, 'Failed to download');
print("Download failed with status: ${response.statusCode}");
logDebug("Download failed with status: ${response.statusCode}");
}
}
Future<void> 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<postFileUpload> {
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<postFileUpload> {
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<postFileUpload> {
// 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<postFileUpload> {
});
} 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<postFileUpload> {
// // 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<postFileUpload> {
}
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<postFileUpload> {
);
// Handle response as needed
print(response.responseText);
logDebug(response.responseText);
}
Future<void> sendExcelFIleTOAPI(Uint8List fileBytes, fileName) async {
@ -539,24 +536,24 @@ class _postFileUploadState extends State<postFileUpload> {
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<postFileUpload> {
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<postFileUpload> {
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<postFileUpload> {
// "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<String, dynamic> 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<postFileUpload> {
}
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<postFileUpload> {
}).toList();
});
}
print(filteredData.length);
logDebug(filteredData.length);
}
@override
@ -696,24 +693,47 @@ class _postFileUploadState extends State<postFileUpload> {
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<postFileUpload> {
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<postFileUpload> {
// 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<postFileUpload> {
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<html.File>(
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<html.File>(
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<postFileUpload> {
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<String, dynamic> item) {
@ -1159,7 +1177,7 @@ class _postFileUploadState extends State<postFileUpload> {
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<postFileUpload> {
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 ||

View File

@ -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<preFileUpload> {
// 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<preFileUpload> {
// }
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<preFileUpload> {
// 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<preFileUpload> {
});
} 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<preFileUpload> {
} 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<List<Data>> 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<preFileUpload> {
"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<preFileUpload> {
// Placeholder function for decoding Excel data
List<List<Data>> 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<preFileUpload> {
// // 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<preFileUpload> {
}
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<preFileUpload> {
);
// Handle response as needed
print(response.responseText);
logDebug(response.responseText);
}
void _retrieveAndUploadFile() {
@ -544,23 +545,23 @@ class _excelVerifyState extends State<preFileUpload> {
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<preFileUpload> {
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<preFileUpload> {
// } 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<String, dynamic> 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<preFileUpload> {
getFileListDetails();
});
// ToastHelper.showErrorToast(context, data['message']);
print('Table');
logDebug('Table');
}
} else {
setState(() {
@ -630,38 +631,38 @@ class _excelVerifyState extends State<preFileUpload> {
// 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<void> 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<preFileUpload> {
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<Map<String, dynamic>>.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<preFileUpload> {
// Future<void> 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<void> _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<preFileUpload> {
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<preFileUpload> {
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<preFileUpload> {
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<preFileUpload> {
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<preFileUpload> {
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<preFileUpload> {
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 ||

View File

@ -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) {

View File

@ -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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> getExcelFileErrorsApi(id,type) async {
print(_token);
Future<Map<String, dynamic>> 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<Map<String, dynamic>> removeAddonsGmcDependentToAPI(
String empCodeString, String addOnsDependentClientPolicyId) async {
print(_token);
logDebug(_token);
if (_token == null) {
await _initializeToken();
}
@ -218,7 +219,7 @@ class ApiService {
Future<Map<String, dynamic>> removeAddonsGmcSiToAPI(
String empCodeString, String topUpClientPolicyId) async {
print(_token);
logDebug(_token);
if (_token == null) {
await _initializeToken();
}
@ -233,7 +234,7 @@ class ApiService {
Future<Map<String, dynamic>> removeAddonsGmcParentSiToAPI(
String empCodeString, String topUpParentClientPolicyId) async {
print(_token);
logDebug(_token);
if (_token == null) {
await _initializeToken();
}
@ -247,7 +248,7 @@ class ApiService {
}
Future<Map<String, dynamic>> deleteItemToApi(id) async {
print(_token);
logDebug(_token);
if (_token == null) {
await _initializeToken();
}
@ -261,7 +262,7 @@ class ApiService {
Future<Map<String, dynamic>> saveFamilyMemberDetailsToApi(
List<Map<String, dynamic>> formDataList) async {
print('saveFamilyMemberDetailsToApi API SERVICE');
logDebug('saveFamilyMemberDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -282,7 +283,7 @@ class ApiService {
Future<Map<String, dynamic>> saveAddOnsDetailsToApi(
List<Map<String, dynamic>> formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -303,7 +304,7 @@ class ApiService {
Future<Map<String, dynamic>> sendAddonsGmcDependentToAPI(
List<Map<String, dynamic>> formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -325,7 +326,7 @@ class ApiService {
Future<Map<String, dynamic>> sendAddonsGmcSiToAPI(
List<Map<String, dynamic>> formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -347,7 +348,7 @@ class ApiService {
Future<Map<String, dynamic>> sendAddonsGmcParentSiToAPI(
List<Map<String, dynamic>> formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -369,7 +370,7 @@ class ApiService {
Future<Map<String, dynamic>> sendAddOnToAPI(
Map<String, dynamic> formData) async {
print('sendAddOnToAPI API SERVICE');
logDebug('sendAddOnToAPI API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -389,7 +390,7 @@ class ApiService {
}
Future<Map<String, dynamic>> topUpSiCalculationToAPI(formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -410,7 +411,7 @@ class ApiService {
Future<Map<String, dynamic>> topUpParentSiCalculationToAPI(
formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -431,7 +432,7 @@ class ApiService {
Future<Map<String, dynamic>> addOnsDependentCalculationToAPI(
formDataList) async {
print('saveAddOnsDetailsToApi API SERVICE');
logDebug('saveAddOnsDetailsToApi API SERVICE');
if (_token == null) {
await _initializeToken();
}
@ -454,8 +455,8 @@ class ApiService {
Future<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> getEcardBulkDownloadApi(client_policy_id,empHrId,emp_policy_ids,String token) async {
Future<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> postHrDashboard(params,token) async {
Future<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> getClaimPoliciesToApi(String token,empClientId) async {
print("getgetClaimPoliciesToApii1");
final url = Uri.parse('${Environment.apiUrlPost}claimsSearch?client_id=$empClientId');
Future<Map<String, dynamic>> 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<Map<String, dynamic>> getClaimPoliciesFileDownload(id,String token) async {
Future<Map<String, dynamic>> getClaimPoliciesFileDownload(
id, String token) async {
final url = Uri.parse('${Environment.apiUrlPost}hrFileDownload?id=$id');
final headers = {
@ -724,11 +732,12 @@ class ApiService {
Future<Map<String, dynamic>> getClaimPoliciesListDataToApi(
String token, Map<String, dynamic> 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<Map<String, dynamic>> getEcardRequest(eCardParam,String token) async {
Future<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> getOpenEndorsementFileData(id, String token) async {
print("getPolicyAndEndorsementFiles");
final url = Uri.parse(
'${Environment.apiUrlPost}downloadPolicyFiles?file_id=$id');
Future<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> 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<Map<String, dynamic>> getFileListToApi(empPrimaryId,cardPolicyNo,empClientId,String token,String type) async {
print(_hrtoken);
Future<Map<String, dynamic>> 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<Map<String, dynamic>> getHrFileDownloadToApi(id,String token) async {
// print(_hrtoken);
// logDebug(_hrtoken);
// if (token == null) {
// await _initializeToken();
// }
@ -885,7 +897,7 @@ class ApiService {
Future<Map<String, dynamic>> 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<Map<String, dynamic>> _makePostRequestWithoutFormData(
Uri url, String body, Map<String, String> 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<Map<String, dynamic>> _makeGetRequest(
Uri url, Map<String, String> 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<Map<String, dynamic>> _makePostRequest(
Uri url, String body, Map<String, String> 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,
);
}
}

View File

@ -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();

View File

@ -76,7 +76,7 @@
// apiService = ApiService(context);
// _loadData();
//
// print("_PreEnrollmentState 1");
// logDebug("_PreEnrollmentState 1");
// }
//
// Future<void> _loadData() async {
@ -86,12 +86,12 @@
//
// Future<void> 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<Map<String, dynamic>>.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<String, dynamic> 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(

View File

@ -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<CdPolicies> {
}
Future<void> 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<CdPolicies> {
getCDPolicies = List<Map<String, dynamic>>.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<CdPolicies> {
// 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<CdPolicies> {
}
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<CdPolicies> {
}).toList();
});
}
print(filteredData.length);
logDebug(filteredData.length);
}
void exportToCsv(List<Map<String, dynamic>> data) {
@ -188,29 +189,29 @@ class _CdPolicieState extends State<CdPolicies> {
}
Future<void> 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<CdPolicies> {
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<CdPolicies> {
_currentPage + 1,
_currentPage + 2,
];
}
List<int> visiblePages = getVisiblePages();
@ -595,7 +596,8 @@ class _CdPolicieState extends State<CdPolicies> {
// 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(

View File

@ -75,7 +75,7 @@
// apiService = ApiService(context);
// _loadData();
//
// print("_PreEnrollmentState 1");
// logDebug("_PreEnrollmentState 1");
// }
//
// Future<void> _loadData() async {
@ -85,12 +85,12 @@
//
// Future<void> 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<Map<String, dynamic>>.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(

View File

@ -19,7 +19,8 @@ class _MultiFileUploadWidgetState extends State<MultiFileUploadWidget> {
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<MultiFileUploadWidget> {
// ),
// ),
],
if (MultiFileUploadWidget.showValidation &&
fileService.files.isEmpty &&
errorMessage == null) ...[
@ -187,7 +187,6 @@ class _MultiFileUploadWidgetState extends State<MultiFileUploadWidget> {
style: TextStyle(color: Colors.red, fontSize: 12),
),
],
if (errorMessage != null) ...[
const SizedBox(height: 4),
Text(
@ -195,7 +194,6 @@ class _MultiFileUploadWidgetState extends State<MultiFileUploadWidget> {
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<MultiFileUploadWidget> {
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<MultiFileUploadWidget> {
),
),
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(

View File

@ -57,29 +57,29 @@ class _SecurePopScopeState extends State<SecurePopScope> {
Navigator.pushNamedAndRemoveUntil(
context,
'hrLogin',
(route) => false,
(route) => false,
);
}
Future<bool> _showLogoutDialog() async {
return await showDialog<bool>(
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;
}

View File

@ -38,7 +38,6 @@ class SvgService {
</svg>
''';
static String getSvg(String svgName) {
switch (svgName) {
case 'dashboard':

View File

@ -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<void> saveEnrollmentData(
List<dynamic> preData,
List<dynamic> postData,
) async {
List<dynamic> preData,
List<dynamic> 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<void> saveSelectedBranch(
Map<String, dynamic> branch) async {
Future<void> saveSelectedBranch(Map<String, dynamic> 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<void> clearAll() async {
@ -178,9 +174,9 @@ class TokenStorageService {
}
Future<void> saveDecodedSessionData(
Map<String, dynamic> decodedToken,
String token,
) async {
Map<String, dynamic> 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<void> resetSessionAndSwitchBranch(
Map<String, dynamic> newBranch,
) async {
Map<String, dynamic> newBranch,
) async {
// 1 Clear ONLY branch/session related keys
await clearBranchSession();
@ -291,5 +283,4 @@ class TokenStorageService {
// 4 Update in-memory cache
_selectedBranch = newBranch;
}
}

View File

@ -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<MyVerify> {
// 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<MyVerify> {
}
Future<void> resendOTP(String mobileNumber) async {
print(mobileNumber);
logDebug(mobileNumber);
// Update the UI as needed
setState(() {
_secondsRemaining = 30;
@ -112,7 +113,8 @@ class _MyVerifyState extends State<MyVerify> {
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<MyVerify> {
}
} 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<MyVerify> {
'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<String, dynamic> 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<String, dynamic>? 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<MyVerify> {
getClientLogoAndDetails();
print('Successfully Login');
logDebug('Successfully Login');
// Redirect to another page
final token = prefs.getString('token');
@ -193,19 +196,19 @@ class _MyVerifyState extends State<MyVerify> {
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<MyVerify> {
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<MyVerify> {
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<String, dynamic> 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<MyVerify> {
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');
}
}