edit payment request
This commit is contained in:
parent
44674da8ac
commit
fd5ea9a1b3
@ -1,4 +1,3 @@
|
||||
// payment_request_bottom_sheet.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/finance/add_payment_request_controller.dart';
|
||||
@ -10,16 +9,31 @@ import 'package:marco/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:marco/helpers/widgets/expense/expense_form_widgets.dart';
|
||||
import 'package:marco/helpers/widgets/my_confirmation_dialog.dart';
|
||||
|
||||
Future<T?> showPaymentRequestBottomSheet<T>({bool isEdit = false}) {
|
||||
Future<T?> showPaymentRequestBottomSheet<T>({
|
||||
bool isEdit = false,
|
||||
Map<String, dynamic>? existingData,
|
||||
VoidCallback? onUpdated,
|
||||
}) {
|
||||
return Get.bottomSheet<T>(
|
||||
_PaymentRequestBottomSheet(isEdit: isEdit),
|
||||
_PaymentRequestBottomSheet(
|
||||
isEdit: isEdit,
|
||||
existingData: existingData,
|
||||
onUpdated: onUpdated,
|
||||
),
|
||||
isScrollControlled: true,
|
||||
);
|
||||
}
|
||||
|
||||
class _PaymentRequestBottomSheet extends StatefulWidget {
|
||||
final bool isEdit;
|
||||
const _PaymentRequestBottomSheet({this.isEdit = false});
|
||||
final Map<String, dynamic>? existingData;
|
||||
final VoidCallback? onUpdated;
|
||||
|
||||
const _PaymentRequestBottomSheet({
|
||||
this.isEdit = false,
|
||||
this.existingData,
|
||||
this.onUpdated,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_PaymentRequestBottomSheet> createState() =>
|
||||
@ -35,6 +49,64 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
|
||||
final _categoryDropdownKey = GlobalKey();
|
||||
final _currencyDropdownKey = GlobalKey();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
if (widget.isEdit && widget.existingData != null) {
|
||||
final data = widget.existingData!;
|
||||
|
||||
// 🧩 Prefill basic text fields
|
||||
controller.titleController.text = data["title"] ?? "";
|
||||
controller.amountController.text = data["amount"]?.toString() ?? "";
|
||||
controller.descriptionController.text = data["description"] ?? "";
|
||||
controller.dueDateController.text =
|
||||
data["dueDate"]?.toString().split(" ")[0] ?? "";
|
||||
|
||||
// 🧩 Prefill dropdowns & toggles
|
||||
controller.selectedProject.value = {
|
||||
'id': data["projectId"],
|
||||
'name': data["projectName"],
|
||||
};
|
||||
controller.selectedPayee.value = data["payee"] ?? "";
|
||||
controller.isAdvancePayment.value = data["isAdvancePayment"] ?? false;
|
||||
|
||||
// 🕒 Wait until categories & currencies are loaded before setting them
|
||||
everAll([
|
||||
controller.categories,
|
||||
controller.currencies,
|
||||
], (_) {
|
||||
controller.selectedCategory.value = controller.categories
|
||||
.firstWhereOrNull((c) => c.id == data["expenseCategoryId"]);
|
||||
controller.selectedCurrency.value = controller.currencies
|
||||
.firstWhereOrNull((c) => c.id == data["currencyId"]);
|
||||
});
|
||||
|
||||
// 🖇 Attachments - Safe parsing (avoids null or wrong type)
|
||||
final attachmentsData = data["attachments"];
|
||||
if (attachmentsData != null &&
|
||||
attachmentsData is List &&
|
||||
attachmentsData.isNotEmpty) {
|
||||
final attachments = attachmentsData
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map((a) => {
|
||||
"id": a["id"],
|
||||
"fileName": a["fileName"],
|
||||
"url": a["url"],
|
||||
"thumbUrl": a["thumbUrl"],
|
||||
"fileSize": a["fileSize"] ?? 0,
|
||||
"contentType": a["contentType"] ?? "",
|
||||
})
|
||||
.toList();
|
||||
controller.existingAttachments.assignAll(attachments);
|
||||
} else {
|
||||
controller.existingAttachments.clear();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Obx(() => Form(
|
||||
@ -49,12 +121,14 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
|
||||
if (_formKey.currentState!.validate() && _validateSelections()) {
|
||||
final success = await controller.submitPaymentRequest();
|
||||
if (success) {
|
||||
// First close the BottomSheet
|
||||
Get.back();
|
||||
// Then show Snackbar
|
||||
if (widget.onUpdated != null) widget.onUpdated!();
|
||||
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Payment request created successfully!",
|
||||
message: widget.isEdit
|
||||
? "Payment request updated successfully!"
|
||||
: "Payment request created successfully!",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
}
|
||||
@ -129,6 +203,8 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
|
||||
));
|
||||
}
|
||||
|
||||
// ---------------- Helper Widgets ----------------
|
||||
|
||||
Widget _buildDropdown<T>(String title, IconData icon, String value,
|
||||
List<T> options, String Function(T) getLabel, ValueChanged<T> onSelected,
|
||||
{required GlobalKey key}) {
|
||||
@ -258,7 +334,6 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
|
||||
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;
|
||||
@ -425,12 +500,15 @@ class _PaymentRequestBottomSheetState extends State<_PaymentRequestBottomSheet>
|
||||
controller.selectedProject.value!['id'].toString().isEmpty) {
|
||||
return _showError("Please select a project");
|
||||
}
|
||||
if (controller.selectedCategory.value == null)
|
||||
if (controller.selectedCategory.value == null) {
|
||||
return _showError("Please select a category");
|
||||
if (controller.selectedPayee.value.isEmpty)
|
||||
}
|
||||
if (controller.selectedPayee.value.isEmpty) {
|
||||
return _showError("Please select a payee");
|
||||
if (controller.selectedCurrency.value == null)
|
||||
}
|
||||
if (controller.selectedCurrency.value == null) {
|
||||
return _showError("Please select currency");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@ -118,8 +118,7 @@ class PaymentRequestData {
|
||||
expenseStatus: ExpenseStatus.fromJson(json['expenseStatus']),
|
||||
paidTransactionId: json['paidTransactionId'],
|
||||
paidAt: json['paidAt'] != null ? DateTime.parse(json['paidAt']) : null,
|
||||
paidBy:
|
||||
json['paidBy'] != null ? User.fromJson(json['paidBy']) : null,
|
||||
paidBy: json['paidBy'] != null ? User.fromJson(json['paidBy']) : null,
|
||||
isAdvancePayment: json['isAdvancePayment'],
|
||||
createdAt: DateTime.parse(json['createdAt']),
|
||||
createdBy: User.fromJson(json['createdBy']),
|
||||
@ -373,7 +372,7 @@ class NextStatus {
|
||||
|
||||
class UpdateLog {
|
||||
String id;
|
||||
ExpenseStatus status;
|
||||
ExpenseStatus? status;
|
||||
ExpenseStatus nextStatus;
|
||||
String comment;
|
||||
DateTime updatedAt;
|
||||
@ -381,7 +380,7 @@ class UpdateLog {
|
||||
|
||||
UpdateLog({
|
||||
required this.id,
|
||||
required this.status,
|
||||
this.status,
|
||||
required this.nextStatus,
|
||||
required this.comment,
|
||||
required this.updatedAt,
|
||||
@ -390,7 +389,9 @@ class UpdateLog {
|
||||
|
||||
factory UpdateLog.fromJson(Map<String, dynamic> json) => UpdateLog(
|
||||
id: json['id'],
|
||||
status: ExpenseStatus.fromJson(json['status']),
|
||||
status: json['status'] != null
|
||||
? ExpenseStatus.fromJson(json['status'])
|
||||
: null,
|
||||
nextStatus: ExpenseStatus.fromJson(json['nextStatus']),
|
||||
comment: json['comment'],
|
||||
updatedAt: DateTime.parse(json['updatedAt']),
|
||||
@ -399,7 +400,7 @@ class UpdateLog {
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'status': status.toJson(),
|
||||
'status': status?.toJson(),
|
||||
'nextStatus': nextStatus.toJson(),
|
||||
'comment': comment,
|
||||
'updatedAt': updatedAt.toIso8601String(),
|
||||
|
||||
@ -115,7 +115,7 @@ class _FAQScreenState extends State<FAQScreen> with UIMixin {
|
||||
color: contentTheme.primary.withOpacity(0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(LucideIcons.badge_help,
|
||||
child: Icon(LucideIcons.badge_alert,
|
||||
color: contentTheme.primary, size: 24),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
|
||||
@ -20,6 +20,7 @@ import 'package:marco/model/employees/employee_info.dart';
|
||||
import 'package:marco/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:marco/model/finance/payment_request_rembursement_bottom_sheet.dart';
|
||||
import 'package:marco/model/finance/make_expense_bottom_sheet.dart';
|
||||
import 'package:marco/model/finance/add_payment_request_bottom_sheet.dart';
|
||||
|
||||
class PaymentRequestDetailScreen extends StatefulWidget {
|
||||
final String paymentRequestId;
|
||||
@ -49,21 +50,10 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
|
||||
void _checkPermissionToSubmit(PaymentRequestData request) {
|
||||
const draftStatusId = '6537018f-f4e9-4cb3-a210-6c3b2da999d7';
|
||||
|
||||
final isCreatedByCurrentUser = employeeInfo?.id == request.createdBy.id;
|
||||
final hasDraftNextStatus =
|
||||
request.nextStatus.any((s) => s.id == draftStatusId);
|
||||
|
||||
final result = isCreatedByCurrentUser && hasDraftNextStatus;
|
||||
|
||||
// Debug log
|
||||
print('🔐 Submit Permission Check:\n'
|
||||
'Logged-in employee: ${employeeInfo?.id}\n'
|
||||
'Created by: ${request.createdBy.id}\n'
|
||||
'Has Draft Next Status: $hasDraftNextStatus\n'
|
||||
'Can Submit: $result');
|
||||
|
||||
canSubmit.value = result;
|
||||
canSubmit.value = isCreatedByCurrentUser && hasDraftNextStatus;
|
||||
}
|
||||
|
||||
Future<void> _loadEmployeeInfo() async {
|
||||
@ -77,6 +67,38 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
return Color(int.parse(hex, radix: 16));
|
||||
}
|
||||
|
||||
void _openEditPaymentRequestBottomSheet(request) {
|
||||
showPaymentRequestBottomSheet(
|
||||
isEdit: true,
|
||||
existingData: {
|
||||
"paymentRequestId": request.paymentRequestUID,
|
||||
"title": request.title,
|
||||
"projectId": request.project.id,
|
||||
"projectName": request.project.name,
|
||||
"expenseCategoryId": request.expenseCategory.id,
|
||||
"expenseCategoryName": request.expenseCategory.name,
|
||||
"amount": request.amount.toString(),
|
||||
"currencyId": request.currency.id,
|
||||
"currencySymbol": request.currency.symbol,
|
||||
"payee": request.payee,
|
||||
"description": request.description,
|
||||
"isAdvancePayment": request.isAdvancePayment,
|
||||
"dueDate": request.dueDate,
|
||||
"attachments": request.attachments
|
||||
.map((a) => {
|
||||
"url": a.url,
|
||||
"fileName": a.fileName,
|
||||
"documentId": a.id,
|
||||
"contentType": a.contentType,
|
||||
})
|
||||
.toList(),
|
||||
},
|
||||
onUpdated: () async {
|
||||
await controller.fetchPaymentRequestDetail();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@ -87,6 +109,7 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
if (controller.isLoading.value) {
|
||||
return SkeletonLoaders.paymentRequestDetailSkeletonLoader();
|
||||
}
|
||||
|
||||
final request = controller.paymentRequest.value;
|
||||
if (controller.errorMessage.isNotEmpty || request == null) {
|
||||
return Center(child: MyText.bodyMedium("No data to display."));
|
||||
@ -125,6 +148,7 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
_DetailsTable(request: request),
|
||||
const Divider(height: 30, thickness: 1.2),
|
||||
_Documents(documents: request.attachments),
|
||||
MySpacing.height(24),
|
||||
],
|
||||
),
|
||||
),
|
||||
@ -135,15 +159,54 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
);
|
||||
}),
|
||||
),
|
||||
bottomNavigationBar: Obx(() {
|
||||
bottomNavigationBar: _buildBottomActionBar(),
|
||||
|
||||
// ✅ Added Floating Action Button for Edit
|
||||
floatingActionButton: Obx(() {
|
||||
if (controller.isLoading.value) return const SizedBox.shrink();
|
||||
|
||||
final request = controller.paymentRequest.value;
|
||||
if (request == null ||
|
||||
controller.isLoading.value ||
|
||||
employeeInfo == null) {
|
||||
if (controller.errorMessage.isNotEmpty || request == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
if (!_checkedPermission) {
|
||||
_checkedPermission = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_checkPermissionToSubmit(request);
|
||||
});
|
||||
}
|
||||
|
||||
final canEdit = PaymentRequestPermissionHelper.canEditPaymentRequest(
|
||||
employeeInfo,
|
||||
request,
|
||||
);
|
||||
|
||||
if (!canEdit) return const SizedBox.shrink();
|
||||
|
||||
return FloatingActionButton.extended(
|
||||
onPressed: () => _openEditPaymentRequestBottomSheet(request),
|
||||
backgroundColor: contentTheme.primary,
|
||||
icon: const Icon(Icons.edit),
|
||||
label: MyText.bodyMedium(
|
||||
"Edit Payment Request",
|
||||
fontWeight: 600,
|
||||
color: Colors.white,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBottomActionBar() {
|
||||
return Obx(() {
|
||||
final request = controller.paymentRequest.value;
|
||||
if (request == null ||
|
||||
controller.isLoading.value ||
|
||||
employeeInfo == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
// Check permissions once
|
||||
if (!_checkedPermission) {
|
||||
_checkedPermission = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@ -151,7 +214,6 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
});
|
||||
}
|
||||
|
||||
// Filter statuses
|
||||
const reimbursementStatusId = '61578360-3a49-4c34-8604-7b35a3787b95';
|
||||
const draftStatusId = '6537018f-f4e9-4cb3-a210-6c3b2da999d7';
|
||||
|
||||
@ -163,7 +225,6 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
.hasAnyPermission(status.permissionIds ?? []);
|
||||
}).toList();
|
||||
|
||||
// If there are no next statuses, show "Create Expense" button
|
||||
if (availableStatuses.isEmpty) {
|
||||
return SafeArea(
|
||||
child: Container(
|
||||
@ -180,20 +241,17 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onPressed: () {
|
||||
showCreateExpenseBottomSheet();
|
||||
},
|
||||
onPressed: () => showCreateExpenseBottomSheet(),
|
||||
child: const Text(
|
||||
"Create Expense",
|
||||
style: TextStyle(
|
||||
color: Colors.white, fontWeight: FontWeight.bold),
|
||||
style:
|
||||
TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Normal status buttons
|
||||
return SafeArea(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
@ -210,8 +268,8 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
|
||||
return ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16, vertical: 10),
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
backgroundColor: color,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
@ -237,8 +295,7 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
context, status.displayName);
|
||||
if (comment == null || comment.trim().isEmpty) return;
|
||||
|
||||
final success =
|
||||
await controller.updatePaymentRequestStatus(
|
||||
final success = await controller.updatePaymentRequestStatus(
|
||||
statusId: status.id,
|
||||
comment: comment.trim(),
|
||||
);
|
||||
@ -248,8 +305,7 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
message: success
|
||||
? 'Status updated successfully'
|
||||
: 'Failed to update status',
|
||||
type:
|
||||
success ? SnackbarType.success : SnackbarType.error,
|
||||
type: success ? SnackbarType.success : SnackbarType.error,
|
||||
);
|
||||
|
||||
if (success) await controller.fetchPaymentRequestDetail();
|
||||
@ -262,8 +318,7 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
PreferredSizeWidget _buildAppBar() {
|
||||
@ -326,6 +381,29 @@ class _PaymentRequestDetailScreenState extends State<PaymentRequestDetailScreen>
|
||||
}
|
||||
}
|
||||
|
||||
class PaymentRequestPermissionHelper {
|
||||
static bool canEditPaymentRequest(
|
||||
EmployeeInfo? employee, PaymentRequestData request) {
|
||||
return employee?.id == request.createdBy.id &&
|
||||
_isInAllowedEditStatus(request.expenseStatus.id);
|
||||
}
|
||||
|
||||
static bool canSubmitPaymentRequest(
|
||||
EmployeeInfo? employee, PaymentRequestData request) {
|
||||
return employee?.id == request.createdBy.id &&
|
||||
request.nextStatus.isNotEmpty;
|
||||
}
|
||||
|
||||
static bool _isInAllowedEditStatus(String statusId) {
|
||||
const editableStatusIds = [
|
||||
"d1ee5eec-24b6-4364-8673-a8f859c60729",
|
||||
"965eda62-7907-4963-b4a1-657fb0b2724b",
|
||||
"297e0d8f-f668-41b5-bfea-e03b354251c8",
|
||||
];
|
||||
return editableStatusIds.contains(statusId);
|
||||
}
|
||||
}
|
||||
|
||||
class _Header extends StatelessWidget {
|
||||
final PaymentRequestData request;
|
||||
final Color Function(String) colorParser;
|
||||
@ -407,8 +485,12 @@ class _Logs extends StatelessWidget {
|
||||
itemBuilder: (_, index) {
|
||||
final log = reversedLogs[index];
|
||||
|
||||
final status = log.status.name;
|
||||
final description = log.status.description;
|
||||
final status = log.status?.name ?? 'Unknown';
|
||||
final description = log.status?.description ?? '';
|
||||
final statusColor = log.status != null
|
||||
? colorParser(log.status!.color)
|
||||
: Colors.grey;
|
||||
|
||||
final comment = log.comment;
|
||||
final nextStatusName = log.nextStatus.name;
|
||||
|
||||
@ -421,7 +503,6 @@ class _Logs extends StatelessWidget {
|
||||
final timestamp = _parseTimestamp(log.updatedAt);
|
||||
final timeAgo = timeago.format(timestamp);
|
||||
|
||||
final statusColor = colorParser(log.status.color);
|
||||
final nextStatusColor = colorParser(log.nextStatus.color);
|
||||
|
||||
return TimelineTile(
|
||||
@ -501,6 +582,7 @@ class _Logs extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class _Parties extends StatelessWidget {
|
||||
final PaymentRequestData request;
|
||||
const _Parties({required this.request});
|
||||
|
||||
@ -215,7 +215,7 @@ class _UserProfileBarState extends State<UserProfileBar>
|
||||
),
|
||||
SizedBox(height: spacingHeight),
|
||||
_menuItemRow(
|
||||
icon: LucideIcons.badge_help,
|
||||
icon: LucideIcons.badge_alert,
|
||||
label: 'FAQ',
|
||||
onTap: () {
|
||||
Get.to(() => FAQScreen());
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user