]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
6844b6ce3d743f471db420ec7d1723dd33f1cd26
[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()) return false;
95             if (acc.isAmountSet()) return false;
96         }
97
98         return true;
99     }
100     public void descriptionSelected(String description) {
101         debug("descr selected", description);
102         if (!accountListIsEmpty()) return;
103
104         String accFilter = mProfile.getPreferredAccountsFilter();
105
106         ArrayList<String> params = new ArrayList<>();
107         StringBuilder sb = new StringBuilder(
108                 "select t.profile, t.id from transactions t where t.description=?");
109         params.add(description);
110
111         if (accFilter != null) {
112             sb.append(" AND EXISTS (")
113               .append("SELECT 1 FROM transaction_accounts ta ")
114               .append("WHERE ta.profile = t.profile")
115               .append(" AND ta.transaction_id = t.id")
116               .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
117             params.add(accFilter.toUpperCase());
118         }
119
120         sb.append(" ORDER BY date desc limit 1");
121
122         final String sql = sb.toString();
123         debug("descr", sql);
124         debug("descr", params.toString());
125
126         try (Cursor c = App.getDatabase()
127                            .rawQuery(sql, params.toArray(new String[]{})))
128         {
129             if (!c.moveToNext()) return;
130
131             String profileUUID = c.getString(0);
132             int transactionId = c.getInt(1);
133             LedgerTransaction tr;
134             MobileLedgerProfile profile = Data.getProfile(profileUUID);
135             if (profile == null) throw new RuntimeException(String.format(
136                     "Unable to find profile %s, which is supposed to contain " +
137                     "transaction %d with description %s", profileUUID, transactionId, description));
138
139             tr = profile.loadTransaction(transactionId);
140             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
141             NewTransactionModel.Item firstNegative = null;
142             boolean singleNegative = false;
143             int negativeCount = 0;
144             for (int i = 0; i < accounts.size(); i++) {
145                 LedgerTransactionAccount acc = accounts.get(i);
146                 NewTransactionModel.Item item;
147                 if (model.getAccountCount() < i + 1) {
148                     model.addAccount(acc);
149                     notifyItemInserted(i + 1);
150                 }
151                 item = model.getItem(i + 1);
152
153                 item.getAccount()
154                     .setAccountName(acc.getAccountName());
155                 if (acc.isAmountSet()) {
156                     item.getAccount()
157                         .setAmount(acc.getAmount());
158                     if (acc.getAmount() < 0) {
159                         if (firstNegative == null) {
160                             firstNegative = item;
161                             singleNegative = true;
162                         }
163                         else
164                             singleNegative = false;
165                     }
166                 }
167                 else
168                     item.getAccount()
169                         .resetAmount();
170                 notifyItemChanged(i + 1);
171             }
172
173             if (singleNegative) {
174                 firstNegative.getAccount()
175                              .resetAmount();
176             }
177         }
178         model.checkTransactionSubmittable(this);
179         model.setFocusedItem(1);
180     }
181     public void toggleAllEditing(boolean editable) {
182         for (int i = 0; i < model.getAccountCount(); i++) {
183             model.getItem(i + 1)
184                  .setEditable(editable);
185             notifyItemChanged(i + 1);
186             // TODO perhaps do only one notification about the whole range [1…count]?
187         }
188     }
189     public void reset() {
190         int presentItemCount = model.getAccountCount();
191         model.reset();
192         notifyItemChanged(0);       // header changed
193         notifyItemRangeChanged(1, 2);    // the two empty rows
194         if (presentItemCount > 2)
195             notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
196     }
197 }