@@ -40,6 +40,9 @@ class SearchExpensesViewModel: BaseViewModel, ObservableObject {
40
40
self . router = router
41
41
super. init ( )
42
42
43
+ NotificationCenter . default. addObserver ( self , selector: #selector( handleUpdateExpense ( notification: ) ) , name: . updateExpense, object: nil )
44
+ NotificationCenter . default. addObserver ( self , selector: #selector( handleDeleteExpense ( notification: ) ) , name: . deleteExpense, object: nil )
45
+
43
46
fetchInitialExpenses ( )
44
47
}
45
48
@@ -152,8 +155,42 @@ class SearchExpensesViewModel: BaseViewModel, ObservableObject {
152
155
}
153
156
154
157
// MARK: - User Actions
155
- func handleExpenseItemTap( expenseId: String ) {
156
- // router.push(.ExpenseDetailView(groupId: groupId, expenseId: expenseId))
158
+ func handleExpenseItemTap( expense: Expense ) {
159
+ if let groupId = expense. groupId, let expenseId = expense. id {
160
+ router. push ( . ExpenseDetailView( groupId: groupId, expenseId: expenseId) )
161
+ }
162
+ }
163
+
164
+ @objc func handleUpdateExpense( notification: Notification ) {
165
+ guard var updatedExpense = notification. object as? Expense else { return }
166
+
167
+ if let index = expenses. firstIndex ( where: { $0. id == updatedExpense. id } ) {
168
+ expenses [ index] = updatedExpense
169
+ }
170
+
171
+ Task { [ weak self] in
172
+ if let user = await self ? . fetchMemberData ( for: updatedExpense. paidBy. keys. first ?? " " ) {
173
+ if let index = self ? . expensesWithUser. firstIndex ( where: { $0. expense. id == updatedExpense. id } ) {
174
+ let updatedExpenseWithUser = ExpenseWithUser ( expense: updatedExpense, user: user)
175
+ withAnimation {
176
+ self ? . expensesWithUser [ index] = updatedExpenseWithUser
177
+ self ? . updateGroupExpenses ( )
178
+ }
179
+ }
180
+ }
181
+ }
182
+ }
183
+
184
+ @objc func handleDeleteExpense( notification: Notification ) {
185
+ guard let deletedExpense = notification. object as? Expense else { return }
186
+ expenses. removeAll { $0. id == deletedExpense. id }
187
+ if let index = expensesWithUser. firstIndex ( where: { $0. expense. id == deletedExpense. id } ) {
188
+ withAnimation {
189
+ expensesWithUser. remove ( at: index)
190
+ updateGroupExpenses ( )
191
+ showToastFor ( toast: . init( type: . success, title: " Success " , message: " Expense deleted successfully. " ) )
192
+ }
193
+ }
157
194
}
158
195
159
196
// MARK: - Error Handling
0 commit comments