]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
add UI and API support for sending posting (transaction account) comments
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.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.annotation.SuppressLint;
21 import android.os.Build;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.text.method.DigitsKeyListener;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.FrameLayout;
30 import android.widget.LinearLayout;
31 import android.widget.TextView;
32
33 import androidx.annotation.NonNull;
34 import androidx.lifecycle.Observer;
35 import androidx.recyclerview.widget.RecyclerView;
36
37 import net.ktnx.mobileledger.R;
38 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MobileLedgerProfile;
42 import net.ktnx.mobileledger.ui.AutoCompleteTextViewWithClear;
43 import net.ktnx.mobileledger.ui.DatePickerFragment;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.MLDB;
46 import net.ktnx.mobileledger.utils.Misc;
47
48 import java.text.DecimalFormatSymbols;
49 import java.util.Calendar;
50 import java.util.Date;
51 import java.util.GregorianCalendar;
52 import java.util.Locale;
53
54 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
55
56 class NewTransactionItemHolder extends RecyclerView.ViewHolder
57         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
58     private final String decimalSeparator;
59     private final String decimalDot;
60     private NewTransactionModel.Item item;
61     private TextView tvDate;
62     private AutoCompleteTextView tvDescription;
63     private AutoCompleteTextView tvAccount;
64     private TextView tvComment;
65     private TextView tvAmount;
66     private LinearLayout lHead;
67     private ViewGroup lAccount;
68     private FrameLayout lPadding;
69     private MobileLedgerProfile mProfile;
70     private Date date;
71     private Observer<Date> dateObserver;
72     private Observer<String> descriptionObserver;
73     private Observer<String> hintObserver;
74     private Observer<Integer> focusedAccountObserver;
75     private Observer<Integer> accountCountObserver;
76     private Observer<Boolean> editableObserver;
77     private boolean inUpdate = false;
78     private boolean syncingData = false;
79     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
80         super(itemView);
81         tvAccount = itemView.findViewById(R.id.account_row_acc_name);
82         tvComment = itemView.findViewById(R.id.comment);
83         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
84         tvDate = itemView.findViewById(R.id.new_transaction_date);
85         tvDescription = itemView.findViewById(R.id.new_transaction_description);
86         lHead = itemView.findViewById(R.id.ntr_data);
87         lAccount = itemView.findViewById(R.id.ntr_account);
88         lPadding = itemView.findViewById(R.id.ntr_padding);
89
90         tvDescription.setNextFocusForwardId(View.NO_ID);
91         tvAccount.setNextFocusForwardId(View.NO_ID);
92         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
93
94         tvDate.setOnClickListener(v -> pickTransactionDate());
95
96         mProfile = Data.profile.getValue();
97         if (mProfile == null)
98             throw new AssertionError();
99
100         View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
101             if (hasFocus) {
102                 boolean wasSyncing = syncingData;
103                 syncingData = true;
104                 try {
105                     final int pos = getAdapterPosition();
106                     adapter.updateFocusedItem(pos);
107                     switch (v.getId()) {
108                         case R.id.account_row_acc_name:
109                             adapter.noteFocusIsOnAccount(pos);
110                             break;
111                         case R.id.account_row_acc_amounts:
112                             adapter.noteFocusIsOnAmount(pos);
113                             break;
114                         case R.id.comment:
115                             adapter.noteFocusIsOnComment(pos);
116                             break;
117                     }
118                 }
119                 finally {
120                     syncingData = wasSyncing;
121                 }
122             }
123         };
124
125         tvDescription.setOnFocusChangeListener(focusMonitor);
126         tvAccount.setOnFocusChangeListener(focusMonitor);
127         tvAmount.setOnFocusChangeListener(focusMonitor);
128
129         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
130                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
131         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
132                 "name", true, this, mProfile);
133
134         // FIXME: react on configuration (locale) changes
135         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
136                                                               .getMonetaryDecimalSeparator());
137         decimalDot = ".";
138
139         final TextWatcher tw = new TextWatcher() {
140             @Override
141             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
142             }
143
144             @Override
145             public void onTextChanged(CharSequence s, int start, int before, int count) {
146             }
147
148             @Override
149             public void afterTextChanged(Editable s) {
150 //                debug("input", "text changed");
151                 if (inUpdate)
152                     return;
153
154                 Logger.debug("textWatcher", "calling syncData()");
155                 syncData();
156                 Logger.debug("textWatcher",
157                         "syncData() returned, checking if transaction is submittable");
158                 adapter.model.checkTransactionSubmittable(adapter);
159                 Logger.debug("textWatcher", "done");
160             }
161         };
162         final TextWatcher amountWatcher = new TextWatcher() {
163             @Override
164             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
165             }
166             @Override
167             public void onTextChanged(CharSequence s, int start, int before, int count) {
168
169             }
170             @Override
171             public void afterTextChanged(Editable s) {
172                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
173                     // only one decimal separator is allowed
174                     // plus and minus are allowed only at the beginning
175                     String val = s.toString();
176                     if (val.isEmpty())
177                         tvAmount.setKeyListener(DigitsKeyListener.getInstance(
178                                 "0123456789+-" + decimalSeparator + decimalDot));
179                     else if (val.contains(decimalSeparator) || val.contains(decimalDot))
180                         tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
181                     else
182                         tvAmount.setKeyListener(DigitsKeyListener.getInstance(
183                                 "0123456789" + decimalSeparator + decimalDot));
184
185                     syncData();
186                     adapter.model.checkTransactionSubmittable(adapter);
187                 }
188             }
189         };
190         tvDescription.addTextChangedListener(tw);
191         tvAccount.addTextChangedListener(tw);
192         tvComment.addTextChangedListener(tw);
193         tvAmount.addTextChangedListener(amountWatcher);
194
195         // FIXME: react on locale changes
196         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
197             tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
198         else
199             tvAmount.setKeyListener(
200                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
201
202         dateObserver = date -> {
203             if (syncingData)
204                 return;
205             syncingData = true;
206             try {
207                 tvDate.setText(item.getFormattedDate());
208             }
209             finally {
210                 syncingData = false;
211             }
212         };
213         descriptionObserver = description -> {
214             if (syncingData)
215                 return;
216             syncingData = true;
217             try {
218                 tvDescription.setText(description);
219             }
220             finally {
221                 syncingData = false;
222             }
223         };
224         hintObserver = hint -> {
225             if (syncingData)
226                 return;
227             syncingData = true;
228             try {
229                 if (hint == null)
230                     tvAmount.setHint(R.string.zero_amount);
231                 else
232                     tvAmount.setHint(hint);
233             }
234             finally {
235                 syncingData = false;
236             }
237         };
238         editableObserver = this::setEditable;
239         focusedAccountObserver = index -> {
240             if ((index != null) && index.equals(getAdapterPosition())) {
241                 switch (item.getType()) {
242                     case generalData:
243                         // bad idea - double pop-up, and not really necessary.
244                         // the user can tap the input to get the calendar
245                         //if (!tvDate.hasFocus()) tvDate.requestFocus();
246                         boolean focused = tvDescription.requestFocus();
247                         tvDescription.dismissDropDown();
248                         if (focused)
249                             Misc.showSoftKeyboard(
250                                     (NewTransactionActivity) tvDescription.getContext());
251                         break;
252                     case transactionRow:
253                         // do nothing if a row element already has the focus
254                         if (!itemView.hasFocus()) {
255                             switch (item.getFocusedElement()) {
256                                 case Amount:
257                                     tvAmount.requestFocus();
258                                     break;
259                                 case Comment:
260                                     tvComment.requestFocus();
261                                     break;
262                                 case Account:
263                                     focused = tvAccount.requestFocus();
264                                     tvAccount.dismissDropDown();
265                                     if (focused)
266                                         Misc.showSoftKeyboard(
267                                                 (NewTransactionActivity) tvAccount.getContext());
268                                     break;
269                             }
270                         }
271
272                         break;
273                 }
274             }
275         };
276         accountCountObserver = count -> {
277             final int adapterPosition = getAdapterPosition();
278             final int layoutPosition = getLayoutPosition();
279             Logger.debug("holder",
280                     String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
281                             adapterPosition, layoutPosition, item.getType()
282                                                                  .toString()
283                                                                  .concat(item.getType() ==
284                                                                          ItemType.transactionRow
285                                                                          ? String.format(Locale.US,
286                                                                          "'%s'=%s",
287                                                                          item.getAccount()
288                                                                              .getAccountName(),
289                                                                          item.getAccount()
290                                                                              .isAmountSet()
291                                                                          ? String.format(Locale.US,
292                                                                                  "%.2f",
293                                                                                  item.getAccount()
294                                                                                      .getAmount())
295                                                                          : "unset") : "")));
296             if (adapterPosition == count)
297                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
298             else
299                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
300         };
301     }
302     private void setEditable(Boolean editable) {
303         tvDate.setEnabled(editable);
304         tvDescription.setEnabled(editable);
305         tvAccount.setEnabled(editable);
306         tvAmount.setEnabled(editable);
307     }
308     private void beginUpdates() {
309         if (inUpdate)
310             throw new RuntimeException("Already in update mode");
311         inUpdate = true;
312     }
313     private void endUpdates() {
314         if (!inUpdate)
315             throw new RuntimeException("Not in update mode");
316         inUpdate = false;
317     }
318     /**
319      * syncData()
320      * <p>
321      * Stores the data from the UI elements into the model item
322      */
323     private void syncData() {
324         if (item == null)
325             return;
326
327         if (syncingData) {
328             Logger.debug("new-trans", "skipping syncData() loop");
329             return;
330         }
331
332         syncingData = true;
333
334         try {
335             switch (item.getType()) {
336                 case generalData:
337                     item.setDate(String.valueOf(tvDate.getText()));
338                     item.setDescription(String.valueOf(tvDescription.getText()));
339                     break;
340                 case transactionRow:
341                     final LedgerTransactionAccount account = item.getAccount();
342                     account.setAccountName(String.valueOf(tvAccount.getText()));
343
344                     account.setComment(String.valueOf(tvComment.getText()));
345
346                     // TODO: handle multiple amounts
347                     String amount = String.valueOf(tvAmount.getText());
348                     amount = amount.trim();
349
350                     if (amount.isEmpty()) {
351                         account.resetAmount();
352                     }
353                     else {
354                         try {
355                             amount = amount.replace(decimalSeparator, decimalDot);
356                             account.setAmount(Float.parseFloat(amount));
357                         }
358                         catch (NumberFormatException e) {
359                             Logger.debug("new-trans", String.format(
360                                     "assuming amount is not set due to number format exception. " +
361                                     "input was '%s'", amount));
362                             account.resetAmount();
363                         }
364                     }
365
366                     break;
367                 case bottomFiller:
368                     throw new RuntimeException("Should not happen");
369             }
370         }
371         finally {
372             syncingData = false;
373         }
374     }
375     private void pickTransactionDate() {
376         DatePickerFragment picker = new DatePickerFragment();
377         picker.setFutureDates(mProfile.getFutureDates());
378         picker.setOnDatePickedListener(this);
379         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
380                 "datePicker");
381     }
382     /**
383      * setData
384      *
385      * @param item updates the UI elements with the data from the model item
386      */
387     @SuppressLint("DefaultLocale")
388     public void setData(NewTransactionModel.Item item) {
389         beginUpdates();
390         try {
391             if (this.item != null && !this.item.equals(item)) {
392                 this.item.stopObservingDate(dateObserver);
393                 this.item.stopObservingDescription(descriptionObserver);
394                 this.item.stopObservingAmountHint(hintObserver);
395                 this.item.stopObservingEditableFlag(editableObserver);
396                 this.item.getModel()
397                          .stopObservingFocusedItem(focusedAccountObserver);
398                 this.item.getModel()
399                          .stopObservingAccountCount(accountCountObserver);
400
401                 this.item = null;
402             }
403
404             switch (item.getType()) {
405                 case generalData:
406                     tvDate.setText(item.getFormattedDate());
407                     tvDescription.setText(item.getDescription());
408                     lHead.setVisibility(View.VISIBLE);
409                     lAccount.setVisibility(View.GONE);
410                     lPadding.setVisibility(View.GONE);
411                     setEditable(true);
412                     break;
413                 case transactionRow:
414                     LedgerTransactionAccount acc = item.getAccount();
415                     tvAccount.setText(acc.getAccountName());
416                     tvComment.setText(acc.getComment());
417                     if (acc.isAmountSet()) {
418                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
419                     }
420                     else {
421                         tvAmount.setText("");
422 //                        tvAmount.setHint(R.string.zero_amount);
423                     }
424                     tvAmount.setHint(item.getAmountHint());
425                     lHead.setVisibility(View.GONE);
426                     lAccount.setVisibility(View.VISIBLE);
427                     lPadding.setVisibility(View.GONE);
428                     setEditable(true);
429                     break;
430                 case bottomFiller:
431                     lHead.setVisibility(View.GONE);
432                     lAccount.setVisibility(View.GONE);
433                     lPadding.setVisibility(View.VISIBLE);
434                     setEditable(false);
435                     break;
436             }
437
438             if (this.item == null) { // was null or has changed
439                 this.item = item;
440                 final NewTransactionActivity activity =
441                         (NewTransactionActivity) tvDescription.getContext();
442                 item.observeDate(activity, dateObserver);
443                 item.observeDescription(activity, descriptionObserver);
444                 item.observeAmountHint(activity, hintObserver);
445                 item.observeEditableFlag(activity, editableObserver);
446                 item.getModel()
447                     .observeFocusedItem(activity, focusedAccountObserver);
448                 item.getModel()
449                     .observeAccountCount(activity, accountCountObserver);
450             }
451         }
452         finally {
453             endUpdates();
454         }
455     }
456     @Override
457     public void onDatePicked(int year, int month, int day) {
458         final Calendar c = GregorianCalendar.getInstance();
459         c.set(year, month, day);
460         item.setDate(c.getTime());
461         boolean focused = tvDescription.requestFocus();
462         if (focused)
463             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
464
465     }
466     @Override
467     public void descriptionSelected(String description) {
468         tvAccount.setText(description);
469         tvAmount.requestFocus(View.FOCUS_FORWARD);
470     }
471 }