This commit is contained in:
venbaittech 2025-05-26 14:10:27 +05:30
commit 9d1873c749
6 changed files with 1396 additions and 17 deletions

View File

@ -0,0 +1,420 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import '../../config/apiUrl.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart';
import '../../widgets/custom_text_forex.dart';
import 'costCenter_list.dart';
class CostCenterData extends StatefulWidget {
final Future<List<dynamic>> Function() fetchGetCostCenter;
final bool isDesktop;
final Color? layoutColor;
final int? costcenterId; // <-- Add this
final Map<String, dynamic>? costcenterData;
const CostCenterData(
{super.key,
required this.isDesktop,
this.layoutColor,
required this.fetchGetCostCenter,
this.costcenterId,
this.costcenterData});
@override
CostCenterDataState createState() => CostCenterDataState();
}
class CostCenterDataState extends State<CostCenterData> {
final ApiService apiService = ApiService();
Map<String, dynamic>? apiData;
final Map<String, FocusNode> focusNodes = {
"name": FocusNode(),
"description": FocusNode(),
};
final Map<String, TextEditingController> controllers = {};
Map<String, String> errorMessages = {};
String? selectedName;
String? selectedDescription;
String? userId;
int? costcenterDataId;
late String isActive = "1";
List<String> dataHeader = [
"name",
"description",
];
Map<String, dynamic> costcenterDetails() {
final data = {
// "cost_center_id": int.parse(costcenterId),
"name": controllers["name"]?.text,
"description": controllers["description"]?.text,
"created_by": userId,
"is_active": isActive,
};
return data;
}
@override
void initState() {
super.initState();
apiData = null;
for (var field in dataHeader) {
controllers[field] = TextEditingController();
}
if (widget.costcenterId != null) {
print('Editing D ID: ${widget.costcenterId}');
updateCostCenterDetails();
}
}
void _clearError() {
setState(() {
errorMessages.clear();
});
}
@override
void dispose() {
for (var controller in controllers.values) {
controller.dispose();
}
super.dispose();
}
void updateCostCenterDetails() {
print("Inside Update Function - ${widget.costcenterData}");
final data = widget.costcenterData;
if (data == null) return;
setState(() {
controllers['name']?.text = data['name'] ?? '';
controllers['description']?.text = data['description'].toString();
isActive = data["is_active"];
final costcenterId = int.tryParse(data['cost_center_id'].toString());
costcenterDataId = costcenterId;
});
}
void toggleStatus() {
setState(() {
isActive = isActive == "1" ? "0" : "1";
});
}
bool validateData() {
errorMessages.clear();
final data = {
"name": controllers["name"]?.text,
"description": controllers["description"]?.text,
};
final requiredFields = ["name", "description"];
bool hasFocused = false;
// Check validation for each field
for (String field in requiredFields) {
if (data[field] == null || data[field]!.trim().isEmpty) {
errorMessages[field] = "Required";
if (!hasFocused) {
focusNodes[field]?.requestFocus();
hasFocused = true;
}
}
}
return errorMessages.isEmpty;
}
Future<void> handleSubmit() async {
userId = await getUserId();
setState(() {
// This triggers UI rebuild with error messages
if (validateData()) {
postCostCenterData();
}
});
final costcenterData1 = costcenterDetails();
print("submit data - $costcenterData1");
}
Future<void> postCostCenterData({int isActive = 1}) async {
// final remarksData = getData();
final costcenterData = costcenterDetails();
print("initially value of the CostCenter - $costcenterData");
final String apiUrldata;
if (costcenterDataId != null) {
print("for edit costcenter id - $costcenterDataId");
apiUrldata = '$apiUrl/api/updateCostCenter/$costcenterDataId';
costcenterData["cost_center_id"] = costcenterDataId.toString();
costcenterData["updated_by"] = userId;
(costcenterData.containsKey("created_by")) ? costcenterData.remove("created_by") : '' ;
} else {
print("for add CostCenter id - null");
apiUrldata = '$apiUrl/api/createCostCenter';
print("called apiUrl - $apiUrldata");
costcenterData["created_by"] = userId;
}
print("recently CostCenter data - $costcenterData");
final token = await getToken(); // Fetch token
if (token == null) {
throw Exception('Token not found. Please log in.');
}
try {
final uri = Uri.parse(apiUrldata);
final headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
final body = jsonEncode(costcenterData);
final response = costcenterDataId != null
? await http.put(uri, headers: headers, body: body)
: await http.post(uri, headers: headers, body: body);
switch (response.statusCode) {
case 200:
print("Update - Response: ${response.body}");
_clearError();
widget.fetchGetCostCenter();
Navigator.of(context).pop();
break;
case 201:
print("Save - Response: ${response.body}");
_clearError();
await widget.fetchGetCostCenter();
Navigator.of(context).pop();
break;
default:
print("Failed to submit costcenter. Status: ${response.statusCode}");
print("Error: ${response.body}");
}
} catch (e) {
print(" Error submitting plan: $e");
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
backgroundColor: Colors.white,
contentPadding: const EdgeInsets.fromLTRB(34, 30, 34, 30),
// contentPadding: const EdgeInsets.fromLTRB(24, 20, 24, 10),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Row 1: Title + Edit + Delete buttons
Row(
children: [
Text(
(costcenterDataId != null) ? 'Edit CostCenter' : 'Create CostCenter',
style: GoogleFonts.poppins(fontSize: 15, color: Colors.black),
),
const Spacer(),
],
),
const SizedBox(height: 2),
Divider(
thickness: 0.2,
color: Colors.blueGrey.shade100,
),
const SizedBox(height: 5),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Name",
style: GoogleFonts.poppins(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF575A74)),
),
SizedBox(height: 5),
CustomTextFieldForexWrapper(
isFocused: false,
isDesktop: widget.isDesktop,
color: Colors.transparent,
child: SizedBox(
height: 40,
child: TextField(
controller: controllers["name"],
focusNode: focusNodes["name"],
style: const TextStyle(fontSize: 12),
decoration: const InputDecoration(
labelText: "Name",
labelStyle: TextStyle(fontSize: 11, color: Colors.grey),
floatingLabelBehavior: FloatingLabelBehavior.never,
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(vertical: 16),
),
)),
),
if (errorMessages["name"] != null) ...[
SizedBox(height: 5), // Space before error message
Text(
errorMessages["name"]!,
style: TextStyle(color: Colors.red, fontSize: 12),
),
],
],
),
SizedBox(
height: 15,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Description",
style: GoogleFonts.poppins(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF575A74)),
),
SizedBox(height: 5),
CustomTextFieldForexWrapper(
isFocused: false,
isDesktop: widget.isDesktop,
color: Colors.transparent,
child: SizedBox(
height: 100,
child: TextField(
controller: controllers["description"],
focusNode: focusNodes["description"],
style: const TextStyle(fontSize: 12),
maxLines: null,
expands: true,
decoration: const InputDecoration(
labelText: "Description",
labelStyle: TextStyle(fontSize: 11, color: Colors.grey),
floatingLabelBehavior: FloatingLabelBehavior.never,
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(vertical: 16),
),
),
),
),
if (errorMessages["description"] != null) ...[
SizedBox(height: 5), // Space before error message
Text(
errorMessages["description"]!,
style: TextStyle(color: Colors.red, fontSize: 12),
),
],
],
),
SizedBox(
height: 15,
),
if (costcenterDataId != null)
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Change Status ",
style: GoogleFonts.poppins(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF575A74)),
),
Tooltip(
message:
isActive == "1" ? "Tap to deactivate" : "Tap to activate",
child: GestureDetector(
onTap: toggleStatus,
child: Text(
isActive == "1" ? "Active" : "Inactive",
style: TextStyle(
fontSize: 13,
fontFamily: "Inter",
color: isActive == "1" ? Colors.green : Colors.red,
),
),
),
)
],
),
if (costcenterDataId != null)
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
// SizedBox(
// child: ElevatedButton(
// onPressed: () {
// // You can get text from commentController.text
// Navigator.of(context).pop(); // Close the modal
// },
// style: ElevatedButton.styleFrom(
// backgroundColor: widget.layoutColor,
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(8),
// ),
// ),
// child: Text('Cancel',
// style: GoogleFonts.poppins(
// fontSize: 13, color: Colors.white)),
// ),
// ),
// SizedBox(
// width: 10,
// ),
SizedBox(
child: ElevatedButton(
onPressed: () {
handleSubmit();
// You can get text from commentController.text
// Navigator.of(context).pop(); // Close the modal
},
style: ElevatedButton.styleFrom(
backgroundColor: widget.layoutColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: Text('Save',
style: GoogleFonts.poppins(
fontSize: 11, color: Colors.white)),
),
),
],
)
// : SizedBox.shrink(),
],
),
);
}
}

View File

@ -0,0 +1,837 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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 'package:shared_preferences/shared_preferences.dart';
import '../../config/apiUrl.dart';
import '../../routes/custom_appBar.dart';
import '../../routes/custom_drawer.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart';
import '../../utils/pagination.dart';
import 'costCenterDetails.dart';
class CostCenterList extends StatefulWidget {
const CostCenterList({super.key});
@override
CostCenterListState createState() => CostCenterListState();
}
class CostCenterListState extends State<CostCenterList> {
final GlobalKey<CostCenterListState> costCenterListKey =
GlobalKey<CostCenterListState>();
final ApiService apiService = ApiService();
late Future<List<dynamic>> futureCostCenter;
late Map<String, dynamic> depSingleData;
String? selectedCostCenterId;
String? orgId;
Color? layoutColor;
Color? bodyColor;
List allCostCenter = [];
List filteredCostCenter = [];
TextEditingController searchController = TextEditingController();
int currentPage = 0;
int itemsPerPage = 10;
@override
void initState() {
super.initState();
futureCostCenter = fetchGetCostCenter();
futureCostCenter.then((object) {
setState(() {
allCostCenter = object;
});
});
WidgetsBinding.instance.addPostFrameCallback((_) {
loadInitialData();
});
// futurePlans = fetchPlans();
}
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<String?> getToken() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString('auth_token');
}
Future<List<dynamic>> refreshData() {
print("Calling Refresh Data");
futureCostCenter = fetchGetCostCenter();
return futureCostCenter.then((object) {
print("Calling Refresh Data $object");
setState(() {
allCostCenter = object;
});
return object;
});
}
Future<List<dynamic>> fetchGetCostCenter() async {
final String apiUrlData = '$apiUrl/api/getCostCenterMaster';
final String? token = await getToken();
print("Fetch CostCenter");
print("2KN Here : $token");
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',
},
);
print("called api : $apiUrlData");
if (response.statusCode == 200) {
final data = json.decode(response.body);
print(data['data']);
return data['data']; // Returning raw JSON list
} else {
throw Exception('Failed to load users');
}
}
void filterCostCenter(String query) {
// print("all before filtering: $query");
// final lowerQuery = query.toLowerCase();
// setState(() {
// filteredCostCenter = allCostCenter.where((object) {
// return (object['cost_center_id']?.toLowerCase().contains(lowerQuery) ??
// false) ||
// (object['description']?.toLowerCase().contains(lowerQuery) ?? false) ||
// (object['user']?.toLowerCase().contains(lowerQuery) ?? false) ||
// (object['is_active']?.toLowerCase().contains(lowerQuery) ?? false);
// }).toList();
// });
// print("filteredPlans: $filteredCostCenter");
print("all before filtering: $query");
final lowerQuery = query.toLowerCase();
setState(() {
filteredCostCenter = allCostCenter.where((object) {
final isActiveStatus =
object['is_active'] == "1" ? "active" : "inactive";
return (object['cost_center_id']?.toLowerCase().contains(lowerQuery) ??
false) ||
(object['name']?.toLowerCase().contains(lowerQuery) ??
false) ||
(object['description']?.toLowerCase().contains(lowerQuery) ?? false) ||
(isActiveStatus.contains(lowerQuery));
}).toList();
});
print("filteredCostCenter: $filteredCostCenter");
}
@override
Widget build(BuildContext context) {
return ResponsiveBuilder(builder: (context, sizingInfo) {
bool isDesktop = sizingInfo.deviceScreenType == DeviceScreenType.desktop;
return Scaffold(
backgroundColor: Color(0xFFf5f5f5),
// appBar: isDesktop ? null : const CustomAppBar(title: 'User Management'),
// drawer: isDesktop ? null : CustomDrawer(isDesktop: false),
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),
// const Expanded(child: Center(child: Text("User Page Content"))),
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.all(1),
decoration: BoxDecoration(
color: isDesktop ? Colors.white : Color(0xFFFCFCFC),
),
// decoration: BoxDecoration(
// // color: Colors.amber,
// // color: bodyColor,
// color: Color(0xFFE1F5FE),
// border: Border.all(
// color: Colors.white,
// // color: Color(0xFFF7F7FB),
// width: 3.5)),
child: buildUserTable(isDesktop),
);
}
Widget buildUserTable(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,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
color: Colors.white,
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Divider(
// thickness: 0.2, // how "thick" the line is
// color: Colors.grey, // optional
// ),
Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Text(
'CostCenter Details',
style: GoogleFonts.poppins(
fontSize: isDesktop ? 16 : 14,
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
],
),
if (isDesktop)
SizedBox(
width: MediaQuery.of(context).size.width * 0.16,
),
if (isDesktop)
Container(
width: MediaQuery.of(context).size.width * 0.2,
height: 40,
child: TextField(
controller: searchController,
onChanged: filterCostCenter,
decoration: InputDecoration(
hintText: "Search ...",
hintStyle: TextStyle(
fontSize: 12, color: Color(0xFF9E9DBD)),
prefixIcon: Icon(
Icons.search,
color: Color(0xFF9E9DBD),
size: 18,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(
color: Colors.grey.shade200, width: 0.5),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(
color: Colors.grey.shade300, width: 1),
),
),
style: GoogleFonts.poppins(
fontSize: 12,
),
),
),
// SizedBox(width: 16),
Spacer(),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Color(0xFF114D8B),
foregroundColor: Colors.white,
disabledBackgroundColor: Color(0xFF114D8B),
disabledForegroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side:
BorderSide(color: Color(0xFF114D8B), width: 2),
),
padding: EdgeInsets.symmetric(
horizontal: 20, vertical: 12),
),
onPressed: () async {
showDialog(
context: context,
builder: (context) => CostCenterData(
isDesktop: isDesktop,
layoutColor: layoutColor!,
fetchGetCostCenter: refreshData,
// role:
// "Travel Agent"
),
);
},
child: Row(
mainAxisSize:
MainAxisSize.min, // Ensures content fits nicely
children: [
Text(
"Add CostCenter",
style: GoogleFonts.poppins(
fontSize: isDesktop ? 13 : 11,
),
),
SizedBox(width: 8), // spacing between icon and text
Icon(
Icons.add_circle_outline_rounded,
size: 15,
color: Colors.white,
),
],
),
),
],
),
if (!isDesktop)
SizedBox(
height: 5,
),
isDesktop
? SizedBox.shrink()
: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: MediaQuery.of(context).size.width * 0.8,
height: 35,
child: TextField(
controller: searchController,
onChanged: filterCostCenter,
decoration: InputDecoration(
hintText: "Search ...",
hintStyle: TextStyle(
fontSize: 12, color: Color(0xFF9E9DBD)),
prefixIcon: Icon(
Icons.search,
color: Color(0xFF9E9DBD),
size: 18,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(
color: Colors.grey.shade200,
width: 0.5),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(
color: Colors.grey.shade300, width: 1),
),
),
style: GoogleFonts.poppins(
fontSize: 12,
),
),
),
// SizedBox(width: 16),
],
),
const SizedBox(height: 10),
FutureBuilder<List<dynamic>>(
future: futureCostCenter,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError ||
!snapshot.hasData ||
snapshot.data!.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// const Icon(Icons.error_outline,
// color: Colors.redAccent, size: 60),
// const SizedBox(height: 16),
// Text(
// "Oops!",
// style: GoogleFonts.poppins(
// fontSize: 20,
// fontWeight: FontWeight.bold,
// color: Colors.redAccent),
// ),
const SizedBox(height: 8),
Text(
"No CostCenter Available ",
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.grey),
),
const SizedBox(height: 20),
Text(
"Please Create CostCenter Details",
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 16, color: Colors.grey),
),
const SizedBox(height: 20),
],
),
),
);
}
/* Here collect the list to displayed the data in table or card Used */
List<dynamic> object =
filteredCostCenter.isNotEmpty ? filteredCostCenter : allCostCenter;
/* List is Sorting here */
object.sort((a, b) {
DateTime dateA = DateTime.parse(a['created_on']);
DateTime dateB = DateTime.parse(b['created_on']);
return dateB
.compareTo(dateA); // Descending: newest first
});
/* For pagination for list ... */
List paginatedCostCenter = object
.skip(currentPage * itemsPerPage)
.take(itemsPerPage)
.toList();
/* Table ... */
Widget table = LayoutBuilder(
builder: (context, constraints) {
double minWidth =
isDesktop ? constraints.maxWidth : 1300;
return ConstrainedBox(
constraints: BoxConstraints(minWidth: minWidth),
child: DataTable(
dividerThickness: 0.5,
columnSpacing: isDesktop ? 24.0 : 16.0,
border: TableBorder(
horizontalInside: BorderSide(
width: 0.5, color: Colors.grey.shade200),
),
columns: [
DataColumn(
label: Text(
'Name',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600),
)),
DataColumn(
label: Text(
'Description',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600),
)),
DataColumn(
label: Text(
'Status',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600),
)),
DataColumn(
label: Text(
'Actions',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600),
)),
],
rows: paginatedCostCenter.map((tableObject) {
String costcenterId = tableObject['cost_center_id']
.toString(); // Get user ID
bool isSelected = selectedCostCenterId == costcenterId;
return DataRow(cells: [
DataCell(Text(tableObject['name'] ?? '',
style: TextStyle(
fontSize: 13,
fontFamily: "Inter",
))),
DataCell(Text(tableObject['description'] ?? 'N/A',
style: TextStyle(
fontSize: 13,
fontFamily: "Inter",
),
softWrap: true,
overflow: TextOverflow.ellipsis)),
DataCell(
Text(
tableObject['is_active'] == "1"
? 'Active'
: 'Inactive',
style: TextStyle(
fontSize: 13,
fontFamily: "Inter",
color: tableObject['is_active'] == "1" ? Colors.green : Colors.red,
),
softWrap: true,
overflow: TextOverflow.ellipsis,
),
),
DataCell(
// UserActionsMenu(
// user: forex,
// getUserDetails: (id) =>
// apiService.getSingleUser(id),
// ),
GestureDetector(
child: Image.asset(
'assets/images/IconsImg/edit.png',
width: 20,
height: 15),
onTap: () async {
// final userId = getUserId(user['user_id']);
// final usersData = await getUserDetails(userId);
//
final costcenterId = int.tryParse(
tableObject['cost_center_id']
.toString());
if (costcenterId != null) {
print("Table cell - costcenter Id -- $costcenterId");
final data = await apiService.getCostCenterDetailsFind(costcenterId);
print("CostCenterId -- $data");
showDialog(
context: context,
builder: (context) => CostCenterData(
isDesktop: isDesktop,
costcenterId: costcenterId, // Pass the ID
costcenterData: data,
layoutColor: layoutColor!,
// fetchGetForex: fetchGetForex,
fetchGetCostCenter: refreshData,
// role:
// "Travel Agent"
),
);
} else {
print("Invalid ID");
}
},
),
),
]);
}).toList(),
),
);
},
);
/* Card ... */
Widget buildMobileCardView(List<dynamic> paginatedUser) {
return ListView.builder(
itemCount: paginatedUser.length,
itemBuilder: (context, index) {
final cardObject = paginatedUser[index];
return Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 3,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Status and Employee Code
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
cardObject['name'] ?? 'N/A',
style: GoogleFonts.poppins(
fontSize: 10,
color: Colors.black87,
fontWeight: FontWeight.w700),
),
GestureDetector(
child: Image.asset(
'assets/images/IconsImg/edit.png',
width: 20,
height: 15),
onTap: () async {
// final userId = getUserId(user['user_id']);
// final usersData = await getUserDetails(userId);
//
final costcenterId = int.tryParse(
cardObject['cost_center_id']
.toString());
if (costcenterId != null) {
print("costcenterId -- $costcenterId");
final data = await apiService
.getCostCenterDetailsFind(costcenterId);
print("CostCenterId -- $data");
showDialog(
context: context,
builder: (context) => CostCenterData(
isDesktop: isDesktop,
costcenterId:costcenterId, // Pass the ID
costcenterData:data,
layoutColor:layoutColor!,
// fetchGetCostCenter: fetchGetCostCenter,
fetchGetCostCenter: refreshData,
// role:
// "Travel Agent"
),
);
} else {
print("Invalid ID");
}
},
),
// PopupMenuButton<int>(
// color: Colors.white,
// padding: EdgeInsets.zero,
// offset: Offset(0, 30),
// icon: Icon(
// Icons.more_vert,
// color: Color(0xFF475569),
// size: 14,
// ),
// itemBuilder: (context) => [
// CustomPopupMenuEntry(
// child: Container(
// padding: EdgeInsets.symmetric(
// horizontal: 8, vertical: 8),
// child: Row(
// mainAxisSize:
// MainAxisSize.min,
// mainAxisAlignment:
// MainAxisAlignment.center,
// children: [
// IconButton(
// icon: Icon(
// Icons
// .remove_red_eye,
// color: Color(
// 0xFF475569),
// size: 18),
// onPressed: () {
// print(
// "USerDAta - $user");
// // dynamic usersData = apiService
// // .getSingleUser(user[
// // 'user_id']
// // is String
// // ? int.parse(user[
// // 'user_id'])
// // : user[
// // 'user_id']);
// //
// // print(
// // "USerDAta - $usersData");
//
// context.go(
// "/CreateUserDetails",
// extra: {
// "selectedUser":
// user,
// "isViewMode": true
// },
// );
// }),
// IconButton(
// icon: Image.asset(
// 'assets/images/IconsImg/edit.png',
// width: 20,
// height: 15),
// onPressed: () {
// context.go(
// "/CreateUserDetails",
// extra: {
// "selectedUser":
// user,
// "isViewMode": false
// },
// );
// },
// ),
// ],
// ),
// ),
// ),
// ],
// ),
],
),
SizedBox(height: 2),
// Trip Id and Trip Name
// Name
Row(
children: [
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
cardObject['description'] ?? '',
style: GoogleFonts.poppins(
fontSize: 10,
color: Colors.black87),
),
],
),
SizedBox(
width: 10,
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
cardObject['description'] ?? '',
style: GoogleFonts.poppins(
fontSize: 10,
color: Colors.black87),
),
],
),
],
),
// Actions
// Actions
],
),
),
);
},
);
}
return Expanded(
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: isDesktop
? (searchController.text.isNotEmpty &&
filteredCostCenter.isEmpty
? Center(
child: Text(
"No matches found",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey),
),
)
: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: table,
))
: (searchController.text.isNotEmpty &&
filteredCostCenter.isEmpty
? Center(
child: Text(
"No matches found",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey),
),
)
: buildMobileCardView(paginatedCostCenter)),
),
// Expanded(
// child: isDesktop
// ? SingleChildScrollView(
// scrollDirection: Axis.vertical,
// child: table, // <-- your existing table
// )
// : buildMobileCardView(paginatedCostCenter),
// ),
PaginationControls(
currentPage: currentPage,
itemsPerPage: itemsPerPage,
totalItems: object.length,
activeColor: layoutColor, // your theme color
onPageChanged: (page) {
setState(() {
currentPage = page;
});
},
onItemsPerPageChanged: (items) {
setState(() {
itemsPerPage = items;
currentPage = 0;
});
},
),
],
),
);
},
)
]),
)),
);
}
}

View File

@ -465,13 +465,6 @@ class DepartmentListState extends State<DepartmentList> {
width: 0.5, color: Colors.grey.shade200),
),
columns: [
DataColumn(
label: Text(
'Department ID',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w600),
)),
DataColumn(
label: Text(
'Name',
@ -509,12 +502,6 @@ class DepartmentListState extends State<DepartmentList> {
selectedDepartmentId == departmentId;
return DataRow(cells: [
DataCell(Text(
"${tableObject['department_id'] ?? ''}",
style: TextStyle(
fontSize: 13,
fontFamily: "Inter",
))),
DataCell(Text(tableObject['name'] ?? '',
style: TextStyle(
fontSize: 13,
@ -562,6 +549,7 @@ class DepartmentListState extends State<DepartmentList> {
final departmentId = int.tryParse(
tableObject['department_id']
.toString());
if (departmentId != null) {
print(
"Table cell - department Id -- $departmentId");
@ -623,7 +611,7 @@ class DepartmentListState extends State<DepartmentList> {
MainAxisAlignment.spaceBetween,
children: [
Text(
cardObject['department_id'] ?? 'N/A',
cardObject['name'] ?? 'N/A',
style: GoogleFonts.poppins(
fontSize: 10,
color: Colors.black87,
@ -758,7 +746,7 @@ class DepartmentListState extends State<DepartmentList> {
CrossAxisAlignment.start,
children: [
Text(
cardObject['name'] ?? '',
cardObject['description'] ?? '',
style: GoogleFonts.poppins(
fontSize: 10,
color: Colors.black87),

View File

@ -25,6 +25,7 @@ import '../Screens/group/groupList.dart';
import '../Screens/myTemplates/template.dart';
import '../Screens/userManagement/create_user/create_user.dart';
import '../Screens/department/department_list.dart';
import '../Screens/costCenter/costCenter_list.dart';
final GoRouter router = GoRouter(
routes: [
@ -131,6 +132,10 @@ final GoRouter router = GoRouter(
path: '/department',
builder: (context, state) => DepartmentList(),
),
GoRoute(
path: '/costcenter',
builder: (context, state) => CostCenterList(),
),
GoRoute(
path: '/CreateGroup',
pageBuilder: (context, state) => MaterialPage(

View File

@ -88,6 +88,12 @@ class OrganizationSettingState extends State<OrganizationSetting> {
'label': 'Email Templates',
'description': ' Edit Email Template'
},
{
'value': '/costcenter',
'icon': Icons.account_balance_wallet,
'label': 'Cost Center',
'description': 'Create and Edit Cost Center'
},
];
List<Widget> rows = [];
@ -112,6 +118,7 @@ class OrganizationSettingState extends State<OrganizationSetting> {
case '/PolicyList':
case '/getPerdiem':
case '/templateList':
case '/costcenter':
context.go(route);
break;
default:
@ -159,8 +166,30 @@ class OrganizationSettingState extends State<OrganizationSetting> {
));
}
// return Container(
// // color: Colors.white,
// padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// 'Organization Settings',
// style: GoogleFonts.poppins(
// fontSize: 15,
// fontWeight: FontWeight.w500,
// color: Colors.black87,
// ),
// ),
// SizedBox(height: 8),
// Divider(thickness: 0.2, color: Colors.blueGrey.shade100),
// SizedBox(height: 12),
// ...rows, // Spread operator to insert all row widgets
// ],
// ),
// );
return Container(
// color: Colors.white,
padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@ -176,9 +205,62 @@ class OrganizationSettingState extends State<OrganizationSetting> {
SizedBox(height: 8),
Divider(thickness: 0.2, color: Colors.blueGrey.shade100),
SizedBox(height: 12),
...rows, // Spread operator to insert all row widgets
Wrap(
spacing: 16, // horizontal space between cards
runSpacing: 16, // vertical space between rows
children: menuItems.map((item) {
return SizedBox(
width: isDesktop ? 325 : double.infinity,
child: Card(
color: Colors.white,
child: InkWell(
onTap: () {
final route = item['value'] as String;
context.go(route);
},
child: Padding(
padding: EdgeInsets.all(12),
child: Row(
children: [
Icon(item['icon'], size: 40, color: Color(0xFF114D8B)),
SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
item['label'],
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 4),
Text(
item['description'],
maxLines: 1,
overflow: TextOverflow.ellipsis,
softWrap: false,
style: TextStyle(
fontSize: 14,
color: Colors.grey[700],
),
),
],
),
),
],
),
),
),
),
);
}).toList(),
),
],
),
);
}
}

View File

@ -996,4 +996,51 @@ class ApiService {
) ??
false; // Default to false if dismissed
}
Future<Map<String, dynamic>> getCostCenterDetailsFind(int id) async {
final String apiUrldata = '$apiUrl/api/findCostCenter?cost_center_id=$id';
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',
},
);
if (response.statusCode == 200) {
try {
final data = json.decode(response.body);
// print('findout the result');
// print(data.runtimeType);
// print(data);
if (!data.containsKey('data') || data['data'] is! List) {
throw Exception(
"Invalid response format: 'data' field is missing or not a List");
}
final List<Map<String, dynamic>> listData =
List<Map<String, dynamic>>.from(data['data']);
if (listData.isEmpty) {
throw Exception("No CostCenter found with ID $id");
}
return listData[0];
} catch (e) {
throw Exception('Error parsing response: $e');
}
} else {
throw Exception('Failed to load CostCenter details');
}
}
}