handle approval in better way

This commit is contained in:
amirrezaghabeli
2025-08-31 10:51:40 +03:30
parent fd9457ee44
commit a8eafc0815
+65
View File
@@ -353,12 +353,58 @@ class TendersViewModel with ChangeNotifier {
required String status,
}) async {
_tenderApprovalErrorMessage = null;
// Get current approval for this tender
final existingApproval = getTenderApprovalForTender(tenderId);
final existingApprovalIndex = tenderApprovals.indexWhere(
(a) => a.tenderId == tenderId,
);
// Create optimistic approval data
TenderApprovalsData? optimisticApproval;
if (existingApproval == null) {
// No existing approval - create new optimistic approval
optimisticApproval = TenderApprovalsData(
id: null, // Will be filled by server
status: status,
tenderId: tenderId,
companyId: null, // Will be filled by server
submissionMode: submissionMode,
createdAt: DateTime.now().millisecondsSinceEpoch,
tender: null,
);
tenderApprovals.add(optimisticApproval);
} else {
// Existing approval - update optimistically
if (existingApproval.status == status) {
// Same status - remove approval (toggle off)
if (existingApprovalIndex != -1) {
tenderApprovals.removeAt(existingApprovalIndex);
}
optimisticApproval = null;
} else {
// Different status - update to new status
optimisticApproval = existingApproval.copyWith(
status: status,
submissionMode: submissionMode,
);
if (existingApprovalIndex != -1) {
tenderApprovals[existingApprovalIndex] = optimisticApproval;
}
}
}
// Notify listeners immediately for optimistic update
notifyListeners();
// Call API
final result = await _tendersRepository.toggleApprovals(
tenderId: tenderId,
submissionMode: submissionMode,
status: status,
);
switch (result) {
case Ok<TenderApprovalsToggleResponse>():
_tenderApprovalToggleData = result.value.data;
@@ -382,12 +428,31 @@ class TendersViewModel with ChangeNotifier {
} else {
tenderApprovals.add(approvalData);
}
} else {
// Server returned null data - remove approval
tenderApprovals.removeWhere((a) => a.tenderId == tenderId);
}
break;
case Error<TenderApprovalsToggleResponse>():
// Revert optimistic update on error
if (existingApproval == null) {
// Remove the optimistic approval we added
tenderApprovals.removeWhere((a) => a.tenderId == tenderId);
} else {
// Restore the original approval - find current index and update, or add if not found
final currentIndex = tenderApprovals.indexWhere(
(a) => a.tenderId == tenderId,
);
if (currentIndex != -1) {
tenderApprovals[currentIndex] = existingApproval;
} else {
tenderApprovals.add(existingApproval);
}
}
_tenderApprovalErrorMessage = result.error.toString();
break;
}
notifyListeners();
_tenderApprovalErrorMessage = null;
notifyListeners();