API_SECURITY

This commit is contained in:
venbaittech 2025-10-08 11:37:26 +05:30
parent f0a0eb3c1d
commit 030d1487a6
78 changed files with 2857 additions and 17682 deletions

View File

@ -231,6 +231,11 @@ class _ListAllPlansState extends State<ListAllPlans> {
// List<dynamic> plansJson = []; // List<dynamic> plansJson = [];
List<dynamic> plansJson = data['data']; List<dynamic> plansJson = data['data'];
return plansJson.map((json) => Plan.fromJson(json)).toList(); return plansJson.map((json) => Plan.fromJson(json)).toList();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -264,6 +269,11 @@ class _ListAllPlansState extends State<ListAllPlans> {
print("Plan Deleted successfully!"); print("Plan Deleted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
initializeData(); initializeData();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -281,7 +291,10 @@ class _ListAllPlansState extends State<ListAllPlans> {
if (confirmed) { if (confirmed) {
try { try {
Map<String, dynamic> planData = await ApiService.getViewPlan(planId); Map<String, dynamic> planData = await ApiService().getViewPlan(
planId,
context,
);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
refresh(); refresh();
// postPlanData(planData, planId); // postPlanData(planData, planId);
@ -321,6 +334,11 @@ class _ListAllPlansState extends State<ListAllPlans> {
approverData = List<Map<String, dynamic>>.from( approverData = List<Map<String, dynamic>>.from(
data['data']['approver_data'] ?? [], data['data']['approver_data'] ?? [],
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print('Failed to load'); print('Failed to load');
label = "Error - Failed to load data"; label = "Error - Failed to load data";
@ -1071,7 +1089,7 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); // Close popup manually ); // Close popup manually
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1095,7 +1113,7 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1137,6 +1155,7 @@ class _ListAllPlansState extends State<ListAllPlans> {
); );
apiService apiService
.getPdfDownload( .getPdfDownload(
context,
plan.planId, plan.planId,
); );
}, },
@ -1162,8 +1181,8 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getForexPdfDownload(
.getForexPdfDownload( context,
plan.forexId, plan.forexId,
); );
}, },
@ -1389,7 +1408,7 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); // Close popup manually ); // Close popup manually
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1414,7 +1433,7 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1454,8 +1473,8 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getPdfDownload(
.getPdfDownload( context,
plan.planId, plan.planId,
); );
}, },
@ -1482,8 +1501,8 @@ class _ListAllPlansState extends State<ListAllPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getForexPdfDownload(
.getForexPdfDownload( context,
plan.forexId, plan.forexId,
); );
}, },

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:frontend/services/apiService.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
@ -22,6 +23,7 @@ class TripInformation extends StatefulWidget {
} }
class _TripInformationState extends State<TripInformation> { class _TripInformationState extends State<TripInformation> {
final ApiService apiService = ApiService();
late Future<Map<String, dynamic>> _tripInfoFuture; late Future<Map<String, dynamic>> _tripInfoFuture;
Future<Map<String, dynamic>> fetchComments() async { Future<Map<String, dynamic>> fetchComments() async {
@ -48,6 +50,11 @@ class _TripInformationState extends State<TripInformation> {
final Map<String, dynamic> dataMap = final Map<String, dynamic> dataMap =
jsonData['data'] as Map<String, dynamic>; jsonData['data'] as Map<String, dynamic>;
return dataMap; return dataMap;
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load comments'); throw Exception('Failed to load comments');
} }

View File

@ -5,6 +5,7 @@ import 'package:http/http.dart' as http;
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import '../../config/apiUrl.dart'; import '../../config/apiUrl.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart'; import '../../utils/auth_utils.dart';
class CommentModalList extends StatefulWidget { class CommentModalList extends StatefulWidget {
@ -24,6 +25,7 @@ class CommentModalList extends StatefulWidget {
} }
class _CommentModalListState extends State<CommentModalList> { class _CommentModalListState extends State<CommentModalList> {
final ApiService apiService = ApiService();
late Future<List<Map<String, dynamic>>> _commentsFuture; late Future<List<Map<String, dynamic>>> _commentsFuture;
// Future<List<Map<String, dynamic>>> fetchComments1() async { // Future<List<Map<String, dynamic>>> fetchComments1() async {
@ -68,6 +70,11 @@ class _CommentModalListState extends State<CommentModalList> {
final jsonData = json.decode(response.body); final jsonData = json.decode(response.body);
final List<dynamic> dataList = jsonData['data']; final List<dynamic> dataList = jsonData['data'];
return dataList.cast<Map<String, dynamic>>(); return dataList.cast<Map<String, dynamic>>();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load comments'); throw Exception('Failed to load comments');
} }

View File

@ -1,5 +1,7 @@
import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:core'; import 'dart:core';
import 'dart:html' as html;
import 'package:frontend/Screens/allTrips/plan_info_mdl.dart'; import 'package:frontend/Screens/allTrips/plan_info_mdl.dart';
import 'package:frontend/data/models/plan.dart'; import 'package:frontend/data/models/plan.dart';
import 'package:frontend/utils/travelAgent_remarks.dart'; import 'package:frontend/utils/travelAgent_remarks.dart';
@ -29,6 +31,7 @@ class TravelAgentListPlans extends StatefulWidget {
class _TravelAgentListPlansState extends State<TravelAgentListPlans> { class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
final ApiService apiService = ApiService(); final ApiService apiService = ApiService();
late StreamSubscription<html.PopStateEvent> _popStateListener;
int currentPage = 0; int currentPage = 0;
int itemsPerPage = 10; int itemsPerPage = 10;
@ -39,6 +42,8 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
String? token; String? token;
String? TripPlanAction; String? TripPlanAction;
late bool _dialogShown = false;
Color? layoutColor; Color? layoutColor;
Color? bodyColor; Color? bodyColor;
late Future<List<Plan>> futurePlans; late Future<List<Plan>> futurePlans;
@ -50,6 +55,7 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
void initState() { void initState() {
super.initState(); super.initState();
_checkAuthAndLoadData(); _checkAuthAndLoadData();
checkbackbutton();
// getToken(); // getToken();
// //
// WidgetsBinding.instance.addPostFrameCallback((_) { // WidgetsBinding.instance.addPostFrameCallback((_) {
@ -82,6 +88,81 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
loadInitialData(); loadInitialData();
} }
void checkbackbutton() async {
roleUser = await getRoleUser();
print(roleUser);
if (roleUser == "Travel Agent") {
print("user");
final prefs = await SharedPreferences.getInstance();
final String? msUserStr = prefs.getString('is_microsoft_user');
final bool msUser = msUserStr?.toLowerCase() == 'true';
print("msUser - $msUser");
html.window.history.pushState(null, '', html.window.location.href);
if (!msUser) {
_popStateListener = html.window.onPopState.listen((event) {
if (!_dialogShown && mounted) {
_showBackConfirmationDialog();
}
// Re-push to prevent leaving
html.window.history.pushState(null, '', html.window.location.href);
});
}
}
}
@override
void dispose() {
_popStateListener.cancel(); // Remove the browser popstate listener
super.dispose();
}
Future<void> _logoutAndRedirect(BuildContext context) async {
print("logue 0");
await apiService.logout(context);
// // Example: clear session or shared preferences
// final prefs = await SharedPreferences.getInstance();
// await prefs.clear();
// context.go("/");
print("logue 1");
}
void _showBackConfirmationDialog() {
if (!mounted) return;
_dialogShown = true;
showDialog(
context: context,
builder:
(context) => AlertDialog(
title: Text("Confirm"),
content: Text("Do you want to logout?"),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context); // Close dialog
_dialogShown = false;
},
child: Text("Cancel"),
),
TextButton(
onPressed: () async {
// Navigator.pop(context); // Close dialog
_dialogShown = false;
await _logoutAndRedirect(context);
},
child: Text("Logout"),
),
],
),
);
}
void filterPlans(String query) { void filterPlans(String query) {
print("allPlans before filtering: $allPlans"); print("allPlans before filtering: $allPlans");
final lowerQuery = query.toLowerCase(); final lowerQuery = query.toLowerCase();
@ -221,6 +302,11 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
// List<dynamic> plansJson = []; // List<dynamic> plansJson = [];
List<dynamic> plansJson = data['data']; List<dynamic> plansJson = data['data'];
return plansJson.map((json) => Plan.fromJson(json)).toList(); return plansJson.map((json) => Plan.fromJson(json)).toList();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -254,6 +340,11 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
print("Plan Deleted successfully!"); print("Plan Deleted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
initializeData(); initializeData();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -271,7 +362,10 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
if (confirmed) { if (confirmed) {
try { try {
Map<String, dynamic> planData = await ApiService.getViewPlan(planId); Map<String, dynamic> planData = await ApiService().getViewPlan(
planId,
context,
);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
refresh(); refresh();
// postPlanData(planData, planId); // postPlanData(planData, planId);
@ -839,7 +933,8 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); // Close popup manually ); // Close popup manually
ApiService.viewPlanTravelAgent( ApiService()
.viewPlanTravelAgent(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -888,6 +983,7 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
); );
apiService apiService
.getPdfDownload( .getPdfDownload(
context,
plan.planId, plan.planId,
); );
}, },
@ -915,6 +1011,7 @@ class _TravelAgentListPlansState extends State<TravelAgentListPlans> {
); );
apiService apiService
.getForexPdfDownload( .getForexPdfDownload(
context,
plan.forexId, plan.forexId,
); );
}, },

View File

@ -204,6 +204,11 @@ class _ApprovalListState extends State<ApprovalList> {
List<dynamic> plansJson = data['data']; List<dynamic> plansJson = data['data'];
print('plansJson $plansJson'); print('plansJson $plansJson');
return plansJson.map((json) => Plan.fromJson(json)).toList(); return plansJson.map((json) => Plan.fromJson(json)).toList();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -237,6 +242,11 @@ class _ApprovalListState extends State<ApprovalList> {
print("Plan Deleted successfully!"); print("Plan Deleted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
initializeData(); initializeData();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -263,7 +273,10 @@ class _ApprovalListState extends State<ApprovalList> {
if (confirmed) { if (confirmed) {
try { try {
Map<String, dynamic> planData = await ApiService.getViewPlan(planId); Map<String, dynamic> planData = await ApiService().getViewPlan(
planId,
context,
);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
refresh(); refresh();
// postPlanData(planData, planId); // postPlanData(planData, planId);
@ -297,6 +310,11 @@ class _ApprovalListState extends State<ApprovalList> {
final Map<String, dynamic>? resData = json.decode(response.body); final Map<String, dynamic>? resData = json.decode(response.body);
return resData?["data"]; return resData?["data"];
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -402,6 +420,11 @@ class _ApprovalListState extends State<ApprovalList> {
approverData = List<Map<String, dynamic>>.from( approverData = List<Map<String, dynamic>>.from(
data['data']['approver_data'] ?? [], data['data']['approver_data'] ?? [],
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print('Failed to load'); print('Failed to load');
label = "Error - Failed to load data"; label = "Error - Failed to load data";
@ -1157,7 +1180,7 @@ class _ApprovalListState extends State<ApprovalList> {
Navigator.pop( Navigator.pop(
context, context,
); );
ApiService.viewPlanForApprover( ApiService().viewPlanForApprover(
context, context,
plan.planId, plan.planId,
plan.approverId, plan.approverId,
@ -1204,6 +1227,7 @@ class _ApprovalListState extends State<ApprovalList> {
); );
apiService apiService
.getPdfDownload( .getPdfDownload(
context,
plan.planId, plan.planId,
); );
}, },
@ -1229,8 +1253,8 @@ class _ApprovalListState extends State<ApprovalList> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getForexPdfDownload(
.getForexPdfDownload( context,
plan.forexId, plan.forexId,
); );
}, },
@ -1511,8 +1535,8 @@ class _ApprovalListState extends State<ApprovalList> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getPdfDownload(
.getPdfDownload( context,
plan.planId, plan.planId,
); );
}, },
@ -1538,8 +1562,8 @@ class _ApprovalListState extends State<ApprovalList> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getForexPdfDownload(
.getForexPdfDownload( context,
plan.forexId, plan.forexId,
); );
}, },

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:html' as html; import 'dart:html' as html;
// import 'dart:ui' as html; // import 'dart:ui' as html;
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
@ -103,12 +104,24 @@ class _LoginWidgetState extends State<LoginWidget> {
print("userData12 - $userRole"); print("userData12 - $userRole");
} }
await apiService.getOrganizationData(); await apiService.getOrganizationData(context);
} catch (e) { } catch (e) {
print('Error decoding token: $e'); print('Error decoding token: $e');
} }
} }
String encryptLoginPayload(Map<String, String> credentials) {
final key = encrypt.Key.fromUtf8('1234567890123456'); // 16 chars key
final iv = encrypt.IV.fromUtf8('abcdefghijklmnop'); // 16 chars IV
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc),
);
final jsonString = jsonEncode(credentials);
final encrypted = encrypter.encrypt(jsonString, iv: iv);
return encrypted.base64;
}
Future<void> _login(BuildContext context) async { Future<void> _login(BuildContext context) async {
if (_formKey.currentState!.validate()) { if (_formKey.currentState!.validate()) {
setState(() { setState(() {
@ -117,6 +130,11 @@ class _LoginWidgetState extends State<LoginWidget> {
const String url = '$apiUrl/api/auth/login'; const String url = '$apiUrl/api/auth/login';
final encryptedData = encryptLoginPayload({
'email': _emailController.text.trim(),
'password': _passwordController.text.trim(),
});
try { try {
final response = await http.post( final response = await http.post(
Uri.parse(url), Uri.parse(url),
@ -125,10 +143,11 @@ class _LoginWidgetState extends State<LoginWidget> {
'Accept': 'application/json', 'Accept': 'application/json',
'app-signature': 'ts-traveltool-2025-signature-123456', 'app-signature': 'ts-traveltool-2025-signature-123456',
}, },
body: jsonEncode({ body: jsonEncode({'encrypted': true, 'payload': encryptedData}),
'email': _emailController.text.trim(), // body: jsonEncode({
'password': _passwordController.text.trim(), // 'email': _emailController.text.trim(),
}), // 'password': _passwordController.text.trim(),
// }),
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
@ -145,7 +164,7 @@ class _LoginWidgetState extends State<LoginWidget> {
msg: "You're in!", msg: "You're in!",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 3,
backgroundColor: Colors.green, backgroundColor: Colors.green,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
@ -159,6 +178,11 @@ class _LoginWidgetState extends State<LoginWidget> {
} else { } else {
context.go('/listPlan'); context.go('/listPlan');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
final body = jsonDecode(response.body); final body = jsonDecode(response.body);
final messages = body['messages']; final messages = body['messages'];
@ -173,7 +197,7 @@ class _LoginWidgetState extends State<LoginWidget> {
msg: "Login Failed: $errorMessage", msg: "Login Failed: $errorMessage",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 6,
backgroundColor: Colors.red, backgroundColor: Colors.red,
textColor: Colors.white, textColor: Colors.white,
fontSize: 16.0, fontSize: 16.0,
@ -200,8 +224,8 @@ class _LoginWidgetState extends State<LoginWidget> {
msg: "Login Failed: $e", msg: "Login Failed: $e",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 5,
backgroundColor: Colors.red, backgroundColor: Colors.green,
textColor: Colors.white, textColor: Colors.white,
fontSize: 16.0, fontSize: 16.0,
webBgColor: "linear-gradient(to right, #dc1c13, #dc1c13)", webBgColor: "linear-gradient(to right, #dc1c13, #dc1c13)",
@ -250,6 +274,11 @@ class _LoginWidgetState extends State<LoginWidget> {
fontSize: 16.0, fontSize: 16.0,
webBgColor: "linear-gradient(to right, #28a745, #28a745)", webBgColor: "linear-gradient(to right, #28a745, #28a745)",
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print(response); print(response);
@ -318,6 +347,11 @@ class _LoginWidgetState extends State<LoginWidget> {
fontSize: 16.0, fontSize: 16.0,
webBgColor: "linear-gradient(to right, #28a745, #28a745)", webBgColor: "linear-gradient(to right, #28a745, #28a745)",
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print('23'); print('23');
print('otp wrong'); print('otp wrong');
@ -1166,6 +1200,11 @@ class _LoginWidgetState extends State<LoginWidget> {
print('auth URL not Founded'); print('auth URL not Founded');
throw Exception('auth URL not Founded'); throw Exception('auth URL not Founded');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
final errorMessage = json.decode(response.body)['message']; final errorMessage = json.decode(response.body)['message'];
print(errorMessage); print(errorMessage);

View File

@ -247,6 +247,12 @@ class CostCenterDataState extends State<CostCenterData> {
}); });
break; break;
case 403:
print("403-FORB");
await apiService.logout(context);
break;
// throw Exception('Failed to load users');
default: default:
print("Failed to submit costcenter. Status: ${response.statusCode}"); print("Failed to submit costcenter. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -157,6 +157,11 @@ class CostCenterListState extends State<CostCenterList> {
final data = json.decode(response.body); final data = json.decode(response.body);
print(data['data']); print(data['data']);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -658,6 +663,7 @@ class CostCenterListState extends State<CostCenterList> {
); );
final data = await apiService final data = await apiService
.getCostCenterDetailsFind( .getCostCenterDetailsFind(
context,
costcenterId, costcenterId,
); );
print("CostCenterId -- $data"); print("CostCenterId -- $data");
@ -751,6 +757,7 @@ class CostCenterListState extends State<CostCenterList> {
); );
final data = await apiService final data = await apiService
.getCostCenterDetailsFind( .getCostCenterDetailsFind(
context,
costcenterId, costcenterId,
); );
print("CostCenterId -- $data"); print("CostCenterId -- $data");

View File

@ -40,6 +40,7 @@ class StatusDashboardState extends State<StatusDashboard> {
List<int> flightData = []; List<int> flightData = [];
List<int> accommodationData = []; List<int> accommodationData = [];
List<int> forexData = []; List<int> forexData = [];
final ApiService apiService = ApiService();
final categoryIcons = { final categoryIcons = {
"flight": Icons.flight, "flight": Icons.flight,
@ -96,8 +97,10 @@ class StatusDashboardState extends State<StatusDashboard> {
_dialogShown = true; _dialogShown = true;
final parentContext = context; // <-- save parent context
showDialog( showDialog(
context: context, context: parentContext,
builder: builder:
(context) => AlertDialog( (context) => AlertDialog(
title: Text("Confirm"), title: Text("Confirm"),
@ -105,16 +108,20 @@ class StatusDashboardState extends State<StatusDashboard> {
actions: [ actions: [
TextButton( TextButton(
onPressed: () { onPressed: () {
Navigator.pop(context); // Close dialog Navigator.pop(parentContext); // Close dialog
_dialogShown = false; _dialogShown = false;
}, },
child: Text("Cancel"), child: Text("Cancel"),
), ),
TextButton( TextButton(
onPressed: () async { onPressed: () async {
Navigator.pop(context); // Close dialog // Navigator.pop(parentContext); // Close dialog
_dialogShown = false; _dialogShown = false;
await _logoutAndRedirect(context); print("logue 1s");
// Use parentContext for navigation, not dialog context
if (!mounted) return;
await _logoutAndRedirect(parentContext);
print("logue 2s");
}, },
child: Text("Logout"), child: Text("Logout"),
), ),
@ -123,14 +130,52 @@ class StatusDashboardState extends State<StatusDashboard> {
); );
} }
// void _showBackConfirmationDialog() {
// if (!mounted) return;
//
// _dialogShown = true;
//
// showDialog(
// context: context,
// builder:
// (context) => AlertDialog(
// title: Text("Confirm"),
// content: Text("Do you want to logout?"),
// actions: [
// TextButton(
// onPressed: () {
// Navigator.pop(context); // Close dialog
// _dialogShown = false;
// },
// child: Text("Cancel"),
// ),
// TextButton(
// onPressed: () async {
// Navigator.pop(context); // Close dialog
// _dialogShown = false;
//
// // Use the parent widget's context
// if (!mounted) return;
// await _logoutAndRedirect(context);
// },
// child: Text("Logout"),
// ),
// ],
// ),
// );
// }
Future<void> _logoutAndRedirect(BuildContext context) async { Future<void> _logoutAndRedirect(BuildContext context) async {
print("logue _logoutAndRedirect");
// Navigator.pop(context); // closes dialog
_dialogShown = false;
print("logue 0"); print("logue 0");
await apiService.logout(context);
// Example: clear session or shared preferences // Example: clear session or shared preferences
final prefs = await SharedPreferences.getInstance(); // final prefs = await SharedPreferences.getInstance();
await prefs.clear(); // await prefs.clear();
context.go("/"); // context.go("/");
print("logue 1"); print("logue 1");
} }
@ -214,6 +259,11 @@ class StatusDashboardState extends State<StatusDashboard> {
final apiData = json.decode(response.body); final apiData = json.decode(response.body);
print("Fetch StatusDashboard -- Reponse Here : $apiData"); print("Fetch StatusDashboard -- Reponse Here : $apiData");
return apiData; // Returning raw JSON list return apiData; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }

View File

@ -41,6 +41,7 @@ class StatusDashboardState extends State<StatusDashboard> {
List<int> flightData = []; List<int> flightData = [];
List<int> accommodationData = []; List<int> accommodationData = [];
List<int> forexData = []; List<int> forexData = [];
final ApiService apiService = ApiService();
final categoryIcons = { final categoryIcons = {
"flight": Icons.flight, "flight": Icons.flight,
@ -53,7 +54,7 @@ class StatusDashboardState extends State<StatusDashboard> {
"Partially Approved", "Partially Approved",
"Approved", "Approved",
"Rejected", "Rejected",
"Cancelled" "Cancelled",
]; ];
// Extract counts for "Both" section // Extract counts for "Both" section
@ -113,7 +114,7 @@ class StatusDashboardState extends State<StatusDashboard> {
), ),
TextButton( TextButton(
onPressed: () async { onPressed: () async {
Navigator.pop(context); // Close dialog // Navigator.pop(context); // Close dialog
_dialogShown = false; _dialogShown = false;
await _logoutAndRedirect(context); await _logoutAndRedirect(context);
}, },
@ -126,12 +127,14 @@ class StatusDashboardState extends State<StatusDashboard> {
Future<void> _logoutAndRedirect(BuildContext context) async { Future<void> _logoutAndRedirect(BuildContext context) async {
print("logue 0"); print("logue 0");
Navigator.pop(context); // closes dialog
_dialogShown = false;
await apiService.logout(context);
// Example: clear session or shared preferences // Example: clear session or shared preferences
final prefs = await SharedPreferences.getInstance(); // final prefs = await SharedPreferences.getInstance();
await prefs.clear(); // await prefs.clear();
context.go("/"); // context.go("/");
print("logue 1"); print("logue 1");
} }
@ -210,6 +213,10 @@ class StatusDashboardState extends State<StatusDashboard> {
final apiData = json.decode(response.body); final apiData = json.decode(response.body);
print("Fetch StatusDashboard -- Reponse Here : $apiData"); print("Fetch StatusDashboard -- Reponse Here : $apiData");
return apiData; // Returning raw JSON list return apiData; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return {};
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -316,25 +323,27 @@ class StatusDashboardState extends State<StatusDashboard> {
setState(() { setState(() {
// currentData = selectedView == "Today" ? todayBasedCount : weekBasedCount; // currentData = selectedView == "Today" ? todayBasedCount : weekBasedCount;
typeData = selectedView == "Today" typeData =
? typeBasedTodayCount selectedView == "Today" ? typeBasedTodayCount : typeBasedWeeklyCount;
: typeBasedWeeklyCount ; statusData =
statusData = selectedView == "Today" selectedView == "Today"
? statusBasedTodayCount ? statusBasedTodayCount
: statusBasedWeeklyCount ; : statusBasedWeeklyCount;
flightData = selectedView == "Today" flightData =
selectedView == "Today"
? getStatusValues(todayBasedCount['flight'] ?? {}) ? getStatusValues(todayBasedCount['flight'] ?? {})
: getStatusValues(weekBasedCount['flight'] ?? {}); : getStatusValues(weekBasedCount['flight'] ?? {});
accommodationData = selectedView == "Today" accommodationData =
selectedView == "Today"
? getStatusValues(todayBasedCount['acomodation'] ?? {}) ? getStatusValues(todayBasedCount['acomodation'] ?? {})
: getStatusValues(weekBasedCount['acomodation'] ?? {}); : getStatusValues(weekBasedCount['acomodation'] ?? {});
forexData = selectedView == "Today" forexData =
selectedView == "Today"
? getStatusValues(todayBasedCount['forex'] ?? {}) ? getStatusValues(todayBasedCount['forex'] ?? {})
: getStatusValues(weekBasedCount['forex'] ?? {}); : getStatusValues(weekBasedCount['forex'] ?? {});
}); });
print("statusBasedCount - => $statusBasedCount"); print("statusBasedCount - => $statusBasedCount");
print("Current Data - => $currentData"); print("Current Data - => $currentData");
// 👇 Local function to create the card widget // 👇 Local function to create the card widget
@ -399,6 +408,7 @@ class StatusDashboardState extends State<StatusDashboard> {
print("dashboard .."); print("dashboard ..");
} }
} }
String capitalize(String s) => s[0].toUpperCase() + s.substring(1); String capitalize(String s) => s[0].toUpperCase() + s.substring(1);
Widget toggleChip(String label) { Widget toggleChip(String label) {
@ -446,7 +456,7 @@ class StatusDashboardState extends State<StatusDashboard> {
child: Column( child: Column(
children: [ children: [
Tooltip( Tooltip(
message: label , message: label,
child: Image.asset( child: Image.asset(
label == 'Domestic' label == 'Domestic'
? 'assets/images/IconsImg/Domestic_new.png' ? 'assets/images/IconsImg/Domestic_new.png'
@ -520,8 +530,12 @@ class StatusDashboardState extends State<StatusDashboard> {
); );
} }
Widget buildCategoryCard(String title, IconData icon, List<String> statusLabels,List<int> values) { Widget buildCategoryCard(
String title,
IconData icon,
List<String> statusLabels,
List<int> values,
) {
final statusIcons = [ final statusIcons = [
Icons.calendar_today, Icons.calendar_today,
Icons.assignment, Icons.assignment,
@ -532,9 +546,9 @@ class StatusDashboardState extends State<StatusDashboard> {
final statusColors = [ final statusColors = [
Color(0xFFFBFFCA), Color(0xFFFBFFCA),
Color(0xFFFFF1CD),// Colors.yellow.shade100, // Color(0xFFCAE77B), Color(0xFFFFF1CD), // Colors.yellow.shade100, // Color(0xFFCAE77B),
Color(0xFFDAFFE8),// Colors.green.shade100, // Color(0xFF72D480), Color(0xFFDAFFE8), // Colors.green.shade100, // Color(0xFF72D480),
Color(0xFFFFD6D3),// Colors.red.shade100, // Color(0xFFF88C8C), Color(0xFFFFD6D3), // Colors.red.shade100, // Color(0xFFF88C8C),
Color(0xFFFFA8A8), // Colors.red.shade200, // Color(0xFFE94B4B), Color(0xFFFFA8A8), // Colors.red.shade200, // Color(0xFFE94B4B),
]; ];
@ -575,17 +589,16 @@ class StatusDashboardState extends State<StatusDashboard> {
color: Color(0xFF004A8E), color: Color(0xFF004A8E),
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
child: Icon( child: Icon(icon, color: Colors.white, size: 20),
icon,
color: Colors.white,
size: 20,
),
), ),
const SizedBox(width: 10), const SizedBox(width: 10),
Text(title, style: GoogleFonts.poppins( Text(
title,
style: GoogleFonts.poppins(
color: Colors.black87, color: Colors.black87,
fontWeight: FontWeight.bold fontWeight: FontWeight.bold,
),), ),
),
], ],
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@ -603,7 +616,9 @@ class StatusDashboardState extends State<StatusDashboard> {
height: 28, height: 28,
decoration: BoxDecoration( decoration: BoxDecoration(
color: statusColors[index], // background color color: statusColors[index], // background color
borderRadius: BorderRadius.circular(4), // square with slight rounding borderRadius: BorderRadius.circular(
4,
), // square with slight rounding
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: Icon( child: Icon(
@ -613,16 +628,20 @@ class StatusDashboardState extends State<StatusDashboard> {
), ),
), ),
const SizedBox(width: 6), const SizedBox(width: 6),
Text(statusLabels[index], style: GoogleFonts.poppins( Text(
color: Colors.black87, statusLabels[index],
),), style: GoogleFonts.poppins(color: Colors.black87),
),
], ],
), ),
Text(values[index].toString(), style: GoogleFonts.poppins( Text(
values[index].toString(),
style: GoogleFonts.poppins(
fontSize: 10, fontSize: 10,
color: Colors.black87, color: Colors.black87,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
),), ),
),
], ],
), ),
); );
@ -799,12 +818,14 @@ class StatusDashboardState extends State<StatusDashboard> {
// icon: item['value'] == "Domestic" // icon: item['value'] == "Domestic"
// ? Icons.home // ? Icons.home
// : Icons.travel_explore, // : Icons.travel_explore,
color: item['value'] == "Domestic" color:
item['value'] == "Domestic"
? Color(0xFF0DB04B) ? Color(0xFF0DB04B)
: Color(0xFF004A8E), : Color(0xFF004A8E),
label: item['value'], label: item['value'],
count: item['count'], count: item['count'],
bgColor: item['value'] == "Domestic" bgColor:
item['value'] == "Domestic"
? const Color(0xFFD6FBE4) ? const Color(0xFFD6FBE4)
: const Color(0xFFD9E8FF), : const Color(0xFFD9E8FF),
), ),
@ -836,7 +857,8 @@ class StatusDashboardState extends State<StatusDashboard> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text("Status", Text(
"Status",
style: GoogleFonts.poppins( style: GoogleFonts.poppins(
fontSize: 19, fontSize: 19,
color: Colors.black87, color: Colors.black87,
@ -845,9 +867,17 @@ class StatusDashboardState extends State<StatusDashboard> {
), ),
const SizedBox(height: 23), const SizedBox(height: 23),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment:
MainAxisAlignment.spaceAround,
children: [ children: [
...statusData.map((item) => statusCard(item['value'], item['count'])).toList(), ...statusData
.map(
(item) => statusCard(
item['value'],
item['count'],
),
)
.toList(),
], ],
), ),
], ],
@ -862,11 +892,32 @@ class StatusDashboardState extends State<StatusDashboard> {
Row( Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded(child: buildCategoryCard("Flight", Icons.flight,statusLabels,flightData)), Expanded(
child: buildCategoryCard(
"Flight",
Icons.flight,
statusLabels,
flightData,
),
),
const SizedBox(width: 10), const SizedBox(width: 10),
Expanded(child: buildCategoryCard("Accomodation", Icons.hotel_outlined,statusLabels,accommodationData)), Expanded(
child: buildCategoryCard(
"Accomodation",
Icons.hotel_outlined,
statusLabels,
accommodationData,
),
),
const SizedBox(width: 10), const SizedBox(width: 10),
Expanded(child: buildCategoryCard("Forex", Icons.attach_money,statusLabels,forexData)), Expanded(
child: buildCategoryCard(
"Forex",
Icons.attach_money,
statusLabels,
forexData,
),
),
], ],
), ),
], ],

View File

@ -249,6 +249,11 @@ class DepartmentDataState extends State<DepartmentData> {
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
), ),
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit. Status: ${response.statusCode}"); print("Failed to submit. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -156,6 +156,11 @@ class DepartmentListState extends State<DepartmentList> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -654,6 +659,7 @@ class DepartmentListState extends State<DepartmentList> {
); );
final data = await apiService final data = await apiService
.getDepartmentDetailsFind( .getDepartmentDetailsFind(
context,
departmentId, departmentId,
); );
print("DepartmentId -- $data"); print("DepartmentId -- $data");
@ -746,6 +752,7 @@ class DepartmentListState extends State<DepartmentList> {
); );
final data = await apiService final data = await apiService
.getDepartmentDetailsFind( .getDepartmentDetailsFind(
context,
departmentId, departmentId,
); );
print("DepartmentId -- $data"); print("DepartmentId -- $data");

View File

@ -8,6 +8,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../../config/apiUrl.dart'; import '../../config/apiUrl.dart';
import '../../data/models/Searchtraveller.dart'; import '../../data/models/Searchtraveller.dart';
import '../../data/models/searchUser.dart'; import '../../data/models/searchUser.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart'; import '../../utils/auth_utils.dart';
import '../../widgets/custom_text_traveller.dart'; import '../../widgets/custom_text_traveller.dart';
@ -32,6 +33,7 @@ class UserSelectionDialog extends StatefulWidget {
} }
class _UserSelectionDialogState extends State<UserSelectionDialog> { class _UserSelectionDialogState extends State<UserSelectionDialog> {
final ApiService apiService = ApiService();
TextEditingController _controller = TextEditingController(); TextEditingController _controller = TextEditingController();
TextEditingController _searchController = TextEditingController(); TextEditingController _searchController = TextEditingController();
// List<String> _filteredUsers = []; // List<String> _filteredUsers = [];
@ -107,6 +109,11 @@ class _UserSelectionDialogState extends State<UserSelectionDialog> {
"Unexpected response format: Expected a List but got ${responseBody.runtimeType}", "Unexpected response format: Expected a List but got ${responseBody.runtimeType}",
); );
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception( throw Exception(
'Failed to load users. Status Code: ${response.statusCode}', 'Failed to load users. Status Code: ${response.statusCode}',
@ -164,6 +171,16 @@ class _UserSelectionDialogState extends State<UserSelectionDialog> {
"Unexpected response format: Expected a List but got ${responseBody.runtimeType}", "Unexpected response format: Expected a List but got ${responseBody.runtimeType}",
); );
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception( throw Exception(
'Failed to load users. Status Code: ${response.statusCode}', 'Failed to load users. Status Code: ${response.statusCode}',
@ -707,6 +724,7 @@ class TravelerForm extends StatefulWidget {
} }
class _TravelerFormState extends State<TravelerForm> { class _TravelerFormState extends State<TravelerForm> {
final ApiService apiService = ApiService();
Future<String?> getToken() async { Future<String?> getToken() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
return prefs.getString('auth_token'); return prefs.getString('auth_token');
@ -819,6 +837,11 @@ class _TravelerFormState extends State<TravelerForm> {
backgroundColor: Colors.green, backgroundColor: Colors.green,
), ),
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
ScaffoldMessenger.of( ScaffoldMessenger.of(
context, context,

View File

@ -141,7 +141,7 @@ class _groupState extends State<Group> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllPolicy(); final result = await apiService.fetchAllPolicy(context);
orgId = await getOrgId(); orgId = await getOrgId();
userId = await getUserId(); userId = await getUserId();
@ -263,10 +263,15 @@ class _groupState extends State<Group> {
if (response.statusCode == 200 || response.statusCode == 201) { if (response.statusCode == 200 || response.statusCode == 201) {
print("GRPDATA"); print("GRPDATA");
await apiService.handleTokenRefresh(userId!); await apiService.handleTokenRefresh(context, userId!);
print("Group submitted successfully!"); print("Group submitted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
context.go('/group'); context.go('/group');
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit group. Status: ${response.statusCode}"); print("Failed to submit group. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -177,7 +177,7 @@ class GroupDataState extends State<GroupData> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllPolicy(); final result = await apiService.fetchAllPolicy(context);
userId = await getUserId(); userId = await getUserId();
@ -286,7 +286,7 @@ class GroupDataState extends State<GroupData> {
_clearError(); _clearError();
await widget.fetchGetGroup(); await widget.fetchGetGroup();
await apiService.handleTokenRefresh(userId!); await apiService.handleTokenRefresh(context, userId!);
if (context.mounted) { if (context.mounted) {
Navigator.of(context).pop(); // Close modal only if mounted Navigator.of(context).pop(); // Close modal only if mounted
} }
@ -295,6 +295,11 @@ class GroupDataState extends State<GroupData> {
}); });
// dispose(); // dispose();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
if (context.mounted) { if (context.mounted) {
Navigator.of(context).pop(); Navigator.of(context).pop();
@ -311,6 +316,11 @@ class GroupDataState extends State<GroupData> {
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
), ),
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -118,13 +118,13 @@ class _GroupListState extends State<GroupList> {
Future<List<dynamic>> fetchGroups() async { Future<List<dynamic>> fetchGroups() async {
// return []; // return [];
final result = await apiService.fetchAllGroup(); final result = await apiService.fetchAllGroup(context);
return result; // Returning raw JSON list return result; // Returning raw JSON list
} }
Future<void> loadAllGroups() async { Future<void> loadAllGroups() async {
try { try {
final result = await apiService.fetchAllGroup(); final result = await apiService.fetchAllGroup(context);
setState(() { setState(() {
allGroups = result; allGroups = result;
filteredGroups = result; filteredGroups = result;
@ -200,6 +200,11 @@ class _GroupListState extends State<GroupList> {
if (response.statusCode == 200 || response.statusCode == 201) { if (response.statusCode == 200 || response.statusCode == 201) {
print("Group status updated successfully to $newStatus!"); print("Group status updated successfully to $newStatus!");
loadAllGroups(); // Refresh groups list after update loadAllGroups(); // Refresh groups list after update
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to update group status. Status: ${response.statusCode}"); print("Failed to update group status. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -713,6 +718,7 @@ class _GroupListState extends State<GroupList> {
if (newGroupID != null) { if (newGroupID != null) {
final data = await apiService final data = await apiService
.getGroupDetailsFind( .getGroupDetailsFind(
context,
newGroupID, newGroupID,
); // Always an int ); // Always an int
showDialog( showDialog(
@ -850,6 +856,7 @@ class _GroupListState extends State<GroupList> {
if (newGroupID != null) { if (newGroupID != null) {
final data = await apiService final data = await apiService
.getGroupDetailsFind( .getGroupDetailsFind(
context,
newGroupID, newGroupID,
); // Always an int ); // Always an int
showDialog( showDialog(

View File

@ -55,7 +55,7 @@ class _GroupListBackUpState extends State<GroupListBackUp> {
Future<void> loadAllGroups() async { Future<void> loadAllGroups() async {
try { try {
final result = await apiService.fetchAllGroup(); final result = await apiService.fetchAllGroup(context);
setState(() { setState(() {
apiAllGroups = result; apiAllGroups = result;
}); });
@ -410,6 +410,7 @@ class _GroupListBackUpState extends State<GroupListBackUp> {
); );
if (newGroupID != null) { if (newGroupID != null) {
final data = await apiService.getGroupDetailsFind( final data = await apiService.getGroupDetailsFind(
context,
newGroupID, newGroupID,
); // Always an int ); // Always an int
showDialog( showDialog(

View File

@ -151,7 +151,7 @@ class HotelsDataState extends State<HotelsData> {
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -269,6 +269,11 @@ class HotelsDataState extends State<HotelsData> {
isDisable = false; isDisable = false;
}); });
// Do NOT re-enable here if success // Do NOT re-enable here if success
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
if (context.mounted) { if (context.mounted) {
Navigator.of(context).pop(); Navigator.of(context).pop();

View File

@ -159,6 +159,11 @@ class HotelsDataListState extends State<HotelsDataList> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -209,6 +214,11 @@ class HotelsDataListState extends State<HotelsDataList> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -755,7 +765,10 @@ class HotelsDataListState extends State<HotelsDataList> {
if (hotelsId != null) { if (hotelsId != null) {
print("HotelsId -- $hotelsId"); print("HotelsId -- $hotelsId");
final data = await apiService final data = await apiService
.getHotelsDetailsFind(hotelsId); .getHotelsDetailsFind(
context,
hotelsId,
);
print("HotelsId -- $data"); print("HotelsId -- $data");
showDialog( showDialog(
@ -841,7 +854,10 @@ class HotelsDataListState extends State<HotelsDataList> {
if (hotelsId != null) { if (hotelsId != null) {
print("HotelsId -- $hotelsId"); print("HotelsId -- $hotelsId");
final data = await apiService final data = await apiService
.getHotelsDetailsFind(hotelsId); .getHotelsDetailsFind(
context,
hotelsId,
);
print("HotelsId -- $data"); print("HotelsId -- $data");
showDialog( showDialog(

View File

@ -182,7 +182,7 @@ class _AccomodationScreenState extends State<AccomodationScreen> {
// } // }
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
loadCountryList(); loadCountryList(context);
final result = getFlightTripDateRange(widget.flightData); final result = getFlightTripDateRange(widget.flightData);
@ -288,7 +288,7 @@ class _AccomodationScreenState extends State<AccomodationScreen> {
// : Colors.redAccent; // : Colors.redAccent;
// }); // });
futureHotels = await apiService.fetchGetHotels(); futureHotels = await apiService.fetchGetHotels(context);
print("futureHotels - $futureHotels"); print("futureHotels - $futureHotels");
@ -489,8 +489,11 @@ class _AccomodationScreenState extends State<AccomodationScreen> {
return errorMessages.isEmpty; // Valid if there are no errors return errorMessages.isEmpty; // Valid if there are no errors
} }
Future<void> loadCountryList() async { Future<void> loadCountryList(BuildContext context) async {
final result = await apiService.fetchFlightsCountryList(widget.tripType); final result = await apiService.fetchFlightsCountryList(
context,
widget.tripType,
);
print("ResultCountry : $result"); print("ResultCountry : $result");

View File

@ -191,7 +191,7 @@ class FlightScreenState extends State<FlightScreen> {
if (tripTypeValue != null && tripTypeValue.isNotEmpty) { if (tripTypeValue != null && tripTypeValue.isNotEmpty) {
print("🚀 Initial loadCountryList for tripType: $tripTypeValue"); print("🚀 Initial loadCountryList for tripType: $tripTypeValue");
loadCountryList(tripTypeValue); loadCountryList(context, tripTypeValue);
} else { } else {
print("⚠️ tripType is null or empty, skipping loadCountryList"); print("⚠️ tripType is null or empty, skipping loadCountryList");
} }
@ -253,14 +253,17 @@ class FlightScreenState extends State<FlightScreen> {
// isCountryLoading = false; // isCountryLoading = false;
// }); // });
// } // }
Future<void> loadCountryList(newTripType) async { Future<void> loadCountryList(BuildContext context, newTripType) async {
print("🔄 loadCountryList called with tripType: ${newTripType}"); print("🔄 loadCountryList called with tripType: ${newTripType}");
setState(() { setState(() {
isCountryLoading = true; isCountryLoading = true;
}); });
final result = await apiService.fetchFlightsCountryList(newTripType); final result = await apiService.fetchFlightsCountryList(
context,
newTripType,
);
print("ResultCountry : $result"); print("ResultCountry : $result");

View File

@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:dropdown_search/dropdown_search.dart'; import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:frontend/services/apiService.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:responsive_builder/responsive_builder.dart'; import 'package:responsive_builder/responsive_builder.dart';
@ -39,6 +40,7 @@ class ForexScreen extends StatefulWidget {
} }
class _ForexScreenState extends State<ForexScreen> { class _ForexScreenState extends State<ForexScreen> {
final ApiService apiService = ApiService();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
late ValueNotifier<String?> flightFirstTripDateNotifier; late ValueNotifier<String?> flightFirstTripDateNotifier;
@ -245,6 +247,11 @@ class _ForexScreenState extends State<ForexScreen> {
} else { } else {
print("Warning: Response does not contain expected fields."); print("Warning: Response does not contain expected fields.");
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -287,7 +287,7 @@ class _TrainScreenState extends State<TrainScreen> {
isCountryLoading = true; isCountryLoading = true;
}); });
final result = await apiService.fetchTrainCountryList(); final result = await apiService.fetchTrainCountryList(context);
print("ResultCountry : $result"); print("ResultCountry : $result");

View File

@ -96,7 +96,10 @@ class _FlightListWidgetState extends State<FlightListWidget> {
} }
Future<void> loadCountryList() async { Future<void> loadCountryList() async {
final result = await apiService.fetchFlightsCountryList(widget.tripType); final result = await apiService.fetchFlightsCountryList(
context,
widget.tripType,
);
print("ResultCountry : $result"); print("ResultCountry : $result");

View File

@ -395,7 +395,7 @@ class _ForexListWidgetState extends State<ForexListWidget> {
final id = int.tryParse(forexIdString ?? ''); final id = int.tryParse(forexIdString ?? '');
if (id != null) { if (id != null) {
apiService.getForexPdfDownload(id); apiService.getForexPdfDownload(context, id);
} else { } else {
print("Invalid forex_id: $forexIdString"); print("Invalid forex_id: $forexIdString");
} }

View File

@ -127,7 +127,7 @@ class _TrainListWidgetState extends State<TrainListWidget> {
Future<void> loadCountryList() async { Future<void> loadCountryList() async {
// final result = await apiService.fetchFlightsCountryList(); // final result = await apiService.fetchFlightsCountryList();
final result = await apiService.fetchTrainCountryList(); final result = await apiService.fetchTrainCountryList(context);
print("ResultCountry : $result"); print("ResultCountry : $result");

View File

@ -487,6 +487,11 @@ class TemplateState extends State<Template> {
isDisable = false; isDisable = false;
}); });
context.go('/templateList'); context.go('/templateList');
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit policyData. Status: ${response.statusCode}"); print("Failed to submit policyData. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -471,6 +471,11 @@ class TemplateForexState extends State<TemplateForex> {
selectedOrglogo = rawLogoPath; selectedOrglogo = rawLogoPath;
}); });
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("❌ Failed to fetch signature: ${response.statusCode}"); print("❌ Failed to fetch signature: ${response.statusCode}");
} }
@ -538,6 +543,11 @@ class TemplateForexState extends State<TemplateForex> {
setState(() { setState(() {
isDisable = false; isDisable = false;
}); });
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit policyData. Status: ${response.statusCode}"); print("Failed to submit policyData. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -187,6 +187,11 @@ class TemplatesListState extends State<TemplatesList> {
print("TemplateDATA--- $data"); print("TemplateDATA--- $data");
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -774,7 +779,10 @@ class TemplatesListState extends State<TemplatesList> {
if (templateId != null) { if (templateId != null) {
print("templateId -- $templateId"); print("templateId -- $templateId");
final data = await apiService final data = await apiService
.getTemplateFind(templateId); .getTemplateFind(
context,
templateId,
);
print("ForexId -- $data"); print("ForexId -- $data");
context.go( context.go(
@ -834,7 +842,10 @@ class TemplatesListState extends State<TemplatesList> {
UserActionsMenu( UserActionsMenu(
user: forex, user: forex,
getUserDetails: getUserDetails:
(id) => apiService.getSingleUser(id), (id) => apiService.getSingleUser(
context,
id,
),
), ),
], ],
), ),

View File

@ -1,5 +1,6 @@
import 'dart:convert'; import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:frontend/services/apiService.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
@ -24,6 +25,7 @@ class MailSetting extends StatefulWidget {
} }
class _MailSettingState extends State<MailSetting> { class _MailSettingState extends State<MailSetting> {
final ApiService apiService = ApiService();
String? orgId; String? orgId;
String? userId; String? userId;
@ -176,6 +178,11 @@ class _MailSettingState extends State<MailSetting> {
if (response.statusCode == 200 || response.statusCode == 201) { if (response.statusCode == 200 || response.statusCode == 201) {
print("Plan submitted successfully!"); print("Plan submitted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -143,7 +143,7 @@ class _OrgSetUpState extends State<OrgSetUp> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllServices(); final result = await apiService.fetchAllServices(context);
setState(() { setState(() {
apiAllServices = result; apiAllServices = result;
}); });
@ -400,7 +400,7 @@ class _OrgSetUpState extends State<OrgSetUp> {
print(orgList); print(orgList);
await updateOrgDataWithNewValues(orgList); await updateOrgDataWithNewValues(orgList);
await apiService.handleTokenRefresh(userId!); await apiService.handleTokenRefresh(context, userId!);
print("📨 Response Organizt Update:"); print("📨 Response Organizt Update:");
// return orgList; // return orgList;
context.go('/OrganizationSettings'); context.go('/OrganizationSettings');
@ -540,15 +540,13 @@ class _OrgSetUpState extends State<OrgSetUp> {
} }
Future<void> logout(BuildContext context) async { Future<void> logout(BuildContext context) async {
// Clear localStorage await apiService.logout(context);
final prefs = await SharedPreferences.getInstance();
await prefs.clear(); // Clears all keys
// Optional: clear sessionStorage if used // Optional: clear sessionStorage if used
// html.window.sessionStorage.clear(); // html.window.sessionStorage.clear();
// Navigate to login or home page // Navigate to login or home page
context.go('/'); // context.go('/');
} }
@override @override

View File

@ -27,7 +27,7 @@ class _OrganizationListState extends State<OrganizationList> {
Future<void> loadAllOrganization() async { Future<void> loadAllOrganization() async {
try { try {
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
setState(() { setState(() {
apiAllOrganization = result; apiAllOrganization = result;
}); });
@ -54,8 +54,10 @@ class _OrganizationListState extends State<OrganizationList> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder(builder: (context, sizingInfo) { return ResponsiveBuilder(
bool isDesktop = sizingInfo.deviceScreenType == DeviceScreenType.desktop; builder: (context, sizingInfo) {
bool isDesktop =
sizingInfo.deviceScreenType == DeviceScreenType.desktop;
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
@ -66,11 +68,12 @@ class _OrganizationListState extends State<OrganizationList> {
body: Row( body: Row(
children: [ children: [
// if (isDesktop) CustomDrawer(isDesktop: true), // if (isDesktop) CustomDrawer(isDesktop: true),
Expanded(child: buildGroupListLayout(isDesktop)) Expanded(child: buildGroupListLayout(isDesktop)),
], ],
), ),
); );
}); },
);
} }
Widget buildGroupListLayout(bool isDesktop) { Widget buildGroupListLayout(bool isDesktop) {
@ -86,9 +89,10 @@ class _OrganizationListState extends State<OrganizationList> {
children: [ children: [
Row( Row(
children: [ children: [
const Text('Organization List', const Text(
style: 'Organization List',
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
IconButton( IconButton(
icon: const Icon(Icons.keyboard_arrow_down), icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () {}, onPressed: () {},
@ -98,20 +102,16 @@ class _OrganizationListState extends State<OrganizationList> {
ElevatedButton( ElevatedButton(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
foregroundColor: Colors.white, foregroundColor: Colors.white,
backgroundColor: Colors.blueAccent), backgroundColor: Colors.blueAccent,
),
onPressed: () async { onPressed: () async {
// List<dynamic> users = await futureUsers; // List<dynamic> users = await futureUsers;
// context.go('/CreateGroup'); // context.go('/CreateGroup');
}, },
child: Row( child: Row(
children: [ children: [
Icon( Icon(Icons.add_circle, color: Colors.white),
Icons.add_circle, SizedBox(width: 5),
color: Colors.white,
),
SizedBox(
width: 5,
),
Text('Create Organization'), Text('Create Organization'),
], ],
), ),
@ -127,16 +127,12 @@ class _OrganizationListState extends State<OrganizationList> {
// color: Colors.red.shade100, // color: Colors.red.shade100,
child: SingleChildScrollView( child: SingleChildScrollView(
scrollDirection: Axis.vertical, scrollDirection: Axis.vertical,
child: Column( child: Column(children: [buildGroupListView(isDesktop)]),
children: [
buildGroupListView(isDesktop),
],
),
), ),
), ),
), ),
], ],
) ),
], ],
), ),
); );
@ -169,12 +165,20 @@ class _OrganizationListState extends State<OrganizationList> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text("Organization Name: ${group['name']}", Text(
"Organization Name: ${group['name']}",
style: TextStyle( style: TextStyle(
fontSize: 13, fontWeight: FontWeight.bold)), fontSize: 13,
Text("Organization Name: ${group['name']}", fontWeight: FontWeight.bold,
),
),
Text(
"Organization Name: ${group['name']}",
style: TextStyle( style: TextStyle(
fontSize: 13, fontWeight: FontWeight.bold)), fontSize: 13,
fontWeight: FontWeight.bold,
),
),
], ],
), ),
SizedBox(height: 4), SizedBox(height: 4),

View File

@ -162,7 +162,7 @@ class ForexDataState extends State<ForexData> {
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -325,6 +325,11 @@ class ForexDataState extends State<ForexData> {
setState(() { setState(() {
isDisable = false; isDisable = false;
}); });
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
if (context.mounted) { if (context.mounted) {
Navigator.of(context).pop(); Navigator.of(context).pop();

View File

@ -175,6 +175,11 @@ class ForexDataListState extends State<ForexDataList> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -225,6 +230,11 @@ class ForexDataListState extends State<ForexDataList> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -843,7 +853,10 @@ class ForexDataListState extends State<ForexDataList> {
if (forexId != null) { if (forexId != null) {
print("ForexId -- $forexId"); print("ForexId -- $forexId");
final data = await apiService final data = await apiService
.getForexDetailsFind(forexId); .getForexDetailsFind(
context,
forexId,
);
print("ForexId -- $data"); print("ForexId -- $data");
showDialog( showDialog(
@ -930,7 +943,10 @@ class ForexDataListState extends State<ForexDataList> {
if (forexId != null) { if (forexId != null) {
print("ForexId -- $forexId"); print("ForexId -- $forexId");
final data = await apiService final data = await apiService
.getForexDetailsFind(forexId); .getForexDetailsFind(
context,
forexId,
);
print("ForexId -- $data"); print("ForexId -- $data");
showDialog( showDialog(

View File

@ -3,6 +3,7 @@ import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:dropdown_search/dropdown_search.dart'; import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'package:super_tooltip/super_tooltip.dart'; import 'package:super_tooltip/super_tooltip.dart';
import 'package:web/web.dart' as web; import 'package:web/web.dart' as web;
@ -850,7 +851,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 404) { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else if (response.statusCode == 404) {
showDialog( showDialog(
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
@ -1015,7 +1023,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
@ -1087,7 +1102,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
@ -1141,7 +1163,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
@ -1193,7 +1222,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
@ -1348,7 +1384,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
// Close loading dialog (ONLY if still mounted) // Close loading dialog (ONLY if still mounted)
if (mounted) Navigator.of(context, rootNavigator: true).pop(); if (mounted) Navigator.of(context, rootNavigator: true).pop();
context.go('/approvallist'); context.go('/approvallist');
} else { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else {
print("$methodName failed. Status: ${response.statusCode}"); print("$methodName failed. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
} }
@ -1559,7 +1602,14 @@ class CreateNewPlansState extends State<CreateNewPlan> {
// ? context.go('/approvallist') // ? context.go('/approvallist')
// : context.go('/listPlan'); // : context.go('/listPlan');
// } // }
} else { }
else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}
else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -3325,7 +3375,7 @@ class CreateNewPlansState extends State<CreateNewPlan> {
_showInputDialog(selected["title"]!); _showInputDialog(selected["title"]!);
} else if (_selectedOption == "Option 1") { } else if (_selectedOption == "Option 1") {
otherUserName = userName; otherUserName = userName;
await apiService.handleTripWiseToken(selfId!); await apiService.handleTripWiseToken(selfId!, context);
fetchUserDetails(); fetchUserDetails();
_selectedTripType = null; _selectedTripType = null;
dynamicItineraryKey.currentState dynamicItineraryKey.currentState
@ -3726,6 +3776,9 @@ class CreateNewPlansState extends State<CreateNewPlan> {
), ),
keyboardType: TextInputType.text, keyboardType: TextInputType.text,
scrollPhysics: BouncingScrollPhysics(), scrollPhysics: BouncingScrollPhysics(),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9_ ]')),
],
), ),
), ),
), ),
@ -4242,10 +4295,12 @@ class CreateNewPlansState extends State<CreateNewPlan> {
if (isTraveller) { if (isTraveller) {
await apiService.handleTripWiseToken( await apiService.handleTripWiseToken(
selfId!, selfId!,
context,
); // since userId is for traveller ); // since userId is for traveller
} else { } else {
await apiService.handleTripWiseToken( await apiService.handleTripWiseToken(
userId, userId,
context,
); // fallback to selfId ); // fallback to selfId
} }
@ -4256,7 +4311,7 @@ class CreateNewPlansState extends State<CreateNewPlan> {
}, },
onClose: () async { onClose: () async {
print("Choosede Clsoes"); print("Choosede Clsoes");
await apiService.handleTripWiseToken(selfId!); await apiService.handleTripWiseToken(selfId!, context);
fetchUserDetails(); fetchUserDetails();
}, },
layoutColorForUser: widget.layoutColor!, layoutColorForUser: widget.layoutColor!,

View File

@ -849,6 +849,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
showDialog( showDialog(
context: context, context: context,
@ -989,6 +994,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -1061,6 +1071,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -1115,6 +1130,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -1167,6 +1187,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -1322,6 +1347,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
// Close loading dialog (ONLY if still mounted) // Close loading dialog (ONLY if still mounted)
if (mounted) Navigator.of(context, rootNavigator: true).pop(); if (mounted) Navigator.of(context, rootNavigator: true).pop();
context.go('/approvallist'); context.go('/approvallist');
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("$methodName failed. Status: ${response.statusCode}"); print("$methodName failed. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -1533,6 +1563,11 @@ class CreateNewPlansState extends State<CreateNewPlan> {
// ? context.go('/approvallist') // ? context.go('/approvallist')
// : context.go('/listPlan'); // : context.go('/listPlan');
// } // }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -199,7 +199,7 @@ class DynamicItineraryState extends State<DynamicItinerary> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllServices(); final result = await apiService.fetchAllServices(context);
setState(() { setState(() {
selectedAllServices = result; selectedAllServices = result;
}); });
@ -213,7 +213,7 @@ class DynamicItineraryState extends State<DynamicItinerary> {
Future<void> loadOrgSelectedAlServices() async { Future<void> loadOrgSelectedAlServices() async {
print('loadOrgSelectedAlServices'); print('loadOrgSelectedAlServices');
try { try {
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
if (result != null && result is Map<String, dynamic>) { if (result != null && result is Map<String, dynamic>) {
final rawServices = result['services_ids']; final rawServices = result['services_ids'];

View File

@ -119,7 +119,7 @@ class _ListPlansState extends State<ListPlans> {
), ),
TextButton( TextButton(
onPressed: () async { onPressed: () async {
Navigator.pop(context); // Close dialog // Navigator.pop(context); // Close dialog
_dialogShown = false; _dialogShown = false;
await _logoutAndRedirect(context); await _logoutAndRedirect(context);
}, },
@ -132,12 +132,13 @@ class _ListPlansState extends State<ListPlans> {
Future<void> _logoutAndRedirect(BuildContext context) async { Future<void> _logoutAndRedirect(BuildContext context) async {
print("logue 0"); print("logue 0");
await apiService.logout(context);
// Example: clear session or shared preferences // // Example: clear session or shared preferences
final prefs = await SharedPreferences.getInstance(); // final prefs = await SharedPreferences.getInstance();
await prefs.clear(); // await prefs.clear();
context.go("/"); // context.go("/");
print("logue 1"); print("logue 1");
} }
@ -155,6 +156,7 @@ class _ListPlansState extends State<ListPlans> {
} else { } else {
if (roleUser == "User") { if (roleUser == "User") {
print("user"); print("user");
print("roleUsers - $roleUser");
// After login is successful and navigation completes: // After login is successful and navigation completes:
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
@ -304,6 +306,11 @@ class _ListPlansState extends State<ListPlans> {
// List<dynamic> plansJson = []; // List<dynamic> plansJson = [];
List<dynamic> plansJson = data['data']; List<dynamic> plansJson = data['data'];
return plansJson.map((json) => Plan.fromJson(json)).toList(); return plansJson.map((json) => Plan.fromJson(json)).toList();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -337,6 +344,11 @@ class _ListPlansState extends State<ListPlans> {
print("Plan Deleted successfully!"); print("Plan Deleted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
initializeData(); initializeData();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -363,7 +375,10 @@ class _ListPlansState extends State<ListPlans> {
if (confirmed) { if (confirmed) {
try { try {
Map<String, dynamic> planData = await ApiService.getViewPlan(planId); Map<String, dynamic> planData = await ApiService().getViewPlan(
planId,
context,
);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
refresh(); refresh();
// postPlanData(planData, planId); // postPlanData(planData, planId);
@ -415,6 +430,11 @@ class _ListPlansState extends State<ListPlans> {
approverData = List<Map<String, dynamic>>.from( approverData = List<Map<String, dynamic>>.from(
data['data']['approver_data'] ?? [], data['data']['approver_data'] ?? [],
); );
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print('Failed to load'); print('Failed to load');
label = "Error - Failed to load data"; label = "Error - Failed to load data";
@ -1185,7 +1205,7 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); // Close popup manually ); // Close popup manually
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1211,7 +1231,7 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1255,6 +1275,7 @@ class _ListPlansState extends State<ListPlans> {
); );
apiService apiService
.getPdfDownload( .getPdfDownload(
context,
plan.planId, plan.planId,
); );
}, },
@ -1281,8 +1302,8 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getForexPdfDownload(
.getForexPdfDownload( context,
plan.forexId, plan.forexId,
); );
}, },
@ -1529,7 +1550,7 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); // Close popup manually ); // Close popup manually
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1556,7 +1577,7 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: isViewMode:
@ -1598,8 +1619,8 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getPdfDownload(
.getPdfDownload( context,
plan.planId, plan.planId,
); );
}, },
@ -1626,8 +1647,8 @@ class _ListPlansState extends State<ListPlans> {
Navigator.pop( Navigator.pop(
context, context,
); );
apiService apiService.getForexPdfDownload(
.getForexPdfDownload( context,
plan.forexId, plan.forexId,
); );
}, },

File diff suppressed because it is too large Load Diff

View File

@ -240,7 +240,7 @@ class _PolicyState extends State<Policy> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllServices(); final result = await apiService.fetchAllServices(context);
setState(() { setState(() {
selectedAllServices = result; selectedAllServices = result;
}); });
@ -252,7 +252,7 @@ class _PolicyState extends State<Policy> {
Future<void> loadOrgSelectedAlServices() async { Future<void> loadOrgSelectedAlServices() async {
try { try {
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
if (result != null && result is Map<String, dynamic>) { if (result != null && result is Map<String, dynamic>) {
final rawServices = result['services_ids']; final rawServices = result['services_ids'];
@ -504,7 +504,7 @@ class _PolicyState extends State<Policy> {
bool result = false; bool result = false;
try { try {
result = await createPolicyData(data); result = await createPolicyData(context, data);
} catch (e) { } catch (e) {
print("Unexpected error during policy creation: $e"); print("Unexpected error during policy creation: $e");
} }
@ -586,7 +586,10 @@ class _PolicyState extends State<Policy> {
} }
} }
Future<bool> createPolicyData(Map<String, dynamic> policyData) async { Future<bool> createPolicyData(
BuildContext context,
Map<String, dynamic> policyData,
) async {
final String apiUrldata = '$apiUrl/api/policy/createOrUpdate'; final String apiUrldata = '$apiUrl/api/policy/createOrUpdate';
final token = await getToken(); // Fetch token final token = await getToken(); // Fetch token
@ -616,9 +619,14 @@ class _PolicyState extends State<Policy> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
print("policyData submitted successfully!"); print("policyData submitted successfully!");
await apiService.handleTokenRefresh(userId!); await apiService.handleTokenRefresh(context, userId!);
print("Response: ${response.body}"); print("Response: ${response.body}");
return true; return true;
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return false;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit policyData. Status: ${response.statusCode}"); print("Failed to submit policyData. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -415,7 +415,7 @@ class PolicyCriteriaState extends State<PolicyCriteria> {
Future<void> fetchTrainFlightClass() async { Future<void> fetchTrainFlightClass() async {
print("ftech api"); print("ftech api");
try { try {
final data = await apiService.fetchMasterDropdown(); final data = await apiService.fetchMasterDropdown(context);
print("fetchTrainFlightClass - $data"); print("fetchTrainFlightClass - $data");

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,428 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:frontend/Screens/group/group.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:responsive_builder/responsive_builder.dart';
import '../../config/apiUrl.dart';
import '../../routes/custom_appBar.dart';
import '../../routes/custom_drawer.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart';
class PolicyListBackup extends StatefulWidget {
@override
_PolicyListBackupState createState() => _PolicyListBackupState();
}
class _PolicyListBackupState extends State<PolicyListBackup> {
final ApiService apiService = ApiService();
List<dynamic>? apiAllGroups;
Color? layoutColor;
Color? bodyColor;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
loadAllGroups();
loadInitialData();
});
}
void loadInitialData() async {
String? layoutString = await getLayoutColor();
String? bodyStringColor = await getBodyColor();
setState(() {
layoutColor =
layoutString != null
? Color(int.parse(layoutString))
: Colors.redAccent;
bodyColor =
bodyStringColor != null
? Color(int.parse(bodyStringColor))
: Colors.white;
});
}
Future<void> loadAllGroups() async {
try {
final result = await apiService.fetchAllPolicy();
// Sort by policy_id descending (latest first)
result.sort((a, b) {
int idA = int.tryParse(a['policy_id'].toString()) ?? 0;
int idB = int.tryParse(b['policy_id'].toString()) ?? 0;
return idB.compareTo(idA); // latest first
});
setState(() {
apiAllGroups = result;
});
print("Fetched services: $apiAllGroups");
} catch (e) {
print('Error fetching role list: $e');
}
}
void handleActiveStatus(
Map<String, dynamic> policyData,
String policyId,
String currentStatus,
) async {
print("Toggling user status - $policyId (Current: $currentStatus)");
final String apiUrlData =
'$apiUrl/api/policy/createOrUpdate'; // API for updating user
final String? token = await getToken();
if (token == null) {
print("Error: Token not found");
return;
}
// Toggle status: If active ("1"), set to inactive ("0"); otherwise, activate ("1")
String newStatus = (currentStatus == "1") ? "0" : "1";
print("STatus 1 - $newStatus");
final int? selectedPolicyId;
if (policyId.isNotEmpty) {
selectedPolicyId = int.tryParse(policyId);
policyData['policy_id'] = selectedPolicyId; // Add only if updating
policyData['is_active'] = newStatus; // Add only if updating
}
try {
final response = await http.post(
Uri.parse(apiUrlData),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
body: jsonEncode(policyData), // Convert map to JSON
);
if (response.statusCode == 200) {
print("policyData submitted successfully!");
print("Response: ${response.body}");
loadAllGroups();
} else {
print("Failed to submit policyData. Status: ${response.statusCode}");
print("Error: ${response.body}");
}
} catch (e) {
print(" Error submitting policyData: $e");
}
}
void deletePolicy(Map<String, dynamic> policydata, policyId, status) {
print("policyId : $policyId");
print("policystatus: $status");
print("policysData: $policydata");
// handleActiveStatus(groupdata, groupId, status);
print("Calling handleActiveStatus with: id=$policyId, status=$status");
handleActiveStatus(policydata, policyId.toString(), status.toString());
}
// Future<void> deleteGroupFromApi(int groupId) async {
// try {
// await apiService.deleteGroup(groupId); // your delete API call
// deleteGroup(groupId); // remove from UI list
// } catch (e) {
// print('Error deleting group: $e');
// }
// }'
@override
Widget build(BuildContext context) {
return ResponsiveBuilder(
builder: (context, sizingInfo) {
bool isDesktop =
sizingInfo.deviceScreenType == DeviceScreenType.desktop;
return Scaffold(
backgroundColor: Color(0xFFf5f5f5),
appBar: CustomAppBar(isDesktop: isDesktop),
drawer: CustomDrawer(isDesktop: false),
body: Padding(
padding:
isDesktop
? EdgeInsets.symmetric(
horizontal:
MediaQuery.of(context).size.width *
0.1, // 30% of screen width as horizontal padding
vertical:
MediaQuery.of(context).size.height *
0, // 5% of screen height as vertical padding
)
: EdgeInsets.all(0),
child: Row(
children: [
// if (isDesktop) CustomDrawer(isDesktop: true),
Expanded(child: buildGroupList(isDesktop)),
],
),
),
);
},
);
}
Widget buildGroupList(bool isDesktop) {
return Container(
margin: isDesktop ? const EdgeInsets.only(top: 10.0, bottom: 10.0) : null,
padding: const EdgeInsets.only(left: 10, right: 10, top: 8),
decoration: BoxDecoration(
color: isDesktop ? Colors.white : Color(0xFFFCFCFC),
),
// decoration: BoxDecoration(
// // color: Colors.amber,
// color: Color(0xFFE1F5FE),
// // color: bodyColor,
// border: Border.all(
// // color: Color(0xFFF7F7FB),
// color: Colors.white,
// width: 3.5)),
child: buildGroupListLayout(isDesktop),
);
}
Widget buildGroupListLayout(bool isDesktop) {
return Container(
// margin: isDesktop
// ? EdgeInsets.all(10.0)
// : EdgeInsets.only(left: 20.0, bottom: 20.0, top: 10.0, right: 20.0),
// padding: const EdgeInsets.all(10),
height:
isDesktop
? MediaQuery.of(context).size.height * 0.98
: MediaQuery.of(context).size.height,
// decoration: BoxDecoration(
// border: isDesktop
// ? Border.all(
// width: 2,
// color: Colors.white,
// // color: Color(0xFFF7F7FB),
// )
// : null,
// color: Colors.white,
// // color: Color(0xFFF7F7FB),
//
// // color: Colors.amber,
// ),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Text(
'Policy List',
style: GoogleFonts.poppins(
fontSize: isDesktop ? 16 : 14,
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
IconButton(
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () {},
),
],
),
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: Color(0xFF114D8B),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
// side: BorderSide(color: , width: 1),
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
),
onPressed: () async {
// List<dynamic> users = await futureUsers;
context.go('/Policy');
},
child: Row(
children: [
Text(
'New Policy',
style: GoogleFonts.poppins(fontSize: 12),
),
SizedBox(width: 5),
Icon(Icons.add_circle_outline_rounded, color: Colors.white),
],
),
),
],
),
SizedBox(height: 5),
Row(
children: [
Expanded(
child: Container(
height: MediaQuery.of(context).size.height * 0.8,
padding: const EdgeInsets.all(10),
// margin: const EdgeInsets.only(bottom: 10),
color: Colors.white,
// color: Colors.red.shade100,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(children: [buildGroupListView(isDesktop)]),
),
),
),
],
),
],
),
);
}
// Widget buildGroupListView(bool isDesktop) {
// return Container(
// child: Text("DAta"),
// );
// }
Widget buildGroupListView(bool isDesktop) {
if (apiAllGroups == null || apiAllGroups!.isEmpty) {
return Center(child: Text("No Policy Found."));
}
return ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: apiAllGroups!.length,
itemBuilder: (context, index) {
final policy = apiAllGroups![index];
return Card(
// color: bodyColor,
// color: Color(0xFFF5F5F5),
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 6, horizontal: 10),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
flex: 1,
child: Text(
"Policy Name",
style: GoogleFonts.poppins(
fontSize: 11.5,
fontWeight: FontWeight.w400,
),
),
),
Expanded(
flex: 1,
child: Text(
"Policy Type",
style: GoogleFonts.poppins(
fontSize: 11.5,
fontWeight: FontWeight.w400,
),
),
),
// Expanded(flex: 1, child: Text("${policy['created_by']}")),
],
),
SizedBox(height: 4),
Row(
children: [
Expanded(
flex: 1,
child: Text(
"${policy['name']}",
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
Expanded(
flex: 1,
child: Text(
policy['domestic'] == "1"
? "Domestic"
: "International",
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
// Expanded(flex: 1, child: Text("${policy['created_by']}")),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
GestureDetector(
onTap: () async {
final rawId = policy['policy_id'];
final intPolicyId =
rawId is int
? rawId
: int.tryParse(rawId.toString()) ?? 0;
Map<String, dynamic> policyData = await apiService
.getSinglePolicy(intPolicyId);
print("PolicyDATa: $policyData");
context.go("/Policy", extra: policyData);
},
child: Image.asset(
'assets/images/IconsImg/edit.png',
width: 20,
height: 15,
),
),
SizedBox(width: 5),
GestureDetector(
onTap: () {
final idStr = policy['policy_id'];
final id = int.tryParse(idStr.toString());
if (id == null) {
print("group_id is null");
return;
}
final status = policy['is_active'];
deletePolicy(policy, id, status);
},
child: Image.asset(
'assets/images/IconsImg/delete.png',
width: 20,
height: 15,
),
),
],
),
],
),
),
);
},
);
}
}

View File

@ -217,7 +217,7 @@ class _PolicyState extends State<Policy> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllServices(); final result = await apiService.fetchAllServices(context);
setState(() { setState(() {
selectedAllServices = result; selectedAllServices = result;
}); });
@ -229,7 +229,7 @@ class _PolicyState extends State<Policy> {
Future<void> loadOrgSelectedAlServices() async { Future<void> loadOrgSelectedAlServices() async {
try { try {
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
if (result != null && result is Map<String, dynamic>) { if (result != null && result is Map<String, dynamic>) {
final rawServices = result['services_ids']; final rawServices = result['services_ids'];

View File

@ -112,7 +112,7 @@ class _PolicyListState extends State<PolicyList> {
} }
Future<List<dynamic>> fetchPolicy() async { Future<List<dynamic>> fetchPolicy() async {
final data = await apiService.fetchAllPolicy(); final data = await apiService.fetchAllPolicy(context);
return data; // Returning raw JSON list return data; // Returning raw JSON list
} }
@ -196,6 +196,11 @@ class _PolicyListState extends State<PolicyList> {
print("policyData submitted successfully!"); print("policyData submitted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
loadAllGroups(); loadAllGroups();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
print("Failed to submit policyData. Status: ${response.statusCode}"); print("Failed to submit policyData. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
@ -219,7 +224,7 @@ class _PolicyListState extends State<PolicyList> {
Future<void> loadAllGroups() async { Future<void> loadAllGroups() async {
try { try {
final result = await apiService.fetchAllPolicy(); final result = await apiService.fetchAllPolicy(context);
setState(() { setState(() {
allPolicy = result; allPolicy = result;
filteredPolicy = result; filteredPolicy = result;
@ -679,6 +684,7 @@ class _PolicyListState extends State<PolicyList> {
await apiService await apiService
.getSinglePolicy( .getSinglePolicy(
intPolicyId, intPolicyId,
context,
); );
print("PolicyDATa: $policyData"); print("PolicyDATa: $policyData");
@ -805,6 +811,7 @@ class _PolicyListState extends State<PolicyList> {
await apiService await apiService
.getSinglePolicy( .getSinglePolicy(
intPolicyId, intPolicyId,
context,
); );
print("PolicyDATa: $policyData"); print("PolicyDATa: $policyData");
@ -971,6 +978,7 @@ class _PolicyListState extends State<PolicyList> {
Map<String, dynamic> policyData = Map<String, dynamic> policyData =
await apiService.getSinglePolicy( await apiService.getSinglePolicy(
intPolicyId, intPolicyId,
context,
); );
print("PolicyDATa: $policyData"); print("PolicyDATa: $policyData");

View File

@ -156,6 +156,11 @@ class PurposeOfTravelListState extends State<PurposeOfTravelList> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -657,6 +662,7 @@ class PurposeOfTravelListState extends State<PurposeOfTravelList> {
); );
final data = await apiService final data = await apiService
.getPurposeOfTravelDetailsFind( .getPurposeOfTravelDetailsFind(
context,
purposeOfTravelId, purposeOfTravelId,
); );
print("PurposeOfTravelId -- $data"); print("PurposeOfTravelId -- $data");
@ -752,6 +758,7 @@ class PurposeOfTravelListState extends State<PurposeOfTravelList> {
); );
final data = await apiService final data = await apiService
.getPurposeOfTravelDetailsFind( .getPurposeOfTravelDetailsFind(
context,
purposeOfTravelId, purposeOfTravelId,
); );
print("PurposeOfTravelId -- $data"); print("PurposeOfTravelId -- $data");

View File

@ -290,6 +290,7 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
loaderFlag = true; loaderFlag = true;
try { try {
final result = await apiService.CallReports( final result = await apiService.CallReports(
context,
'advancePurchaseReport', 'advancePurchaseReport',
jsonEncode({ jsonEncode({
"fromDate": '$formattedfromDate', "fromDate": '$formattedfromDate',
@ -329,7 +330,6 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
if (textControllers["from_date"]!.text.isEmpty || if (textControllers["from_date"]!.text.isEmpty ||
textControllers["to_date"]!.text.isEmpty) { textControllers["to_date"]!.text.isEmpty) {
Fluttertoast.showToast( Fluttertoast.showToast(
msg: "Please choose a valid date range.", msg: "Please choose a valid date range.",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
@ -356,8 +356,6 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
final safeName = name.replaceAll(RegExp(r'[^\w\s-]'), ''); final safeName = name.replaceAll(RegExp(r'[^\w\s-]'), '');
final excelName = '$safeName'; final excelName = '$safeName';
Map<String, dynamic> result = { Map<String, dynamic> result = {
"status": false, "status": false,
"message": "Data Not Found", "message": "Data Not Found",
@ -365,6 +363,7 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) { if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'advancePurchaseReport', 'advancePurchaseReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -374,8 +373,10 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
excelName, excelName,
); );
} }
if (selectedTabName == 'international' && dataAvailableInternationFlag == 1) { if (selectedTabName == 'international' &&
dataAvailableInternationFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'advancePurchaseReport', 'advancePurchaseReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -386,21 +387,23 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
); );
} }
final String displayBackgroundColor =
final String displayBackgroundColor = result['status'] ? '#28a745' : '#dc1c13'; result['status'] ? '#28a745' : '#dc1c13';
final Color displayColor = result['status'] ? Colors.green : Colors.redAccent; final Color displayColor =
result['status'] ? Colors.green : Colors.redAccent;
final String displayMessage = result['message']; final String displayMessage = result['message'];
// final bool status = result['status'] == true; // final bool status = result['status'] == true;
Fluttertoast.showToast( Fluttertoast.showToast(
msg: displayMessage , msg: displayMessage,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
backgroundColor: displayColor, backgroundColor: displayColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
webBgColor: "linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)", webBgColor:
"linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)",
); );
} }
@ -441,17 +444,18 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ?? (object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['Service']?.toLowerCase().contains(lowerQuery) ?? (object['Service']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['created_on']?.toLowerCase().contains(lowerQuery) ?? false) || (object['created_on']?.toLowerCase().contains(lowerQuery) ??
(object['created_time']?.toLowerCase().contains(lowerQuery) ?? false) || false) ||
(object['FirstTravelDt']?.toLowerCase().contains(lowerQuery) ?? false) || (object['created_time']?.toLowerCase().contains(lowerQuery) ??
false) ||
(object['FirstTravelDt']?.toLowerCase().contains(lowerQuery) ??
false) ||
(object['AdvPurch']?.toLowerCase().contains(lowerQuery)); (object['AdvPurch']?.toLowerCase().contains(lowerQuery));
}).toList(); }).toList();
currentPage1 = 0; currentPage1 = 0;
@ -498,17 +502,18 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ?? (object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['Service']?.toLowerCase().contains(lowerQuery) ?? (object['Service']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['created_on']?.toLowerCase().contains(lowerQuery) ?? false) || (object['created_on']?.toLowerCase().contains(lowerQuery) ??
(object['created_time']?.toLowerCase().contains(lowerQuery) ?? false) || false) ||
(object['FirstTravelDt']?.toLowerCase().contains(lowerQuery) ?? false) || (object['created_time']?.toLowerCase().contains(lowerQuery) ??
false) ||
(object['FirstTravelDt']?.toLowerCase().contains(lowerQuery) ??
false) ||
(object['AdvPurch']?.toLowerCase().contains(lowerQuery)); (object['AdvPurch']?.toLowerCase().contains(lowerQuery));
}).toList(); }).toList();
currentPage2 = 0; currentPage2 = 0;
@ -1074,8 +1079,10 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
paginatedDomestic.map(( paginatedDomestic.map((
entry, entry,
) { ) {
final FromDate = entry['created_on']; final FromDate =
final ToDate = entry['FirstTravelDt']; entry['created_on'];
final ToDate =
entry['FirstTravelDt'];
return DataRow( return DataRow(
cells: [ cells: [
DataCell( DataCell(
@ -1647,8 +1654,10 @@ class _AdvancePurchaseState extends State<AdvancePurchase>
paginatedInternational.map(( paginatedInternational.map((
entry, entry,
) { ) {
final FromDate = entry['created_on']; final FromDate =
final ToDate = entry['FirstTravelDt']; entry['created_on'];
final ToDate =
entry['FirstTravelDt'];
return DataRow( return DataRow(
cells: [ cells: [
DataCell( DataCell(

View File

@ -266,6 +266,7 @@ class _GuestHouseState extends State<GuestHouse>
loaderFlag = true; loaderFlag = true;
try { try {
final result = await apiService.CallReports( final result = await apiService.CallReports(
context,
'guestHouseReport', 'guestHouseReport',
jsonEncode({ jsonEncode({
"fromDate": '$formattedfromDate', "fromDate": '$formattedfromDate',
@ -303,9 +304,8 @@ class _GuestHouseState extends State<GuestHouse>
if (textControllers["from_date"]!.text.isEmpty || if (textControllers["from_date"]!.text.isEmpty ||
textControllers["to_date"]!.text.isEmpty) { textControllers["to_date"]!.text.isEmpty) {
Fluttertoast.showToast( Fluttertoast.showToast(
msg: "Please choose a valid date range." , msg: "Please choose a valid date range.",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
@ -332,6 +332,7 @@ class _GuestHouseState extends State<GuestHouse>
final excelName = '$safeName'; final excelName = '$safeName';
final result = await apiService.reportExcelDownload( final result = await apiService.reportExcelDownload(
context,
'guestHouseReport', 'guestHouseReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -341,20 +342,23 @@ class _GuestHouseState extends State<GuestHouse>
excelName, excelName,
); );
final String displayBackgroundColor = result['status'] ? '#28a745' : '#dc1c13'; final String displayBackgroundColor =
final Color displayColor = result['status'] ? Colors.green : Colors.redAccent; result['status'] ? '#28a745' : '#dc1c13';
final Color displayColor =
result['status'] ? Colors.green : Colors.redAccent;
final String displayMessage = result['message']; final String displayMessage = result['message'];
// final bool status = result['status'] == true; // final bool status = result['status'] == true;
Fluttertoast.showToast( Fluttertoast.showToast(
msg: displayMessage , msg: displayMessage,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
backgroundColor: displayColor, backgroundColor: displayColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
webBgColor: "linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)", webBgColor:
"linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)",
); );
} }
@ -385,9 +389,7 @@ class _GuestHouseState extends State<GuestHouse>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['flight_trip_type']?.toLowerCase().contains( (object['flight_trip_type']?.toLowerCase().contains(
lowerQuery, lowerQuery,
@ -433,9 +435,7 @@ class _GuestHouseState extends State<GuestHouse>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['flight_trip_type']?.toLowerCase().contains( (object['flight_trip_type']?.toLowerCase().contains(
lowerQuery, lowerQuery,

View File

@ -267,6 +267,7 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
loaderFlag = true; loaderFlag = true;
try { try {
final result = await apiService.CallReports( final result = await apiService.CallReports(
context,
'misAirReport', 'misAirReport',
jsonEncode({ jsonEncode({
"fromDate": '$formattedfromDate', "fromDate": '$formattedfromDate',
@ -308,7 +309,6 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
if (textControllers["from_date"]!.text.isEmpty || if (textControllers["from_date"]!.text.isEmpty ||
textControllers["to_date"]!.text.isEmpty) { textControllers["to_date"]!.text.isEmpty) {
Fluttertoast.showToast( Fluttertoast.showToast(
msg: "Please choose a valid date range.", msg: "Please choose a valid date range.",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
@ -335,7 +335,6 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
final safeName = name.replaceAll(RegExp(r'[^\w\s-]'), ''); final safeName = name.replaceAll(RegExp(r'[^\w\s-]'), '');
final excelName = '$safeName'; final excelName = '$safeName';
Map<String, dynamic> result = { Map<String, dynamic> result = {
"status": false, "status": false,
"message": "Data Not Found", "message": "Data Not Found",
@ -343,6 +342,7 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) { if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misAirReport', 'misAirReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -352,8 +352,10 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
excelName, excelName,
); );
} }
if (selectedTabName == 'international' && dataAvailableInternationFlag == 1) { if (selectedTabName == 'international' &&
dataAvailableInternationFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misAirReport', 'misAirReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -364,20 +366,23 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
); );
} }
final String displayBackgroundColor = result['status'] ? '#28a745' : '#dc1c13'; final String displayBackgroundColor =
final Color displayColor = result['status'] ? Colors.green : Colors.redAccent; result['status'] ? '#28a745' : '#dc1c13';
final Color displayColor =
result['status'] ? Colors.green : Colors.redAccent;
final String displayMessage = result['message']; final String displayMessage = result['message'];
// final bool status = result['status'] == true; // final bool status = result['status'] == true;
Fluttertoast.showToast( Fluttertoast.showToast(
msg: displayMessage , msg: displayMessage,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
backgroundColor: displayColor, backgroundColor: displayColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
webBgColor: "linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)", webBgColor:
"linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)",
); );
} }
@ -408,9 +413,7 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['flight_trip_type']?.toLowerCase().contains( (object['flight_trip_type']?.toLowerCase().contains(
lowerQuery, lowerQuery,
@ -420,7 +423,10 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
false) || false) ||
(object['flight_class']?.toLowerCase().contains(lowerQuery) ?? (object['flight_class']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['flight_travel_date']?.toLowerCase().contains(lowerQuery) ?? false) || (object['flight_travel_date']?.toLowerCase().contains(
lowerQuery,
) ??
false) ||
(object['sector']?.toLowerCase().contains(lowerQuery)); (object['sector']?.toLowerCase().contains(lowerQuery));
}).toList(); }).toList();
currentPage1 = 0; currentPage1 = 0;
@ -457,9 +463,7 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['flight_trip_type']?.toLowerCase().contains( (object['flight_trip_type']?.toLowerCase().contains(
lowerQuery, lowerQuery,
@ -469,7 +473,10 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
false) || false) ||
(object['flight_class']?.toLowerCase().contains(lowerQuery) ?? (object['flight_class']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['flight_travel_date']?.toLowerCase().contains(lowerQuery) ?? false) || (object['flight_travel_date']?.toLowerCase().contains(
lowerQuery,
) ??
false) ||
(object['sector']?.toLowerCase().contains(lowerQuery)); (object['sector']?.toLowerCase().contains(lowerQuery));
}).toList(); }).toList();
currentPage2 = 0; currentPage2 = 0;
@ -1024,7 +1031,8 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
paginatedDomestic.map(( paginatedDomestic.map((
entry, entry,
) { ) {
final TravelDate = entry['flight_travel_date']; final TravelDate =
entry['flight_travel_date'];
return DataRow( return DataRow(
cells: [ cells: [
DataCell( DataCell(
@ -1537,7 +1545,8 @@ class _MISairState extends State<MISair> with SingleTickerProviderStateMixin {
paginatedInternational.map(( paginatedInternational.map((
entry, entry,
) { ) {
final TravelDate = entry['flight_travel_date']; final TravelDate =
entry['flight_travel_date'];
return DataRow( return DataRow(
cells: [ cells: [
DataCell( DataCell(

View File

@ -234,6 +234,7 @@ class _MISforexState extends State<MISforex>
loaderFlag = true; loaderFlag = true;
try { try {
final result = await apiService.CallReports( final result = await apiService.CallReports(
context,
'misForexReport', 'misForexReport',
jsonEncode({ jsonEncode({
"fromDate": '$formattedfromDate', "fromDate": '$formattedfromDate',
@ -296,8 +297,10 @@ class _MISforexState extends State<MISforex>
"message": "Data Not Found", "message": "Data Not Found",
}; };
if (selectedTabName == 'international' && dataAvailableInternationFlag == 1) { if (selectedTabName == 'international' &&
dataAvailableInternationFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misForexReport', 'misForexReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -308,21 +311,23 @@ class _MISforexState extends State<MISforex>
); );
} }
final String displayBackgroundColor =
final String displayBackgroundColor = result['status'] ? '#28a745' : '#dc1c13'; result['status'] ? '#28a745' : '#dc1c13';
final Color displayColor = result['status'] ? Colors.green : Colors.redAccent; final Color displayColor =
result['status'] ? Colors.green : Colors.redAccent;
final String displayMessage = result['message']; final String displayMessage = result['message'];
// final bool status = result['status'] == true; // final bool status = result['status'] == true;
Fluttertoast.showToast( Fluttertoast.showToast(
msg: displayMessage , msg: displayMessage,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
backgroundColor: displayColor, backgroundColor: displayColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
webBgColor: "linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)", webBgColor:
"linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)",
); );
} }
@ -367,9 +372,7 @@ class _MISforexState extends State<MISforex>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['visiting_country']?.toLowerCase().contains( (object['visiting_country']?.toLowerCase().contains(
lowerQuery, lowerQuery,
@ -822,7 +825,8 @@ class _MISforexState extends State<MISforex>
paginatedInternational.map(( paginatedInternational.map((
entry, entry,
) { ) {
final forexFromDate = entry['forex_from_date']; final forexFromDate =
entry['forex_from_date'];
// DateFormat( // DateFormat(
// 'dd-MM-yyyy', // 'dd-MM-yyyy',
// ).format( // ).format(
@ -830,7 +834,8 @@ class _MISforexState extends State<MISforex>
// entry['forex_from_date'], // entry['forex_from_date'],
// ), // ),
// ); // );
final forexToDate = entry['forex_to_date']; final forexToDate =
entry['forex_to_date'];
// DateFormat( // DateFormat(
// 'dd-MM-yyyy', // 'dd-MM-yyyy',
// ).format( // ).format(

View File

@ -268,6 +268,7 @@ class _MIShotelState extends State<MIShotel>
loaderFlag = true; loaderFlag = true;
try { try {
final result = await apiService.CallReports( final result = await apiService.CallReports(
context,
'misHotelReport', 'misHotelReport',
jsonEncode({ jsonEncode({
"fromDate": '$formattedfromDate', "fromDate": '$formattedfromDate',
@ -309,7 +310,6 @@ class _MIShotelState extends State<MIShotel>
if (textControllers["from_date"]!.text.isEmpty || if (textControllers["from_date"]!.text.isEmpty ||
textControllers["to_date"]!.text.isEmpty) { textControllers["to_date"]!.text.isEmpty) {
Fluttertoast.showToast( Fluttertoast.showToast(
msg: "Please choose a valid date range.", msg: "Please choose a valid date range.",
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
@ -343,6 +343,7 @@ class _MIShotelState extends State<MIShotel>
if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) { if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misHotelReport', 'misHotelReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -352,8 +353,10 @@ class _MIShotelState extends State<MIShotel>
excelName, excelName,
); );
} }
if (selectedTabName == 'international' && dataAvailableInternationFlag == 1) { if (selectedTabName == 'international' &&
dataAvailableInternationFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misHotelReport', 'misHotelReport',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -364,20 +367,23 @@ class _MIShotelState extends State<MIShotel>
); );
} }
final String displayBackgroundColor = result['status'] ? '#28a745' : '#dc1c13'; final String displayBackgroundColor =
final Color displayColor = result['status'] ? Colors.green : Colors.redAccent; result['status'] ? '#28a745' : '#dc1c13';
final Color displayColor =
result['status'] ? Colors.green : Colors.redAccent;
final String displayMessage = result['message']; final String displayMessage = result['message'];
// final bool status = result['status'] == true; // final bool status = result['status'] == true;
Fluttertoast.showToast( Fluttertoast.showToast(
msg: displayMessage , msg: displayMessage,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
backgroundColor: displayColor, backgroundColor: displayColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
webBgColor: "linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)", webBgColor:
"linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)",
); );
} }
@ -421,16 +427,16 @@ class _MIShotelState extends State<MIShotel>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ?? (object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['hotel_name']?.toLowerCase().contains(lowerQuery) ?? (object['hotel_name']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['check_in_date'].toLowerCase().contains(lowerQuery) ?? false) || (object['check_in_date'].toLowerCase().contains(lowerQuery) ??
(object['check_out_date'].toLowerCase().contains(lowerQuery) ?? false) || false) ||
(object['check_out_date'].toLowerCase().contains(lowerQuery) ??
false) ||
(object['hotel_city']?.toLowerCase().contains(lowerQuery)); (object['hotel_city']?.toLowerCase().contains(lowerQuery));
}).toList(); }).toList();
currentPage1 = 0; currentPage1 = 0;
@ -479,16 +485,16 @@ class _MIShotelState extends State<MIShotel>
false) || false) ||
(object['so_number']?.toLowerCase().contains(lowerQuery) ?? (object['so_number']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['cost_center']?.toLowerCase().contains( (object['cost_center']?.toLowerCase().contains(lowerQuery) ??
lowerQuery,
) ??
false) || false) ||
(object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ?? (object['plan_trip_type']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['hotel_name']?.toLowerCase().contains(lowerQuery) ?? (object['hotel_name']?.toLowerCase().contains(lowerQuery) ??
false) || false) ||
(object['check_in_date']?.toLowerCase().contains(lowerQuery) ?? false) || (object['check_in_date']?.toLowerCase().contains(lowerQuery) ??
(object['check_out_date'].toLowerCase().contains(lowerQuery) ?? false) || false) ||
(object['check_out_date'].toLowerCase().contains(lowerQuery) ??
false) ||
(object['hotel_city']?.toLowerCase().contains(lowerQuery)); (object['hotel_city']?.toLowerCase().contains(lowerQuery));
}).toList(); }).toList();
currentPage2 = 0; currentPage2 = 0;
@ -1067,9 +1073,11 @@ class _MIShotelState extends State<MIShotel>
paginatedDomestic.map(( paginatedDomestic.map((
entry, entry,
) { ) {
final checkInDate = entry['check_in_date']; final checkInDate =
entry['check_in_date'];
final checkOutDate = entry['check_out_date']; final checkOutDate =
entry['check_out_date'];
return DataRow( return DataRow(
cells: [ cells: [
@ -1674,7 +1682,8 @@ class _MIShotelState extends State<MIShotel>
paginatedInternational.map(( paginatedInternational.map((
entry, entry,
) { ) {
final checkInDate = entry['check_in_date']; final checkInDate =
entry['check_in_date'];
// DateFormat( // DateFormat(
// 'dd-MM-yyyy', // 'dd-MM-yyyy',
// ).format( // ).format(
@ -1682,7 +1691,8 @@ class _MIShotelState extends State<MIShotel>
// entry['check_in_date'], // entry['check_in_date'],
// ), // ),
// ); // );
final checkOutDate = entry['check_out_date']; final checkOutDate =
entry['check_out_date'];
// DateFormat( // DateFormat(
// 'dd-MM-yyyy', // 'dd-MM-yyyy',
// ).format( // ).format(

View File

@ -270,6 +270,7 @@ class _ServicesAnalysisState extends State<ServicesAnalysis>
loaderFlag = true; loaderFlag = true;
try { try {
final result = await apiService.CallReports( final result = await apiService.CallReports(
context,
'misServicesAnalysis', 'misServicesAnalysis',
jsonEncode({ jsonEncode({
"fromDate": '$formattedfromDate', "fromDate": '$formattedfromDate',
@ -338,7 +339,6 @@ class _ServicesAnalysisState extends State<ServicesAnalysis>
final safeName = name.replaceAll(RegExp(r'[^\w\s-]'), ''); final safeName = name.replaceAll(RegExp(r'[^\w\s-]'), '');
final excelName = '$safeName'; final excelName = '$safeName';
Map<String, dynamic> result = { Map<String, dynamic> result = {
"status": false, "status": false,
"message": "Data Not Found", "message": "Data Not Found",
@ -346,6 +346,7 @@ class _ServicesAnalysisState extends State<ServicesAnalysis>
if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) { if (selectedTabName == 'domestic' && dataAvailableDomesticFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misServicesAnalysis', 'misServicesAnalysis',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -355,8 +356,10 @@ class _ServicesAnalysisState extends State<ServicesAnalysis>
excelName, excelName,
); );
} }
if (selectedTabName == 'international' && dataAvailableInternationFlag == 1) { if (selectedTabName == 'international' &&
dataAvailableInternationFlag == 1) {
result = await apiService.reportExcelDownload( result = await apiService.reportExcelDownload(
context,
'misServicesAnalysis', 'misServicesAnalysis',
jsonEncode({ jsonEncode({
"fromDate": formattedFromDate, "fromDate": formattedFromDate,
@ -368,20 +371,23 @@ class _ServicesAnalysisState extends State<ServicesAnalysis>
} }
// Now you can safely access result // Now you can safely access result
final String displayBackgroundColor = result['status'] ? '#28a745' : '#dc1c13'; final String displayBackgroundColor =
final Color displayColor = result['status'] ? Colors.green : Colors.redAccent; result['status'] ? '#28a745' : '#dc1c13';
final Color displayColor =
result['status'] ? Colors.green : Colors.redAccent;
final String displayMessage = result['message']; final String displayMessage = result['message'];
// final bool status = result['status'] == true; // final bool status = result['status'] == true;
Fluttertoast.showToast( Fluttertoast.showToast(
msg: displayMessage , msg: displayMessage,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER, gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2, timeInSecForIosWeb: 2,
backgroundColor: displayColor, backgroundColor: displayColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 18.0, fontSize: 18.0,
webBgColor: "linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)", webBgColor:
"linear-gradient(to right, $displayBackgroundColor, $displayBackgroundColor)",
); );
} }

View File

@ -270,6 +270,12 @@ class TravellerDataState extends State<TravellerData> {
}); });
break; break;
case 403:
print("403-FORB");
await apiService.logout(context);
break;
// throw Exception('Failed to load users');
default: default:
print("Failed to submit traveller. Status: ${response.statusCode}"); print("Failed to submit traveller. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");

View File

@ -158,6 +158,11 @@ class TravellerListState extends State<TravellerList> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -670,6 +675,7 @@ class TravellerListState extends State<TravellerList> {
); );
final data = await apiService final data = await apiService
.getTravellerDetailsFind( .getTravellerDetailsFind(
context,
travellerId, travellerId,
); );
print("TravellerId -- $data"); print("TravellerId -- $data");
@ -758,6 +764,7 @@ class TravellerListState extends State<TravellerList> {
print("travellerId -- $travellerId"); print("travellerId -- $travellerId");
final data = await apiService final data = await apiService
.getTravellerDetailsFind( .getTravellerDetailsFind(
context,
travellerId, travellerId,
); );
print("TravellerId -- $data"); print("TravellerId -- $data");

View File

@ -507,7 +507,7 @@ class _CreateTravelAgentFormDetialsState
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -518,7 +518,7 @@ class _CreateTravelAgentFormDetialsState
Future<void> fetchDepartment() async { Future<void> fetchDepartment() async {
try { try {
List<dynamic> department = await apiService.fetchCostCenter(); List<dynamic> department = await apiService.fetchCostCenter(context);
setState(() { setState(() {
apiCostData = department; apiCostData = department;
}); });
@ -529,7 +529,7 @@ class _CreateTravelAgentFormDetialsState
Future<void> fetchUsers() async { Future<void> fetchUsers() async {
try { try {
List<dynamic> users = await apiService.fetchUsers(); List<dynamic> users = await apiService.fetchUsers(context);
setState(() { setState(() {
// apiUserData = users; // apiUserData = users;
@ -552,7 +552,7 @@ class _CreateTravelAgentFormDetialsState
Future<void> fetchRoles() async { Future<void> fetchRoles() async {
try { try {
final response = await apiService.fetchMasterDropdown(); final response = await apiService.fetchMasterDropdown(context);
if (response is Map<String, dynamic> && response.containsKey("role")) { if (response is Map<String, dynamic> && response.containsKey("role")) {
List<dynamic> roleList = response["role"]; // Extract the list List<dynamic> roleList = response["role"]; // Extract the list

View File

@ -140,6 +140,11 @@ class _TravelAgentListScreenState extends State<TravelAgentListScreen> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
print('Failed to load users'); print('Failed to load users');
return []; return [];
@ -192,6 +197,11 @@ class _TravelAgentListScreenState extends State<TravelAgentListScreen> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -836,7 +846,10 @@ class _TravelAgentListScreenState extends State<TravelAgentListScreen> {
user['user_id'].toString(), user['user_id'].toString(),
); );
final usersData = await apiService final usersData = await apiService
.getSingleUser(userId); .getSingleUser(
context,
userId,
);
context.go( context.go(
"/CreateTravelAgent", "/CreateTravelAgent",
extra: { extra: {
@ -912,7 +925,7 @@ class _TravelAgentListScreenState extends State<TravelAgentListScreen> {
user['user_id'].toString(), user['user_id'].toString(),
); );
final usersData = await apiService final usersData = await apiService
.getSingleUser(userId); .getSingleUser(context, userId);
context.go( context.go(
"/CreateTravelAgent", "/CreateTravelAgent",
extra: { extra: {

View File

@ -207,6 +207,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
} }
final response = await apiService.CheckDuplicate( final response = await apiService.CheckDuplicate(
context,
label, label,
field, field,
value, value,
@ -252,7 +253,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
Future<void> fetchRoles() async { Future<void> fetchRoles() async {
try { try {
final response = await apiService.fetchMasterDropdown(); final response = await apiService.fetchMasterDropdown(context);
if (response is Map<String, dynamic> && response.containsKey("role")) { if (response is Map<String, dynamic> && response.containsKey("role")) {
List<dynamic> roleList = response["role"]; // Extract the list List<dynamic> roleList = response["role"]; // Extract the list
@ -274,7 +275,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -287,7 +288,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
try { try {
print("getUpdatedServices"); print("getUpdatedServices");
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
print("UUPdatedServices - $result"); print("UUPdatedServices - $result");
setState(() { setState(() {
final servicesRaw = selectedOrg?['services_ids']; final servicesRaw = selectedOrg?['services_ids'];
@ -367,7 +368,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllServices(); final result = await apiService.fetchAllServices(context);
setState(() { setState(() {
// apiAllServices = result; // apiAllServices = result;
setState(() { setState(() {

View File

@ -167,6 +167,11 @@ class ChangePasswordDialogDataState extends State<ChangePasswordDialogData> {
print("Response: ${response.body}"); print("Response: ${response.body}");
_clearError(); _clearError();
Navigator.of(context).pop(); Navigator.of(context).pop();
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
Navigator.of(context).pop(); Navigator.of(context).pop();
final message = jsonDecode(response.body)['message'] ?? 'Unknown error'; final message = jsonDecode(response.body)['message'] ?? 'Unknown error';

View File

@ -597,7 +597,7 @@ class _CreateUserFormDetialsState extends State<CreateUserFormDetials> {
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -608,7 +608,7 @@ class _CreateUserFormDetialsState extends State<CreateUserFormDetials> {
Future<void> fetchDepartment() async { Future<void> fetchDepartment() async {
try { try {
List<dynamic> department = await apiService.fetchCostCenter(); List<dynamic> department = await apiService.fetchCostCenter(context);
setState(() { setState(() {
apiCostData = department; apiCostData = department;
}); });
@ -619,7 +619,7 @@ class _CreateUserFormDetialsState extends State<CreateUserFormDetials> {
Future<void> fetchUsers() async { Future<void> fetchUsers() async {
try { try {
List<dynamic> users = await apiService.fetchUsers(); List<dynamic> users = await apiService.fetchUsers(context);
setState(() { setState(() {
// apiUserData = users; // apiUserData = users;
@ -642,7 +642,7 @@ class _CreateUserFormDetialsState extends State<CreateUserFormDetials> {
Future<void> fetchRoles() async { Future<void> fetchRoles() async {
try { try {
final response = await apiService.fetchMasterDropdown(); final response = await apiService.fetchMasterDropdown(context);
if (response is Map<String, dynamic> && response.containsKey("role")) { if (response is Map<String, dynamic> && response.containsKey("role")) {
List<dynamic> roleList = response["role"]; // Extract the list List<dynamic> roleList = response["role"]; // Extract the list
@ -1033,7 +1033,7 @@ class _CreateUserFormDetialsState extends State<CreateUserFormDetials> {
String value, String value,
String? userId, String? userId,
) { ) {
return apiService.CheckDuplicate(label, field, value, userId) return apiService.CheckDuplicate(context, label, field, value, userId)
.then((response) { .then((response) {
if (response.isNotEmpty) { if (response.isNotEmpty) {
errorMessages[field] = errorMessages[field] =

File diff suppressed because it is too large Load Diff

View File

@ -256,6 +256,7 @@ class OfficeDetailsState extends State<OfficeDetails> {
// Basic validation: Check mobile number length // Basic validation: Check mobile number length
final response = await apiService.CheckDuplicate( final response = await apiService.CheckDuplicate(
context,
label, label,
field, field,
value, value,
@ -315,7 +316,7 @@ class OfficeDetailsState extends State<OfficeDetails> {
Future<void> fetchUsers() async { Future<void> fetchUsers() async {
try { try {
print("Test Users"); print("Test Users");
List<dynamic> users = await apiService.fetchUsers(); List<dynamic> users = await apiService.fetchUsers(context);
setState(() { setState(() {
// apiUserData = users; // apiUserData = users;
@ -341,7 +342,9 @@ class OfficeDetailsState extends State<OfficeDetails> {
Future<void> fetchDepartment() async { Future<void> fetchDepartment() async {
try { try {
print("Test department"); print("Test department");
List<dynamic> department = await apiService.fetchDepartmentCostCenter(); List<dynamic> department = await apiService.fetchDepartmentCostCenter(
context,
);
setState(() { setState(() {
apiCostData = department; apiCostData = department;
}); });
@ -354,7 +357,7 @@ class OfficeDetailsState extends State<OfficeDetails> {
Future<void> fetchFindGroup() async { Future<void> fetchFindGroup() async {
try { try {
print("Test Groups"); print("Test Groups");
final result = await apiService.fetchAllGroup(); final result = await apiService.fetchAllGroup(context);
setState(() { setState(() {
apiAllGroups = result; apiAllGroups = result;

View File

@ -247,6 +247,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
} }
final response = await apiService.CheckDuplicate( final response = await apiService.CheckDuplicate(
context,
label, label,
field, field,
value, value,
@ -292,7 +293,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
Future<void> fetchRoles() async { Future<void> fetchRoles() async {
try { try {
final response = await apiService.fetchMasterDropdown(); final response = await apiService.fetchMasterDropdown(context);
if (response is Map<String, dynamic> && response.containsKey("role")) { if (response is Map<String, dynamic> && response.containsKey("role")) {
List<dynamic> roleList = response["role"]; // Extract the list List<dynamic> roleList = response["role"]; // Extract the list
@ -312,7 +313,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -325,7 +326,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
try { try {
print("getUpdatedServices"); print("getUpdatedServices");
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
print("UUPdatedServices - $result"); print("UUPdatedServices - $result");
setState(() { setState(() {
final servicesRaw = selectedOrg?['services_ids']; final servicesRaw = selectedOrg?['services_ids'];
@ -426,7 +427,7 @@ class PersonalDetailsState extends State<PersonalDetails> {
Future<void> loadAllServices() async { Future<void> loadAllServices() async {
try { try {
final result = await apiService.fetchAllServices(); final result = await apiService.fetchAllServices(context);
setState(() { setState(() {
// apiAllServices = result; // apiAllServices = result;
setState(() { setState(() {

View File

@ -138,7 +138,6 @@ class TravellerDetailsState extends State<TravellerDetails> {
Color layoutColor = Colors.grey; Color layoutColor = Colors.grey;
Color? bodyColor; Color? bodyColor;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@ -346,6 +345,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
) async { ) async {
try { try {
final response = await apiService.CheckDuplicate( final response = await apiService.CheckDuplicate(
context,
label, label,
field, field,
value, value,
@ -871,7 +871,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
Future<void> fetchCountries() async { Future<void> fetchCountries() async {
try { try {
List<dynamic> countries = await apiService.fetchCountryList(); List<dynamic> countries = await apiService.fetchCountryList(context);
setState(() { setState(() {
apiCountryData = countries; apiCountryData = countries;
}); });
@ -882,7 +882,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
Future<void> fetchHotels() async { Future<void> fetchHotels() async {
try { try {
List<dynamic> countries = await apiService.fetchHotelsList(); List<dynamic> countries = await apiService.fetchHotelsList(context);
setState(() { setState(() {
apiHotelsData = countries; apiHotelsData = countries;
}); });
@ -893,7 +893,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
Future<void> loadCountryList() async { Future<void> loadCountryList() async {
final newTripType = "2"; final newTripType = "2";
final result = await apiService.fetchAirlineList(); final result = await apiService.fetchAirlineList(context);
// final result = await apiService.fetchFlightsCountryList(newTripType); // final result = await apiService.fetchFlightsCountryList(newTripType);
print("resultFlight: $result "); print("resultFlight: $result ");
@ -923,7 +923,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
Future<void> fetchApiData() async { Future<void> fetchApiData() async {
try { try {
final data = await apiService.fetchMasterDropdown(); final data = await apiService.fetchMasterDropdown(context);
print("fetchApiData - $data"); print("fetchApiData - $data");
@ -1423,7 +1423,10 @@ class TravellerDetailsState extends State<TravellerDetails> {
), ),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color : (layoutColor), width: 0.5), borderSide: BorderSide(
color: (layoutColor),
width: 0.5,
),
), ),
contentPadding: EdgeInsets.symmetric( contentPadding: EdgeInsets.symmetric(
horizontal: 8, horizontal: 8,
@ -1452,7 +1455,9 @@ class TravellerDetailsState extends State<TravellerDetails> {
print("_selectedTripType - $_selectedTripType"); print("_selectedTripType - $_selectedTripType");
}); });
}, },
),),), ),
),
),
), ),
), ),
], ],
@ -2041,21 +2046,53 @@ class TravellerDetailsState extends State<TravellerDetails> {
// } // }
Widget buildPassportDocument() { Widget buildPassportDocument() {
void pickPDFWeb() { // void pickPDFWeb() {
// html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
// uploadInput.accept = '.pdf';
// uploadInput.click();
//
// uploadInput.onChange.listen((e) {
// final file = uploadInput.files!.first;
//
// // Ensure the file is a PDF
// if (!file.type.contains("pdf")) {
// print("Error: Not a PDF file");
// return;
// }
//
// // 🔹 File size check: Ensure it does not exceed 3MB
// int maxFileSize = 3 * 1024 * 1024; // 3MB in bytes
// if (file.size > maxFileSize) {
// print('Error: File size exceeds 3MB');
// return;
// }
//
// setState(() {
// selectedFileNames = file.name;
// passportFile = file;
// passportFileUrlFromApi = null;
// });
//
// print('PDF File selected: ${file.name}');
// });
// }
void pickFileWeb() {
html.FileUploadInputElement uploadInput = html.FileUploadInputElement(); html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
uploadInput.accept = '.pdf'; // Accept PDFs and common image formats
uploadInput.accept = '.pdf,.jpg,.jpeg,.png,.gif';
uploadInput.click(); uploadInput.click();
uploadInput.onChange.listen((e) { uploadInput.onChange.listen((e) {
final file = uploadInput.files!.first; final file = uploadInput.files!.first;
// Ensure the file is a PDF // Ensure the file is PDF or image
if (!file.type.contains("pdf")) { if (!(file.type.contains("pdf") || file.type.contains("image"))) {
print("Error: Not a PDF file"); print("Error: Not a PDF or image file");
return; return;
} }
// 🔹 File size check: Ensure it does not exceed 3MB // File size check: Ensure it does not exceed 3MB
int maxFileSize = 3 * 1024 * 1024; // 3MB in bytes int maxFileSize = 3 * 1024 * 1024; // 3MB in bytes
if (file.size > maxFileSize) { if (file.size > maxFileSize) {
print('Error: File size exceeds 3MB'); print('Error: File size exceeds 3MB');
@ -2068,7 +2105,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
passportFileUrlFromApi = null; passportFileUrlFromApi = null;
}); });
print('PDF File selected: ${file.name}'); print('File selected: ${file.name}');
}); });
} }
@ -2090,7 +2127,7 @@ class TravellerDetailsState extends State<TravellerDetails> {
child: SizedBox( child: SizedBox(
height: 40, height: 40,
child: GestureDetector( child: GestureDetector(
onTap: pickPDFWeb, onTap: pickFileWeb,
child: Container( child: Container(
padding: EdgeInsets.symmetric(horizontal: 10), padding: EdgeInsets.symmetric(horizontal: 10),
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
@ -2557,25 +2594,23 @@ class TravellerDetailsState extends State<TravellerDetails> {
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
borderSide: BorderSide( borderSide: BorderSide(
color: color:
(_dSeatPrefFocus) (_dSeatPrefFocus) ? (layoutColor) : Colors.white,
? (layoutColor)
: Colors.white,
width: 0.5, width: 0.5,
), ),
), ),
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide( borderSide: BorderSide(
color: color:
(_dSeatPrefFocus) (_dSeatPrefFocus) ? (layoutColor) : Colors.white,
? (layoutColor)
: Colors.white,
width: 0.5, width: 0.5,
// const Color(0xFFD6D5E6), // const Color(0xFFD6D5E6),
), ),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide( borderSide: BorderSide(
color : (layoutColor), width: 0.5), color: (layoutColor),
width: 0.5,
),
), ),
hintText: "Select Seat", hintText: "Select Seat",
hintStyle: GoogleFonts.poppins( hintStyle: GoogleFonts.poppins(
@ -2605,7 +2640,10 @@ class TravellerDetailsState extends State<TravellerDetails> {
} }
return Text( return Text(
selectedItem['dropdown_value'] ?? 'Select Seat', selectedItem['dropdown_value'] ?? 'Select Seat',
style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), style: GoogleFonts.poppins(
fontSize: 12,
color: Colors.black,
),
); );
}, },
items: seatOptions, items: seatOptions,
@ -2619,11 +2657,14 @@ class TravellerDetailsState extends State<TravellerDetails> {
: (Map<String, dynamic>? newItem) { : (Map<String, dynamic>? newItem) {
if (newItem != null) { if (newItem != null) {
setState(() { setState(() {
selectedDomesticSeat = newItem['dropdown_value']; selectedDomesticSeat =
newItem['dropdown_value'];
}); });
} }
}, },
),),), ),
),
),
), ),
), ),
], ],
@ -2832,25 +2873,23 @@ class TravellerDetailsState extends State<TravellerDetails> {
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
borderSide: BorderSide( borderSide: BorderSide(
color: color:
(_iSeatPrefFocus) (_iSeatPrefFocus) ? (layoutColor) : Colors.white,
? (layoutColor)
: Colors.white,
width: 0.5, width: 0.5,
), ),
), ),
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide( borderSide: BorderSide(
color: color:
(_iSeatPrefFocus) (_iSeatPrefFocus) ? (layoutColor) : Colors.white,
? (layoutColor)
: Colors.white,
width: 0.5, width: 0.5,
// const Color(0xFFD6D5E6), // const Color(0xFFD6D5E6),
), ),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide( borderSide: BorderSide(
color : (layoutColor), width: 0.5), color: (layoutColor),
width: 0.5,
),
), ),
contentPadding: EdgeInsets.symmetric( contentPadding: EdgeInsets.symmetric(
horizontal: 10, horizontal: 10,
@ -2880,7 +2919,10 @@ class TravellerDetailsState extends State<TravellerDetails> {
} }
return Text( return Text(
selectedItem['dropdown_value'] ?? 'Select Seat', selectedItem['dropdown_value'] ?? 'Select Seat',
style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), style: GoogleFonts.poppins(
fontSize: 12,
color: Colors.black,
),
); );
}, },
items: seatOptionsInt, items: seatOptionsInt,
@ -2899,7 +2941,9 @@ class TravellerDetailsState extends State<TravellerDetails> {
}); });
} }
}, },
),),), ),
),
),
), ),
), ),
], ],
@ -3200,7 +3244,8 @@ class TravellerDetailsState extends State<TravellerDetails> {
widget.isViewMode widget.isViewMode
? null ? null
: () async { : () async {
focusNodes["forex_expiry_dateFocusNode"]?.requestFocus(); focusNodes["forex_expiry_dateFocusNode"]
?.requestFocus();
await _selectExpiryDate(context); await _selectExpiryDate(context);
}, },
child: AbsorbPointer( child: AbsorbPointer(

View File

@ -139,6 +139,11 @@ class _UserListScreenState extends State<UserListScreen> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
@ -189,6 +194,11 @@ class _UserListScreenState extends State<UserListScreen> {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
@ -464,7 +474,7 @@ class _UserListScreenState extends State<UserListScreen> {
} }
Future<void> handleDownload() async { Future<void> handleDownload() async {
final result = await apiService.getDownloadUserTemplateForUpload(); final result = await apiService.getDownloadUserTemplateForUpload(context);
final String displayBackgroundColor = final String displayBackgroundColor =
result['status'] ? '#28a745' : '#dc1c13'; result['status'] ? '#28a745' : '#dc1c13';
@ -985,7 +995,7 @@ class _UserListScreenState extends State<UserListScreen> {
), ),
tooltip: 'Sample Template Download', tooltip: 'Sample Template Download',
onPressed: () { onPressed: () {
apiService.getDownloadUserTemplateForUpload(); apiService.getDownloadUserTemplateForUpload(context);
}, },
), ),
SizedBox(width: 5), SizedBox(width: 5),
@ -1354,7 +1364,10 @@ class _UserListScreenState extends State<UserListScreen> {
user['user_id'].toString(), user['user_id'].toString(),
); );
final usersData = await apiService final usersData = await apiService
.getSingleUser(userId); .getSingleUser(
context,
userId,
);
context.go( context.go(
"/CreateUserDetails", "/CreateUserDetails",
extra: { extra: {
@ -1611,7 +1624,7 @@ class _UserListScreenState extends State<UserListScreen> {
user['user_id'].toString(), user['user_id'].toString(),
); );
final usersData = await apiService final usersData = await apiService
.getSingleUser(userId); .getSingleUser(context, userId);
context.go( context.go(
"/CreateUserDetails", "/CreateUserDetails",
extra: { extra: {

View File

@ -34,6 +34,7 @@ class _MyAppState extends State<MyApp> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// SemanticsBinding.instance // SemanticsBinding.instance
// .ensureSemantics(); // -only for testing uncomment, Otherwise Email Template wont allow to type // .ensureSemantics(); // -only for testing uncomment, Otherwise Email Template wont allow to type
if (kIsWeb) { if (kIsWeb) {
@ -191,7 +192,7 @@ class _MyAppState extends State<MyApp> {
print("MicroSoft UserData ROLE FECTHED - $userRole"); print("MicroSoft UserData ROLE FECTHED - $userRole");
} }
print("MicroSoft Started"); print("MicroSoft Started");
await apiService.getOrganizationData(); await apiService.getOrganizationData(context);
print("MicroSoft end"); print("MicroSoft end");
} catch (e) { } catch (e) {
print('Error decoding token MS: $e'); print('Error decoding token MS: $e');

View File

@ -1,9 +1,17 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart'; import 'package:flutter/rendering.dart';
import 'package:http/http.dart' as http;
import 'app.dart'; import 'app.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart';
void main() { void main() {
// setUrlStrategy(PathUrlStrategy()); // setUrlStrategy(PathUrlStrategy());
// await fetchAllApiStatuses();
runApp(const MyApp()); runApp(const MyApp());
} }
// Future<void> fetchAllApiStatuses() async {
// final res = await http.get(Uri.parse('https://example.com/api'));
// print("API status: ${res.statusCode}");
// ApiStatusCache.latestStatus = res.statusCode;
// }

View File

@ -74,7 +74,7 @@ class _CustomAppBarState extends State<CustomAppBar> {
userIdRaw is int ? userIdRaw : int.tryParse(userIdRaw.toString()); userIdRaw is int ? userIdRaw : int.tryParse(userIdRaw.toString());
if (userId != null) { if (userId != null) {
profileUserDetails = await apiService.getSingleUser(userId); profileUserDetails = await apiService.getSingleUser(context, userId);
print("getProfileUser-$profileUserDetails"); print("getProfileUser-$profileUserDetails");
} else { } else {
print("❌ Invalid user_id: $userIdRaw"); print("❌ Invalid user_id: $userIdRaw");
@ -194,7 +194,7 @@ class _CustomAppBarState extends State<CustomAppBar> {
try { try {
print("getUpdatedServices"); print("getUpdatedServices");
final result = await apiService.fetchOrganization(); final result = await apiService.fetchOrganization(context);
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
print("UUPdatedServices - $result"); print("UUPdatedServices - $result");
@ -291,15 +291,15 @@ class _CustomAppBarState extends State<CustomAppBar> {
} }
Future<void> logout(BuildContext context) async { Future<void> logout(BuildContext context) async {
// Clear localStorage await apiService.logout(context);
final prefs = await SharedPreferences.getInstance();
await prefs.clear(); // Clears all keys
// Optional: clear sessionStorage if used // final prefs = await SharedPreferences.getInstance();
// html.window.sessionStorage.clear(); // await prefs.clear();
// // Optional: clear sessionStorage if used
// Navigate to login or home page // // html.window.sessionStorage.clear();
context.go('/'); //
// // Navigate to login or home page
// context.go('/');
} }
void _handleBackButton() { void _handleBackButton() {

View File

@ -17,6 +17,7 @@ import 'package:frontend/Screens/userManagement/user_List.dart';
import 'package:frontend/routes/organizationSetting.dart'; import 'package:frontend/routes/organizationSetting.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:responsive_builder/responsive_builder.dart'; import 'package:responsive_builder/responsive_builder.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Screens/allTrips/list_all_plans.dart'; import '../Screens/allTrips/list_all_plans.dart';
import '../Screens/allTrips/travel_agent_list.dart'; import '../Screens/allTrips/travel_agent_list.dart';
@ -43,9 +44,27 @@ import '../Screens/reports/misForex.dart';
import '../Screens/reports/guestHouse.dart'; import '../Screens/reports/guestHouse.dart';
import '../Screens/userManagement/create_traveller_agent/listTravelAgent.dart'; import '../Screens/userManagement/create_traveller_agent/listTravelAgent.dart';
import '../utils/auth_utils.dart';
import 'mainLayout.dart'; import 'mainLayout.dart';
// class AuthState extends ChangeNotifier {
// String? role;
//
// Future<void> loadRole() async {
// final prefs = await SharedPreferences.getInstance();
// final userData = prefs.getString('user_data');
// if (userData != null) {
// final decoded = jsonDecode(userData);
// role = decoded["role"];
// notifyListeners();
// }
// }
// }
//
// final authState = AuthState();
final GoRouter router = GoRouter( final GoRouter router = GoRouter(
// refreshListenable: authState,
routes: [ routes: [
// Public routes without app bar // Public routes without app bar
GoRoute(path: '/', builder: (context, state) => LoginPage()), GoRoute(path: '/', builder: (context, state) => LoginPage()),
@ -148,6 +167,13 @@ final GoRouter router = GoRouter(
path: '/statusdashboard', path: '/statusdashboard',
builder: (context, state) => StatusDashboard(), builder: (context, state) => StatusDashboard(),
), ),
GoRoute(
path: '/unauthorized',
builder:
(context, state) =>
const Scaffold(body: Center(child: Text("🚫 Access Denied"))),
),
GoRoute( GoRoute(
path: '/traveller', path: '/traveller',
builder: (context, state) => TravellerList(), builder: (context, state) => TravellerList(),
@ -194,100 +220,30 @@ final GoRouter router = GoRouter(
], ],
), ),
], ],
// redirect: (context, state) async {
// print('Check REDIRECTION');
// final apiStatus = ApiStatusCache.latestStatus;
//
// print('Check apiStatus - $apiStatus');
// return null;
// if (apiStatus == 404) return '/';
// return null;
// final role = await getRoleUser(); // async not allowed here per-route
// print('Check REDIRECTION');
// print('getRoleUser1 - $role');
// // for top-level GoRouter, you can use async redirect
// if (role == null) return '/'; // not logged in
// if (state.matchedLocation == '/statusdashboard' &&
// role != 'Org Admin' &&
// role != 'Travel Admin') {
// return '/unauthorized';
// }
// return null; //
// },
); );
// final GoRouter router = GoRouter( class ApiStatusCache {
// routes: [ static int? latestStatus;
// GoRoute(path: '/', builder: (context, state) => LoginPage()), }
// // GoRoute(
// // path: '/authredirection',
// // builder: (context, state) {
// // final code = state.uri.queryParameters['code'];
// // return MicrosoftPage(code: code);
// // },
// // ),
// GoRoute(path: '/home', builder: (context, state) => HomePage()),
// GoRoute(path: '/listAllPlan', builder: (context, state) => ListAllPlans()),
// GoRoute(
// path: '/listTravelAgentPlan',
// builder: (context, state) => TravelAgentListPlans(),
// ),
// GoRoute(path: '/listPlan', builder: (context, state) => ListPlans()),
// GoRoute(path: '/createPlan', builder: (context, state) => CreatePlan()),
// GoRoute(path: '/allTrips/trips', builder: (context, state) => CreatePlan()),
// GoRoute(path: '/approver/plans', builder: (context, state) => CreatePlan()),
// GoRoute(path: '/listUser', builder: (context, state) => UserListScreen()),
// GoRoute(
// path: '/CreateUserDetails',
// builder: (context, state) => CreateUserFormDetials(),
// // builder: (context, state) {
// // final userParam = state.uri.queryParameters['user'];
// //
// // final isEditProfile =
// // state.uri.queryParameters['isEditProfile'] == 'true';
// // final isViewMode = state.uri.queryParameters['isViewMode'] == 'true';
// //
// // final user = userParam != null
// // ? jsonDecode(Uri.decodeComponent(userParam))
// // : null;
// //
// // return CreateUserForm(
// // apiselectedUser: user,
// // isEditProfile: isEditProfile,
// // isViewMode: isViewMode,
// // );
// // }
// ),
// GoRoute(
// path: '/Policy',
// // builder: (context, state) => Policy(),
// pageBuilder:
// (context, state) => MaterialPage(child: Policy.fromState(state)),
// ),
// GoRoute(path: '/PolicyList', builder: (context, state) => PolicyList()),
// GoRoute(
// path: '/OrganizationSetup',
// builder: (context, state) => OrgSetUp(),
// ),
// GoRoute(
// path: '/OrganizationSettings',
// builder: (context, state) => OrganizationSetting(),
// ),
// GoRoute(path: '/group', builder: (context, state) => GroupList()),
// GoRoute(path: '/getPerdiem', builder: (context, state) => ForexDataList()),
// GoRoute(
// path: '/templateList',
// builder: (context, state) => TemplatesList(),
// ),
// // GoRoute(
// // path: '/template',
// // builder: (context, state) => MyHomePage(),
// // ),
// GoRoute(
// path: '/template',
// // builder: (context, state) => Template(),
// pageBuilder:
// (context, state) => MaterialPage(child: Template.fromState(state)),
// ),
// GoRoute(
// path: '/templateForex',
// pageBuilder:
// (context, state) =>
// MaterialPage(child: TemplateForex.fromState(state)),
// ),
// GoRoute(path: '/approvallist', builder: (context, state) => ApprovalList()),
// GoRoute(path: '/department', builder: (context, state) => DepartmentList()),
// GoRoute(path: '/costcenter', builder: (context, state) => CostCenterList()),
// GoRoute(path: '/hotels', builder: (context, state) => HotelsDataList()),
// GoRoute(
// path: '/statusdashboard',
// builder: (context, state) => StatusDashboard(),
// ),
// GoRoute(path: '/traveller', builder: (context, state) => TravellerList()),
// GoRoute(
// path: '/CreateGroup',
// pageBuilder:
// (context, state) => MaterialPage(child: Group.fromState(state)),
// ),
// ],
// );

View File

@ -13,7 +13,7 @@ import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
class ApiService { class ApiService {
Future<void> storeUserDetails(String token) async { Future<void> storeUserDetails(BuildContext context, String token) async {
try { try {
final parts = token.split('.'); final parts = token.split('.');
if (parts.length != 3) throw Exception('Invalid token format'); if (parts.length != 3) throw Exception('Invalid token format');
@ -43,13 +43,53 @@ class ApiService {
// print("userData12 - $userRole"); // print("userData12 - $userRole");
} }
await getOrganizationData(); await getOrganizationData(context);
} catch (e) { } catch (e) {
print('Error decoding token: $e'); print('Error decoding token: $e');
} }
} }
Future<void> storeTripUserDetails(String token) async { Future<void> logout(BuildContext context) async {
await logoutApi();
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
// Optional: clear sessionStorage if used
// html.window.sessionStorage.clear();
// Navigate to login or home page
context?.go('/');
}
Future<void> logoutApi() async {
String? userId = await getUserId();
print('userId - $userId');
final String apiUrldata = '$apiUrl/api/auth/logout?user_id=$userId';
final token = await getToken();
if (token == null) {
throw Exception('Token not found. Please log in.');
}
final response = await http.get(
Uri.parse(apiUrldata),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
'app-signature': 'ts-traveltool-2025-signature-123456',
},
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
print("Logout API response: $data");
} else {
throw Exception('Failed to logout. Status: ${response.statusCode}');
}
}
Future<void> storeTripUserDetails(BuildContext context, String token) async {
try { try {
final parts = token.split('.'); final parts = token.split('.');
if (parts.length != 3) throw Exception('Invalid token format'); if (parts.length != 3) throw Exception('Invalid token format');
@ -79,16 +119,16 @@ class ApiService {
// print("userData12 - $userRole"); // print("userData12 - $userRole");
} }
await getOrganizationData(); await getOrganizationData(context);
} catch (e) { } catch (e) {
print('Error decoding token: $e'); print('Error decoding token: $e');
} }
} }
Future<void> getOrganizationData() async { Future<void> getOrganizationData(BuildContext context) async {
try { try {
print("ORG getUpdatedServices"); print("ORG getUpdatedServices");
final result = await fetchOrganization(); final result = await fetchOrganization(context);
print("UUPdatedServices - $result"); print("UUPdatedServices - $result");
// Save to local storage // Save to local storage
@ -103,7 +143,7 @@ class ApiService {
} }
} }
Future<List<dynamic>> fetchCountryList() async { Future<List<dynamic>> fetchCountryList(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getcountryMaster'; final String apiUrldata = '$apiUrl/api/getcountryMaster';
final token = await getToken(); final token = await getToken();
@ -135,12 +175,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load country list'); throw Exception('Failed to load country list');
} }
} }
Future<List<dynamic>> fetchHotelsList() async { Future<List<dynamic>> fetchHotelsList(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getHotels'; final String apiUrldata = '$apiUrl/api/getHotels';
final token = await getToken(); final token = await getToken();
@ -172,12 +217,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load country list'); throw Exception('Failed to load country list');
} }
} }
Future<List<dynamic>> fetchAirlineList() async { Future<List<dynamic>> fetchAirlineList(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getAirlineMaster'; final String apiUrldata = '$apiUrl/api/getAirlineMaster';
final token = await getToken(); final token = await getToken();
@ -209,12 +259,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load country list'); throw Exception('Failed to load country list');
} }
} }
Future<List<dynamic>> fetchUsers() async { Future<List<dynamic>> fetchUsers(BuildContext context) async {
String? ordId = await getOrgId(); String? ordId = await getOrgId();
final String apiUrlData = '$apiUrl/api/users?org_id=$ordId'; final String apiUrlData = '$apiUrl/api/users?org_id=$ordId';
final String? token = await getToken(); final String? token = await getToken();
@ -238,12 +293,17 @@ class ApiService {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }
} }
Future<List> fetchCostCenter() async { Future<List> fetchCostCenter(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getCostCenterMaster'; final String apiUrldata = '$apiUrl/api/getCostCenterMaster';
final token = await getToken(); final token = await getToken();
@ -294,12 +354,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<List> fetchDepartmentCostCenter() async { Future<List> fetchDepartmentCostCenter(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getDepartmentList'; final String apiUrldata = '$apiUrl/api/getDepartmentList';
final token = await getToken(); final token = await getToken();
@ -350,12 +415,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<Map<String, dynamic>> fetchMasterDropdown() async { Future<Map<String, dynamic>> fetchMasterDropdown(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getDropdownMaster'; final String apiUrldata = '$apiUrl/api/getDropdownMaster';
final token = await getToken(); final token = await getToken();
@ -390,12 +460,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<List<dynamic>> fetchAllServices() async { Future<List<dynamic>> fetchAllServices(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/service'; final String apiUrldata = '$apiUrl/api/service';
final token = await getToken(); final token = await getToken();
@ -426,12 +501,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<List<dynamic>> fetchAllGroup() async { Future<List<dynamic>> fetchAllGroup(BuildContext context) async {
String? orgId = await getOrgId(); String? orgId = await getOrgId();
final String apiUrldata = '$apiUrl/api/groups?for=table_view&org_id=$orgId'; final String apiUrldata = '$apiUrl/api/groups?for=table_view&org_id=$orgId';
@ -464,12 +544,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<List<dynamic>> fetchFindGroup() async { Future<List<dynamic>> fetchFindGroup(BuildContext context) async {
String? orgId = await getOrgId(); String? orgId = await getOrgId();
final String apiUrldata = '$apiUrl/api/groups/find/$orgId'; final String apiUrldata = '$apiUrl/api/groups/find/$orgId';
@ -502,12 +587,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<List<dynamic>> fetchAllPolicy() async { Future<List<dynamic>> fetchAllPolicy(BuildContext context) async {
String? orgId = await getOrgId(); String? orgId = await getOrgId();
final String apiUrldata = '$apiUrl/api/policy?for=table_view&org_id=$orgId'; final String apiUrldata = '$apiUrl/api/policy?for=table_view&org_id=$orgId';
@ -540,12 +630,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<Map<String, dynamic>> getSinglePolicy(int policyId) async { Future<Map<String, dynamic>> getSinglePolicy(
int policyId,
BuildContext context,
) async {
final String apiUrldata = '$apiUrl/api/policy/find/${policyId}'; final String apiUrldata = '$apiUrl/api/policy/find/${policyId}';
final token = await getToken(); final token = await getToken();
@ -580,12 +678,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<Map<String, dynamic>> fetchOrganization() async { Future<Map<String, dynamic>> fetchOrganization(BuildContext context) async {
String? orgId = await getOrgId(); String? orgId = await getOrgId();
// final String apiUrldata = '$apiUrl/api/organizations'; // final String apiUrldata = '$apiUrl/api/organizations';
@ -625,12 +728,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load organizations'); throw Exception('Failed to load organizations');
} }
} }
static Future<Map<String, dynamic>> getViewPlan(String planId) async { Future<Map<String, dynamic>> getViewPlan(
String planId,
BuildContext context,
) async {
final String apiUrldata = '$apiUrl/api/plans/cancle_plan?plan_id=$planId'; final String apiUrldata = '$apiUrl/api/plans/cancle_plan?plan_id=$planId';
// final String apiUrldata = '$apiUrl/api/plans/find/$planId'; // final String apiUrldata = '$apiUrl/api/plans/find/$planId';
@ -652,12 +763,20 @@ class ApiService {
final Map<String, dynamic>? resData = json.decode(response.body); final Map<String, dynamic>? resData = json.decode(response.body);
return resData?["data"]; return resData?["data"];
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
static Future<Map<String, dynamic>> getViewPlanEdit(String planId) async { Future<Map<String, dynamic>> getViewPlanEdit(
String planId,
BuildContext context,
) async {
final String apiUrldata = '$apiUrl/api/plans/find/$planId'; final String apiUrldata = '$apiUrl/api/plans/find/$planId';
print("API URL: $apiUrldata"); print("API URL: $apiUrldata");
// final token = await getToken(); // final token = await getToken();
@ -677,12 +796,17 @@ class ApiService {
final Map<String, dynamic>? resData = json.decode(response.body); final Map<String, dynamic>? resData = json.decode(response.body);
return resData?["data"]; return resData?["data"];
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<void> handleTokenRefresh(String userId) async { Future<void> handleTokenRefresh(BuildContext context, String userId) async {
final String apiUrldata = final String apiUrldata =
'$apiUrl/api/user/refreshUserToken?user_id=$userId'; '$apiUrl/api/user/refreshUserToken?user_id=$userId';
print("API URL: $userId"); print("API URL: $userId");
@ -707,13 +831,18 @@ class ApiService {
// final userId = data['user_id'].toString(); // final userId = data['user_id'].toString();
print("Token - $token"); print("Token - $token");
await storeUserDetails(token); await storeUserDetails(context, token);
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<void> handleTripWiseToken(String userId) async { Future<void> handleTripWiseToken(String userId, BuildContext context) async {
final String apiUrldata = final String apiUrldata =
'$apiUrl/api/user/refreshUserToken?user_id=$userId'; '$apiUrl/api/user/refreshUserToken?user_id=$userId';
print("API URL: $userId"); print("API URL: $userId");
@ -738,20 +867,25 @@ class ApiService {
// final userId = data['user_id'].toString(); // final userId = data['user_id'].toString();
print("Token - $token"); print("Token - $token");
await storeTripUserDetails(token); await storeTripUserDetails(context, token);
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return null;
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
static Future<void> viewPlan( Future<void> viewPlan(
BuildContext context, BuildContext context,
String planId, { String planId, {
bool isViewMode = false, bool isViewMode = false,
bool isMyTrips = false, bool isMyTrips = false,
}) async { }) async {
try { try {
Map<String, dynamic> planData = await getViewPlanEdit(planId); Map<String, dynamic> planData = await getViewPlanEdit(planId, context);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
context.go( context.go(
@ -763,7 +897,7 @@ class ApiService {
} }
} }
static Future<void> viewPlanForApprover( Future<void> viewPlanForApprover(
BuildContext context, BuildContext context,
String planId, String planId,
String? approverId, String? approverId,
@ -773,7 +907,7 @@ class ApiService {
bool isApprover = true, bool isApprover = true,
}) async { }) async {
try { try {
Map<String, dynamic> planData = await getViewPlanEdit(planId); Map<String, dynamic> planData = await getViewPlanEdit(planId, context);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
context.replace( context.replace(
@ -792,7 +926,9 @@ class ApiService {
} }
} }
Future<Map<String, dynamic>> fetchUserApprovalList() async { Future<Map<String, dynamic>> fetchUserApprovalList(
BuildContext context,
) async {
String? orgId = await getOrgId(); String? orgId = await getOrgId();
String? userId = await getUserId(); String? userId = await getUserId();
@ -836,6 +972,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load organizations'); throw Exception('Failed to load organizations');
} }
@ -843,7 +984,10 @@ class ApiService {
// Flight From - To // Flight From - To
Future<List<dynamic>> fetchFlightsCountryList(String? tripType) async { Future<List<dynamic>> fetchFlightsCountryList(
BuildContext context,
String? tripType,
) async {
print("FlightTripType- $tripType"); print("FlightTripType- $tripType");
final String apiUrldata = final String apiUrldata =
@ -879,12 +1023,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load country list'); throw Exception('Failed to load country list');
} }
} }
Future<List<dynamic>> fetchTrainCountryList() async { Future<List<dynamic>> fetchTrainCountryList(BuildContext context) async {
final String apiUrldata = '$apiUrl/api/getTrainCodeMaster'; final String apiUrldata = '$apiUrl/api/getTrainCodeMaster';
final token = await getToken(); final token = await getToken();
@ -917,12 +1066,17 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load country list'); throw Exception('Failed to load country list');
} }
} }
Future<void> getPdfDownload(planId) async { Future<void> getPdfDownload(BuildContext context, planId) async {
final String apiUrldata = '$apiUrl/api/plans/download?plan_id=$planId'; final String apiUrldata = '$apiUrl/api/plans/download?plan_id=$planId';
// final String apiUrldata = '$apiUrl/auth/googlelogin'; // final String apiUrldata = '$apiUrl/auth/googlelogin';
@ -963,6 +1117,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
// showDialog( // showDialog(
// context: context, // context: context,
@ -986,7 +1145,7 @@ class ApiService {
} }
} }
Future<void> getForexPdfDownload(forexId) async { Future<void> getForexPdfDownload(BuildContext context, forexId) async {
final String apiUrldata = final String apiUrldata =
'$apiUrl/api/plans/forexDownload?forex_id=$forexId'; '$apiUrl/api/plans/forexDownload?forex_id=$forexId';
@ -1028,6 +1187,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return null;
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
// showDialog( // showDialog(
// context: context, // context: context,
@ -1052,7 +1216,9 @@ class ApiService {
} }
// download the Template for bulk upload the user // download the Template for bulk upload the user
Future<Map<String, dynamic>> getDownloadUserTemplateForUpload() async { Future<Map<String, dynamic>> getDownloadUserTemplateForUpload(
BuildContext context,
) async {
final String apiUrldata = final String apiUrldata =
'$apiUrl/api/user/userUploadTemplate'; // download the Template for bulk upload user => api '$apiUrl/api/user/userUploadTemplate'; // download the Template for bulk upload user => api
@ -1095,6 +1261,11 @@ class ApiService {
} catch (e) { } catch (e) {
return {'status': false, 'message': 'Download error: $e'}; return {'status': false, 'message': 'Download error: $e'};
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
return {'status': false, 'message': 'File not found (404).'}; return {'status': false, 'message': 'File not found (404).'};
} else { } else {
@ -1104,7 +1275,10 @@ class ApiService {
//---------------------------------------User Management----------------------------------- //---------------------------------------User Management-----------------------------------
Future<Map<String, dynamic>> getSingleUser(int userId) async { Future<Map<String, dynamic>> getSingleUser(
BuildContext context,
int userId,
) async {
print('Single USer 1 - $userId'); print('Single USer 1 - $userId');
final String apiUrldata = '$apiUrl/api/users/find/$userId'; final String apiUrldata = '$apiUrl/api/users/find/$userId';
@ -1143,12 +1317,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<Map<String, dynamic>> getForexDetailsFind(int userId) async { Future<Map<String, dynamic>> getForexDetailsFind(
BuildContext context,
int userId,
) async {
print('Single Forez 1 - $userId'); print('Single Forez 1 - $userId');
// final String apiUrldata = '$apiUrl/api/users/find/$userId'; // final String apiUrldata = '$apiUrl/api/users/find/$userId';
@ -1191,13 +1373,21 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
// --- // ---
Future<Map<String, dynamic>> getDepartmentDetailsFind(int id) async { Future<Map<String, dynamic>> getDepartmentDetailsFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/findDepartment?id=$id'; final String apiUrldata = '$apiUrl/api/findDepartment?id=$id';
final token = await getToken(); final token = await getToken();
@ -1239,12 +1429,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load department details'); throw Exception('Failed to load department details');
} }
} }
Future<Map<String, dynamic>> getPurposeOfTravelDetailsFind(int id) async { Future<Map<String, dynamic>> getPurposeOfTravelDetailsFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/findPurposeOfTravel?id=$id'; final String apiUrldata = '$apiUrl/api/findPurposeOfTravel?id=$id';
final token = await getToken(); final token = await getToken();
@ -1286,12 +1484,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load department details'); throw Exception('Failed to load department details');
} }
} }
Future<Map<String, dynamic>> getTemplateFind(int id) async { Future<Map<String, dynamic>> getTemplateFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/template/find/$id'; final String apiUrldata = '$apiUrl/api/template/find/$id';
final token = await getToken(); final token = await getToken();
@ -1340,6 +1546,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load department details'); throw Exception('Failed to load department details');
} }
@ -1474,14 +1685,14 @@ class ApiService {
false; // Default to false if dismissed false; // Default to false if dismissed
} }
static Future<void> viewPlanTravelAgent( Future<void> viewPlanTravelAgent(
BuildContext context, BuildContext context,
String planId, { String planId, {
bool isViewMode = false, bool isViewMode = false,
bool isMyTrips = false, bool isMyTrips = false,
}) async { }) async {
try { try {
Map<String, dynamic> planData = await getViewPlanEdit(planId); Map<String, dynamic> planData = await getViewPlanEdit(planId, context);
print("ViewAAA - $planData"); print("ViewAAA - $planData");
context.go( context.go(
@ -1493,7 +1704,10 @@ class ApiService {
} }
} }
Future<Map<String, dynamic>> getCostCenterDetailsFind(int id) async { Future<Map<String, dynamic>> getCostCenterDetailsFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/findCostCenter?cost_center_id=$id'; final String apiUrldata = '$apiUrl/api/findCostCenter?cost_center_id=$id';
final token = await getToken(); final token = await getToken();
@ -1535,12 +1749,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load CostCenter details'); throw Exception('Failed to load CostCenter details');
} }
} }
Future<Map<String, dynamic>> getHotelsDetailsFind(int id) async { Future<Map<String, dynamic>> getHotelsDetailsFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/findHotels?hotel_id=$id'; final String apiUrldata = '$apiUrl/api/findHotels?hotel_id=$id';
final token = await getToken(); final token = await getToken();
@ -1582,12 +1804,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load Hotel details'); throw Exception('Failed to load Hotel details');
} }
} }
Future<Map<String, dynamic>> getGroupDetailsFind(int id) async { Future<Map<String, dynamic>> getGroupDetailsFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/groups/find/$id'; final String apiUrldata = '$apiUrl/api/groups/find/$id';
final token = await getToken(); final token = await getToken();
@ -1624,12 +1854,20 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load plans'); throw Exception('Failed to load plans');
} }
} }
Future<Map<String, dynamic>> getTravellerDetailsFind(int id) async { Future<Map<String, dynamic>> getTravellerDetailsFind(
BuildContext context,
int id,
) async {
final String apiUrldata = '$apiUrl/api/travellers/find?traveller_id=$id'; final String apiUrldata = '$apiUrl/api/travellers/find?traveller_id=$id';
//c //c
@ -1669,6 +1907,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load Hotel details'); throw Exception('Failed to load Hotel details');
} }
@ -1676,6 +1919,7 @@ class ApiService {
// ----------------------- User Management - CheckDuplicate --------------- // ----------------------- User Management - CheckDuplicate ---------------
Future<Map<String, dynamic>> CheckDuplicate( Future<Map<String, dynamic>> CheckDuplicate(
BuildContext context,
String label, String label,
String field, String field,
String value, String value,
@ -1717,6 +1961,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception( throw Exception(
'Failed to load checkDuplicate data. Status code: ${response.statusCode}', 'Failed to load checkDuplicate data. Status code: ${response.statusCode}',
@ -1726,7 +1975,11 @@ class ApiService {
// ----------------------- User Management - CheckDuplicate end here ---------------------------------- // ----------------------- User Management - CheckDuplicate end here ----------------------------------
// ----------------------- Report ------------------------- // ----------------------- Report -------------------------
Future<Map<String, dynamic>> CallReports(String apiRoute, String body) async { Future<Map<String, dynamic>> CallReports(
BuildContext context,
String apiRoute,
String body,
) async {
String apiUrldata = '$apiUrl/api/$apiRoute'; String apiUrldata = '$apiUrl/api/$apiRoute';
final token = await getToken(); final token = await getToken();
@ -1751,6 +2004,11 @@ class ApiService {
} catch (e) { } catch (e) {
throw Exception('Error parsing response: $e'); throw Exception('Error parsing response: $e');
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception( throw Exception(
'Failed to load data. Status code: ${response.statusCode}', 'Failed to load data. Status code: ${response.statusCode}',
@ -1759,6 +2017,7 @@ class ApiService {
} }
Future<Map<String, dynamic>> reportExcelDownload( Future<Map<String, dynamic>> reportExcelDownload(
BuildContext context,
String apiRoute, String apiRoute,
String body, String body,
String name, String name,
@ -1812,6 +2071,11 @@ class ApiService {
// throw Exception('Error parsing response: $e'); // throw Exception('Error parsing response: $e');
return {'status': false, 'message': 'Download error: $e'}; return {'status': false, 'message': 'Download error: $e'};
} }
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return {};
// throw Exception('Failed to load users');
} else if (response.statusCode == 404) { } else if (response.statusCode == 404) {
// throw Exception('File not found.'); // throw Exception('File not found.');
return {'status': false, 'message': 'File not found (404).'}; return {'status': false, 'message': 'File not found (404).'};
@ -1823,7 +2087,7 @@ class ApiService {
// ----------------------- Report ------------------------- // ----------------------- Report -------------------------
Future<List<dynamic>> fetchGetHotels() async { Future<List<dynamic>> fetchGetHotels(BuildContext context) async {
// return []; // return [];
final orgId = await getOrgId(); final orgId = await getOrgId();
final String apiUrlData = '$apiUrl/api/getHotels'; final String apiUrlData = '$apiUrl/api/getHotels';
@ -1848,6 +2112,11 @@ class ApiService {
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
return data['data']; // Returning raw JSON list return data['data']; // Returning raw JSON list
} else if (response.statusCode == 403) {
print("403-FORB");
await logout(context);
return [];
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load users'); throw Exception('Failed to load users');
} }

View File

@ -66,6 +66,8 @@ Future<String?> getRoleUser() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final String? userDataString = prefs.getString('user_data'); final String? userDataString = prefs.getString('user_data');
print('getRoleUser');
// print("UserDataSTr - $userDataString"); // print("UserDataSTr - $userDataString");
if (userDataString != null) { if (userDataString != null) {

View File

@ -6,6 +6,7 @@ import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../config/apiUrl.dart'; import '../config/apiUrl.dart';
import '../services/apiService.dart';
class CommentModal extends StatefulWidget { class CommentModal extends StatefulWidget {
final String planId; final String planId;
@ -32,6 +33,8 @@ class CommentModalState extends State<CommentModal> {
bool editRemarks = false; bool editRemarks = false;
TextEditingController commentController = TextEditingController(); TextEditingController commentController = TextEditingController();
final ApiService apiService = ApiService();
// Map<String, dynamic> getData() { // Map<String, dynamic> getData() {
// final map = { // final map = {
// "plan_id": int.parse(widget.planId), // "plan_id": int.parse(widget.planId),
@ -148,6 +151,11 @@ class CommentModalState extends State<CommentModal> {
); );
} }
return data['data']; return data['data'];
} else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return {};
// throw Exception('Failed to load users');
} else { } else {
throw Exception('Failed to load remarks'); throw Exception('Failed to load remarks');
} }
@ -195,7 +203,12 @@ class CommentModalState extends State<CommentModal> {
if (response.statusCode == 200) { if (response.statusCode == 200) {
print("Plan submitted successfully!"); print("Plan submitted successfully!");
print("Response: ${response.body}"); print("Response: ${response.body}");
} else { } else if (response.statusCode == 403) {
print("403-FORB");
await apiService.logout(context);
return null;
// throw Exception('Failed to load users');
}else {
print("Failed to submit plan. Status: ${response.statusCode}"); print("Failed to submit plan. Status: ${response.statusCode}");
print("Error: ${response.body}"); print("Error: ${response.body}");
} }

View File

@ -45,7 +45,7 @@ class PlanPopupMenu extends StatelessWidget {
icon: Icon(Icons.remove_red_eye, size: 18), icon: Icon(Icons.remove_red_eye, size: 18),
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
ApiService.viewPlan( ApiService().viewPlan(
context, context,
plan.planId, plan.planId,
isViewMode: true, isViewMode: true,
@ -77,7 +77,7 @@ class PlanPopupMenu extends StatelessWidget {
), ),
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
apiService.getPdfDownload(plan.planId); apiService.getPdfDownload(context,plan.planId);
}, },
), ),
@ -93,7 +93,7 @@ class PlanPopupMenu extends StatelessWidget {
tooltip: 'Download Forex PDF', tooltip: 'Download Forex PDF',
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
apiService.getPdfDownload(plan.forexId); apiService.getPdfDownload(context,plan.forexId);
}, },
), ),
IconButton( IconButton(

View File

@ -33,6 +33,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.7.0" version: "2.7.0"
asn1lib:
dependency: transitive
description:
name: asn1lib
sha256: "9a8f69025044eb466b9b60ef3bc3ac99b4dc6c158ae9c56d25eeccf5bc56d024"
url: "https://pub.dev"
source: hosted
version: "1.6.5"
async: async:
dependency: transitive dependency: transitive
description: description:
@ -209,6 +217,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.8.5+1" version: "0.8.5+1"
encrypt:
dependency: "direct main"
description:
name: encrypt
sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2"
url: "https://pub.dev"
source: hosted
version: "5.0.3"
fake_async: fake_async:
dependency: transitive dependency: transitive
description: description:
@ -813,6 +829,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.8" version: "2.1.8"
pointycastle:
dependency: transitive
description:
name: pointycastle
sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe"
url: "https://pub.dev"
source: hosted
version: "3.9.1"
pool: pool:
dependency: transitive dependency: transitive
description: description:

View File

@ -65,6 +65,7 @@ dependencies:
flutter_launcher_icons: ^0.14.4 flutter_launcher_icons: ^0.14.4
dotted_border: ^3.1.0 dotted_border: ^3.1.0
flutter_riverpod: ^3.0.0 flutter_riverpod: ^3.0.0
encrypt: ^5.0.3