Compare commits

...

76 Commits

Author SHA1 Message Date
b461d5c2a9 resolved reabse conflicts 2025-11-24 12:37:08 +05:30
2bda44dd19 Merge branch 'Dev_Manish_17/11' of https://git.marcoaiot.com/admin/marco.pms.mobileapp into Dev_Manish_17/11 2025-11-24 12:16:15 +05:30
83e1686778 UI enhancement 2025-11-24 12:14:54 +05:30
17d1a66e1b check box color change to white 2025-11-24 12:14:54 +05:30
b4e6ea4380 upadted with select enployee sheet 2025-11-24 12:14:54 +05:30
cc53227722 unwanted code removed 2025-11-24 12:14:16 +05:30
3a6756c8d3 advance paymen 2025-11-24 12:14:16 +05:30
34456efbbd done with employee list dropdown updation 2025-11-24 12:13:42 +05:30
4265efd897 added multiselect bottom sheet in assign task bottom sheet form 2025-11-24 12:13:18 +05:30
abe8e978c4 done landscape responsive of all screen 2025-11-24 12:12:00 +05:30
ebd1448a70 UI enhancement 2025-11-24 12:10:13 +05:30
55d6b2fd11 check box color change to white 2025-11-24 12:10:13 +05:30
6a2d16a2b2 upadted with select enployee sheet 2025-11-24 12:10:12 +05:30
abe1f44fb4 unwanted code removed 2025-11-24 12:09:53 +05:30
8289546710 advance paymen 2025-11-24 12:09:53 +05:30
d4307814af done with employee list dropdown updation 2025-11-24 12:09:25 +05:30
d983620524 added multiselect bottom sheet in assign task bottom sheet form 2025-11-24 12:08:44 +05:30
2b1cbf129d Done all screen landscape responsive for mobile and tablet 2025-11-24 12:08:16 +05:30
9745c00638 done landscape responsive of all screen 2025-11-24 12:07:49 +05:30
4daa412a87 done tags UX updates 2025-11-24 12:06:37 +05:30
a85bea54f8 UI enhancement 2025-11-24 12:06:37 +05:30
0c957ad152 check box color change to white 2025-11-24 12:06:37 +05:30
f17c3fde8a upadted with select enployee sheet 2025-11-24 12:06:37 +05:30
3f458fc5f9 unwanted code removed 2025-11-24 12:06:37 +05:30
7a3947b6bc advance paymen 2025-11-24 12:06:37 +05:30
79c0ef3f65 added multiselect bottom sheet in assign task bottom sheet form 2025-11-24 12:06:37 +05:30
f73643b391 Done all screen landscape responsive for mobile and tablet 2025-11-24 12:06:37 +05:30
a79ab9fcab done landscape responsive of all screen 2025-11-24 12:06:37 +05:30
c005d2574c UI enhancement 2025-11-24 12:06:37 +05:30
f0969e1e46 check box color change to white 2025-11-24 12:06:36 +05:30
69585fae82 upadted with select enployee sheet 2025-11-24 12:06:36 +05:30
eed2cdc639 unwanted code removed 2025-11-24 12:06:36 +05:30
fc72d3562d advance paymen 2025-11-24 12:06:36 +05:30
7a816ed26e done with employee list dropdown updation 2025-11-24 12:06:36 +05:30
7c4f86dd94 added multiselect bottom sheet in assign task bottom sheet form 2025-11-24 12:06:36 +05:30
70b144ffce Done all screen landscape responsive for mobile and tablet 2025-11-24 12:06:36 +05:30
bf03023db7 done landscape responsive of all screen 2025-11-24 12:06:36 +05:30
4518504fe5 Merge branch 'Dev_Manish_17/11' of https://git.marcoaiot.com/admin/marco.pms.mobileapp into Dev_Manish_17/11 2025-11-24 11:24:15 +05:30
dc734e96d0 done tags UX updates 2025-11-24 11:05:51 +05:30
490ecbc567 UI enhancement 2025-11-24 11:05:51 +05:30
e6eb0178c0 check box color change to white 2025-11-24 11:05:51 +05:30
40467074ca upadted with select enployee sheet 2025-11-24 11:05:50 +05:30
3c08ee447c unwanted code removed 2025-11-24 11:05:08 +05:30
c6c11cc6fc advance paymen 2025-11-24 11:05:08 +05:30
d83bc838f4 added multiselect bottom sheet in assign task bottom sheet form 2025-11-24 11:02:31 +05:30
6bae9e389c Done all screen landscape responsive for mobile and tablet 2025-11-24 11:01:02 +05:30
c4897bccc8 done landscape responsive of all screen 2025-11-24 10:58:46 +05:30
a11fc80050 UI enhancement 2025-11-24 10:56:44 +05:30
02758a03bf check box color change to white 2025-11-24 10:56:44 +05:30
2e45d0de81 upadted with select enployee sheet 2025-11-24 10:56:43 +05:30
40e8a0d911 unwanted code removed 2025-11-24 10:52:34 +05:30
d3e3061d31 advance paymen 2025-11-24 10:52:34 +05:30
a9fa0448e3 done with employee list dropdown updation 2025-11-24 10:52:34 +05:30
b9847e03b1 added multiselect bottom sheet in assign task bottom sheet form 2025-11-24 10:52:34 +05:30
380b6d3552 Done all screen landscape responsive for mobile and tablet 2025-11-24 10:52:34 +05:30
c6419c0737 done landscape responsive of all screen 2025-11-24 10:48:24 +05:30
3ff97eb0d8 done tags UX updates 2025-11-24 10:16:41 +05:30
da1508b4e0 Merge branch 'Dev_Manish_17/11' of https://git.marcoaiot.com/admin/marco.pms.mobileapp into Dev_Manish_17/11 2025-11-22 11:58:32 +05:30
19e6979c0e UI enhancement 2025-11-22 11:58:11 +05:30
84395765fd check box color change to white 2025-11-22 11:58:11 +05:30
6162b9be89 upadted with select enployee sheet 2025-11-22 11:58:11 +05:30
39d0f96ecd unwanted code removed 2025-11-22 11:58:11 +05:30
270d24ed8c advance paymen 2025-11-22 11:58:11 +05:30
170ff050c4 done with employee list dropdown updation 2025-11-22 11:58:11 +05:30
7a9673e2c2 added multiselect bottom sheet in assign task bottom sheet form 2025-11-22 11:58:11 +05:30
125a09c772 Done all screen landscape responsive for mobile and tablet 2025-11-22 11:58:10 +05:30
261cba9dcf done landscape responsive of all screen 2025-11-22 11:52:54 +05:30
8cbefbb9e8 UI enhancement 2025-11-21 17:36:56 +05:30
3e317328b2 check box color change to white 2025-11-21 16:17:00 +05:30
542f27635a upadted with select enployee sheet 2025-11-21 16:04:40 +05:30
a03876bdb7 unwanted code removed 2025-11-20 12:00:28 +05:30
aa846f1a55 advance paymen 2025-11-20 11:57:13 +05:30
6515a511ee done with employee list dropdown updation 2025-11-20 10:44:17 +05:30
abbe3f3896 added multiselect bottom sheet in assign task bottom sheet form 2025-11-20 10:37:53 +05:30
0b4f429f54 Done all screen landscape responsive for mobile and tablet 2025-11-20 10:37:52 +05:30
c94efac1de done landscape responsive of all screen 2025-11-20 10:37:52 +05:30
25 changed files with 1757 additions and 1277 deletions

View File

@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
@ -50,10 +51,22 @@ class AddExpenseController extends GetxController {
final isEditMode = false.obs;
final isSearchingEmployees = false.obs;
// --- Paid By (Single + Multi Selection Support) ---
// single selection
final selectedPaidBy = Rxn<EmployeeModel>();
// helper setters
void setSelectedPaidBy(EmployeeModel? emp) {
selectedPaidBy.value = emp;
}
// --- Dropdown Selections & Data ---
final selectedPaymentMode = Rxn<PaymentModeModel>();
final selectedExpenseType = Rxn<ExpenseTypeModel>();
final selectedPaidBy = Rxn<EmployeeModel>();
// final selectedPaidBy = Rxn<EmployeeModel>();
final selectedProject = ''.obs;
final selectedTransactionDate = Rxn<DateTime>();

View File

@ -14,6 +14,7 @@ import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/helpers/widgets/time_stamp_image_helper.dart';
import 'package:on_field_work/model/finance/expense_category_model.dart';
import 'package:on_field_work/model/finance/currency_list_model.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
class AddPaymentRequestController extends GetxController {
// Loading States
@ -32,7 +33,7 @@ class AddPaymentRequestController extends GetxController {
// Selected Values
final selectedProject = Rx<Map<String, dynamic>?>(null);
final selectedCategory = Rx<ExpenseCategory?>(null);
final selectedPayee = ''.obs;
final selectedPayee = Rx<EmployeeModel?>(null);
final selectedCurrency = Rx<Currency?>(null);
final isAdvancePayment = false.obs;
final selectedDueDate = Rx<DateTime?>(null);
@ -184,7 +185,7 @@ class AddPaymentRequestController extends GetxController {
selectedProject.value = project;
void selectCategory(ExpenseCategory category) =>
selectedCategory.value = category;
void selectPayee(String payee) => selectedPayee.value = payee;
void selectPayee(EmployeeModel payee) => selectedPayee.value = payee;
void selectCurrency(Currency currency) => selectedCurrency.value = currency;
void addAttachment(File file) => attachments.add(file);
@ -268,7 +269,7 @@ class AddPaymentRequestController extends GetxController {
"amount": double.tryParse(amountController.text.trim()) ?? 0,
"currencyId": selectedCurrency.value?.id ?? '',
"description": descriptionController.text.trim(),
"payee": selectedPayee.value,
"payee": selectedPayee.value?.id ?? "",
"dueDate": selectedDueDate.value?.toIso8601String(),
"isAdvancePayment": isAdvancePayment.value,
"billAttachments": billAttachments.map((a) {
@ -337,7 +338,7 @@ class AddPaymentRequestController extends GetxController {
"amount": double.tryParse(amountController.text.trim()) ?? 0,
"currencyId": selectedCurrency.value?.id ?? '',
"description": descriptionController.text.trim(),
"payee": selectedPayee.value,
"payee": selectedPayee.value?.id ?? "",
"dueDate": selectedDueDate.value?.toIso8601String(),
"isAdvancePayment": isAdvancePayment.value,
"billAttachments": billAttachments.map((a) {
@ -388,7 +389,7 @@ class AddPaymentRequestController extends GetxController {
return _errorSnackbar("Please select a project");
if (selectedCategory.value == null)
return _errorSnackbar("Please select a category");
if (selectedPayee.value.isEmpty)
if (selectedPayee.value == null)
return _errorSnackbar("Please select a payee");
if (selectedCurrency.value == null)
return _errorSnackbar("Please select currency");
@ -408,7 +409,7 @@ class AddPaymentRequestController extends GetxController {
descriptionController.clear();
selectedProject.value = null;
selectedCategory.value = null;
selectedPayee.value = '';
selectedPayee.value = null;
selectedCurrency.value = null;
isAdvancePayment.value = false;
attachments.clear();

View File

@ -75,7 +75,7 @@ class AddServiceProjectJobController extends GetxController {
assignees: assigneeIds.map((id) => {"id": id}).toList(),
startDate: startDate.value!,
dueDate: dueDate.value!,
tags: enteredTags.map((tag) => {"name": tag}).toList(),
tags: enteredTags.map((tag) => {"name": tag.trim()}).toList(),
);
isLoading.value = false;

View File

@ -282,86 +282,129 @@ class ExpenseList extends StatelessWidget {
@override
Widget build(BuildContext context) {
if (expenseList.isEmpty && !Get.find<ExpenseController>().isLoading.value) {
return Center(child: MyText.bodyMedium('No expenses found.'));
}
final ExpenseController controller = Get.find<ExpenseController>();
return ListView.separated(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 80),
itemCount: expenseList.length,
separatorBuilder: (_, __) =>
Divider(color: Colors.grey.shade300, height: 20),
itemBuilder: (context, index) {
final expense = expenseList[index];
final formattedDate = DateTimeUtils.convertUtcToLocal(
expense.transactionDate.toIso8601String(),
format: 'dd MMM yyyy',
);
return SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final bool isLandscape = constraints.maxWidth > constraints.maxHeight;
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () async {
await Get.to(
() => ExpenseDetailScreen(expenseId: expense.id),
);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
if (controller.isLoading.value && expenseList.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (expenseList.isEmpty) {
return const Center(
child: Text(
'No expenses found.',
style: TextStyle(color: Colors.grey),
),
);
}
// PORTRAIT MODE
if (!isLandscape) {
return ListView.separated(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 80),
itemCount: expenseList.length,
separatorBuilder: (_, __) =>
Divider(color: Colors.grey.shade300, height: 20),
itemBuilder: _buildItem,
);
}
// LANDSCAPE WRAP IN SCROLL FOR SAFETY
return SingleChildScrollView(
child: SizedBox(
height: constraints.maxHeight * 1.3,
child: ListView.separated(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 80),
itemCount: expenseList.length,
separatorBuilder: (_, __) =>
Divider(color: Colors.grey.shade300, height: 20),
itemBuilder: _buildItem,
),
),
);
},
),
);
}
Widget _buildItem(BuildContext context, int index) {
final expense = expenseList[index];
final formattedDate = DateTimeUtils.convertUtcToLocal(
expense.transactionDate.toIso8601String(),
format: 'dd MMM yyyy',
);
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () async {
final result = await Get.to(
() => ExpenseDetailScreen(expenseId: expense.id),
arguments: {'expense': expense},
);
if (result == true && onViewDetail != null) {
await onViewDetail!();
}
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MyText.bodyMedium(expense.expenseCategory.name,
fontWeight: 600),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MyText.bodyMedium(expense.expenseCategory.name,
MyText.bodyMedium('${expense.formattedAmount}',
fontWeight: 600),
Row(
children: [
MyText.bodyMedium('${expense.formattedAmount}',
fontWeight: 600),
if (expense.status.name.toLowerCase() == 'draft') ...[
const SizedBox(width: 8),
GestureDetector(
onTap: () =>
_showDeleteConfirmation(context, expense),
child: const Icon(Icons.delete,
color: Colors.red, size: 20),
),
],
],
),
],
),
const SizedBox(height: 6),
Row(
children: [
MyText.bodySmall(formattedDate, fontWeight: 500),
const Spacer(),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Color(int.parse(
'0xff${expense.status.color.substring(1)}'))
.withOpacity(0.5),
borderRadius: BorderRadius.circular(5),
if (expense.status.name.toLowerCase() == 'draft') ...[
const SizedBox(width: 8),
GestureDetector(
onTap: () =>
_showDeleteConfirmation(context, expense),
child: const Icon(Icons.delete,
color: Colors.red, size: 20),
),
child: MyText.bodySmall(
expense.status.name,
color: Colors.white,
fontWeight: 500,
),
),
],
],
),
],
),
),
const SizedBox(height: 6),
Row(
children: [
MyText.bodySmall(formattedDate, fontWeight: 500),
const Spacer(),
Container(
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Color(int.parse(
'0xff${expense.status.color.substring(1)}'))
.withOpacity(0.5),
borderRadius: BorderRadius.circular(5),
),
child: MyText.bodySmall(
expense.status.name,
color: Colors.white,
fontWeight: 500,
),
),
],
),
],
),
);
},
),
),
);
}
}

View File

@ -123,7 +123,6 @@ class _AttendanceFilterBottomSheetState
}).toList();
final List<Widget> widgets = [
// 🔹 View Section
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Align(
@ -146,7 +145,6 @@ class _AttendanceFilterBottomSheetState
}),
];
// 🔹 Organization filter
widgets.addAll([
const Divider(),
Padding(
@ -165,24 +163,6 @@ class _AttendanceFilterBottomSheetState
color: Colors.grey.shade300,
borderRadius: BorderRadius.circular(12),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 100,
height: 14,
color: Colors.grey.shade400,
),
Container(
width: 18,
height: 18,
decoration: BoxDecoration(
color: Colors.grey.shade400,
shape: BoxShape.circle,
),
),
],
),
);
} else if (widget.controller.organizations.isEmpty) {
return Center(
@ -200,7 +180,6 @@ class _AttendanceFilterBottomSheetState
}),
]);
// 🔹 Date Range (only for Attendance Logs)
if (tempSelectedTab == 'attendanceLogs') {
widgets.addAll([
const Divider(),
@ -211,16 +190,12 @@ class _AttendanceFilterBottomSheetState
child: MyText.titleSmall("Date Range", fontWeight: 600),
),
),
// Reusable DateRangePickerWidget
DateRangePickerWidget(
startDate: widget.controller.startDateAttendance,
endDate: widget.controller.endDateAttendance,
startLabel: "Start Date",
endLabel: "End Date",
onDateRangeSelected: (start, end) {
// Optional: trigger UI updates if needed
setState(() {});
},
onDateRangeSelected: (_, __) => setState(() {}),
),
]);
}
@ -232,18 +207,36 @@ class _AttendanceFilterBottomSheetState
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
child: BaseBottomSheet(
title: "Attendance Filter",
submitText: "Apply",
onCancel: () => Navigator.pop(context),
onSubmit: () => Navigator.pop(context, {
'selectedTab': tempSelectedTab,
'selectedOrganization': widget.controller.selectedOrganization?.id,
}),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: buildMainFilters(),
),
child: LayoutBuilder(
builder: (context, constraints) {
final bool isLandscape = constraints.maxWidth > constraints.maxHeight;
return BaseBottomSheet(
title: "Attendance Filter",
submitText: "Apply",
onCancel: () => Navigator.pop(context),
onSubmit: () => Navigator.pop(context, {
'selectedTab': tempSelectedTab,
'selectedOrganization':
widget.controller.selectedOrganization?.id,
}),
// ---------------- UPDATED RESPONSIVE CHILD ----------------
child: SizedBox(
height: isLandscape
? constraints.maxHeight // 🔥 Full screen in landscape
: constraints.maxHeight * 0.78, // normal in portrait
child: SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: buildMainFilters(),
),
),
),
);
},
),
);
}

View File

@ -1,3 +1,6 @@
// Updated AssignTaskBottomSheet with bottom sheet height fix
// Only modified layout for employee selection area to prevent overflow.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/controller/task_Planning/daily_task_Planning_controller.dart';
@ -12,6 +15,8 @@ import 'package:on_field_work/helpers/widgets/tenant/organization_selector.dart'
import 'package:on_field_work/helpers/widgets/tenant/service_selector.dart';
import 'package:on_field_work/model/attendance/organization_per_project_list_model.dart';
import 'package:on_field_work/model/tenant/tenant_services_model.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/model/employees/multiple_select_role_bottomsheet.dart';
class AssignTaskBottomSheet extends StatefulWidget {
final String workLocation;
@ -43,14 +48,15 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
final DailyTaskPlanningController controller = Get.find();
final ProjectController projectController = Get.find();
final OrganizationController orgController = Get.put(OrganizationController());
final OrganizationController orgController =
Get.put(OrganizationController());
final ServiceController serviceController = Get.put(ServiceController());
final TextEditingController targetController = TextEditingController();
final TextEditingController descriptionController = TextEditingController();
final ScrollController _employeeListScrollController = ScrollController();
String? selectedProjectId;
String? selectedRoleId;
Organization? selectedOrganization;
Service? selectedService;
@ -79,12 +85,14 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
serviceId: selectedService?.id,
organizationId: selectedOrganization?.id,
);
await controller.fetchTaskData(selectedProjectId, serviceId: selectedService?.id);
await controller.fetchTaskData(
selectedProjectId,
serviceId: selectedService?.id,
);
}
@override
void dispose() {
_employeeListScrollController.dispose();
targetController.dispose();
descriptionController.dispose();
super.dispose();
@ -92,20 +100,21 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
@override
Widget build(BuildContext context) {
return Obx(() => BaseBottomSheet(
title: "Assign Task",
child: _buildAssignTaskForm(),
onCancel: () => Get.back(),
onSubmit: _onAssignTaskPressed,
isSubmitting: controller.isAssigningTask.value,
));
return Obx(
() => BaseBottomSheet(
title: "Assign Task",
child: _buildAssignTaskForm(),
onCancel: () => Get.back(),
onSubmit: _onAssignTaskPressed,
isSubmitting: controller.isAssigningTask.value,
),
);
}
Widget _buildAssignTaskForm() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Organization Selector
SizedBox(
height: 50,
child: OrganizationSelector(
@ -117,9 +126,9 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
},
),
),
MySpacing.height(12),
// Service Selector
SizedBox(
height: 50,
child: ServiceSelector(
@ -131,49 +140,75 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
},
),
),
MySpacing.height(16),
// Work Location Info
_infoRow(Icons.location_on, "Work Location",
"${widget.buildingName} > ${widget.floorName} > ${widget.workAreaName} > ${widget.activityName}"),
const Divider(),
_infoRow(
Icons.location_on,
"Work Location",
"${widget.buildingName} > ${widget.floorName} > ${widget.workAreaName} > ${widget.activityName}",
),
Icons.pending_actions, "Pending Task", "${widget.pendingTask}"),
const Divider(),
// Pending Task Info
_infoRow(Icons.pending_actions, "Pending Task", "${widget.pendingTask}"),
const Divider(),
// Role Selector
GestureDetector(
onTap: _onRoleMenuPressed,
child: Row(
children: [
MyText.titleMedium("Select Team :", fontWeight: 600),
const SizedBox(width: 4),
const Icon(Icons.tune, color: Color.fromARGB(255, 95, 132, 255)),
],
),
child: Row(children: [
MyText.titleMedium("Select Team :", fontWeight: 600),
const SizedBox(width: 4),
const Icon(Icons.tune, color: Color.fromARGB(255, 95, 132, 255)),
]),
),
MySpacing.height(8),
// Employee List
Container(
constraints: const BoxConstraints(maxHeight: 180),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(6),
),
child: _buildEmployeeList(),
),
MySpacing.height(8),
/// TEAM SELECT BOX
GestureDetector(
onTap: _openEmployeeSelectionSheet,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(6),
),
child: Row(
children: [
const Icon(Icons.group, color: Colors.black54),
const SizedBox(width: 10),
// Selected Employees Chips
// Expanded name area
Expanded(
child: Obx(() {
final count = controller.selectedEmployees.length;
if (count == 0) {
return MyText(
"Select team members",
color: Colors.grey.shade700,
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
final names = controller.selectedEmployees
.map((e) => e.name)
.join(", ");
return Text(
names,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 14),
);
}),
),
const Icon(Icons.arrow_drop_down, color: Colors.grey),
],
)),
),
MySpacing.height(8),
_buildSelectedEmployees(),
MySpacing.height(8),
// Target Input
_buildTextField(
icon: Icons.track_changes,
label: "Target for Today :",
@ -182,9 +217,9 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
keyboardType: const TextInputType.numberWithOptions(decimal: true),
validatorType: "target",
),
MySpacing.height(16),
// Description Input
_buildTextField(
icon: Icons.description,
label: "Description :",
@ -198,7 +233,8 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
}
void _onRoleMenuPressed() {
final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
final RenderBox overlay =
Overlay.of(context).context.findRenderObject() as RenderBox;
final Size screenSize = overlay.size;
showMenu(
@ -211,69 +247,18 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
),
items: [
const PopupMenuItem(value: 'all', child: Text("All Roles")),
...controller.roles.map((role) {
return PopupMenuItem(
...controller.roles.map(
(role) => PopupMenuItem(
value: role['id'].toString(),
child: Text(role['name'] ?? 'Unknown Role'),
);
}),
),
),
],
).then((value) {
if (value != null) controller.onRoleSelected(value == 'all' ? null : value);
});
}
Widget _buildEmployeeList() {
return Obx(() {
if (controller.isFetchingEmployees.value) {
return Center(child: CircularProgressIndicator());
if (value != null) {
selectedRoleId = value == 'all' ? null : value;
controller.onRoleSelected(selectedRoleId);
}
final filteredEmployees = controller.selectedRoleId.value == null
? controller.employees
: controller.employees
.where((e) => e.jobRoleID.toString() == controller.selectedRoleId.value)
.toList();
if (filteredEmployees.isEmpty) {
return Center(child: Text("No employees available for selected role."));
}
return Scrollbar(
controller: _employeeListScrollController,
thumbVisibility: true,
child: ListView.builder(
controller: _employeeListScrollController,
itemCount: filteredEmployees.length,
itemBuilder: (context, index) {
final employee = filteredEmployees[index];
final rxBool = controller.uploadingStates[employee.id];
return Obx(() => ListTile(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
leading: Checkbox(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
value: rxBool?.value ?? false,
onChanged: (selected) {
if (rxBool != null) {
rxBool.value = selected ?? false;
controller.updateSelectedEmployees();
}
},
fillColor: MaterialStateProperty.resolveWith((states) =>
states.contains(MaterialState.selected)
? const Color.fromARGB(255, 95, 132, 255)
: Colors.transparent),
checkColor: Colors.white,
side: const BorderSide(color: Colors.black),
),
title: Text(employee.name, style: const TextStyle(fontSize: 14)),
visualDensity: VisualDensity.compact,
));
},
),
);
});
}
@ -285,20 +270,14 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
spacing: 4,
runSpacing: 4,
children: controller.selectedEmployees.map((e) {
return Obx(() {
final isSelected = controller.uploadingStates[e.id]?.value ?? false;
if (!isSelected) return Container();
return Chip(
label: Text(e.name, style: const TextStyle(color: Colors.white)),
backgroundColor: const Color.fromARGB(255, 95, 132, 255),
deleteIcon: const Icon(Icons.close, color: Colors.white),
onDeleted: () {
controller.uploadingStates[e.id]?.value = false;
controller.updateSelectedEmployees();
},
);
});
return Chip(
label: Text(e.name, style: const TextStyle(color: Colors.white)),
backgroundColor: const Color.fromARGB(255, 95, 132, 255),
deleteIcon: const Icon(Icons.close, color: Colors.white),
onDeleted: () {
controller.selectedEmployees.remove(e);
},
);
}).toList(),
);
});
@ -328,10 +307,15 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
maxLines: maxLines,
decoration: InputDecoration(
hintText: hintText,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(6)),
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(6),
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
),
validator: (value) => this.controller.formFieldValidator(value, fieldType: validatorType),
validator: (value) => this
.controller
.formFieldValidator(value, fieldType: validatorType),
),
],
);
@ -350,32 +334,83 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
text: TextSpan(
children: [
WidgetSpan(
child: MyText.titleMedium("$title: ", fontWeight: 600, color: Colors.black),
child: MyText.titleMedium(
"$title: ",
fontWeight: 600,
color: Colors.black,
),
),
TextSpan(
text: value,
style: const TextStyle(color: Colors.black),
),
TextSpan(text: value, style: const TextStyle(color: Colors.black)),
],
),
),
),
)
],
),
);
}
Future<void> _openEmployeeSelectionSheet() async {
final result = await showModalBottomSheet<List<EmployeeModel>>(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) {
return DraggableScrollableSheet(
expand: false,
initialChildSize: 0.85,
minChildSize: 0.6,
maxChildSize: 1.0,
builder: (_, scrollController) {
return Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: MultipleSelectRoleBottomSheet(
projectId: selectedProjectId!,
organizationId: selectedOrganization?.id,
serviceId: selectedService?.id,
roleId: selectedRoleId,
initiallySelected: controller.selectedEmployees.toList(),
scrollController: scrollController,
),
);
},
);
},
);
if (result != null) {
controller.selectedEmployees
.assignAll(result); // RxList updates UI automatically
}
}
void _onAssignTaskPressed() {
final selectedTeam = controller.uploadingStates.entries
.where((e) => e.value.value)
.map((e) => e.key)
.toList();
final selectedTeam = controller.selectedEmployees;
if (selectedTeam.isEmpty) {
showAppSnackbar(title: "Team Required", message: "Please select at least one team member", type: SnackbarType.error);
showAppSnackbar(
title: "Team Required",
message: "Please select at least one team member",
type: SnackbarType.error,
);
return;
}
final target = double.tryParse(targetController.text.trim());
if (target == null || target <= 0) {
showAppSnackbar(title: "Invalid Input", message: "Please enter a valid target number", type: SnackbarType.error);
showAppSnackbar(
title: "Invalid Input",
message: "Please enter a valid target number",
type: SnackbarType.error,
);
return;
}
@ -390,7 +425,11 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
final description = descriptionController.text.trim();
if (description.isEmpty) {
showAppSnackbar(title: "Description Required", message: "Please enter a description", type: SnackbarType.error);
showAppSnackbar(
title: "Description Required",
message: "Please enter a description",
type: SnackbarType.error,
);
return;
}
@ -398,7 +437,7 @@ class _AssignTaskBottomSheetState extends State<AssignTaskBottomSheet> {
workItemId: widget.workItemId,
plannedTask: target.toInt(),
description: description,
taskTeam: selectedTeam,
taskTeam: selectedTeam.map((e) => e.id).toList(), // pass IDs
assignmentDate: widget.assignmentDate,
organizationId: selectedOrganization?.id,
serviceId: selectedService?.id,

View File

@ -15,6 +15,7 @@ class DirectoryFilterBottomSheet extends StatefulWidget {
class _DirectoryFilterBottomSheetState
extends State<DirectoryFilterBottomSheet> {
final DirectoryController controller = Get.find<DirectoryController>();
final _categorySearchQuery = ''.obs;
final _bucketSearchQuery = ''.obs;
@ -59,84 +60,100 @@ class _DirectoryFilterBottomSheetState
Get.back();
},
onCancel: Get.back,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Obx(() {
final hasSelections = _tempSelectedCategories.isNotEmpty ||
_tempSelectedBuckets.isNotEmpty;
if (!hasSelections) return const SizedBox.shrink();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
child: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 16, left: 4, right: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Obx(() {
final hasSelections = _tempSelectedCategories.isNotEmpty ||
_tempSelectedBuckets.isNotEmpty;
if (!hasSelections) return const SizedBox.shrink();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MyText("Selected Filters:", fontWeight: 600),
const SizedBox(height: 4),
_buildChips(_tempSelectedCategories,
controller.contactCategories, _toggleCategory),
_buildChips(_tempSelectedBuckets,
controller.contactBuckets, _toggleBucket),
const SizedBox(height: 10),
],
);
}),
// RESET BUTTON
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
MyText("Selected Filters:", fontWeight: 600),
const SizedBox(height: 4),
_buildChips(_tempSelectedCategories,
controller.contactCategories, _toggleCategory),
_buildChips(_tempSelectedBuckets, controller.contactBuckets,
_toggleBucket),
],
);
}),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton.icon(
onPressed: _resetFilters,
icon: const Icon(Icons.restart_alt, size: 18),
label: MyText("Reset All", color: Colors.red),
style: TextButton.styleFrom(
foregroundColor: Colors.red.shade400,
TextButton.icon(
onPressed: _resetFilters,
icon: const Icon(Icons.restart_alt, size: 18),
label: MyText("Reset All", color: Colors.red),
),
),
],
),
if (controller.contactCategories.isNotEmpty)
Obx(() => _buildExpandableFilterSection(
title: "Categories",
expanded: _categoryExpanded,
searchQuery: _categorySearchQuery,
allItems: controller.contactCategories,
selectedItems: _tempSelectedCategories,
onToggle: _toggleCategory,
)),
if (controller.contactBuckets.isNotEmpty)
Obx(() => _buildExpandableFilterSection(
title: "Buckets",
expanded: _bucketExpanded,
searchQuery: _bucketSearchQuery,
allItems: controller.contactBuckets,
selectedItems: _tempSelectedBuckets,
onToggle: _toggleBucket,
)),
],
),
),
],
),
// CATEGORIES
if (controller.contactCategories.isNotEmpty)
Obx(() => _buildExpandableFilterSection(
title: "Categories",
expanded: _categoryExpanded,
searchQuery: _categorySearchQuery,
allItems: controller.contactCategories,
selectedItems: _tempSelectedCategories,
onToggle: _toggleCategory,
)),
// BUCKETS
if (controller.contactBuckets.isNotEmpty)
Obx(() => _buildExpandableFilterSection(
title: "Buckets",
expanded: _bucketExpanded,
searchQuery: _bucketSearchQuery,
allItems: controller.contactBuckets,
selectedItems: _tempSelectedBuckets,
onToggle: _toggleBucket,
)),
const SizedBox(height: 20),
],
),
);
},
),
);
}
// ------------------------------
// CHIP UI FOR SELECTED FILTERS
// ------------------------------
Widget _buildChips(RxList<String> selectedIds, List<dynamic> allItems,
Function(String) onRemoved) {
final idToName = {for (var item in allItems) item.id: item.name};
return Wrap(
spacing: 4,
runSpacing: 4,
children: selectedIds
.map((id) => Chip(
label: MyText(idToName[id] ?? "", color: Colors.black87),
deleteIcon: const Icon(Icons.close, size: 16),
onDeleted: () => onRemoved(id),
backgroundColor: Colors.blue.shade50,
))
.toList(),
children: selectedIds.map((id) {
return Chip(
label: MyText(idToName[id] ?? "", color: Colors.black87),
deleteIcon: const Icon(Icons.close, size: 16),
onDeleted: () => onRemoved(id),
backgroundColor: Colors.blue.shade50,
);
}).toList(),
);
}
// ------------------------------
// EXPANDABLE FILTER UI
// ------------------------------
Widget _buildExpandableFilterSection({
required String title,
required RxBool expanded,
@ -146,7 +163,7 @@ class _DirectoryFilterBottomSheetState
required Function(String) onToggle,
}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(
children: [
GestureDetector(
@ -159,28 +176,27 @@ class _DirectoryFilterBottomSheetState
: Icons.keyboard_arrow_right,
size: 20,
),
const SizedBox(width: 4),
MyText(
"$title",
fontWeight: 600,
fontSize: 16,
),
const SizedBox(width: 6),
MyText(title, fontWeight: 600, fontSize: 16),
],
),
),
if (expanded.value)
_buildFilterSection(
title: title,
searchQuery: searchQuery,
allItems: allItems,
selectedItems: selectedItems,
onToggle: onToggle,
title: title,
),
],
),
);
}
// ------------------------------
// FILTER LIST + SEARCH
// ------------------------------
Widget _buildFilterSection({
required String title,
required RxString searchQuery,
@ -189,14 +205,16 @@ class _DirectoryFilterBottomSheetState
required Function(String) onToggle,
}) {
final filteredList = allItems.where((item) {
if (searchQuery.isEmpty) return true;
if (searchQuery.value.isEmpty) return true;
return item.name.toLowerCase().contains(searchQuery.value.toLowerCase());
}).toList();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 6),
const SizedBox(height: 8),
// SEARCH BOX
TextField(
onChanged: (value) => searchQuery.value = value,
style: const TextStyle(fontSize: 13),
@ -215,7 +233,10 @@ class _DirectoryFilterBottomSheetState
fillColor: Colors.grey.shade100,
),
),
const SizedBox(height: 8),
// NO RESULTS
if (filteredList.isEmpty)
Row(
children: [
@ -227,7 +248,7 @@ class _DirectoryFilterBottomSheetState
)
else
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 230),
constraints: const BoxConstraints(maxHeight: 260),
child: ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
@ -238,7 +259,7 @@ class _DirectoryFilterBottomSheetState
return Obx(() {
final isSelected = selectedItems.contains(item.id);
return GestureDetector(
return InkWell(
onTap: () => onToggle(item.id),
child: Container(
padding: const EdgeInsets.symmetric(
@ -271,7 +292,7 @@ class _DirectoryFilterBottomSheetState
});
},
),
)
),
],
);
}

View File

@ -9,6 +9,7 @@ import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/model/directory/contact_bucket_list_model.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';
class EditBucketBottomSheet {
static void show(
@ -21,10 +22,8 @@ class EditBucketBottomSheet {
final nameController = TextEditingController(text: bucket.name);
final descController = TextEditingController(text: bucket.description);
final searchController = TextEditingController();
final selectedIds = RxSet<String>({...bucket.employeeIds});
final searchText = ''.obs;
InputDecoration _inputDecoration(String label) {
return InputDecoration(
@ -84,6 +83,15 @@ class EditBucketBottomSheet {
}
}
Future<void> _handleSubmitBottomSheet(BuildContext sheetContext) async {
await _handleSubmit();
// close bottom sheet safely
if (Navigator.of(sheetContext).canPop()) {
Navigator.of(sheetContext).pop();
}
}
Widget _formContent() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@ -101,117 +109,72 @@ class EditBucketBottomSheet {
MySpacing.height(20),
MyText.labelLarge('Shared With', fontWeight: 600),
MySpacing.height(8),
Obx(() => TextField(
controller: searchController,
onChanged: (value) => searchText.value = value.toLowerCase(),
decoration: InputDecoration(
hintText: 'Search employee...',
prefixIcon: const Icon(Icons.search, size: 20),
suffixIcon: searchText.value.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear, size: 18),
onPressed: () {
searchController.clear();
searchText.value = '';
},
)
: null,
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
filled: true,
fillColor: Colors.grey.shade100,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(color: Colors.grey.shade300),
),
),
)),
MySpacing.height(8),
Obx(() {
final filtered = allEmployees.where((emp) {
final fullName = '${emp.firstName} ${emp.lastName}'.toLowerCase();
return fullName.contains(searchText.value);
}).toList();
if (selectedIds.isEmpty) return const SizedBox.shrink();
return SizedBox(
height: 180,
child: ListView.separated(
itemCount: filtered.length,
separatorBuilder: (_, __) => const SizedBox(height: 2),
itemBuilder: (context, index) {
final emp = filtered[index];
final fullName = '${emp.firstName} ${emp.lastName}'.trim();
final selectedEmployees =
allEmployees.where((e) => selectedIds.contains(e.id)).toList();
return Obx(() => Theme(
data: Theme.of(context).copyWith(
unselectedWidgetColor: Colors.grey.shade500,
checkboxTheme: CheckboxThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
side: const BorderSide(color: Colors.grey),
fillColor:
MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.selected)) {
return Colors.blueAccent;
}
return Colors.white;
}),
checkColor: MaterialStateProperty.all(Colors.white),
),
),
child: CheckboxListTile(
dense: true,
contentPadding: EdgeInsets.zero,
visualDensity: const VisualDensity(vertical: -4),
controlAffinity: ListTileControlAffinity.leading,
value: selectedIds.contains(emp.id),
onChanged: emp.id == ownerId
? null
: (val) {
if (val == true) {
selectedIds.add(emp.id);
} else {
selectedIds.remove(emp.id);
}
},
title: Row(
children: [
Expanded(
child: MyText.bodyMedium(
fullName.isNotEmpty ? fullName : 'Unnamed',
fontWeight: 600,
),
),
if (emp.id == ownerId)
Container(
margin: const EdgeInsets.only(left: 6),
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.red.shade50,
borderRadius: BorderRadius.circular(4),
),
child: MyText.labelSmall(
"Owner",
fontWeight: 600,
color: Colors.red,
),
),
],
),
subtitle: emp.jobRole.isNotEmpty
? MyText.bodySmall(
emp.jobRole,
color: Colors.grey.shade600,
)
: null,
),
));
},
),
return Wrap(
spacing: 8,
children: selectedEmployees.map((emp) {
final fullName = '${emp.firstName} ${emp.lastName}'.trim();
return Chip(
label: Text(fullName),
onDeleted: emp.id == ownerId
? null
: () => selectedIds.remove(emp.id),
);
}).toList(),
);
}),
MySpacing.height(8),
// --- Open new EmployeeSelectionBottomSheet ---
GestureDetector(
onTap: () async {
final initiallySelected = allEmployees
.where((e) => selectedIds.contains(e.id))
.toList();
final result = await showModalBottomSheet<List<EmployeeModel>>(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(22)),
),
builder: (_) => EmployeeSelectionBottomSheet(
initiallySelected: initiallySelected,
multipleSelection: true,
title: "Shared With",
),
);
if (result != null) {
selectedIds
..clear()
..addAll(result.map((e) => e.id));
}
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey.shade300),
),
child: Row(
children: const [
Icon(Icons.search, color: Colors.grey),
SizedBox(width: 8),
Expanded(child: Text("Search & Select Employees")),
],
),
),
),
MySpacing.height(8),
const SizedBox.shrink(),
],
);
}
@ -224,7 +187,7 @@ class EditBucketBottomSheet {
return BaseBottomSheet(
title: "Edit Bucket",
onCancel: () => Navigator.pop(context),
onSubmit: _handleSubmit,
onSubmit: () => _handleSubmitBottomSheet(context),
child: _formContent(),
);
},

View File

@ -72,7 +72,7 @@ class EmployeeModel {
};
}
/// Add equality based on unique `id`
///Equality based on unique `id` required for multi-selection to work
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;

View File

@ -1,3 +1,4 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.dart';
@ -24,33 +25,72 @@ class EmployeeSelectionBottomSheet extends StatefulWidget {
class _EmployeeSelectionBottomSheetState
extends State<EmployeeSelectionBottomSheet> {
final TextEditingController _searchController = TextEditingController();
final RxBool _isSearching = false.obs;
final RxList<EmployeeModel> _searchResults = <EmployeeModel>[].obs;
final RxList<EmployeeModel> _allResults = <EmployeeModel>[].obs;
late RxList<EmployeeModel> _selectedEmployees;
Timer? _debounce;
@override
void initState() {
super.initState();
_selectedEmployees = RxList<EmployeeModel>.from(widget.initiallySelected);
_searchEmployees('');
_performSearch('');
}
@override
void dispose() {
_debounce?.cancel();
_searchController.dispose();
super.dispose();
}
Future<void> _searchEmployees(String query) async {
// ------------------------------------------------------
// 🔥 Optimized debounce-based search
// ------------------------------------------------------
void _onSearchChanged(String query) {
_debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 300), () {
_performSearch(query.trim());
});
}
Future<void> _performSearch(String query) async {
_isSearching.value = true;
final data = await ApiService.searchEmployeesBasic(searchString: query);
final results = (data as List)
.map((e) => EmployeeModel.fromJson(e as Map<String, dynamic>))
.toList();
_searchResults.assignAll(results);
// ------------------------------------------------------
// Auto-move selected employees to top
// ------------------------------------------------------
results.sort((a, b) {
if (widget.multipleSelection) {
// Only move selected employees to top in multi-select
final aSel = _selectedEmployees.contains(a) ? 0 : 1;
final bSel = _selectedEmployees.contains(b) ? 0 : 1;
if (aSel != bSel) return aSel.compareTo(bSel);
}
// Otherwise, keep original order (or alphabetically if needed)
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
_allResults.assignAll(results);
_isSearching.value = false;
}
// ------------------------------------------------------
// Handle tap & checkbox
// ------------------------------------------------------
void _toggleEmployee(EmployeeModel emp) {
if (widget.multipleSelection) {
if (_selectedEmployees.contains(emp)) {
@ -61,9 +101,14 @@ class _EmployeeSelectionBottomSheetState
} else {
_selectedEmployees.assignAll([emp]);
}
_selectedEmployees.refresh(); // important for Obx rebuild
// Re-sort list after each toggle
_performSearch(_searchController.text.trim());
}
// ------------------------------------------------------
// Submit selection
// ------------------------------------------------------
void _handleSubmit() {
if (widget.multipleSelection) {
Navigator.of(context).pop(_selectedEmployees.toList());
@ -73,11 +118,14 @@ class _EmployeeSelectionBottomSheetState
}
}
// ------------------------------------------------------
// Search bar widget
// ------------------------------------------------------
Widget _searchBar() => Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: TextField(
controller: _searchController,
onChanged: _searchEmployees,
onChanged: _onSearchChanged,
decoration: InputDecoration(
hintText: 'Search employees...',
filled: true,
@ -88,7 +136,7 @@ class _EmployeeSelectionBottomSheetState
icon: const Icon(Icons.close, color: Colors.grey),
onPressed: () {
_searchController.clear();
_searchEmployees('');
_performSearch('');
},
)
: null,
@ -102,60 +150,64 @@ class _EmployeeSelectionBottomSheetState
),
);
// ------------------------------------------------------
// Employee list (optimized)
// ------------------------------------------------------
Widget _employeeList() => Expanded(
child: Obx(() {
if (_isSearching.value) {
return const Center(child: CircularProgressIndicator());
}
if (_searchResults.isEmpty) {
return const Center(child: Text("No employees found"));
}
final results = _allResults;
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 4),
itemCount: _searchResults.length,
itemCount: results.length,
itemBuilder: (context, index) {
final emp = _searchResults[index];
final emp = results[index];
final isSelected = _selectedEmployees.contains(emp);
return Obx(() {
final isSelected = _selectedEmployees.contains(emp);
return ListTile(
leading: CircleAvatar(
backgroundColor: Colors.blueAccent,
child: Text(
(emp.firstName.isNotEmpty ? emp.firstName[0] : 'U')
.toUpperCase(),
style: const TextStyle(color: Colors.white),
),
Widget trailingWidget;
if (widget.multipleSelection) {
// Multiple selection normal checkbox
trailingWidget = Checkbox(
value: isSelected,
onChanged: (_) => _toggleEmployee(emp),
fillColor: MaterialStateProperty.resolveWith<Color>(
(states) => states.contains(MaterialState.selected)
? Colors.blueAccent
: Colors.white,
),
title: Text('${emp.firstName} ${emp.lastName}'),
subtitle: Text(emp.email),
trailing: Checkbox(
value: isSelected,
onChanged: (_) {
FocusScope.of(context).unfocus(); // hide keyboard
_toggleEmployee(emp);
},
fillColor: MaterialStateProperty.resolveWith<Color>(
(states) => states.contains(MaterialState.selected)
? Colors.blueAccent
: Colors.white,
),
),
onTap: () {
FocusScope.of(context).unfocus();
_toggleEmployee(emp);
},
contentPadding:
const EdgeInsets.symmetric(horizontal: 0, vertical: 4),
);
});
} else {
// Single selection check circle
trailingWidget = isSelected
? const Icon(Icons.check_circle, color: Colors.blueAccent)
: const Icon(Icons.circle_outlined, color: Colors.grey);
}
return ListTile(
leading: CircleAvatar(
backgroundColor: Colors.blueAccent,
child: Text(
(emp.firstName.isNotEmpty ? emp.firstName[0] : 'U')
.toUpperCase(),
style: const TextStyle(color: Colors.white),
),
),
title: Text('${emp.firstName} ${emp.lastName}'),
subtitle: Text(emp.email),
trailing: trailingWidget,
onTap: () => _toggleEmployee(emp),
contentPadding:
const EdgeInsets.symmetric(horizontal: 0, vertical: 4),
);
},
);
}),
);
// ------------------------------------------------------
// Build bottom sheet
// ------------------------------------------------------
@override
Widget build(BuildContext context) {
return BaseBottomSheet(
@ -164,10 +216,12 @@ class _EmployeeSelectionBottomSheetState
onSubmit: _handleSubmit,
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.7,
child: Column(children: [
_searchBar(),
_employeeList(),
]),
child: Column(
children: [
_searchBar(),
_employeeList(),
],
),
),
);
}

View File

@ -0,0 +1,218 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.dart';
import 'package:on_field_work/helpers/widgets/my_custom_skeleton.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/controller/task_Planning/daily_task_Planning_controller.dart';
class MultipleSelectRoleBottomSheet extends StatefulWidget {
final String title;
final bool multipleSelection;
final String projectId;
final String? serviceId;
final String? organizationId;
final String? roleId;
final ScrollController? scrollController;
final List<EmployeeModel> initiallySelected;
const MultipleSelectRoleBottomSheet({
super.key,
this.title = "Select Employees",
this.multipleSelection = true,
required this.projectId,
this.serviceId,
this.organizationId,
this.roleId,
this.initiallySelected = const [],
this.scrollController,
});
@override
State<MultipleSelectRoleBottomSheet> createState() =>
_MultipleSelectRoleBottomSheetState();
}
class _MultipleSelectRoleBottomSheetState
extends State<MultipleSelectRoleBottomSheet> {
final RxList<EmployeeModel> _employees = <EmployeeModel>[].obs;
final RxList<EmployeeModel> _filtered = <EmployeeModel>[].obs;
final RxBool _isLoading = true.obs;
late RxList<EmployeeModel> _selected;
final TextEditingController _searchController = TextEditingController();
late DailyTaskPlanningController controller;
@override
void initState() {
super.initState();
_selected = widget.initiallySelected.obs;
controller = Get.find<DailyTaskPlanningController>();
_fetchEmployeesFiltered();
}
Future<void> _fetchEmployeesFiltered() async {
_isLoading.value = true;
try {
List<EmployeeModel> employees = controller.employees.toList();
if (widget.roleId != null && widget.roleId!.isNotEmpty) {
employees =
employees.where((emp) => emp.jobRoleID == widget.roleId).toList();
}
employees.sort((a, b) {
final aSel = _selected.any((e) => e.id == a.id) ? 0 : 1;
final bSel = _selected.any((e) => e.id == b.id) ? 0 : 1;
return aSel != bSel
? aSel.compareTo(bSel)
: a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
_employees.assignAll(employees);
_filtered.assignAll(employees);
} catch (e) {
print("Error fetching employees: $e");
} finally {
_isLoading.value = false;
}
}
void _onSearch(String text) {
if (text.isEmpty) {
_filtered.assignAll(_employees);
} else {
_filtered.assignAll(
_employees.where((e) =>
e.name.toLowerCase().contains(text.toLowerCase()) ||
e.designation.toLowerCase().contains(text.toLowerCase())),
);
}
_filtered.sort((a, b) {
final aSel = _selected.any((e) => e.id == a.id) ? 0 : 1;
final bSel = _selected.any((e) => e.id == b.id) ? 0 : 1;
return aSel != bSel
? aSel.compareTo(bSel)
: a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
}
void _onTap(EmployeeModel emp) {
if (widget.multipleSelection) {
if (_selected.any((e) => e.id == emp.id)) {
_selected.removeWhere((e) => e.id == emp.id);
} else {
_selected.add(emp);
}
} else {
// Single selection return immediately
Get.back(result: [emp]);
}
_onSearch(_searchController.text.trim());
}
bool _isSelected(EmployeeModel emp) {
return _selected.any((e) => e.id == emp.id);
}
Widget _searchBar() => Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: TextField(
controller: _searchController,
onChanged: _onSearch,
decoration: InputDecoration(
hintText: 'Search employees...',
filled: true,
fillColor: Colors.grey.shade100,
prefixIcon: const Icon(Icons.search, color: Colors.grey),
suffixIcon: _searchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.close, color: Colors.grey),
onPressed: () {
_searchController.clear();
_onSearch('');
},
)
: null,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: BorderSide.none,
),
),
),
);
@override
Widget build(BuildContext context) {
return BaseBottomSheet(
title: widget.title,
onCancel: () => Get.back(),
onSubmit: () => Get.back(result: _selected.toList()), // Return plain list
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.55,
child: Column(
children: [
_searchBar(),
Expanded(
child: Obx(() {
if (_isLoading.value) {
return SkeletonLoaders.employeeSkeletonCard();
}
if (_filtered.isEmpty) {
return const Center(child: Text("No employees found"));
}
return ListView.builder(
controller: widget.scrollController,
padding: const EdgeInsets.only(bottom: 20),
itemCount: _filtered.length,
itemBuilder: (_, index) {
final emp = _filtered[index];
final isSelected = _isSelected(emp);
return ListTile(
onTap: () => _onTap(emp),
leading: CircleAvatar(
backgroundColor: Colors.blueAccent,
child: Text(
emp.name.isNotEmpty ? emp.name[0].toUpperCase() : "?",
style: const TextStyle(color: Colors.white),
),
),
title: Text(emp.name),
subtitle: Text(emp.designation),
trailing: Checkbox(
value: isSelected,
onChanged: (_) => _onTap(emp),
fillColor:
MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.selected)) {
return Colors.blueAccent;
}
return Colors.white;
}),
checkColor: Colors.white,
side: const BorderSide(color: Colors.grey),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 6,
),
);
},
);
}),
),
],
),
),
);
}
}

View File

@ -5,13 +5,15 @@ import 'package:on_field_work/controller/expense/add_expense_controller.dart';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';
import 'package:on_field_work/model/expense/expense_type_model.dart';
import 'package:on_field_work/model/expense/payment_types_model.dart';
import 'package:on_field_work/model/expense/employee_selector_bottom_sheet.dart';
// import 'package:on_field_work/model/expense/employee_selector_bottom_sheet.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.dart';
import 'package:on_field_work/helpers/utils/validators.dart';
import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/helpers/widgets/my_confirmation_dialog.dart';
import 'package:on_field_work/helpers/widgets/expense/expense_form_widgets.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';
/// Show bottom sheet wrapper
Future<T?> showAddExpenseBottomSheet<T>({
@ -52,24 +54,36 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet>
/// Show employee list
Future<void> _showEmployeeList() async {
await showModalBottomSheet(
final result = await showModalBottomSheet<dynamic>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (_) => ReusableEmployeeSelectorBottomSheet(
searchController: controller.employeeSearchController,
searchResults: controller.employeeSearchResults,
isSearching: controller.isSearchingEmployees,
onSearch: controller.searchEmployees,
onSelect: (emp) => controller.selectedPaidBy.value = emp,
builder: (_) => EmployeeSelectionBottomSheet(
initiallySelected: controller.selectedPaidBy.value != null
? [controller.selectedPaidBy.value!]
: [],
multipleSelection: false,
title: "Select Paid By",
),
);
controller.employeeSearchController.clear();
controller.employeeSearchResults.clear();
if (result == null) return;
// result will be EmployeeModel or [EmployeeModel]
if (result is EmployeeModel) {
controller.setSelectedPaidBy(result);
} else if (result is List && result.isNotEmpty) {
controller.setSelectedPaidBy(result.first as EmployeeModel);
}
// cleanup
try {
controller.employeeSearchController.clear();
controller.employeeSearchResults.clear();
} catch (_) {}
}
/// Generic option list
@ -343,23 +357,26 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet>
const SectionTitle(
icon: Icons.person_outline, title: "Paid By", requiredField: true),
MySpacing.height(6),
// Main tile: tap to choose mode + selection sheet
GestureDetector(
onTap: _showEmployeeList,
child: TileContainer(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
controller.selectedPaidBy.value == null
? "Select Paid By"
: '${controller.selectedPaidBy.value?.firstName ?? ''} ${controller.selectedPaidBy.value?.lastName ?? ''}',
style: const TextStyle(fontSize: 14),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
controller.selectedPaidBy.value?.name ?? "Select Paid By",
style: TextStyle(fontSize: 15),
overflow: TextOverflow.ellipsis,
),
const Icon(Icons.arrow_drop_down, size: 22),
],
),
),
),
Icon(Icons.arrow_drop_down, size: 22),
],
)),
),
// small helper: long-press to quickly open multi-select directly (optional)
const SizedBox(height: 6),
],
);
}

View File

@ -9,6 +9,8 @@ import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/helpers/widgets/expense/expense_form_widgets.dart';
import 'package:on_field_work/helpers/widgets/my_confirmation_dialog.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
Future<T?> showPaymentRequestBottomSheet<T>({
bool isEdit = false,
@ -58,12 +60,10 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
if (widget.isEdit && widget.existingData != null) {
final data = widget.existingData!;
// Prefill text fields
controller.titleController.text = data["title"] ?? "";
controller.amountController.text = data["amount"]?.toString() ?? "";
controller.descriptionController.text = data["description"] ?? "";
// Prefill due date
if (data["dueDate"] != null && data["dueDate"].toString().isNotEmpty) {
DateTime? dueDate = DateTime.tryParse(data["dueDate"].toString());
if (dueDate != null) {
@ -73,15 +73,15 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
}
}
// Prefill dropdowns & toggles
controller.selectedProject.value = {
'id': data["projectId"],
'name': data["projectName"],
};
controller.selectedPayee.value = data["payee"] ?? "";
controller.isAdvancePayment.value = data["isAdvancePayment"] ?? false;
// Categories & currencies
// When categories and currencies load, set selected ones
everAll([controller.categories, controller.currencies], (_) {
controller.selectedCategory.value = controller.categories
.firstWhereOrNull((c) => c.id == data["expenseCategoryId"]);
@ -89,7 +89,6 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
.firstWhereOrNull((c) => c.id == data["currencyId"]);
});
// Attachments
final attachmentsData = data["attachments"];
if (attachmentsData != null &&
attachmentsData is List &&
@ -116,21 +115,21 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
@override
Widget build(BuildContext context) {
return Obx(() => Form(
return Obx(
() => SafeArea(
child: Form(
key: _formKey,
child: BaseBottomSheet(
title: widget.isEdit
? "Edit Payment Request"
: "Create Payment Request",
title: widget.isEdit ? "Edit Payment Request" : "Create Payment Request",
isSubmitting: controller.isSubmitting.value,
onCancel: Get.back,
submitText: "Save as Draft",
onSubmit: () async {
if (_formKey.currentState!.validate() && _validateSelections()) {
bool success = false;
if (widget.isEdit && widget.existingData != null) {
final requestId =
widget.existingData!['id']?.toString() ?? '';
final requestId = widget.existingData!['id']?.toString() ?? '';
if (requestId.isNotEmpty) {
success = await controller.submitEditedPaymentRequest(
requestId: requestId);
@ -144,7 +143,7 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
if (success) {
Get.back();
if (widget.onUpdated != null) widget.onUpdated!();
widget.onUpdated?.call();
showAppSnackbar(
title: "Success",
@ -157,31 +156,33 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
}
},
child: SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildDropdown(
"Select Project",
Icons.work_outline,
controller.selectedProject.value?['name'] ??
"Select Project",
controller.globalProjects,
(p) => p['name'],
controller.selectProject,
key: _projectDropdownKey),
"Select Project",
Icons.work_outline,
controller.selectedProject.value?['name'] ?? "Select Project",
controller.globalProjects,
(p) => p['name'],
controller.selectProject,
key: _projectDropdownKey,
),
_gap(),
_buildDropdown(
"Expense Category",
Icons.category_outlined,
controller.selectedCategory.value?.name ??
"Select Category",
controller.categories,
(c) => c.name,
controller.selectCategory,
key: _categoryDropdownKey),
"Expense Category",
Icons.category_outlined,
controller.selectedCategory.value?.name ?? "Select Category",
controller.categories,
(c) => c.name,
controller.selectCategory,
key: _categoryDropdownKey,
),
_gap(),
_buildTextField(
"Title", Icons.title_outlined, controller.titleController,
_buildTextField("Title", Icons.title_outlined,
controller.titleController,
hint: "Enter title", validator: Validators.requiredField),
_gap(),
_buildRadio("Is Advance Payment", Icons.attach_money_outlined,
@ -199,17 +200,17 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
? null
: "Enter valid amount"),
_gap(),
_buildPayeeAutocompleteField(),
_buildPayeeField(),
_gap(),
_buildDropdown(
"Currency",
Icons.monetization_on_outlined,
controller.selectedCurrency.value?.currencyName ??
"Select Currency",
controller.currencies,
(c) => c.currencyName,
controller.selectCurrency,
key: _currencyDropdownKey),
"Currency",
Icons.monetization_on_outlined,
controller.selectedCurrency.value?.currencyName ?? "Select Currency",
controller.currencies,
(c) => c.currencyName,
controller.selectCurrency,
key: _currencyDropdownKey,
),
_gap(),
_buildTextField("Description", Icons.description_outlined,
controller.descriptionController,
@ -218,11 +219,14 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
validator: Validators.requiredField),
_gap(),
_buildAttachmentsSection(),
MySpacing.height(30),
],
),
),
),
));
),
),
);
}
Widget _buildDropdown<T>(String title, IconData icon, String value,
@ -234,9 +238,10 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
SectionTitle(icon: icon, title: title, requiredField: true),
MySpacing.height(6),
DropdownTile(
key: key,
title: value,
onTap: () => _showOptionList(options, getLabel, onSelected, key)),
key: key,
title: value,
onTap: () => _showOptionList(options, getLabel, onSelected, key),
),
],
);
}
@ -265,7 +270,7 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
}
Widget _buildRadio(
String title, IconData icon, RxBool controller, List<String> labels) {
String title, IconData icon, RxBool controllerBool, List<String> labels) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@ -284,15 +289,16 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
final i = entry.key;
final label = entry.value;
final value = i == 0;
return Expanded(
child: RadioListTile<bool>(
contentPadding: EdgeInsets.zero,
title: Text(label),
value: value,
groupValue: controller.value,
groupValue: controllerBool.value,
activeColor: contentTheme.primary,
onChanged: (val) =>
val != null ? controller.value = val : null,
val != null ? controllerBool.value = val : null,
),
);
}).toList(),
@ -306,9 +312,7 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SectionTitle(
icon: Icons.calendar_today,
title: "Due To Date",
requiredField: true),
icon: Icons.calendar_today, title: "Due To Date", requiredField: true),
MySpacing.height(6),
GestureDetector(
onTap: () => controller.pickDueDate(context),
@ -336,75 +340,35 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
);
}
Widget _buildPayeeAutocompleteField() {
Widget _buildPayeeField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(
icon: Icons.person_outline, title: "Payee", requiredField: true),
const SizedBox(height: 6),
Autocomplete<String>(
optionsBuilder: (textEditingValue) {
final query = textEditingValue.text.toLowerCase();
return query.isEmpty
? const Iterable<String>.empty()
: controller.payees
.where((p) => p.toLowerCase().contains(query));
},
displayStringForOption: (option) => option,
fieldViewBuilder:
(context, fieldController, focusNode, onFieldSubmitted) {
// Avoid updating during build
WidgetsBinding.instance.addPostFrameCallback((_) {
if (fieldController.text != controller.selectedPayee.value) {
fieldController.text = controller.selectedPayee.value;
fieldController.selection = TextSelection.fromPosition(
TextPosition(offset: fieldController.text.length));
}
});
return TextFormField(
controller: fieldController,
focusNode: focusNode,
decoration: InputDecoration(
hintText: "Type or select payee",
filled: true,
fillColor: Colors.grey.shade100,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.grey.shade300),
const SectionTitle(
icon: Icons.person_outline,
title: "Payee",
requiredField: true,
),
MySpacing.height(6),
GestureDetector(
onTap: _showPayeeSelector,
child: TileContainer(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Obx(() => Text(
controller.selectedPayee.value?.name ?? "Select Payee",
style: const TextStyle(fontSize: 15),
overflow: TextOverflow.ellipsis,
)),
),
),
validator: (v) =>
v == null || v.trim().isEmpty ? "Please enter payee" : null,
onChanged: (val) => controller.selectedPayee.value = val,
);
},
onSelected: (selection) => controller.selectedPayee.value = selection,
optionsViewBuilder: (context, onSelected, options) => Material(
color: Colors.white,
elevation: 4,
borderRadius: BorderRadius.circular(8),
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 200, minWidth: 300),
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: options.length,
itemBuilder: (_, index) => InkWell(
onTap: () => onSelected(options.elementAt(index)),
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 12),
child: Text(options.elementAt(index),
style: const TextStyle(fontSize: 14)),
),
),
),
const Icon(Icons.arrow_drop_down, size: 22),
],
),
),
),
const SizedBox(height: 6),
],
);
}
@ -492,8 +456,7 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
return;
}
final RenderBox button =
key.currentContext!.findRenderObject() as RenderBox;
final RenderBox button = key.currentContext!.findRenderObject() as RenderBox;
final RenderBox overlay =
Overlay.of(context).context.findRenderObject() as RenderBox;
final position = button.localToGlobal(Offset.zero, ancestor: overlay);
@ -507,8 +470,7 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
items: options
.map(
(opt) => PopupMenuItem<T>(value: opt, child: Text(getLabel(opt))))
.map((opt) => PopupMenuItem<T>(value: opt, child: Text(getLabel(opt))))
.toList(),
);
@ -523,7 +485,7 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
if (controller.selectedCategory.value == null) {
return _showError("Please select a category");
}
if (controller.selectedPayee.value.isEmpty) {
if (controller.selectedPayee.value == null) {
return _showError("Please select a payee");
}
if (controller.selectedCurrency.value == null) {
@ -532,6 +494,25 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
return true;
}
Future<void> _showPayeeSelector() async {
final result = await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => EmployeeSelectionBottomSheet(
title: "Select Payee",
multipleSelection: false,
initiallySelected: controller.selectedPayee.value != null
? [controller.selectedPayee.value!]
: [],
),
);
if (result is EmployeeModel) {
controller.selectedPayee.value = result;
}
}
bool _showError(String msg) {
showAppSnackbar(title: "Error", message: msg, type: SnackbarType.error);
return false;

View File

@ -8,7 +8,7 @@ import 'package:on_field_work/helpers/widgets/my_text_style.dart';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';
import 'package:on_field_work/helpers/widgets/date_range_picker.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/model/expense/employee_selector_for_filter_bottom_sheet.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';
class PaymentRequestFilterBottomSheet extends StatefulWidget {
final PaymentRequestController controller;
@ -441,9 +441,9 @@ class _PaymentRequestFilterBottomSheetState
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) => EmployeeSelectorBottomSheet(
selectedEmployees: selectedEmployees,
searchEmployees: (query) => searchEmployees(query, items),
builder: (context) => EmployeeSelectionBottomSheet(
initiallySelected: selectedEmployees.toList(),
multipleSelection: true,
title: title,
),
);

View File

@ -204,11 +204,37 @@ class _AddServiceProjectJobBottomSheetState
height: 48,
child: TextFormField(
controller: controller.tagCtrl,
textInputAction: TextInputAction.done,
onEditingComplete: () {
final raw = controller.tagCtrl.text.trim();
if (raw.isEmpty) return;
final parts = raw
.split(',')
.map((s) => s.trim())
.where((s) => s.isNotEmpty);
for (final p in parts) {
if (!controller.enteredTags.contains(p)) {
controller.enteredTags.add(p);
}
}
controller.tagCtrl.clear();
},
onFieldSubmitted: (v) {
final value = v.trim();
if (value.isNotEmpty &&
!controller.enteredTags.contains(value)) {
controller.enteredTags.add(value);
// also handle normal submit
final raw = v.trim();
if (raw.isEmpty) return;
final parts = raw
.split(',')
.map((s) => s.trim())
.where((s) => s.isNotEmpty);
for (final p in parts) {
if (!controller.enteredTags.contains(p)) {
controller.enteredTags.add(p);
}
}
controller.tagCtrl.clear();
},

View File

@ -99,34 +99,60 @@ class _DirectoryMainScreenState extends State<DirectoryMainScreen>
),
),
),
body: Column(
children: [
// ---------------- TabBar ----------------
Container(
color: Colors.white,
child: TabBar(
controller: _tabController,
labelColor: Colors.black,
unselectedLabelColor: Colors.grey,
indicatorColor: Colors.red,
tabs: const [
Tab(text: "Directory"),
Tab(text: "Notes"),
],
body: SafeArea(
child: Column(
children: [
// ---------------- TabBar ----------------
Container(
color: Colors.white,
child: TabBar(
controller: _tabController,
labelColor: Colors.black,
unselectedLabelColor: Colors.grey,
indicatorColor: Colors.red,
tabs: const [
Tab(text: "Directory"),
Tab(text: "Notes"),
],
),
),
),
// ---------------- TabBarView ----------------
Expanded(
child: TabBarView(
controller: _tabController,
children: [
DirectoryView(),
NotesView(),
],
// ---------------- TabBarView + Scroll / Landscape Support ----------------
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
final bool isLandscape =
constraints.maxWidth > constraints.maxHeight;
if (isLandscape) {
return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: SizedBox(
height: constraints.maxHeight * 1.3,
child: TabBarView(
controller: _tabController,
children: [
DirectoryView(),
NotesView(),
],
),
),
);
}
// Portrait
return TabBarView(
controller: _tabController,
children: [
DirectoryView(),
NotesView(),
],
);
},
),
),
),
],
],
),
),
);
}

View File

@ -48,116 +48,133 @@ class _AssignProjectBottomSheetState extends State<AssignProjectBottomSheet> {
onCancel: () => Navigator.pop(context),
onSubmit: _handleAssign,
submitText: "Assign",
child: Obx(() {
if (assignController.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
final projects = assignController.allProjects;
if (projects.isEmpty) {
return const Center(child: Text('No projects available.'));
}
/// 🔥 MAKE BODY SCROLLABLE (fix for landscape)
child: LayoutBuilder(
builder: (context, constraints) {
return Obx(() {
if (assignController.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MyText.bodySmall(
'Select the projects to assign this employee.',
color: Colors.grey[600],
),
MySpacing.height(8),
final projects = assignController.allProjects;
if (projects.isEmpty) {
return const Center(child: Text('No projects available.'));
}
// Select All
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Projects (${projects.length})',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
TextButton(
onPressed: () {
assignController.toggleSelectAll();
},
child: Obx(() {
return Text(
assignController.areAllSelected()
? 'Deselect All'
: 'Select All',
style: const TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.w600,
),
);
}),
),
],
),
// List of Projects
SizedBox(
height: 300,
child: ListView.builder(
controller: _scrollController,
itemCount: projects.length,
itemBuilder: (context, index) {
final GlobalProjectModel project = projects[index];
return Obx(() {
final bool isSelected =
assignController.isProjectSelected(
project.id.toString(),
);
return Theme(
data: Theme.of(context).copyWith(
checkboxTheme: CheckboxThemeData(
fillColor: WidgetStateProperty.resolveWith<Color>(
(states) => states.contains(WidgetState.selected)
? Colors.blueAccent
: Colors.white,
),
side: const BorderSide(
color: Colors.black,
width: 2,
),
checkColor:
WidgetStateProperty.all(Colors.white),
),
),
child: CheckboxListTile(
dense: true,
value: isSelected,
title: Text(
project.name,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14,
),
),
onChanged: (checked) {
assignController.toggleProjectSelection(
project.id.toString(),
checked ?? false,
);
},
activeColor: Colors.blueAccent,
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
);
});
},
return ConstrainedBox(
constraints: BoxConstraints(
/// 🔥 Always allow enough height for scroll
maxHeight: constraints.maxHeight,
),
),
],
);
}),
child: SingleChildScrollView(
controller: _scrollController,
padding: const EdgeInsets.only(bottom: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MyText.bodySmall(
'Select the projects to assign this employee.',
color: Colors.grey[600],
),
MySpacing.height(8),
// Header Row
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Projects (${projects.length})',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
TextButton(
onPressed: () {
assignController.toggleSelectAll();
},
child: Obx(() {
return Text(
assignController.areAllSelected()
? 'Deselect All'
: 'Select All',
style: const TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.w600,
),
);
}),
),
],
),
/// 🔥 List auto grows and scrolls no fixed height
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: projects.length,
itemBuilder: (context, index) {
final GlobalProjectModel project = projects[index];
return Obx(() {
final bool isSelected =
assignController.isProjectSelected(
project.id.toString(),
);
return Theme(
data: Theme.of(context).copyWith(
checkboxTheme: CheckboxThemeData(
fillColor:
WidgetStateProperty.resolveWith<Color>(
(states) =>
states.contains(WidgetState.selected)
? Colors.blueAccent
: Colors.white,
),
side: const BorderSide(
color: Colors.black,
width: 2,
),
checkColor:
WidgetStateProperty.all(Colors.white),
),
),
child: CheckboxListTile(
dense: true,
value: isSelected,
title: Text(
project.name,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14,
),
),
onChanged: (checked) {
assignController.toggleProjectSelection(
project.id.toString(),
checked ?? false,
);
},
activeColor: Colors.blueAccent,
controlAffinity:
ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
);
});
},
),
],
),
),
);
});
},
),
);
},
);

View File

@ -8,9 +8,10 @@ import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/helpers/widgets/my_text_style.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/model/expense/employee_selector_for_filter_bottom_sheet.dart';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';
import 'package:on_field_work/helpers/widgets/date_range_picker.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';
class ExpenseFilterBottomSheet extends StatefulWidget {
final ExpenseController expenseController;
@ -303,12 +304,13 @@ class _ExpenseFilterBottomSheetState extends State<ExpenseFilterBottomSheet>
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) => EmployeeSelectorBottomSheet(
selectedEmployees: selectedEmployees,
searchEmployees: searchEmployees,
builder: (context) => EmployeeSelectionBottomSheet(
initiallySelected: selectedEmployees.toList(),
multipleSelection: true,
title: title,
),
);
if (result != null) selectedEmployees.assignAll(result);
},
child: Container(

View File

@ -35,8 +35,8 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
}
});
controller.searchQuery.listen((q) {
if (_searchCtrl.text != q) _searchCtrl.text = q;
_searchCtrl.addListener(() {
controller.searchQuery.value = _searchCtrl.text.trim();
});
}
@ -49,39 +49,50 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(
0xFFF5F5F5),
backgroundColor: const Color(0xFFF5F5F5),
appBar: _buildAppBar(),
body: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: RefreshIndicator(
onRefresh: () async {
final emp = controller.selectedEmployee.value;
if (emp != null) {
await controller.fetchAdvancePayments(emp.id.toString());
}
},
color: Colors.white,
backgroundColor: contentTheme.primary,
strokeWidth: 2.5,
displacement: 60,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Container(
color:
const Color(0xFFF5F5F5),
child: Column(
children: [
_buildSearchBar(),
_buildEmployeeDropdown(context),
_buildTopBalance(),
_buildPaymentList(),
],
body: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final bool isLandscape =
constraints.maxWidth > constraints.maxHeight;
return RefreshIndicator(
onRefresh: () async {
final emp = controller.selectedEmployee.value;
if (emp != null) {
await controller.fetchAdvancePayments(emp.id.toString());
}
},
color: Colors.white,
backgroundColor: contentTheme.primary,
strokeWidth: 2.5,
displacement: 60,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
FocusScope.of(context).unfocus();
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Container(
width: double.infinity,
color: const Color(0xFFF5F5F5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildSearchBar(),
_buildEmployeeDropdown(context),
_buildTopBalance(),
_buildPaymentList(),
],
),
),
),
),
),
),
);
},
),
),
);
@ -162,7 +173,6 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
child: TextField(
controller: _searchCtrl,
focusNode: _searchFocus,
onChanged: (v) => controller.searchQuery.value = v.trim(),
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
@ -236,8 +246,11 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
return InkWell(
onTap: () {
controller.selectEmployee(e);
_searchCtrl.text = e.name;
controller.searchQuery.value = e.name;
_searchCtrl.selection =
TextSelection.fromPosition(TextPosition(offset: e.name.length));
FocusScope.of(context).unfocus();
SystemChannels.textInput.invokeMethod('TextInput.hide');
controller.employees.clear();
@ -322,7 +335,6 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
);
}
// No employee selected yet
if (controller.selectedEmployee.value == null) {
return const Padding(
padding: EdgeInsets.only(top: 100),
@ -330,7 +342,6 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
);
}
// Employee selected but no payments found
if (controller.payments.isEmpty) {
return const Padding(
padding: EdgeInsets.only(top: 100),
@ -340,7 +351,6 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
);
}
// Payments available
return ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
@ -355,29 +365,27 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
// ---------------- Payment Item ----------------
Widget _buildPaymentItem(dynamic item) {
final dateStr = (item.date ?? '').toString();
DateTime? parsedDate;
DateTime? parsed;
try {
parsedDate = DateTime.parse(dateStr);
parsed = DateTime.parse(dateStr);
} catch (_) {}
final formattedDate = parsedDate != null
? DateFormat('dd MMM yyyy').format(parsedDate)
final formattedDate = parsed != null
? DateFormat('dd MMM yyyy').format(parsed)
: (dateStr.isNotEmpty ? dateStr : '');
final formattedTime =
parsedDate != null ? DateFormat('hh:mm a').format(parsedDate) : '';
final project = item.name ?? '';
final desc = item.title ?? '';
final amount = (item.amount ?? 0).toDouble();
final isCredit = amount >= 0;
final accentColor = isCredit ? Colors.green.shade700 : Colors.red.shade700;
final accent = isCredit ? Colors.green.shade700 : Colors.red.shade700;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
color: Colors.grey[100],
border: Border(
border: const Border(
bottom: BorderSide(color: Color(0xFFE0E0E0), width: 0.9),
),
),
@ -389,25 +397,9 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
formattedDate,
style:
TextStyle(fontSize: 12, color: Colors.grey.shade600),
),
if (formattedTime.isNotEmpty) ...[
const SizedBox(width: 6),
Text(
formattedTime,
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade500,
fontStyle: FontStyle.italic),
),
]
],
),
Text(formattedDate,
style:
TextStyle(fontSize: 12, color: Colors.grey.shade600)),
const SizedBox(height: 4),
Text(
project.isNotEmpty ? project : 'No Project',
@ -422,10 +414,7 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
desc.isNotEmpty ? desc : 'No Details',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: Colors.grey.shade700,
),
style: TextStyle(fontSize: 13, color: Colors.grey.shade700),
),
],
),
@ -436,7 +425,7 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: accentColor,
color: accent,
),
),
],
@ -445,16 +434,16 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
}
// ---------------- Utilities ----------------
String _initials(String? firstName, [String? lastName]) {
if ((firstName?.isEmpty ?? true) && (lastName?.isEmpty ?? true)) return '?';
return ((firstName?.isNotEmpty == true ? firstName![0] : '') +
(lastName?.isNotEmpty == true ? lastName![0] : ''))
String _initials(String? first, [String? last]) {
if ((first?.isEmpty ?? true) && (last?.isEmpty ?? true)) return '?';
return ((first?.isNotEmpty == true ? first![0] : '') +
(last?.isNotEmpty == true ? last![0] : ''))
.toUpperCase();
}
String _formatAmount(num amount) {
final format = NumberFormat('#,##,###.##', 'en_IN');
return format.format(amount);
final f = NumberFormat('#,##,###.##', 'en_IN');
return f.format(amount);
}
static Color _avatarColorFor(String name) {
@ -467,7 +456,7 @@ class _AdvancePaymentScreenState extends State<AdvancePaymentScreen>
Colors.teal,
Colors.amber,
];
final hash = name.codeUnits.fold(0, (p, e) => p + e);
final hash = name.codeUnits.fold(0, (p, c) => p + c);
return colors[hash % colors.length];
}
}

View File

@ -113,171 +113,219 @@ class _FinanceScreenState extends State<FinanceScreen>
),
),
),
body: FadeTransition(
opacity: _fadeAnimation,
child: Obx(() {
if (menuController.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
body: SafeArea(
child: FadeTransition(
opacity: _fadeAnimation,
child: LayoutBuilder(
builder: (context, constraints) {
final bool isLandscape =
constraints.maxWidth > constraints.maxHeight;
if (menuController.hasError.value || menuController.menuItems.isEmpty) {
return const Center(
child: Text(
"Failed to load menus. Please try again later.",
style: TextStyle(color: Colors.red),
),
);
}
return Obx(() {
if (menuController.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
// Filter allowed Finance menus dynamically
final financeMenuIds = [
MenuItems.expenseReimbursement,
MenuItems.paymentRequests,
MenuItems.advancePaymentStatements,
];
if (menuController.hasError.value ||
menuController.menuItems.isEmpty) {
return const Center(
child: Text(
"Failed to load menus. Please try again later.",
style: TextStyle(color: Colors.red),
),
);
}
final financeMenus = menuController.menuItems
.where((m) => financeMenuIds.contains(m.id) && m.available)
.toList();
// Filter allowed Finance menus dynamically
final financeMenuIds = [
MenuItems.expenseReimbursement,
MenuItems.paymentRequests,
MenuItems.advancePaymentStatements,
];
if (financeMenus.isEmpty) {
return const Center(
child: Text(
"You dont have access to the Finance section.",
style: TextStyle(color: Colors.grey),
),
);
}
final financeMenus = menuController.menuItems
.where((m) => financeMenuIds.contains(m.id) && m.available)
.toList();
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildFinanceModulesCompact(financeMenus),
MySpacing.height(24),
ExpenseByStatusWidget(controller: dashboardController),
MySpacing.height(24),
ExpenseTypeReportChart(),
MySpacing.height(24),
MonthlyExpenseDashboardChart(),
],
),
);
}),
if (financeMenus.isEmpty) {
return const Center(
child: Text(
"You dont have access to the Finance section.",
style: TextStyle(color: Colors.grey),
),
);
}
// ---------------------- PORTRAIT MODE ----------------------
if (!isLandscape) {
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildFinanceModulesCompact(financeMenus),
MySpacing.height(24),
ExpenseByStatusWidget(controller: dashboardController),
MySpacing.height(24),
ExpenseTypeReportChart(),
MySpacing.height(24),
MonthlyExpenseDashboardChart(),
],
),
);
}
// ---------------------- LANDSCAPE MODE ----------------------
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildFinanceModulesCompact(financeMenus),
MySpacing.height(24),
// Wider charts behave better side-by-side or full width
SizedBox(
width: constraints.maxWidth,
child: ExpenseByStatusWidget(
controller: dashboardController),
),
MySpacing.height(24),
SizedBox(
width: constraints.maxWidth,
child: ExpenseTypeReportChart(),
),
MySpacing.height(24),
SizedBox(
width: constraints.maxWidth,
child: MonthlyExpenseDashboardChart(),
),
],
),
);
});
},
),
),
),
);
}
// --- Finance Modules (Compact Dashboard-style) ---
Widget _buildFinanceModulesCompact(List<MenuItem> financeMenus) {
// Map menu IDs to icon + color
final Map<String, _FinanceCardMeta> financeCardMeta = {
MenuItems.expenseReimbursement: _FinanceCardMeta(LucideIcons.badge_dollar_sign, contentTheme.info),
MenuItems.paymentRequests: _FinanceCardMeta(LucideIcons.receipt_text, contentTheme.primary),
MenuItems.advancePaymentStatements: _FinanceCardMeta(LucideIcons.wallet, contentTheme.warning),
};
Widget _buildFinanceModulesCompact(List<MenuItem> financeMenus) {
// Map menu IDs to icon + color
final Map<String, _FinanceCardMeta> financeCardMeta = {
MenuItems.expenseReimbursement:
_FinanceCardMeta(LucideIcons.badge_dollar_sign, contentTheme.info),
MenuItems.paymentRequests:
_FinanceCardMeta(LucideIcons.receipt_text, contentTheme.primary),
MenuItems.advancePaymentStatements:
_FinanceCardMeta(LucideIcons.wallet, contentTheme.warning),
};
// Build the stat items using API-provided mobileLink
final stats = financeMenus.map((menu) {
final meta = financeCardMeta[menu.id]!;
// Build the stat items using API-provided mobileLink
final stats = financeMenus.map((menu) {
final meta = financeCardMeta[menu.id]!;
// --- Log the routing info ---
debugPrint(
"[Finance Card] ID: ${menu.id}, Title: ${menu.name}, Route: ${menu.mobileLink}");
// --- Log the routing info ---
debugPrint(
"[Finance Card] ID: ${menu.id}, Title: ${menu.name}, Route: ${menu.mobileLink}");
return _FinanceStatItem(
meta.icon,
menu.name,
meta.color,
menu.mobileLink, // Each card navigates to its own route
);
}).toList();
return _FinanceStatItem(
meta.icon,
menu.name,
meta.color,
menu.mobileLink, // Each card navigates to its own route
);
}).toList();
final projectSelected = projectController.selectedProject != null;
final projectSelected = projectController.selectedProject != null;
return LayoutBuilder(builder: (context, constraints) {
// Determine number of columns dynamically
int crossAxisCount = (constraints.maxWidth ~/ 80).clamp(2, 4);
double cardWidth = (constraints.maxWidth - (crossAxisCount - 1) * 6) / crossAxisCount;
return LayoutBuilder(builder: (context, constraints) {
// Determine number of columns dynamically
int crossAxisCount = (constraints.maxWidth ~/ 80).clamp(2, 4);
double cardWidth =
(constraints.maxWidth - (crossAxisCount - 1) * 6) / crossAxisCount;
return Wrap(
spacing: 6,
runSpacing: 6,
alignment: WrapAlignment.end,
children: stats
.map((stat) => _buildFinanceModuleCard(stat, projectSelected, cardWidth))
.toList(),
);
});
}
return Wrap(
spacing: 6,
runSpacing: 6,
alignment: WrapAlignment.end,
children: stats
.map((stat) =>
_buildFinanceModuleCard(stat, projectSelected, cardWidth))
.toList(),
);
});
}
Widget _buildFinanceModuleCard(
_FinanceStatItem stat, bool isProjectSelected, double width) {
return Opacity(
opacity: isProjectSelected ? 1.0 : 0.4, // Dim if no project selected
child: IgnorePointer(
ignoring: !isProjectSelected,
child: InkWell(
onTap: () => _onCardTap(stat, isProjectSelected),
borderRadius: BorderRadius.circular(5),
child: MyCard.bordered(
width: width,
height: 60,
paddingAll: 4,
borderRadiusAll: 5,
border: Border.all(color: Colors.grey.withOpacity(0.15)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: stat.color.withOpacity(0.1),
borderRadius: BorderRadius.circular(4),
),
child: Icon(
stat.icon,
size: 16,
color: stat.color,
),
),
MySpacing.height(4),
Flexible(
child: Text(
stat.title,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 10,
overflow: TextOverflow.ellipsis,
Widget _buildFinanceModuleCard(
_FinanceStatItem stat, bool isProjectSelected, double width) {
return Opacity(
opacity: isProjectSelected ? 1.0 : 0.4, // Dim if no project selected
child: IgnorePointer(
ignoring: !isProjectSelected,
child: InkWell(
onTap: () => _onCardTap(stat, isProjectSelected),
borderRadius: BorderRadius.circular(5),
child: MyCard.bordered(
width: width,
height: 60,
paddingAll: 4,
borderRadiusAll: 5,
border: Border.all(color: Colors.grey.withOpacity(0.15)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: stat.color.withOpacity(0.1),
borderRadius: BorderRadius.circular(4),
),
child: Icon(
stat.icon,
size: 16,
color: stat.color,
),
maxLines: 2,
softWrap: true,
),
),
],
MySpacing.height(4),
Flexible(
child: Text(
stat.title,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 10,
overflow: TextOverflow.ellipsis,
),
maxLines: 2,
softWrap: true,
),
),
],
),
),
),
),
),
);
}
void _onCardTap(_FinanceStatItem statItem, bool isEnabled) {
if (!isEnabled) {
Get.defaultDialog(
title: "No Project Selected",
middleText: "Please select a project before accessing this section.",
confirm: ElevatedButton(
onPressed: () => Get.back(),
child: const Text("OK"),
),
);
} else {
// Navigate to the card's specific route
Get.toNamed(statItem.route);
}
void _onCardTap(_FinanceStatItem statItem, bool isEnabled) {
if (!isEnabled) {
Get.defaultDialog(
title: "No Project Selected",
middleText: "Please select a project before accessing this section.",
confirm: ElevatedButton(
onPressed: () => Get.back(),
child: const Text("OK"),
),
);
} else {
// Navigate to the card's specific route
Get.toNamed(statItem.route);
}
}
}
}
class _FinanceStatItem {
final IconData icon;

View File

@ -99,41 +99,76 @@ class _PaymentRequestMainScreenState extends State<PaymentRequestMainScreen>
return Scaffold(
backgroundColor: Colors.white,
appBar: _buildAppBar(),
body: Column(
children: [
Container(
color: Colors.white,
child: TabBar(
controller: _tabController,
labelColor: Colors.black,
unselectedLabelColor: Colors.grey,
indicatorColor: Colors.red,
tabs: const [
Tab(text: "Current Month"),
Tab(text: "History"),
],
),
),
Expanded(
child: Container(
color: Colors.grey[100],
child: Column(
children: [
_buildSearchBar(),
Expanded(
child: TabBarView(
controller: _tabController,
children: [
_buildPaymentRequestList(isHistory: false),
_buildPaymentRequestList(isHistory: true),
],
),
body: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final bool isLandscape =
constraints.maxWidth > constraints.maxHeight;
return Column(
children: [
// ---------------- TabBar ----------------
Container(
color: Colors.white,
child: TabBar(
controller: _tabController,
labelColor: Colors.black,
unselectedLabelColor: Colors.grey,
indicatorColor: Colors.red,
tabs: const [
Tab(text: "Current Month"),
Tab(text: "History"),
],
),
],
),
),
),
],
),
// ---------------- Content Area ----------------
Expanded(
child: Container(
color: Colors.grey[100],
child: isLandscape
? SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: SizedBox(
height: constraints.maxHeight * 1.3,
child: Column(
children: [
_buildSearchBar(),
Expanded(
child: TabBarView(
controller: _tabController,
children: [
_buildPaymentRequestList(
isHistory: false),
_buildPaymentRequestList(
isHistory: true),
],
),
),
],
),
),
)
: Column(
children: [
_buildSearchBar(),
Expanded(
child: TabBarView(
controller: _tabController,
children: [
_buildPaymentRequestList(isHistory: false),
_buildPaymentRequestList(isHistory: true),
],
),
),
],
),
),
),
],
);
},
),
),
floatingActionButton: Obx(() {
if (permissionController.permissions.isEmpty) {

View File

@ -16,6 +16,7 @@ import 'package:on_field_work/view/tenant/tenant_selection_screen.dart';
import 'package:on_field_work/controller/tenant/tenant_switch_controller.dart';
import 'package:on_field_work/helpers/theme/theme_editor_widget.dart';
class UserProfileBar extends StatefulWidget {
final bool isCondensed;
const UserProfileBar({Key? key, this.isCondensed = false}) : super(key: key);
@ -52,6 +53,7 @@ class _UserProfileBarState extends State<UserProfileBar>
@override
Widget build(BuildContext context) {
final bool isCondensed = widget.isCondensed;
return Padding(
padding: const EdgeInsets.only(left: 14),
child: ClipRRect(
@ -88,41 +90,52 @@ class _UserProfileBarState extends State<UserProfileBar>
bottom: true,
child: Stack(
children: [
// ======================= MAIN PROFILE SIDEBAR =======================
Offstage(
offstage: _isThemeEditorVisible,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_isLoading
? const _LoadingSection()
: _userProfileSection(isCondensed),
if (!_isLoading && !isCondensed) _switchTenantRow(),
MySpacing.height(12),
Divider(
indent: 18,
endIndent: 18,
thickness: 0.7,
color: Colors.grey.withOpacity(0.25),
),
MySpacing.height(12),
_supportAndSettingsMenu(isCondensed),
MySpacing.height(12),
// Subtle version text for expanded mode
if (!isCondensed && _appVersion.isNotEmpty)
_versionText(),
const Spacer(),
Divider(
indent: 18,
endIndent: 18,
thickness: 0.35,
color: Colors.grey.withOpacity(0.18),
),
_logoutButton(isCondensed),
],
child: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
physics: const ClampingScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: constraints.maxHeight),
child: IntrinsicHeight(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_isLoading
? const _LoadingSection()
: _userProfileSection(isCondensed),
if (!_isLoading && !isCondensed)
_switchTenantRow(),
MySpacing.height(12),
Divider(
indent: 18,
endIndent: 18,
thickness: 0.7,
color: Colors.grey.withOpacity(0.25),
),
MySpacing.height(12),
_supportAndSettingsMenu(isCondensed),
const Spacer(),
Divider(
indent: 18,
endIndent: 18,
thickness: 0.35,
color: Colors.grey.withOpacity(0.18),
),
_logoutButton(isCondensed),
],
),
),
),
);
},
),
),
// ======================= THEME EDITOR VIEW =======================
Offstage(
offstage: !_isThemeEditorVisible,
child: ThemeEditorWidget(
@ -131,9 +144,6 @@ class _UserProfileBarState extends State<UserProfileBar>
},
),
),
// Floating badge for condensed mode
if (isCondensed && _appVersion.isNotEmpty) _versionBadge(),
],
),
),
@ -143,96 +153,7 @@ class _UserProfileBarState extends State<UserProfileBar>
);
}
// =================== Version Widgets ===================
Widget _versionText() {
return Padding(
padding: const EdgeInsets.only(top: 4, bottom: 12),
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
decoration: BoxDecoration(
color: Colors.grey.shade100.withOpacity(0.85),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: Colors.grey.shade200,
width: 0.7,
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.12),
blurRadius: 3,
offset: const Offset(0, 1),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.info_outline, size: 14, color: Colors.grey[700]),
const SizedBox(width: 4),
Text(
'Version: $_appVersion',
style: TextStyle(
fontSize: 12,
color: Colors.grey[800],
fontWeight: FontWeight.w600,
),
),
],
),
),
),
),
),
);
}
Widget _versionBadge() {
return Positioned(
bottom: 10,
right: 14,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
decoration: BoxDecoration(
color: Colors.grey.shade100.withOpacity(0.85),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: Colors.grey.shade300,
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.17),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: Text(
_appVersion,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Colors.black87,
letterSpacing: 0.4,
),
),
),
),
),
);
}
// =================== Existing methods ===================
// ==================== EXISTING CODE (UNCHANGED) =====================
Widget _switchTenantRow() {
final TenantSwitchController tenantSwitchController =
@ -337,17 +258,25 @@ class _UserProfileBarState extends State<UserProfileBar>
child: const Center(child: CircularProgressIndicator(strokeWidth: 2)),
);
Widget _noTenantContainer() => Container(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
decoration: BoxDecoration(
color: Colors.blue.shade50,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.blue.shade200, width: 1),
border: Border.all(
color: Colors.blue.shade200,
width: 1,
),
),
child: MyText.bodyMedium(
"No tenants available",
color: Colors.blueAccent,
fontWeight: 600,
child: const Center(
child: Text(
"No organizations available",
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black87,
),
),
),
);

View File

@ -201,7 +201,7 @@ class _JobsTabState extends State<JobsTab> {
children: job.tags!.map((tag) {
return Chip(
label: Text(
tag.name,
tag.name.replaceAll('_', ' '),
style:
const TextStyle(fontSize: 12),
),
@ -318,7 +318,7 @@ class _JobsTabState extends State<JobsTab> {
final success =
await ApiService.editServiceProjectJobApi(
jobId: job.id ,
jobId: job.id,
operations: operations,
);

View File

@ -39,6 +39,10 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
final TextEditingController _dueDateController = TextEditingController();
final TextEditingController _tagTextController = TextEditingController();
final RxList<String> tags = <String>[].obs; // For showing/editing tag chips
final TextEditingController tagController =
TextEditingController(); // For tag input
final RxList<Assignee> _selectedAssignees = <Assignee>[].obs;
final RxList<Tag> _selectedTags = <Tag>[].obs;
final RxBool isEditing = false.obs;
@ -47,21 +51,38 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
@override
void initState() {
super.initState();
controller = Get.put(ServiceProjectDetailsController());
controller.fetchJobDetail(widget.jobId).then((_) {
controller = Get.find<ServiceProjectDetailsController>();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await controller.fetchJobDetail(widget.jobId);
final job = controller.jobDetail.value?.data;
if (job != null) {
_titleController.text = job.title ?? '';
_descriptionController.text = job.description ?? '';
_startDateController.text = DateTimeUtils.convertUtcToLocal(
job.startDate ?? DateTime.now().toIso8601String(),
format: "yyyy-MM-dd");
_dueDateController.text = DateTimeUtils.convertUtcToLocal(
job.dueDate ?? '',
format: "yyyy-MM-dd");
_selectedAssignees.value = job.assignees ?? [];
_selectedTags.value = job.tags ?? [];
// ---------- TAG FIX ----------
final tagList = job.tags ?? [];
final cleanedTags = tagList
.map((t) => (t.name ?? "").replaceAll("_", " ").trim())
.toList();
tags.assignAll(cleanedTags);
tagController.clear();
}
setState(() {});
});
}
@ -165,11 +186,21 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
if (success) {
showAppSnackbar(
title: "Success",
message: "Job updated successfully",
type: SnackbarType.success);
title: "Success",
message: "Job updated successfully",
type: SnackbarType.success,
);
/// Refresh detail screen
await controller.fetchJobDetail(widget.jobId);
/// 🔥 Auto refresh job list UI (main Service Project Details screen)
if (Get.isRegistered<ServiceProjectDetailsController>()) {
await Get.find<ServiceProjectDetailsController>().refreshJobsAfterAdd();
}
isEditing.value = false;
Navigator.pop(context); // optional if you want auto-close
} else {
showAppSnackbar(
title: "Error",

View File

@ -22,11 +22,11 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
final TextEditingController searchController = TextEditingController();
final ServiceProjectController controller =
Get.put(ServiceProjectController());
@override
void initState() {
super.initState();
// Fetch projects safely after first frame
WidgetsBinding.instance.addPostFrameCallback((_) {
controller.fetchProjects();
});
@ -42,38 +42,29 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
Widget _buildProjectCard(ProjectItem project) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
margin: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
shadowColor: Colors.indigo.withOpacity(0.10),
color: Colors.white,
child: InkWell(
borderRadius: BorderRadius.circular(14),
borderRadius: BorderRadius.circular(5),
onTap: () {
// Navigate to ServiceProjectDetailsScreen
Get.to(() => ServiceProjectDetailsScreen(
projectId: project.id,
projectName: project.name,
));
Get.to(() => ServiceProjectDetailsScreen(projectId: project.id));
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
/// Project Header
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MyText.titleMedium(
project.name,
fontWeight: 700,
),
MySpacing.height(4),
],
child: MyText.titleMedium(
project.name,
fontWeight: 700,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
if (project.status?.status.isNotEmpty ?? false)
@ -92,47 +83,32 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
),
],
),
MySpacing.height(10),
/// Assigned Date
MySpacing.height(8),
_buildDetailRow(
Icons.date_range_outlined,
Colors.teal,
"Assigned: ${DateTimeUtils.convertUtcToLocal(project.assignedDate.toIso8601String(), format: DateTimeUtils.defaultFormat)}",
fontSize: 13,
),
MySpacing.height(8),
/// Client Info
MySpacing.height(6),
if (project.client != null)
_buildDetailRow(
Icons.account_circle_outlined,
Colors.indigo,
"Client: ${project.client!.name} (${project.client!.contactPerson})",
fontSize: 13,
),
MySpacing.height(8),
/// Contact Info
MySpacing.height(6),
_buildDetailRow(
Icons.phone,
Colors.green,
"Contact: ${project.contactName} (${project.contactPhone})",
fontSize: 13,
),
MySpacing.height(12),
/// Services List
MySpacing.height(10),
if (project.services.isNotEmpty)
Wrap(
spacing: 6,
runSpacing: 4,
children: project.services
.map((service) => _buildServiceChip(service.name))
.map((e) => _buildServiceChip(e.name))
.toList(),
),
],
@ -148,7 +124,7 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
color: Colors.orange.withOpacity(0.1),
borderRadius: BorderRadius.circular(6),
),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: MyText.labelSmall(
name,
color: Colors.orange[800],
@ -157,19 +133,18 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
);
}
Widget _buildDetailRow(IconData icon, Color iconColor, String value,
{double fontSize = 12}) {
Widget _buildDetailRow(IconData icon, Color color, String value) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(icon, size: 18, color: iconColor),
Icon(icon, size: 18, color: color),
MySpacing.width(8),
Flexible(
Expanded(
child: MyText.bodySmall(
value,
color: Colors.grey[900],
maxLines: 2,
overflow: TextOverflow.ellipsis,
fontWeight: 500,
fontSize: fontSize,
color: Colors.grey[900],
),
),
],
@ -184,7 +159,7 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
const Icon(Icons.work_outline, size: 60, color: Colors.grey),
MySpacing.height(18),
MyText.titleMedium('No matching projects found.',
fontWeight: 600, color: Colors.grey),
color: Colors.grey, fontWeight: 600),
MySpacing.height(10),
MyText.bodySmall('Try adjusting your filters or refresh.',
color: Colors.grey),
@ -195,91 +170,150 @@ class _ServiceProjectScreenState extends State<ServiceProjectScreen>
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF5F5F5),
appBar: CustomAppBar(
title: "Service Projects",
projectName: 'All Service Projects',
onBackPressed: () => Get.toNamed('/dashboard'),
),
body: Column(
children: [
/// Search bar and actions
Padding(
padding: MySpacing.xy(8, 8),
child: Row(
return SafeArea(
child: Scaffold(
backgroundColor: const Color(0xFFF5F5F5),
appBar: CustomAppBar(
title: "Service Projects",
onBackPressed: () => Get.toNamed('/dashboard'),
),
body: LayoutBuilder(
builder: (context, constraints) {
return Column(
children: [
Expanded(
child: SizedBox(
height: 35,
child: TextField(
controller: searchController,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(horizontal: 12),
prefixIcon: const Icon(Icons.search,
size: 20, color: Colors.grey),
suffixIcon: ValueListenableBuilder<TextEditingValue>(
valueListenable: searchController,
builder: (context, value, _) {
if (value.text.isEmpty) {
return const SizedBox.shrink();
}
return IconButton(
icon: const Icon(Icons.clear,
/// SEARCH BAR AREA
Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: SizedBox(
height: 38,
child: TextField(
controller: searchController,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(horizontal: 12),
prefixIcon: const Icon(Icons.search,
size: 20, color: Colors.grey),
onPressed: () {
searchController.clear();
controller.updateSearch('');
},
);
},
),
hintText: 'Search projects...',
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(color: Colors.grey.shade300),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(color: Colors.grey.shade300),
suffixIcon:
ValueListenableBuilder<TextEditingValue>(
valueListenable: searchController,
builder: (context, value, _) {
return value.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear,
size: 20, color: Colors.grey),
onPressed: () {
searchController.clear();
controller.updateSearch('');
},
)
: const SizedBox.shrink();
},
),
hintText: 'Search projects...',
fillColor: Colors.white,
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide:
BorderSide(color: Colors.grey.shade300),
),
),
),
),
),
),
MySpacing.width(8),
/// FILTER BUTTON
_roundIconButton(Icons.tune),
MySpacing.width(8),
/// ACTION MENU
_roundMenuButton(),
],
),
),
/// LIST AREA
Expanded(
child: Obx(() {
if (controller.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
final projects = controller.filteredProjects;
return MyRefreshIndicator(
onRefresh: _refreshProjects,
color: Colors.white,
backgroundColor: Colors.indigo,
child: projects.isEmpty
? _buildEmptyState()
: ListView.separated(
padding: const EdgeInsets.only(
left: 8, right: 8, top: 4, bottom: 20),
itemCount: projects.length,
separatorBuilder: (_, __) => MySpacing.height(12),
itemBuilder: (_, index) =>
_buildProjectCard(projects[index]),
),
);
}),
),
],
);
},
),
),
);
}
Widget _roundIconButton(IconData icon) {
return Container(
height: 38,
width: 38,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Colors.grey.shade300),
),
child: Icon(icon, size: 20, color: Colors.black87),
);
}
Widget _roundMenuButton() {
return Container(
height: 38,
width: 38,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(5),
),
child: PopupMenuButton<int>(
padding: EdgeInsets.zero,
icon: const Icon(Icons.more_vert, size: 20, color: Colors.black87),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
itemBuilder: (context) => [
const PopupMenuItem<int>(
enabled: false,
height: 30,
child: Text("Actions",
style:
TextStyle(fontWeight: FontWeight.bold, color: Colors.grey)),
),
const PopupMenuItem<int>(
value: 1,
child: Row(
children: [
Expanded(child: Text("Manage Projects")),
Icon(Icons.chevron_right, size: 20, color: Colors.indigo),
],
),
),
/// Project List
Expanded(
child: Obx(() {
if (controller.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
final projects = controller.filteredProjects;
return MyRefreshIndicator(
onRefresh: _refreshProjects,
backgroundColor: Colors.indigo,
color: Colors.white,
child: projects.isEmpty
? _buildEmptyState()
: ListView.separated(
physics: const AlwaysScrollableScrollPhysics(),
padding: MySpacing.only(
left: 8, right: 8, top: 4, bottom: 80),
itemCount: projects.length,
separatorBuilder: (_, __) => MySpacing.height(12),
itemBuilder: (_, index) =>
_buildProjectCard(projects[index]),
),
);
}),
),
],
),
);