]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
1585f1d8d48bde6c1cbb85f0ce04b93f3fb9373b
[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 import android.widget.TableRow;
25
26 import androidx.annotation.NonNull;
27 import androidx.recyclerview.widget.RecyclerView;
28
29 import net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.R;
31 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
32 import net.ktnx.mobileledger.model.Data;
33 import net.ktnx.mobileledger.model.LedgerTransaction;
34 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
35 import net.ktnx.mobileledger.model.MobileLedgerProfile;
36 import net.ktnx.mobileledger.utils.Logger;
37
38 import java.util.ArrayList;
39 import java.util.Locale;
40
41 import static net.ktnx.mobileledger.utils.Logger.debug;
42
43 class NewTransactionItemsAdapter extends RecyclerView.Adapter<NewTransactionItemHolder>
44         implements DescriptionSelectedCallback {
45     NewTransactionModel model;
46     private MobileLedgerProfile mProfile;
47     NewTransactionItemsAdapter(NewTransactionModel viewModel, MobileLedgerProfile profile) {
48         super();
49         model = viewModel;
50         mProfile = profile;
51         int size = model.getAccountCount();
52         while (size < 2) {
53             Logger.debug("new-transaction",
54                     String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
55             size = addRow();
56         }
57     }
58     public void setProfile(MobileLedgerProfile profile) {
59         mProfile = profile;
60     }
61     int addRow() {
62         final int newAccountCount = model.addAccount(new LedgerTransactionAccount(""));
63         Logger.debug("new-transaction",
64                 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
65         // the header is at position 0
66         notifyItemInserted(newAccountCount);
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         holder.setData(model.getItem(position));
81         Logger.debug("bind", String.format(Locale.US, "Bound item at position %d", position));
82     }
83     @Override
84     public int getItemCount() {
85         final int itemCount = model.getAccountCount() + 2;
86         Logger.debug("new-transaction",
87                 String.format(Locale.US, "getItemCount() returning %d", itemCount));
88         return itemCount;
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             TableRow firstNegative = null;
142             int negativeCount = 0;
143             for (int i = 0; i < accounts.size(); i++) {
144                 LedgerTransactionAccount acc = accounts.get(i);
145                 NewTransactionModel.Item item;
146                 if (model.getAccountCount() < i) {
147                     model.addAccount(acc);
148                     notifyItemInserted(i + 1);
149                 }
150                 item = model.getItem(i + 1);
151
152                 item.getAccount()
153                     .setAccountName(acc.getAccountName());
154                 if (acc.isAmountSet()) item.getAccount()
155                                            .setAmount(acc.getAmount());
156                 else item.getAccount()
157                          .resetAmount();
158                 notifyItemChanged(i + 1);
159             }
160         }
161         model.checkTransactionSubmittable(this);
162         model.setFocusedItem(1);
163     }
164     public void toggleAllEditing(boolean editable) {
165         for (int i = 0; i < model.getAccountCount(); i++) {
166             model.getItem(i + 1)
167                  .setEditable(editable);
168             notifyItemChanged(i + 1);
169             // TODO perhaps do only one notification about the whole range [1…count]?
170         }
171     }
172     public void reset() {
173         int presentItemCount = model.getAccountCount();
174         model.reset();
175         notifyItemChanged(0);       // header changed
176         notifyItemRangeChanged(1, 2);    // the two empty rows
177         if (presentItemCount > 2)
178             notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
179     }
180     public void removeItem(int pos) {
181         model.removeItem(pos - 1, this);
182         notifyItemRemoved(pos);
183     }
184 }