added add new project in projectselection

This commit is contained in:
Vaibhav Surve 2025-10-01 15:47:21 +05:30
parent c9e6840161
commit e4165f2ee8

View File

@ -19,10 +19,7 @@ Future<T?> showAddExpenseBottomSheet<T>({
Map<String, dynamic>? existingExpense, Map<String, dynamic>? existingExpense,
}) { }) {
return Get.bottomSheet<T>( return Get.bottomSheet<T>(
_AddExpenseBottomSheet( _AddExpenseBottomSheet(isEdit: isEdit, existingExpense: existingExpense),
isEdit: isEdit,
existingExpense: existingExpense,
),
isScrollControlled: true, isScrollControlled: true,
); );
} }
@ -49,95 +46,6 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet> {
final GlobalKey _expenseTypeDropdownKey = GlobalKey(); final GlobalKey _expenseTypeDropdownKey = GlobalKey();
final GlobalKey _paymentModeDropdownKey = GlobalKey(); final GlobalKey _paymentModeDropdownKey = GlobalKey();
/// Show employee list
Future<void> _showEmployeeList() async {
await showModalBottomSheet(
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,
),
);
controller.employeeSearchController.clear();
controller.employeeSearchResults.clear();
}
/// Generic option list
Future<void> _showOptionList<T>(
List<T> options,
String Function(T) getLabel,
ValueChanged<T> onSelected,
GlobalKey triggerKey,
) async {
final RenderBox button =
triggerKey.currentContext!.findRenderObject() as RenderBox;
final RenderBox overlay =
Overlay.of(context).context.findRenderObject() as RenderBox;
final position = button.localToGlobal(Offset.zero, ancestor: overlay);
final selected = await showMenu<T>(
context: context,
position: RelativeRect.fromLTRB(
position.dx,
position.dy + button.size.height,
overlay.size.width - position.dx - button.size.width,
0,
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
items: options
.map((opt) => PopupMenuItem<T>(
value: opt,
child: Text(getLabel(opt)),
))
.toList(),
);
if (selected != null) onSelected(selected);
}
/// Validate required selections
bool _validateSelections() {
if (controller.selectedProject.value.isEmpty) {
_showError("Please select a project");
return false;
}
if (controller.selectedExpenseType.value == null) {
_showError("Please select an expense type");
return false;
}
if (controller.selectedPaymentMode.value == null) {
_showError("Please select a payment mode");
return false;
}
if (controller.selectedPaidBy.value == null) {
_showError("Please select a person who paid");
return false;
}
if (controller.attachments.isEmpty &&
controller.existingAttachments.isEmpty) {
_showError("Please attach at least one document");
return false;
}
return true;
}
void _showError(String msg) {
showAppSnackbar(
title: "Error",
message: msg,
type: SnackbarType.error,
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Obx( return Obx(
@ -147,155 +55,147 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet> {
title: widget.isEdit ? "Edit Expense" : "Add Expense", title: widget.isEdit ? "Edit Expense" : "Add Expense",
isSubmitting: controller.isSubmitting.value, isSubmitting: controller.isSubmitting.value,
onCancel: Get.back, onCancel: Get.back,
onSubmit: () { onSubmit: _handleSubmit,
if (_formKey.currentState!.validate() && _validateSelections()) {
controller.submitOrUpdateExpense();
} else {
_showError("Please fill all required fields correctly");
}
},
child: SingleChildScrollView( child: SingleChildScrollView(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// 👇 Add New Project Button _buildCreateProjectButton(),
Align( _buildProjectDropdown(),
_gap(),
_buildExpenseTypeDropdown(),
if (controller.selectedExpenseType.value?.noOfPersonsRequired ==
true) ...[
_gap(),
_buildNumberField(
icon: Icons.people_outline,
title: "No. of Persons",
controller: controller.noOfPersonsController,
hint: "Enter No. of Persons",
validator: Validators.requiredField,
),
],
_gap(),
_buildPaymentModeDropdown(),
_gap(),
_buildPaidBySection(),
_gap(),
_buildAmountField(),
_gap(),
_buildSupplierField(),
_gap(),
_buildTransactionDateField(),
_gap(),
_buildTransactionIdField(),
_gap(),
_buildLocationField(),
_gap(),
_buildAttachmentsSection(),
_gap(),
_buildDescriptionField(),
],
),
),
),
),
);
}
/// 🟦 UI SECTION BUILDERS
Widget _buildCreateProjectButton() {
return Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: TextButton.icon( child: TextButton.icon(
onPressed: () async { onPressed: () async {
await Get.bottomSheet( await Get.bottomSheet(const CreateProjectBottomSheet(),
const CreateProjectBottomSheet(), isScrollControlled: true);
isScrollControlled: true,
);
// 🔄 Refresh project list after adding new project (optional)
await controller.fetchGlobalProjects(); await controller.fetchGlobalProjects();
}, },
icon: const Icon(Icons.add, color: Colors.blue), icon: const Icon(Icons.add, color: Colors.blue),
label: const Text( label: const Text(
"Add Project", "Create Project",
style: TextStyle( style: TextStyle(color: Colors.blue, fontWeight: FontWeight.w600),
color: Colors.blue,
fontWeight: FontWeight.w600,
), ),
), ),
), );
), }
_gap(),
_buildDropdownField<String>( Widget _buildProjectDropdown() {
return _buildDropdownField<String>(
icon: Icons.work_outline, icon: Icons.work_outline,
title: "Project", title: "Project",
requiredField: true, requiredField: true,
value: controller.selectedProject.value.isEmpty value: controller.selectedProject.value.isEmpty
? "Select Project" ? "Select Project"
: controller.selectedProject.value, : controller.selectedProject.value,
onTap: () => _showOptionList<String>( onTap: _showProjectSelector,
controller.globalProjects.toList(),
(p) => p,
(val) => controller.selectedProject.value = val,
_projectDropdownKey,
),
dropdownKey: _projectDropdownKey, dropdownKey: _projectDropdownKey,
), );
_gap(), }
_buildDropdownField<ExpenseTypeModel>( Widget _buildExpenseTypeDropdown() {
return _buildDropdownField<ExpenseTypeModel>(
icon: Icons.category_outlined, icon: Icons.category_outlined,
title: "Expense Type", title: "Expense Type",
requiredField: true, requiredField: true,
value: controller.selectedExpenseType.value?.name ?? value:
"Select Expense Type", controller.selectedExpenseType.value?.name ?? "Select Expense Type",
onTap: () => _showOptionList<ExpenseTypeModel>( onTap: () => _showOptionList(
controller.expenseTypes.toList(), controller.expenseTypes.toList(),
(e) => e.name, (e) => e.name,
(val) => controller.selectedExpenseType.value = val, (val) => controller.selectedExpenseType.value = val,
_expenseTypeDropdownKey, _expenseTypeDropdownKey,
), ),
dropdownKey: _expenseTypeDropdownKey, dropdownKey: _expenseTypeDropdownKey,
), );
}
// Persons if required Widget _buildPaymentModeDropdown() {
if (controller.selectedExpenseType.value?.noOfPersonsRequired == return _buildDropdownField<PaymentModeModel>(
true) ...[
_gap(),
_buildTextFieldSection(
icon: Icons.people_outline,
title: "No. of Persons",
controller: controller.noOfPersonsController,
hint: "Enter No. of Persons",
keyboardType: TextInputType.number,
validator: Validators.requiredField,
),
],
_gap(),
_buildDropdownField<PaymentModeModel>(
icon: Icons.payment, icon: Icons.payment,
title: "Payment Mode", title: "Payment Mode",
requiredField: true, requiredField: true,
value: controller.selectedPaymentMode.value?.name ?? value:
"Select Payment Mode", controller.selectedPaymentMode.value?.name ?? "Select Payment Mode",
onTap: () => _showOptionList<PaymentModeModel>( onTap: () => _showOptionList(
controller.paymentModes.toList(), controller.paymentModes.toList(),
(p) => p.name, (p) => p.name,
(val) => controller.selectedPaymentMode.value = val, (val) => controller.selectedPaymentMode.value = val,
_paymentModeDropdownKey, _paymentModeDropdownKey,
), ),
dropdownKey: _paymentModeDropdownKey, dropdownKey: _paymentModeDropdownKey,
), );
_gap(), }
_buildPaidBySection(), Widget _buildPaidBySection() {
_gap(), return _buildTileSelector(
icon: Icons.person_outline,
title: "Paid By",
required: true,
displayText: controller.selectedPaidBy.value == null
? "Select Paid By"
: '${controller.selectedPaidBy.value?.firstName ?? ''} ${controller.selectedPaidBy.value?.lastName ?? ''}',
onTap: _showEmployeeList,
);
}
_buildTextFieldSection( Widget _buildAmountField() => _buildNumberField(
icon: Icons.currency_rupee, icon: Icons.currency_rupee,
title: "Amount", title: "Amount",
controller: controller.amountController, controller: controller.amountController,
hint: "Enter Amount", hint: "Enter Amount",
keyboardType: TextInputType.number, validator: (v) =>
validator: (v) => Validators.isNumeric(v ?? "") Validators.isNumeric(v ?? "") ? null : "Enter valid amount",
? null );
: "Enter valid amount",
),
_gap(),
_buildTextFieldSection( Widget _buildSupplierField() => _buildTextField(
icon: Icons.store_mall_directory_outlined, icon: Icons.store_mall_directory_outlined,
title: "Supplier Name/Transporter Name/Other", title: "Supplier Name/Transporter Name/Other",
controller: controller.supplierController, controller: controller.supplierController,
hint: "Enter Supplier Name/Transporter Name or Other", hint: "Enter Supplier Name/Transporter Name or Other",
validator: Validators.nameValidator, validator: Validators.nameValidator,
),
_gap(),
_buildTransactionDateField(),
_gap(),
_buildTransactionIdField(),
_gap(),
_buildLocationField(),
_gap(),
_buildAttachmentsSection(),
_gap(),
_buildTextFieldSection(
icon: Icons.description_outlined,
title: "Description",
controller: controller.descriptionController,
hint: "Enter Description",
maxLines: 3,
validator: Validators.requiredField,
),
],
),
),
),
),
); );
}
Widget _buildTransactionIdField() { Widget _buildTransactionIdField() {
final paymentMode = final paymentMode =
@ -304,126 +204,32 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet> {
paymentMode != 'cash' && paymentMode != 'cash' &&
paymentMode != 'cheque'; paymentMode != 'cheque';
return Column( return _buildTextField(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(
icon: Icons.confirmation_number_outlined, icon: Icons.confirmation_number_outlined,
title: "Transaction ID", title: "Transaction ID",
requiredField: isRequired,
),
MySpacing.height(6),
CustomTextField(
controller: controller.transactionIdController, controller: controller.transactionIdController,
hint: "Enter Transaction ID", hint: "Enter Transaction ID",
validator: (v) { validator: (v) {
if (isRequired) { if (isRequired) {
if (v == null || v.isEmpty) { if (v == null || v.isEmpty)
return "Transaction ID is required for this payment mode"; return "Transaction ID is required for this payment mode";
}
return Validators.transactionIdValidator(v); return Validators.transactionIdValidator(v);
} }
return null; return null;
}, },
), requiredField: isRequired,
],
);
}
Widget _gap([double h = 16]) => MySpacing.height(h);
Widget _buildDropdownField<T>({
required IconData icon,
required String title,
required bool requiredField,
required String value,
required VoidCallback onTap,
required GlobalKey dropdownKey,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(icon: icon, title: title, requiredField: requiredField),
MySpacing.height(6),
DropdownTile(key: dropdownKey, title: value, onTap: onTap),
],
);
}
Widget _buildTextFieldSection({
required IconData icon,
required String title,
required TextEditingController controller,
String? hint,
TextInputType? keyboardType,
FormFieldValidator<String>? validator,
int maxLines = 1,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(
icon: icon, title: title, requiredField: validator != null),
MySpacing.height(6),
CustomTextField(
controller: controller,
hint: hint ?? "",
keyboardType: keyboardType ?? TextInputType.text,
validator: validator,
maxLines: maxLines,
),
],
);
}
Widget _buildPaidBySection() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SectionTitle(
icon: Icons.person_outline, title: "Paid By", requiredField: true),
MySpacing.height(6),
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),
),
const Icon(Icons.arrow_drop_down, size: 22),
],
),
),
),
],
); );
} }
Widget _buildTransactionDateField() { Widget _buildTransactionDateField() {
return Column( return _buildTileSelector(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SectionTitle(
icon: Icons.calendar_today, icon: Icons.calendar_today,
title: "Transaction Date", title: "Transaction Date",
requiredField: true), required: true,
MySpacing.height(6), displayText: controller.transactionDateController.text.isEmpty
GestureDetector( ? "Select Transaction Date"
: controller.transactionDateController.text,
onTap: () => controller.pickTransactionDate(context), onTap: () => controller.pickTransactionDate(context),
child: AbsorbPointer(
child: CustomTextField(
controller: controller.transactionDateController,
hint: "Select Transaction Date",
validator: Validators.requiredField,
),
),
),
],
); );
} }
@ -467,13 +273,196 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const SectionTitle( const SectionTitle(
icon: Icons.attach_file, title: "Attachments", requiredField: true), icon: Icons.attach_file,
title: "Attachments",
requiredField: true,
),
MySpacing.height(6), MySpacing.height(6),
AttachmentsSection( AttachmentsSection(
attachments: controller.attachments, attachments: controller.attachments,
existingAttachments: controller.existingAttachments, existingAttachments: controller.existingAttachments,
onRemoveNew: controller.removeAttachment, onRemoveNew: controller.removeAttachment,
onRemoveExisting: (item) async { onRemoveExisting: _confirmRemoveAttachment,
onAdd: controller.pickAttachments,
),
],
);
}
Widget _buildDescriptionField() => _buildTextField(
icon: Icons.description_outlined,
title: "Description",
controller: controller.descriptionController,
hint: "Enter Description",
maxLines: 3,
validator: Validators.requiredField,
);
/// 🟩 COMMON HELPERS
Widget _gap([double h = 16]) => MySpacing.height(h);
Widget _buildDropdownField<T>({
required IconData icon,
required String title,
required bool requiredField,
required String value,
required VoidCallback onTap,
required GlobalKey dropdownKey,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(icon: icon, title: title, requiredField: requiredField),
MySpacing.height(6),
DropdownTile(key: dropdownKey, title: value, onTap: onTap),
],
);
}
Widget _buildTextField({
required IconData icon,
required String title,
required TextEditingController controller,
String? hint,
FormFieldValidator<String>? validator,
bool requiredField = true,
int maxLines = 1,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(icon: icon, title: title, requiredField: requiredField),
MySpacing.height(6),
CustomTextField(
controller: controller,
hint: hint ?? "",
validator: validator,
maxLines: maxLines,
),
],
);
}
Widget _buildNumberField({
required IconData icon,
required String title,
required TextEditingController controller,
String? hint,
FormFieldValidator<String>? validator,
}) {
return _buildTextField(
icon: icon,
title: title,
controller: controller,
hint: hint,
validator: validator,
);
}
Widget _buildTileSelector({
required IconData icon,
required String title,
required String displayText,
required VoidCallback onTap,
bool required = false,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(icon: icon, title: title, requiredField: required),
MySpacing.height(6),
GestureDetector(
onTap: onTap,
child: TileContainer(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(displayText, style: const TextStyle(fontSize: 14)),
const Icon(Icons.arrow_drop_down, size: 22),
],
),
),
),
],
);
}
/// 🧰 LOGIC HELPERS
Future<void> _showProjectSelector() async {
final sortedProjects = controller.globalProjects.toList()
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
const specialOption = 'Create New Project';
final displayList = [...sortedProjects, specialOption];
final selected = await showMenu<String>(
context: context,
position: _getPopupMenuPosition(_projectDropdownKey),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
items: displayList.map((opt) {
final isSpecial = opt == specialOption;
return PopupMenuItem<String>(
value: opt,
child: isSpecial
? Row(
children: const [
Icon(Icons.add, color: Colors.blue),
SizedBox(width: 8),
Text(
specialOption,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.blue,
),
),
],
)
: Text(
opt,
style: const TextStyle(
fontWeight: FontWeight.normal,
color: Colors.black,
),
),
);
}).toList(),
);
if (selected == null) return;
if (selected == specialOption) {
controller.selectedProject.value = specialOption;
await Get.bottomSheet(const CreateProjectBottomSheet(),
isScrollControlled: true);
await controller.fetchGlobalProjects();
controller.selectedProject.value = "";
} else {
controller.selectedProject.value = selected;
}
}
Future<void> _showEmployeeList() async {
await showModalBottomSheet(
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,
),
);
controller.employeeSearchController.clear();
controller.employeeSearchResults.clear();
}
Future<void> _confirmRemoveAttachment(item) async {
await showDialog( await showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@ -497,10 +486,72 @@ class _AddExpenseBottomSheetState extends State<_AddExpenseBottomSheet> {
}, },
), ),
); );
}, }
onAdd: controller.pickAttachments,
), Future<void> _showOptionList<T>(
], List<T> options,
String Function(T) getLabel,
ValueChanged<T> onSelected,
GlobalKey triggerKey,
) async {
final selected = await showMenu<T>(
context: context,
position: _getPopupMenuPosition(triggerKey),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
items: options
.map((opt) => PopupMenuItem<T>(
value: opt,
child: Text(getLabel(opt)),
))
.toList(),
);
if (selected != null) onSelected(selected);
}
RelativeRect _getPopupMenuPosition(GlobalKey key) {
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);
return RelativeRect.fromLTRB(
position.dx,
position.dy + button.size.height,
overlay.size.width - position.dx - button.size.width,
0,
); );
} }
bool _validateSelections() {
if (controller.selectedProject.value.isEmpty) {
return _error("Please select a project");
}
if (controller.selectedExpenseType.value == null) {
return _error("Please select an expense type");
}
if (controller.selectedPaymentMode.value == null) {
return _error("Please select a payment mode");
}
if (controller.selectedPaidBy.value == null) {
return _error("Please select a person who paid");
}
if (controller.attachments.isEmpty &&
controller.existingAttachments.isEmpty) {
return _error("Please attach at least one document");
}
return true;
}
bool _error(String msg) {
showAppSnackbar(title: "Error", message: msg, type: SnackbarType.error);
return false;
}
void _handleSubmit() {
if (_formKey.currentState!.validate() && _validateSelections()) {
controller.submitOrUpdateExpense();
} else {
_error("Please fill all required fields correctly");
}
}
} }