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 28, 2024
1 parent 1bb2728 commit 103db69
Show file tree
Hide file tree
Showing 11 changed files with 50 additions and 52 deletions.
2 changes: 1 addition & 1 deletion Data/Data/Model/Expense.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public struct Expense: Codable, Hashable, Identifiable {
public var splitData: [String: Double]? // Use this to store percentage or share data
public var isActive: Bool

public init(name: String, amount: Double, date: Timestamp, updatedAt: Timestamp, paidBy: [String: Double],
public init(name: String, amount: Double, date: Timestamp, updatedAt: Timestamp = Timestamp(), paidBy: [String: Double],
addedBy: String, updatedBy: String, note: String? = nil, imageUrl: String? = nil, splitTo: [String],
splitType: SplitType = .equally, splitData: [String: Double]? = [:], isActive: Bool = true) {
self.name = name
Expand Down
2 changes: 1 addition & 1 deletion Data/Data/Model/Transaction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public struct Transactions: Codable, Hashable, Identifiable {
public var isActive: Bool

public init(payerId: String, receiverId: String, addedBy: String, updatedBy: String, note: String? = nil,
imageUrl: String? = nil, amount: Double, date: Timestamp, updatedAt: Timestamp, isActive: Bool = true) {
imageUrl: String? = nil, amount: Double, date: Timestamp, updatedAt: Timestamp = Timestamp(), isActive: Bool = true) {
self.payerId = payerId
self.receiverId = receiverId
self.addedBy = addedBy
Expand Down
4 changes: 2 additions & 2 deletions Data/Data/Repository/GroupRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ public class GroupRepository: ObservableObject {
let uploadedImageUrl = try await uploadImage(imageData: imageData, group: updatedGroup)
updatedGroup.imageUrl = uploadedImageUrl
} else if let currentUrl = group.imageUrl, newImageUrl == nil {
// If there's a current image URL and we want to remove it, delete the image and set imageUrl to nil
// If there's a current image URL and we want to remove it, delete the image and set imageUrl empty
try await storageManager.deleteImage(imageUrl: currentUrl)
updatedGroup.imageUrl = nil
updatedGroup.imageUrl = ""
} else if let newImageUrl = newImageUrl {
// If a new image URL is explicitly passed, update it
updatedGroup.imageUrl = newImageUrl
Expand Down
6 changes: 2 additions & 4 deletions Splito/UI/Home/Expense/AddExpenseView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,12 @@ struct AddExpenseView: View {
}
.sheet(isPresented: $viewModel.showAddNoteEditor) {
NavigationStack {
AddNoteView(viewModel: AddNoteViewModel(group: viewModel.selectedGroup, expense: viewModel.expense,
note: viewModel.expenseNote,
AddNoteView(viewModel: AddNoteViewModel(group: viewModel.selectedGroup, expense: viewModel.expense, note: viewModel.expenseNote,
handleSaveNoteTap: viewModel.handleNoteSaveBtnTap(note:)))
}
}
.sheet(isPresented: $viewModel.showImagePicker) {
ImagePickerView(cropOption: .square,
sourceType: !viewModel.sourceTypeIsCamera ? .photoLibrary : .camera,
ImagePickerView(cropOption: .square, sourceType: !viewModel.sourceTypeIsCamera ? .photoLibrary : .camera,
image: $viewModel.expenseImage, isPresented: $viewModel.showImagePicker)
}
.toolbar {
Expand Down
19 changes: 9 additions & 10 deletions Splito/UI/Home/Expense/AddExpenseViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ extension AddExpenseViewModel {

private func handleAddExpenseAction(userId: String, group: Groups) async -> Bool {
let expense = Expense(name: expenseName.trimming(spaces: .leadingAndTrailing), amount: expenseAmount,
date: Timestamp(date: expenseDate), updatedAt: Timestamp(), paidBy: selectedPayers,
date: Timestamp(date: expenseDate), paidBy: selectedPayers,
addedBy: userId, updatedBy: userId, note: expenseNote,
splitTo: (splitType == .equally) ? selectedMembers : splitData.map({ $0.key }),
splitType: splitType, splitData: splitData)
Expand All @@ -385,12 +385,9 @@ extension AddExpenseViewModel {
private func addExpense(group: Groups, expense: Expense) async -> Bool {
guard let groupId = group.id else { return false }

let resizedImage = expenseImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)

do {
showLoader = true
let newExpense = try await expenseRepository.addExpense(group: group, expense: expense, imageData: imageData)
let newExpense = try await expenseRepository.addExpense(group: group, expense: expense, imageData: getImageData())
let expenseInfo: [String: Any] = ["groupId": groupId, "expense": newExpense]
NotificationCenter.default.post(name: .addExpense, object: nil, userInfo: expenseInfo)

Expand Down Expand Up @@ -437,14 +434,10 @@ extension AddExpenseViewModel {
return false
}

let resizedImage = expenseImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)

do {
showLoader = true

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

guard hasExpenseChanged(updatedExpense, oldExpense: oldExpense) else { return true }
Expand All @@ -461,6 +454,12 @@ extension AddExpenseViewModel {
}
}

private func getImageData() -> Data? {
let resizedImage = expenseImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)
return imageData
}

private func hasExpenseChanged(_ expense: Expense, oldExpense: Expense) -> Bool {
return oldExpense.amount != expense.amount || oldExpense.paidBy != expense.paidBy ||
oldExpense.splitTo != expense.splitTo || oldExpense.splitType != expense.splitType ||
Expand Down
6 changes: 5 additions & 1 deletion Splito/UI/Home/Expense/Note/AddNoteViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class AddNoteViewModel: BaseViewModel, ObservableObject {
LogD("AddNoteViewModel: \(#function) Expense note updated successfully.")
return true
} catch {
showLoader = false
LogE("AddNoteViewModel: \(#function) Failed to update expense note: \(error).")
showToastForError()
return false
Expand All @@ -79,7 +80,10 @@ class AddNoteViewModel: BaseViewModel, ObservableObject {
do {
showLoader = true
let members = try await fetchMembers(payerId: payment.payerId, receiverId: payment.receiverId)
guard let members else { return false }
guard let members else {
showLoader = false
return false
}

var updatedPayment = payment
updatedPayment.note = note
Expand Down
3 changes: 1 addition & 2 deletions Splito/UI/Home/Groups/Create Group/CreateGroupView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ struct CreateGroupView: View {
}
}
.sheet(isPresented: $viewModel.showImagePicker) {
ImagePickerView(cropOption: .square,
sourceType: !viewModel.sourceTypeIsCamera ? .photoLibrary : .camera,
ImagePickerView(cropOption: .square, sourceType: !viewModel.sourceTypeIsCamera ? .photoLibrary : .camera,
image: $viewModel.profileImage, isPresented: $viewModel.showImagePicker)
}
}
Expand Down
17 changes: 8 additions & 9 deletions Splito/UI/Home/Groups/Create Group/CreateGroupViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,9 @@ class CreateGroupViewModel: BaseViewModel, ObservableObject {
let group = Groups(name: groupName.trimming(spaces: .leadingAndTrailing), createdBy: userId, updatedBy: userId, imageUrl: nil,
members: [userId], balances: [memberBalance], createdAt: Timestamp(), updatedAt: Timestamp())

let resizedImage = profileImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)

do {
showLoader = true
let group = try await groupRepository.createGroup(group: group, imageData: imageData)
let group = try await groupRepository.createGroup(group: group, imageData: getImageData())
NotificationCenter.default.post(name: .addGroup, object: group)

showLoader = false
Expand All @@ -130,13 +127,9 @@ class CreateGroupViewModel: BaseViewModel, ObservableObject {
newGroup.updatedBy = userId
newGroup.updatedAt = Timestamp()

let resizedImage = profileImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)

do {
self.showLoader = true
let updatedGroup = try await groupRepository.updateGroupWithImage(imageData: imageData, newImageUrl: profileImageUrl,
group: newGroup, oldGroupName: group.name)
let updatedGroup = try await groupRepository.updateGroupWithImage(imageData: getImageData(), newImageUrl: profileImageUrl, group: newGroup, oldGroupName: group.name)
NotificationCenter.default.post(name: .updateGroup, object: updatedGroup)

showLoader = false
Expand All @@ -149,6 +142,12 @@ class CreateGroupViewModel: BaseViewModel, ObservableObject {
return false
}
}

private func getImageData() -> Data? {
let resizedImage = profileImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)
return imageData
}
}

// MARK: - Image Picker Action sheet
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,12 @@ struct GroupPaymentView: View {
}
}
.sheet(isPresented: $viewModel.showImagePicker) {
ImagePickerView(cropOption: .square,
sourceType: !viewModel.sourceTypeIsCamera ? .photoLibrary : .camera,
ImagePickerView(cropOption: .square, sourceType: !viewModel.sourceTypeIsCamera ? .photoLibrary : .camera,
image: $viewModel.paymentImage, isPresented: $viewModel.showImagePicker)
}
.sheet(isPresented: $viewModel.showAddNoteEditor) {
NavigationStack {
AddNoteView(viewModel: AddNoteViewModel(group: viewModel.group, payment: viewModel.transaction,
note: viewModel.paymentNote,
AddNoteView(viewModel: AddNoteViewModel(group: viewModel.group, payment: viewModel.transaction, note: viewModel.paymentNote,
handleSaveNoteTap: viewModel.handleNoteSaveBtnTap(note:)))
}
}
Expand Down Expand Up @@ -193,9 +191,9 @@ struct DatePickerView: View {
VStack(spacing: 0) {
NavigationBarTopView(title: "Choose date", leadingButton: EmptyView(),
trailingButton: DismissButton(padding: (16, 0), foregroundColor: primaryText, onDismissAction: {
showDatePicker = false
})
.fontWeight(.regular)
showDatePicker = false
})
.fontWeight(.regular)
)
.padding(.leading, 16)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ class GroupPaymentViewModel: BaseViewModel, ObservableObject {
@Inject private var transactionRepository: TransactionRepository

@Published var amount: Double = 0
@Published var paymentNote: String = ""
@Published var paymentDate = Date()
@Published var paymentImage: UIImage?

@Published var paymentNote: String = ""
@Published private(set) var paymentImageUrl: String?

@Published var showImagePicker = false
Expand Down Expand Up @@ -240,7 +241,7 @@ class GroupPaymentViewModel: BaseViewModel, ObservableObject {
return await updateTransaction(transaction: newTransaction, oldTransaction: transaction)
} else {
let transaction = Transactions(payerId: payerId, receiverId: receiverId, addedBy: userId, updatedBy: userId,
note: paymentNote, amount: amount, date: .init(date: paymentDate), updatedAt: Timestamp())
note: paymentNote, amount: amount, date: .init(date: paymentDate))
return await addTransaction(transaction: transaction)
}
}
Expand All @@ -251,14 +252,11 @@ class GroupPaymentViewModel: BaseViewModel, ObservableObject {
return false
}

let resizedImage = paymentImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)

do {
showLoader = true

self.transaction = try await transactionRepository.addTransaction(group: group, transaction: transaction,
members: (payer, receiver), imageData: imageData)
members: (payer, receiver), imageData: getImageData())
NotificationCenter.default.post(name: .addTransaction, object: transaction)
await updateGroupMemberBalance(updateType: .Add)

Expand All @@ -280,13 +278,10 @@ class GroupPaymentViewModel: BaseViewModel, ObservableObject {
}
guard validateGroupMembers() else { return false }

let resizedImage = paymentImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)

do {
showLoader = true

self.transaction = try await transactionRepository.updateTransactionWithImage(imageData: imageData, newImageUrl: paymentImageUrl, group: group, transaction: (transaction, oldTransaction), members: (payer, receiver))
self.transaction = try await transactionRepository.updateTransactionWithImage(imageData: getImageData(), newImageUrl: paymentImageUrl, group: group, transaction: (transaction, oldTransaction), members: (payer, receiver))

defer {
NotificationCenter.default.post(name: .updateTransaction, object: self.transaction)
Expand All @@ -306,6 +301,12 @@ class GroupPaymentViewModel: BaseViewModel, ObservableObject {
}
}

private func getImageData() -> Data? {
let resizedImage = paymentImage?.aspectFittedToHeight(200)
let imageData = resizedImage?.jpegData(compressionQuality: 0.2)
return imageData
}

private func hasTransactionChanged(_ transaction: Transactions, oldTransaction: Transactions) -> Bool {
return oldTransaction.payerId != transaction.payerId || oldTransaction.receiverId != transaction.receiverId ||
oldTransaction.amount != transaction.amount || oldTransaction.isActive != transaction.isActive
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,6 @@ struct GroupTransactionDetailView: View {
)
}
}
.fullScreenCover(isPresented: $viewModel.showAddNoteEditor) {
NavigationStack {
AddNoteView(viewModel: AddNoteViewModel(group: viewModel.group, payment: viewModel.transaction, note: viewModel.paymentNote))
}
}
.toolbarRole(.editor)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Expand All @@ -106,6 +101,11 @@ struct GroupTransactionDetailView: View {
}
}
}
.fullScreenCover(isPresented: $viewModel.showAddNoteEditor) {
NavigationStack {
AddNoteView(viewModel: AddNoteViewModel(group: viewModel.group, payment: viewModel.transaction, note: viewModel.paymentNote))
}
}
.navigationDestination(isPresented: $showImageDisplayView) {
if let imageUrl = viewModel.transaction?.imageUrl {
ExpenseImageZoomView(imageUrl: imageUrl, animationNamespace: Namespace())
Expand Down

0 comments on commit 103db69

Please sign in to comment.