Skip to content

Commit

Permalink
Removed unnecessary param from commentRepo,changed csv file name
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-nirali-s committed Jan 17, 2025
1 parent 71feb02 commit 1e316ad
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 50 deletions.
24 changes: 7 additions & 17 deletions Data/Data/Repository/CommentRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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] = []
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions Data/Data/Store/ExpenseStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down
6 changes: 4 additions & 2 deletions Data/Data/Store/TransactionStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions Splito/UI/Home/Groups/Group/GroupHomeViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
48 changes: 26 additions & 22 deletions Splito/UI/Home/Groups/Group/GroupHomeViewModelExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,75 +78,80 @@ 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)
}
completion(true)
} catch {
LogE("GroupHomeViewModel: \(#function) Failed to fetch Expenses/payments: \(error).")
showToastForError()
self.showToastForError()
completion(false)
}
}
}

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 {
let date = payment.date.dateValue().numericDate
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 }) {
Expand All @@ -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 {
Expand Down

0 comments on commit 1e316ad

Please sign in to comment.