From 1e316ad340ce12b538700641e28315beaa5dce30 Mon Sep 17 00:00:00 2001 From: Nirali Canopas Date: Fri, 17 Jan 2025 12:51:54 +0530 Subject: [PATCH] Removed unnecessary param from commentRepo,changed csv file name --- Data/Data/Repository/CommentRepository.swift | 24 +++------- Data/Data/Store/ExpenseStore.swift | 6 ++- Data/Data/Store/TransactionStore.swift | 6 ++- .../GroupTransactionDetailViewModel.swift | 7 +-- .../Groups/Group/GroupHomeViewModel.swift | 4 +- .../Group/GroupHomeViewModelExtension.swift | 48 ++++++++++--------- 6 files changed, 45 insertions(+), 50 deletions(-) diff --git a/Data/Data/Repository/CommentRepository.swift b/Data/Data/Repository/CommentRepository.swift index 18d20476..ed1c59a5 100644 --- a/Data/Data/Repository/CommentRepository.swift +++ b/Data/Data/Repository/CommentRepository.swift @@ -14,8 +14,7 @@ public class CommentRepository { @Inject private var activityLogRepository: ActivityLogRepository public func addComment(group: Groups, expense: Expense? = nil, transaction: Transactions? = nil, - members: (payer: AppUser, receiver: AppUser)? = nil, comment: Comment, - existingCommenterIds: [String]) async throws -> Comment? { + comment: Comment, existingCommenterIds: [String]) async throws -> Comment? { guard let groupId = group.id else { return nil } let addedComment = try await store.addComment(groupId: groupId, @@ -24,14 +23,13 @@ public class CommentRepository { try await addActivityLogsInParallel(group: group, expense: expense, transaction: transaction, comment: comment.comment, - existingCommenterIds: existingCommenterIds, members: members) + existingCommenterIds: existingCommenterIds) return addedComment } /// Add activity logs for all involved users asynchronously and in parallel private func addActivityLogsInParallel(group: Groups, expense: Expense? = nil, transaction: Transactions? = nil, - comment: String, existingCommenterIds: [String], - members: (payer: AppUser, receiver: AppUser)? = nil) async throws { + comment: String, existingCommenterIds: [String]) async throws { guard let user = preference.user else { return } var errors: [Error] = [] @@ -43,7 +41,7 @@ public class CommentRepository { taskGroup.addTask { [weak self] in guard let self else { return nil } let context = createActivityLogContext(expense: expense, transaction: transaction, group: group, - comment: comment, memberId: memberId, members: members) + comment: comment, memberId: memberId) return await self.addActivityLog(context: context) } } @@ -82,25 +80,17 @@ public class CommentRepository { /// Create ActivityLogContext for expense or transaction private func createActivityLogContext(expense: Expense? = nil, transaction: Transactions? = nil, - group: Groups, comment: String, memberId: String, - members: (payer: AppUser, receiver: AppUser)? = nil) -> ActivityLogContext? { + group: Groups, comment: String, memberId: String) -> ActivityLogContext? { guard let user = preference.user else { return nil } var context: ActivityLogContext? if let expense { context = ActivityLogContext(group: group, expense: expense, comment: comment, type: .expenseCommentAdded, memberId: memberId, currentUser: user) - } else if let transaction, let members { - let payerName = (user.id == transaction.payerId && memberId == transaction.payerId) ? - (user.id == transaction.addedBy ? "You" : "you") : - (memberId == transaction.payerId) ? "you" : members.payer.nameWithLastInitial - - let receiverName = (memberId == transaction.receiverId) ? "you" : (memberId == transaction.receiverId) ? "you" : members.receiver.nameWithLastInitial - + } else if let transaction { context = ActivityLogContext(group: group, transaction: transaction, comment: comment, type: .transactionCommentAdded, memberId: memberId, - currentUser: user, payerName: payerName, receiverName: receiverName, - paymentReason: transaction.reason) + currentUser: user, paymentReason: transaction.reason) } return context diff --git a/Data/Data/Store/ExpenseStore.swift b/Data/Data/Store/ExpenseStore.swift index 858ee951..f283b7cb 100644 --- a/Data/Data/Store/ExpenseStore.swift +++ b/Data/Data/Store/ExpenseStore.swift @@ -76,10 +76,12 @@ public class ExpenseStore: ObservableObject { try document.data(as: Expense.self) } } else { - return try await expenseReference(groupId: groupId) + let query = expenseReference(groupId: groupId) .whereField("is_active", isEqualTo: true) .order(by: "date", descending: true) - .getDocuments(as: Expense.self).data + return try await query.getDocuments(source: .server).documents.map { + try $0.data(as: Expense.self) + } } } diff --git a/Data/Data/Store/TransactionStore.swift b/Data/Data/Store/TransactionStore.swift index 4dd19dfc..81aa307f 100644 --- a/Data/Data/Store/TransactionStore.swift +++ b/Data/Data/Store/TransactionStore.swift @@ -72,10 +72,12 @@ public class TransactionStore: ObservableObject { try document.data(as: Transactions.self) } } else { - return try await transactionReference(groupId: groupId) + let query = transactionReference(groupId: groupId) .whereField("is_active", isEqualTo: true) .order(by: "date", descending: true) - .getDocuments(as: Transactions.self).data + return try await query.getDocuments(source: .server).documents.map { + try $0.data(as: Transactions.self) + } } } diff --git a/Splito/UI/Home/Groups/Group/Group Options/Settlements/Transaction Detail/GroupTransactionDetailViewModel.swift b/Splito/UI/Home/Groups/Group/Group Options/Settlements/Transaction Detail/GroupTransactionDetailViewModel.swift index 8a8b5cfa..e5ff0989 100644 --- a/Splito/UI/Home/Groups/Group/Group Options/Settlements/Transaction Detail/GroupTransactionDetailViewModel.swift +++ b/Splito/UI/Home/Groups/Group/Group Options/Settlements/Transaction Detail/GroupTransactionDetailViewModel.swift @@ -198,9 +198,7 @@ class GroupTransactionDetailViewModel: BaseViewModel, ObservableObject { } private func addComment() { - guard let transaction, let group, let transactionId = transaction.id, let userId = preference.user?.id, - let payer = transactionUsersData.first(where: { $0.id == transaction.payerId }), - let receiver = transactionUsersData.first(where: { $0.id == transaction.receiverId }) else { + guard let transaction, let group, let transactionId = transaction.id, let userId = preference.user?.id else { LogE("GroupTransactionDetailViewModel: \(#function) Missing required data for adding comment.") return } @@ -212,8 +210,7 @@ class GroupTransactionDetailViewModel: BaseViewModel, ObservableObject { let comment = Comment(parentId: transactionId, comment: self.comment.trimming(spaces: .leadingAndTrailing), commentedBy: userId) - let addedComment = try await self.commentRepository.addComment(group: group, transaction: transaction, - members: (payer, receiver), comment: comment, + let addedComment = try await self.commentRepository.addComment(group: group, transaction: transaction, comment: comment, existingCommenterIds: self.comments.map { $0.commentedBy }) if let addedComment { diff --git a/Splito/UI/Home/Groups/Group/GroupHomeViewModel.swift b/Splito/UI/Home/Groups/Group/GroupHomeViewModel.swift index 2d4bf737..38175afb 100644 --- a/Splito/UI/Home/Groups/Group/GroupHomeViewModel.swift +++ b/Splito/UI/Home/Groups/Group/GroupHomeViewModel.swift @@ -22,7 +22,7 @@ class GroupHomeViewModel: BaseViewModel, ObservableObject { @Published var group: Groups? @Published var generatedReportURL: URL? @Published private(set) var groupId: String - + @Published var transactionsCount: Int = 0 @Published private(set) var overallOwingAmount: Double = 0.0 @Published private(set) var currentMonthSpending: Double = 0.0 @@ -33,7 +33,7 @@ class GroupHomeViewModel: BaseViewModel, ObservableObject { @Published var expensesWithUser: [ExpenseWithUser] = [] @Published private(set) var memberOwingAmount: [String: Double] = [:] @Published private(set) var groupExpenses: [String: [ExpenseWithUser]] = [:] - + @Published var showSearchBar = false @Published var showShareSheet = false @Published var showSettleUpSheet = false diff --git a/Splito/UI/Home/Groups/Group/GroupHomeViewModelExtension.swift b/Splito/UI/Home/Groups/Group/GroupHomeViewModelExtension.swift index b94438c7..cc95edc0 100644 --- a/Splito/UI/Home/Groups/Group/GroupHomeViewModelExtension.swift +++ b/Splito/UI/Home/Groups/Group/GroupHomeViewModelExtension.swift @@ -78,14 +78,19 @@ extension GroupHomeViewModel { startDate = nil } - Task { + Task { [weak self] in + guard let self else { return } do { - let expenses = try await expenseRepository.fetchExpenses(groupId: groupId, startDate: startDate, endDate: today) - let transactions = try await transactionRepository.fetchTransactions(groupId: groupId, startDate: startDate, endDate: today) - print("xxx \(expenses.count) \(transactions.count)") + let expenses = try await self.expenseRepository.fetchExpenses(groupId: self.groupId, startDate: startDate, endDate: today) + let transactions = try await self.transactionRepository.fetchTransactions(groupId: self.groupId, startDate: startDate, endDate: today) LogD("GroupHomeViewModel: \(#function) Expenses/payments fetched successfully.") - if let reportURL = generateCSVReport(expenses: expenses, payments: transactions) { - self.generatedReportURL = reportURL // Store the file URL + guard !expenses.isEmpty && !transactions.isEmpty else { + self.showToastFor(toast: ToastPrompt(type: .info, title: "No Data", message: "Expenses and settlements not found for the selected period.")) + completion(false) + return + } + if let reportURL = self.generateCSVReport(expenses: expenses, payments: transactions) { + self.generatedReportURL = reportURL // Store the file URL completion(true) } else { completion(false) @@ -93,7 +98,7 @@ extension GroupHomeViewModel { completion(true) } catch { LogE("GroupHomeViewModel: \(#function) Failed to fetch Expenses/payments: \(error).") - showToastForError() + self.showToastForError() completion(false) } } @@ -101,30 +106,30 @@ extension GroupHomeViewModel { func generateCSVReport(expenses: [Expense], payments: [Transactions]) -> URL? { guard let group else { return nil } - + var csvContent = "" // Add Expenses Section csvContent += "Expenses\n" - + let memberNames = group.members.map { getMemberDataBy(id: $0)?.nameWithLastInitial ?? "Unknown" } let header = "Date, Description, Category, Cost, Currency, \(memberNames.joined(separator: ", "))\n\n" csvContent += header - + for expense in expenses { let date = expense.date.dateValue().numericDate var expenseRow = "\(date), \(expense.name), \(expense.category ?? "General"), \(expense.amount), \(expense.currencyCode ?? "INR")" - + // Add owe amounts for each group member for member in group.members { let oweAmount = expense.getCalculatedSplitAmountOf(member: member) expenseRow += ", \(oweAmount)" } - + csvContent += expenseRow + "\n" } csvContent += "\n" - + // Add Settlements Section csvContent += "Settlements\n" for payment in payments { @@ -132,21 +137,21 @@ extension GroupHomeViewModel { let payer = getMemberDataBy(id: payment.payerId)?.nameWithLastInitial ?? "Unknown" let receiver = getMemberDataBy(id: payment.receiverId)?.nameWithLastInitial ?? "Unknown" var paymentRow = "\(date), \(payer) paid \(receiver), Payment, \(payment.amount), INR" - + // Add owe amounts for each group member for member in group.members { let amount = member == payment.payerId ? payment.amount : (member == payment.receiverId) ? -payment.amount : 0.00 paymentRow += ", \(amount)" } - + csvContent += paymentRow + "\n" } csvContent += "\n" - + // Add Total balance Section - let date = Date().numericDate - csvContent += "\(date), Total balance, , , INR" - + let date = Date() + csvContent += "\(date.numericDate), Total balance, , , INR" + for member in group.members { // Find the balance for the current member if let memberBalance = group.balances.first(where: { $0.id == member }) { @@ -157,10 +162,9 @@ extension GroupHomeViewModel { } // Save the file to the temporary directory - let fileName = "Group_Report.csv" - let filePath = FileManager.default.temporaryDirectory.appendingPathComponent(fileName) - do { + let fileName = "Splito group report \(date.shortDate).csv" + let filePath = FileManager.default.temporaryDirectory.appendingPathComponent(fileName) try csvContent.write(to: filePath, atomically: true, encoding: .utf8) return filePath } catch {