]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/account_summary/AccountSummaryFragment.java
bump androidx.constraintlayout library version
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / account_summary / AccountSummaryFragment.java
1 /*
2  * Copyright © 2024 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.account_summary;
19
20 import static net.ktnx.mobileledger.utils.Logger.debug;
21
22 import android.content.Context;
23 import android.os.Bundle;
24 import android.view.LayoutInflater;
25 import android.view.Menu;
26 import android.view.MenuInflater;
27 import android.view.MenuItem;
28 import android.view.View;
29 import android.view.ViewGroup;
30
31 import androidx.annotation.NonNull;
32 import androidx.annotation.Nullable;
33 import androidx.lifecycle.ViewModelProvider;
34 import androidx.recyclerview.widget.DividerItemDecoration;
35 import androidx.recyclerview.widget.LinearLayoutManager;
36 import androidx.recyclerview.widget.RecyclerView;
37 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
38
39 import net.ktnx.mobileledger.App;
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.GeneralBackgroundTasks;
42 import net.ktnx.mobileledger.databinding.AccountSummaryFragmentBinding;
43 import net.ktnx.mobileledger.db.AccountWithAmounts;
44 import net.ktnx.mobileledger.db.DB;
45 import net.ktnx.mobileledger.db.Profile;
46 import net.ktnx.mobileledger.model.AccountListItem;
47 import net.ktnx.mobileledger.model.Data;
48 import net.ktnx.mobileledger.model.LedgerAccount;
49 import net.ktnx.mobileledger.ui.FabManager;
50 import net.ktnx.mobileledger.ui.MainModel;
51 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
52 import net.ktnx.mobileledger.ui.activity.MainActivity;
53 import net.ktnx.mobileledger.utils.Colors;
54
55 import org.jetbrains.annotations.NotNull;
56
57 import java.util.ArrayList;
58 import java.util.HashMap;
59 import java.util.List;
60
61 public class AccountSummaryFragment extends MobileLedgerListFragment {
62     public AccountSummaryAdapter modelAdapter;
63     private AccountSummaryFragmentBinding b;
64     private MenuItem menuShowZeroBalances;
65     private MainModel model;
66     @Override
67     public void onCreate(@Nullable Bundle savedInstanceState) {
68         super.onCreate(savedInstanceState);
69         debug("flow", "AccountSummaryFragment.onCreate()");
70         setHasOptionsMenu(true);
71     }
72     public void onAttach(@NotNull Context context) {
73         super.onAttach(context);
74         debug("flow", "AccountSummaryFragment.onAttach()");
75     }
76     @Override
77     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
78                              @Nullable Bundle savedInstanceState) {
79         debug("flow", "AccountSummaryFragment.onCreateView()");
80         b = AccountSummaryFragmentBinding.inflate(inflater, container, false);
81         return b.getRoot();
82     }
83     @Override
84     public SwipeRefreshLayout getRefreshLayout() {
85         return b.accountSwipeRefreshLayout;
86     }
87     @Override
88     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
89         debug("flow", "AccountSummaryFragment.onActivityCreated()");
90         super.onViewCreated(view, savedInstanceState);
91
92         model = new ViewModelProvider(requireActivity()).get(MainModel.class);
93
94         Data.backgroundTasksRunning.observe(this.getViewLifecycleOwner(),
95                 this::onBackgroundTaskRunningChanged);
96
97         modelAdapter = new AccountSummaryAdapter();
98         MainActivity mainActivity = getMainActivity();
99
100         LinearLayoutManager llm = new LinearLayoutManager(mainActivity);
101         llm.setOrientation(RecyclerView.VERTICAL);
102         b.accountRoot.setLayoutManager(llm);
103         b.accountRoot.setAdapter(modelAdapter);
104         DividerItemDecoration did =
105                 new DividerItemDecoration(mainActivity, DividerItemDecoration.VERTICAL);
106         b.accountRoot.addItemDecoration(did);
107
108         mainActivity.fabShouldShow();
109
110         FabManager.handle(mainActivity, b.accountRoot);
111
112         Colors.themeWatch.observe(getViewLifecycleOwner(), this::themeChanged);
113         b.accountSwipeRefreshLayout.setOnRefreshListener(() -> {
114             debug("ui", "refreshing accounts via swipe");
115             model.scheduleTransactionListRetrieval();
116         });
117
118         Data.observeProfile(this, profile -> onProfileChanged(profile, Boolean.TRUE.equals(
119                 model.getShowZeroBalanceAccounts()
120                      .getValue())));
121         model.getShowZeroBalanceAccounts()
122              .setValue(App.getShowZeroBalanceAccounts());
123     }
124     @Override
125     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
126         inflater.inflate(R.menu.account_list, menu);
127
128         menuShowZeroBalances = menu.findItem(R.id.menu_account_list_show_zero_balances);
129         if ((menuShowZeroBalances == null))
130             throw new AssertionError();
131
132         menuShowZeroBalances.setOnMenuItemClickListener(menuItem -> {
133             model.getShowZeroBalanceAccounts()
134                  .setValue(Boolean.FALSE.equals(model.getShowZeroBalanceAccounts()
135                                                      .getValue()));
136             return true;
137         });
138
139         model.getShowZeroBalanceAccounts()
140              .observe(this, v -> {
141                  menuShowZeroBalances.setChecked(v);
142                  onProfileChanged(Data.getProfile(), v);
143                  App.storeShowZeroBalanceAccounts(v);
144              });
145
146         super.onCreateOptionsMenu(menu, inflater);
147     }
148     private void onProfileChanged(Profile profile, boolean showZeroBalanceAccounts) {
149         if (profile == null)
150             return;
151
152         DB.get()
153           .getAccountDAO()
154           .getAllWithAmounts(profile.getId(), showZeroBalanceAccounts)
155           .observe(getViewLifecycleOwner(), list -> GeneralBackgroundTasks.run(() -> {
156               List<AccountListItem> adapterList = new ArrayList<>();
157               adapterList.add(new AccountListItem.Header(Data.lastAccountsUpdateText));
158               HashMap<String, LedgerAccount> accMap = new HashMap<>();
159               for (AccountWithAmounts dbAcc : list) {
160                   LedgerAccount parent = null;
161                   String parentName = dbAcc.account.getParentName();
162                   if (parentName != null)
163                       parent = accMap.get(parentName);
164                   if (parent != null)
165                       parent.setHasSubAccounts(true);
166                   final LedgerAccount account = LedgerAccount.fromDBO(dbAcc, parent);
167                   if (account.isVisible())
168                       adapterList.add(new AccountListItem.Account(account));
169                   accMap.put(dbAcc.account.getName(), account);
170               }
171
172               if (!showZeroBalanceAccounts) {
173                   removeZeroAccounts(adapterList);
174               }
175               modelAdapter.setAccounts(adapterList);
176               Data.lastUpdateAccountCount.postValue(adapterList.size() - 1);
177           }));
178     }
179     private void removeZeroAccounts(List<AccountListItem> list) {
180         boolean removed = true;
181
182         while (removed) {
183             AccountListItem last = null;
184             removed = false;
185             List<AccountListItem> newList = new ArrayList<>();
186
187             for (AccountListItem item : list) {
188                 if (last == null) {
189                     last = item;
190                     continue;
191                 }
192
193                 if (!last.isAccount() || !last.toAccount()
194                                               .allAmountsAreZero() || last.toAccount()
195                                                                           .getAccount()
196                                                                           .isParentOf(
197                                                                                   item.toAccount()
198                                                                                       .getAccount()))
199                 {
200                     newList.add(last);
201                 }
202                 else {
203                     removed = true;
204                 }
205
206                 last = item;
207             }
208
209             if (last != null) {
210                 if (!last.isAccount() || !last.toAccount()
211                                               .allAmountsAreZero())
212                 {
213                     newList.add(last);
214                 }
215                 else {
216                     removed = true;
217                 }
218             }
219
220             list.clear();
221             list.addAll(newList);
222         }
223     }
224 }