]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
move new transaction UI into a fragment, have a clean saving progress
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemsAdapter.java
1 /*
2  * Copyright © 2019 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.activity;
19
20 import android.database.Cursor;
21 import android.view.LayoutInflater;
22 import android.view.ViewGroup;
23 import android.widget.LinearLayout;
24
25 import androidx.annotation.NonNull;
26 import androidx.recyclerview.widget.RecyclerView;
27
28 import net.ktnx.mobileledger.App;
29 import net.ktnx.mobileledger.R;
30 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
31 import net.ktnx.mobileledger.model.Data;
32 import net.ktnx.mobileledger.model.LedgerTransaction;
33 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
34 import net.ktnx.mobileledger.model.MobileLedgerProfile;
35 import net.ktnx.mobileledger.utils.Logger;
36
37 import java.util.ArrayList;
38 import java.util.Locale;
39
40 import static net.ktnx.mobileledger.utils.Logger.debug;
41
42 class NewTransactionItemsAdapter extends RecyclerView.Adapter<NewTransactionItemHolder>
43         implements DescriptionSelectedCallback {
44     NewTransactionModel model;
45     private MobileLedgerProfile mProfile;
46     NewTransactionItemsAdapter(NewTransactionModel viewModel, MobileLedgerProfile profile) {
47         super();
48         model = viewModel;
49         mProfile = profile;
50         int size = model.getAccountCount();
51         while (size < 2) {
52             Logger.debug("new-transaction",
53                     String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
54             size = addRow();
55         }
56     }
57     public void setProfile(MobileLedgerProfile profile) {
58         mProfile = profile;
59     }
60     int addRow() {
61         final int newAccountCount = model.addAccount(new LedgerTransactionAccount(""));
62         Logger.debug("new-transaction",
63                 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
64         // the header is at position 0
65         notifyItemInserted(newAccountCount);
66         model.sendCountNotifications(); // needed after holders' positions have changed
67         return newAccountCount;
68     }
69     @NonNull
70     @Override
71     public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
72         LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
73                                                         .inflate(R.layout.new_transaction_row,
74                                                                 parent, false);
75         return new NewTransactionItemHolder(row, this);
76     }
77     @Override
78     public void onBindViewHolder(@NonNull NewTransactionItemHolder holder, int position) {
79         Logger.debug("bind", String.format(Locale.US, "Binding item at position %d", position));
80         NewTransactionModel.Item item = model.getItem(position);
81         holder.setData(item);
82         Logger.debug("bind", String.format(Locale.US, "Bound %s item at position %d", item.getType()
83                                                                                           .toString(),
84                 position));
85     }
86     @Override
87     public int getItemCount() {
88         return model.getAccountCount() + 2;
89     }
90     boolean accountListIsEmpty() {
91         for (int i = 0; i < model.getAccountCount(); i++) {
92             LedgerTransactionAccount acc = model.getAccount(i);
93             if (!acc.getAccountName()
94                     .isEmpty())
95                 return false;
96             if (acc.isAmountSet())
97                 return false;
98         }
99
100         return true;
101     }
102     public void descriptionSelected(String description) {
103         debug("descr selected", description);
104         if (!accountListIsEmpty())
105             return;
106
107         String accFilter = mProfile.getPreferredAccountsFilter();
108
109         ArrayList<String> params = new ArrayList<>();
110         StringBuilder sb = new StringBuilder(
111                 "select t.profile, t.id from transactions t where t.description=?");
112         params.add(description);
113
114         if (accFilter != null) {
115             sb.append(" AND EXISTS (")
116               .append("SELECT 1 FROM transaction_accounts ta ")
117               .append("WHERE ta.profile = t.profile")
118               .append(" AND ta.transaction_id = t.id")
119               .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
120             params.add(accFilter.toUpperCase());
121         }
122
123         sb.append(" ORDER BY date desc limit 1");
124
125         final String sql = sb.toString();
126         debug("descr", sql);
127         debug("descr", params.toString());
128
129         try (Cursor c = App.getDatabase()
130                            .rawQuery(sql, params.toArray(new String[]{})))
131         {
132             if (!c.moveToNext())
133                 return;
134
135             String profileUUID = c.getString(0);
136             int transactionId = c.getInt(1);
137             LedgerTransaction tr;
138             MobileLedgerProfile profile = Data.getProfile(profileUUID);
139             if (profile == null)
140                 throw new RuntimeException(String.format(
141                         "Unable to find profile %s, which is supposed to contain " +
142                         "transaction %d with description %s", profileUUID, transactionId,
143                         description));
144
145             tr = profile.loadTransaction(transactionId);
146             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
147             NewTransactionModel.Item firstNegative = null;
148             boolean singleNegative = false;
149             int negativeCount = 0;
150             for (int i = 0; i < accounts.size(); i++) {
151                 LedgerTransactionAccount acc = accounts.get(i);
152                 NewTransactionModel.Item item;
153                 if (model.getAccountCount() < i + 1) {
154                     model.addAccount(acc);
155                     notifyItemInserted(i + 1);
156                 }
157                 item = model.getItem(i + 1);
158
159                 item.getAccount()
160                     .setAccountName(acc.getAccountName());
161                 if (acc.isAmountSet()) {
162                     item.getAccount()
163                         .setAmount(acc.getAmount());
164                     if (acc.getAmount() < 0) {
165                         if (firstNegative == null) {
166                             firstNegative = item;
167                             singleNegative = true;
168                         }
169                         else
170                             singleNegative = false;
171                     }
172                 }
173                 else
174                     item.getAccount()
175                         .resetAmount();
176                 notifyItemChanged(i + 1);
177             }
178
179             if (singleNegative) {
180                 firstNegative.getAccount()
181                              .resetAmount();
182             }
183         }
184         model.checkTransactionSubmittable(this);
185         model.setFocusedItem(1);
186     }
187     public void toggleAllEditing(boolean editable) {
188         // item 0 is the header
189         for (int i = 0; i <= model.getAccountCount(); i++) {
190             model.getItem(i)
191                  .setEditable(editable);
192             notifyItemChanged(i);
193             // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
194         }
195     }
196     public void reset() {
197         int presentItemCount = model.getAccountCount();
198         model.reset();
199         notifyItemChanged(0);       // header changed
200         notifyItemRangeChanged(1, 2);    // the two empty rows
201         if (presentItemCount > 2)
202             notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
203     }
204 }