Skip to content

Commit

Permalink
Refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-nirali-s committed Nov 21, 2024
1 parent ac303a0 commit 46a5e39
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 30 deletions.
21 changes: 12 additions & 9 deletions Data/Data/Repository/ExpenseRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,20 @@ public class ExpenseRepository: ObservableObject {
@Inject private var activityLogRepository: ActivityLogRepository

public func addExpense(group: Groups, expense: Expense, imageData: Data?) async throws -> Expense {
var newExpense = try await store.addExpense(groupId: group.id ?? "", expense: expense)
// Generate a new document ID for the expense
let documentRef = store.expenseReference(groupId: group.id ?? "").document()
let expenseId = documentRef.documentID

var newExpense = expense
newExpense.id = expenseId

// If image data is provided, upload the image and update the expense's imageUrl
if let imageData = imageData {
let imageUrl = try await uploadImage(imageData: imageData, expense: newExpense)
newExpense.imageUrl = imageUrl

try await store.updateExpense(groupId: group.id ?? "", expense: newExpense)
}

try await store.addExpense(documentRef: documentRef, expense: newExpense)
try await addActivityLogForExpense(group: group, expense: newExpense, oldExpense: newExpense, type: .expenseAdded)
return newExpense
}
Expand All @@ -38,15 +42,14 @@ public class ExpenseRepository: ObservableObject {
try await updateExpense(group: group, expense: updatedExpense, oldExpense: expense, type: .expenseDeleted)
}

public func updateExpenseWithImage(imageData: Data?, newImageUrl: String?, group: Groups, expense: Expense, oldExpense: Expense, type: ActivityType) async throws -> Expense {
var updatedExpense = expense
public func updateExpenseWithImage(imageData: Data?, newImageUrl: String?, group: Groups, expense: (new: Expense, old: Expense), type: ActivityType) async throws -> Expense {
var updatedExpense = expense.new

// If image data is provided, upload the new image and update the imageUrl
if let imageData {
// Upload the image and get the new image URL
let uploadedImageUrl = try await uploadImage(imageData: imageData, expense: updatedExpense)
updatedExpense.imageUrl = uploadedImageUrl
} else if let currentUrl = group.imageUrl, newImageUrl == nil {
} else if let currentUrl = updatedExpense.imageUrl, newImageUrl == nil {
// If there's a current image URL and we want to remove it, delete the image and set imageUrl to nil
try await storageManager.deleteImage(imageUrl: currentUrl)
updatedExpense.imageUrl = nil
Expand All @@ -55,8 +58,8 @@ public class ExpenseRepository: ObservableObject {
updatedExpense.imageUrl = newImageUrl
}

guard hasExpenseChanged(updatedExpense, oldExpense: oldExpense) else { return updatedExpense }
try await updateExpense(group: group, expense: updatedExpense, oldExpense: oldExpense, type: type)
guard hasExpenseChanged(updatedExpense, oldExpense: expense.old) else { return updatedExpense }
try await updateExpense(group: group, expense: updatedExpense, oldExpense: expense.old, type: type)
return updatedExpense
}

Expand Down
15 changes: 10 additions & 5 deletions Data/Data/Repository/GroupRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,20 +189,25 @@ public class GroupRepository: ObservableObject {
}

public func fetchMemberBy(userId: String) async throws -> AppUser? {
// Read from groupMembers safely
// Use a synchronous read to check if the member already exists in groupMembers
let existingMember = groupMembersQueue.sync { groupMembers.first(where: { $0.id == userId }) }

if let existingMember {
return existingMember // Return the available member from groupMembers
} else {
let member = try await userRepository.fetchUserBy(userID: userId)
if let member {
}

let member = try await userRepository.fetchUserBy(userID: userId)

// Append to groupMembers safely with a barrier, ensuring thread safety
if let member {
try await withCheckedThrowingContinuation { continuation in
groupMembersQueue.async(flags: .barrier) {
self.groupMembers.append(member)
continuation.resume() // Resume after append is complete
}
}
return member
}
return member
}

public func fetchMembersBy(memberIds: [String]) async throws -> [AppUser] {
Expand Down
12 changes: 3 additions & 9 deletions Data/Data/Store/ExpenseStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,15 @@ public class ExpenseStore: ObservableObject {
private let COLLECTION_NAME: String = "groups"
private let SUB_COLLECTION_NAME: String = "expenses"

private func expenseReference(groupId: String) -> CollectionReference {
func expenseReference(groupId: String) -> CollectionReference {
database
.collection(COLLECTION_NAME)
.document(groupId)
.collection(SUB_COLLECTION_NAME)
}

func addExpense(groupId: String, expense: Expense) async throws -> Expense {
let documentRef = expenseReference(groupId: groupId).document()

var newExpense = expense
newExpense.id = documentRef.documentID

try documentRef.setData(from: newExpense)
return newExpense
func addExpense(documentRef: DocumentReference, expense: Expense) async throws {
try documentRef.setData(from: expense)
}

func updateExpense(groupId: String, expense: Expense) async throws {
Expand Down
6 changes: 3 additions & 3 deletions Splito/UI/Home/Expense/AddExpenseView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ private struct ExpenseInfoView: View {
ExpenseDetailRow(name: $viewModel.expenseName, focusedField: focusedField, subtitle: "Paid by",
inputValue: viewModel.payerName, onTap: viewModel.handlePayerBtnAction)

ExpenseDetailRow(name: $viewModel.expenseName, focusedField: focusedField, subtitle: "Spilt option",
ExpenseDetailRow(name: $viewModel.expenseName, focusedField: focusedField, subtitle: "Split option",
inputValue: viewModel.splitType == .equally ? "Equally" : "Unequally",
onTap: viewModel.handleSplitTypeBtnAction)
}
Expand Down Expand Up @@ -221,7 +221,7 @@ private struct BottomCardView: View {

DatePickerView(date: $date)

ExpenseImagePickerButton(image: expenseImage, imageUrl: expenseImageUrl, handleImageBtnTap: handleExpenseImageTap)
ExpenseImagePickerView(image: expenseImage, imageUrl: expenseImageUrl, handleImageBtnTap: handleExpenseImageTap)
}
.padding(.vertical, 12)
.padding(.horizontal, 16)
Expand Down Expand Up @@ -315,7 +315,7 @@ private struct DateDisplayView: View {
}
}

private struct ExpenseImagePickerButton: View {
private struct ExpenseImagePickerView: View {

let image: UIImage?
let imageUrl: String?
Expand Down
6 changes: 4 additions & 2 deletions Splito/UI/Home/Expense/AddExpenseViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,9 @@ extension AddExpenseViewModel {
case .restricted, .denied:
showAlertFor(alert: .init(title: "Important!", message: "Camera access is required to take picture for your profile",
positiveBtnTitle: "Allow", positiveBtnAction: { [weak self] in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsURL)
}
self?.showAlert = false
}))
case .authorized:
Expand Down Expand Up @@ -415,7 +417,7 @@ extension AddExpenseViewModel {
showLoader = true

let updatedExpense = try await expenseRepository.updateExpenseWithImage(imageData: imageData, newImageUrl: expenseImageUrl,
group: group, expense: expense, oldExpense: oldExpense, type: .expenseUpdated)
group: group, expense: (expense, oldExpense), type: .expenseUpdated)
NotificationCenter.default.post(name: .updateExpense, object: updatedExpense)

guard hasExpenseChanged(updatedExpense, oldExpense: oldExpense) else { return true }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct ExpenseSplitOptionsView: View {
var body: some View {
VStack(spacing: 0) {
NavigationBarTopView(
title: "Spilt options",
title: "Split options",
leadingButton: {
DismissButton(iconSize: (22, .regular), padding: (16, 0),
foregroundColor: primaryText, onDismissAction: { dismiss() })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ class CreateGroupViewModel: BaseViewModel, ObservableObject {
case .restricted, .denied:
showAlertFor(alert: .init(title: "Important!", message: "Camera access is required to take picture for your profile",
positiveBtnTitle: "Allow", positiveBtnAction: { [weak self] in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsURL)
}
self?.showAlert = false
}))
case .authorized:
Expand Down

0 comments on commit 46a5e39

Please sign in to comment.