Skip to content

Commit

Permalink
added setting page and income distribution loggic but its now working…
Browse files Browse the repository at this point in the history
… like we planned
  • Loading branch information
yashkite committed Nov 6, 2024
1 parent fc4149e commit 1fa18bc
Show file tree
Hide file tree
Showing 9 changed files with 514 additions and 22 deletions.
3 changes: 3 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
<activity
android:name=".ui.about.AboutActivity"
android:theme="@style/Theme.UMoney.NoActionBar" />
<activity
android:name=".ui.settings.SettingsActivity"
android:theme="@style/Theme.UMoney.NoActionBar" />
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class Transaction {
private String userId;
private String notes;
private String attachmentUri;
private String parentTransactionId;

// Required for Firestore
public Transaction() {}
Expand Down Expand Up @@ -96,4 +97,12 @@ public String getAttachmentUri() {
public void setAttachmentUri(String attachmentUri) {
this.attachmentUri = attachmentUri;
}

public String getParentTransactionId() {
return parentTransactionId;
}

public void setParentTransactionId(String parentTransactionId) {
this.parentTransactionId = parentTransactionId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.elececo.umoney.data.model;
public class UserPreferences {
private int needsPercentage;
private int wantsPercentage;
private int savingsPercentage;

public UserPreferences(int needsPercentage, int wantsPercentage, int savingsPercentage) {
this.needsPercentage = needsPercentage;
this.wantsPercentage = wantsPercentage;
this.savingsPercentage = savingsPercentage;
}

public int getNeedsPercentage() { return needsPercentage; }
public int getWantsPercentage() { return wantsPercentage; }
public int getSavingsPercentage() { return savingsPercentage; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.elececo.umoney.ui.auth.GoogleLoginActivity;
import com.elececo.umoney.ui.dashboard.fragments.DashboardFragment;
import com.elececo.umoney.ui.needs.NeedsFragment;
import com.elececo.umoney.ui.settings.SettingsActivity;
import com.elececo.umoney.ui.wants.WantsFragment;
import com.elececo.umoney.ui.savings.SavingsFragment;
import com.elececo.umoney.ui.income.IncomeFragment;
Expand Down Expand Up @@ -112,7 +113,7 @@ public boolean onNavigationItemSelected(@NonNull MenuItem item) {
} else if (itemId == R.id.nav_about) {
startActivity(new Intent(this, AboutActivity.class));
} else if (itemId == R.id.nav_settings) {
// TODO: Navigate to Settings
startActivity(new Intent(this, SettingsActivity.class));
} else if (itemId == R.id.nav_categories) {
// TODO: Navigate to Categories
} else if (itemId == R.id.nav_logout) {
Expand Down
56 changes: 43 additions & 13 deletions app/src/main/java/com/elececo/umoney/ui/income/IncomeFragment.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
import android.app.Activity;
import android.content.Intent;
import androidx.annotation.Nullable;
import com.elececo.umoney.data.model.UserPreferences;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import com.elececo.umoney.ui.common.TransactionEntryDialog;
import java.util.List;

public class IncomeFragment extends BaseFragment<IncomeViewModel> implements TransactionEntryDialog.TransactionEntryListener {
private static final int PICK_FILE_REQUEST = 1;
Expand All @@ -47,27 +49,55 @@ protected void setupObservers() {
viewModel.getTransactions().observe(getViewLifecycleOwner(), transactions -> {
adapter.setTransactions(transactions);

// Update summary card
double inAmount = 0;
double outAmount = 0;
for (Transaction transaction : transactions) {
if (transaction.getAmount() > 0) {
inAmount += transaction.getAmount();
} else {
outAmount += Math.abs(transaction.getAmount());
}
}
final double finalInAmount = calculateInAmount(transactions);
final double finalOutAmount = calculateOutAmount(transactions);
final double finalTotalIncome = finalInAmount - finalOutAmount;

TextView inAmountView = requireView().findViewById(R.id.in_amount);
TextView outAmountView = requireView().findViewById(R.id.out_amount);
TextView holdAmountView = requireView().findViewById(R.id.hold_amount);

inAmountView.setText(String.format("In: ₹%.2f", inAmount));
outAmountView.setText(String.format("Out: ₹%.2f", outAmount));
holdAmountView.setText(String.format("Hold: ₹%.2f", inAmount - outAmount));
inAmountView.setText(String.format("In: ₹%.2f", finalInAmount));
outAmountView.setText(String.format("Out: ₹%.2f", finalOutAmount));
holdAmountView.setText(String.format("Hold: ₹%.2f", finalTotalIncome));

viewModel.getUserPreferences().observe(getViewLifecycleOwner(), preferences -> {
double needsPercentage = preferences.getNeedsPercentage() / 100.0;
double wantsPercentage = preferences.getWantsPercentage() / 100.0;
double savingsPercentage = preferences.getSavingsPercentage() / 100.0;

double needsAmount = finalTotalIncome * needsPercentage;
double wantsAmount = finalTotalIncome * wantsPercentage;
double savingsAmount = finalTotalIncome * savingsPercentage;

TextView needsPercentageView = requireView().findViewById(R.id.needs_percentage);
TextView wantsPercentageView = requireView().findViewById(R.id.wants_percentage);
TextView savingsPercentageView = requireView().findViewById(R.id.savings_percentage);

needsPercentageView.setText(String.format("Needs (%d%%): ₹%.2f",
preferences.getNeedsPercentage(), needsAmount));
wantsPercentageView.setText(String.format("Wants (%d%%): ₹%.2f",
preferences.getWantsPercentage(), wantsAmount));
savingsPercentageView.setText(String.format("Savings (%d%%): ₹%.2f",
preferences.getSavingsPercentage(), savingsAmount));
});
});
}

private double calculateInAmount(List<Transaction> transactions) {
return transactions.stream()
.filter(transaction -> transaction.getAmount() > 0)
.mapToDouble(Transaction::getAmount)
.sum();
}

private double calculateOutAmount(List<Transaction> transactions) {
return transactions.stream()
.filter(transaction -> transaction.getAmount() < 0)
.mapToDouble(transaction -> Math.abs(transaction.getAmount()))
.sum();
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,185 @@
package com.elececo.umoney.ui.income.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.elececo.umoney.data.model.Transaction;
import com.elececo.umoney.data.repository.TransactionRepository;
import com.elececo.umoney.data.model.UserPreferences;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class IncomeViewModel extends ViewModel {
private final TransactionRepository repository;
private final LiveData<List<Transaction>> transactions;
private final FirebaseFirestore db;
private final FirebaseAuth auth;
private final MutableLiveData<List<Transaction>> transactions;
private final MutableLiveData<UserPreferences> userPreferences;

public IncomeViewModel() {
repository = new TransactionRepository();
transactions = repository.getTransactionsByType("INCOME");
db = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
transactions = new MutableLiveData<>(new ArrayList<>());
userPreferences = new MutableLiveData<>();
loadTransactions();
loadUserPreferences();
}

public LiveData<List<Transaction>> getTransactions() {
return transactions;
}

public LiveData<UserPreferences> getUserPreferences() {
return userPreferences;
}

private void loadTransactions() {
String userId = auth.getCurrentUser().getUid();
db.collection("users")
.document(userId)
.collection("transactions")
.whereEqualTo("type", "INCOME")
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
List<Transaction> transactionList = new ArrayList<>();
for (QueryDocumentSnapshot document : queryDocumentSnapshots) {
Transaction transaction = document.toObject(Transaction.class);
transactionList.add(transaction);
}
transactions.setValue(transactionList);
});
}

private void loadUserPreferences() {
String userId = auth.getCurrentUser().getUid();
db.collection("users")
.document(userId)
.get()
.addOnSuccessListener(document -> {
if (document.exists()) {
Map<String, Object> data = document.getData();
int needs = data.containsKey("needsPercentage") ?
((Long) data.get("needsPercentage")).intValue() : 50;
int wants = data.containsKey("wantsPercentage") ?
((Long) data.get("wantsPercentage")).intValue() : 30;
int savings = data.containsKey("savingsPercentage") ?
((Long) data.get("savingsPercentage")).intValue() : 20;

userPreferences.setValue(new UserPreferences(needs, wants, savings));
} else {
userPreferences.setValue(new UserPreferences(50, 30, 20));
}
})
.addOnFailureListener(e -> {
userPreferences.setValue(new UserPreferences(50, 30, 20));
});
}

public void distributeIncome(double totalIncome, UserPreferences preferences, String parentTransactionId) {
String userId = auth.getCurrentUser().getUid();

// Calculate amounts for each category
double needsAmount = totalIncome * (preferences.getNeedsPercentage() / 100.0);
double wantsAmount = totalIncome * (preferences.getWantsPercentage() / 100.0);
double savingsAmount = totalIncome * (preferences.getSavingsPercentage() / 100.0);

Date currentTime = new Date();

// Create distributed transactions
Transaction needsTransaction = new Transaction();
needsTransaction.setAmount(needsAmount);
needsTransaction.setNotes("Auto-distributed from Income");
needsTransaction.setCategory("NEEDS");
needsTransaction.setType("INCOME");
needsTransaction.setTimestamp(currentTime);
needsTransaction.setParentTransactionId(parentTransactionId);
needsTransaction.setUserId(userId);

Transaction wantsTransaction = new Transaction();
wantsTransaction.setAmount(wantsAmount);
wantsTransaction.setNotes("Auto-distributed from Income");
wantsTransaction.setCategory("WANTS");
wantsTransaction.setType("INCOME");
wantsTransaction.setTimestamp(currentTime);
wantsTransaction.setParentTransactionId(parentTransactionId);
wantsTransaction.setUserId(userId);

Transaction savingsTransaction = new Transaction();
savingsTransaction.setAmount(savingsAmount);
savingsTransaction.setNotes("Auto-distributed from Income");
savingsTransaction.setCategory("SAVINGS");
savingsTransaction.setType("INCOME");
savingsTransaction.setTimestamp(currentTime);
savingsTransaction.setParentTransactionId(parentTransactionId);
savingsTransaction.setUserId(userId);

// Save all transactions
db.collection("users")
.document(userId)
.collection("transactions")
.add(needsTransaction);

db.collection("users")
.document(userId)
.collection("transactions")
.add(wantsTransaction);

db.collection("users")
.document(userId)
.collection("transactions")
.add(savingsTransaction);
}

public void saveTransaction(Transaction transaction) {
repository.saveTransaction(transaction);
String userId = auth.getCurrentUser().getUid();
db.collection("users")
.document(userId)
.collection("transactions")
.add(transaction)
.addOnSuccessListener(documentReference -> {
String transactionId = documentReference.getId();
transaction.setId(transactionId);
loadTransactions();
// After saving income transaction, distribute it
if (transaction.getType().equals("INCOME")) {
getUserPreferences().observeForever(preferences -> {
distributeIncome(transaction.getAmount(), preferences, transactionId);
});
}
});
}

public LiveData<List<Transaction>> getTransactions() {
return transactions;
public void updateDistributedTransactions(String parentTransactionId, double newAmount, UserPreferences preferences) {
String userId = auth.getCurrentUser().getUid();

db.collection("users")
.document(userId)
.collection("transactions")
.whereEqualTo("parentTransactionId", parentTransactionId)
.get()
.addOnSuccessListener(querySnapshot -> {
double needsAmount = newAmount * (preferences.getNeedsPercentage() / 100.0);
double wantsAmount = newAmount * (preferences.getWantsPercentage() / 100.0);
double savingsAmount = newAmount * (preferences.getSavingsPercentage() / 100.0);

for (QueryDocumentSnapshot document : querySnapshot) {
Transaction transaction = document.toObject(Transaction.class);
switch (transaction.getType()) {
case "NEEDS":
transaction.setAmount(needsAmount);
break;
case "WANTS":
transaction.setAmount(wantsAmount);
break;
case "SAVINGS":
transaction.setAmount(savingsAmount);
break;
}
document.getReference().set(transaction);
}
});
}
}
Loading

0 comments on commit 1fa18bc

Please sign in to comment.