2 * Copyright © 2020 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.
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.
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/>.
18 package net.ktnx.mobileledger.json;
20 import com.fasterxml.jackson.databind.MappingIterator;
22 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
23 import net.ktnx.mobileledger.model.LedgerAccount;
25 import java.util.ArrayList;
26 import java.util.HashMap;
28 import static net.ktnx.mobileledger.utils.Logger.debug;
30 abstract public class AccountListParser {
31 protected MappingIterator<net.ktnx.mobileledger.json.ParsedLedgerAccount> iterator;
33 public ParsedLedgerAccount nextAccount() {
34 if (!iterator.hasNext())
37 ParsedLedgerAccount next = iterator.next();
40 .equalsIgnoreCase("root"))
43 debug("accounts", String.format("Got account '%s' [v1.15]", next.getAname()));
46 public LedgerAccount nextLedgerAccount(RetrieveTransactionsTask task,
47 HashMap<String, LedgerAccount> map) {
48 ParsedLedgerAccount parsedAccount = nextAccount();
49 if (parsedAccount == null)
52 task.addNumberOfPostings(parsedAccount.getAnumpostings());
53 final String accName = parsedAccount.getAname();
54 LedgerAccount acc = map.get(accName);
56 throw new RuntimeException(
57 String.format("Account '%s' already present", acc.getName()));
58 String parentName = LedgerAccount.extractParentName(accName);
59 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
61 if (parentName == null) {
65 parent = task.ensureAccountExists(parentName, map, createdParents);
66 parent.setHasSubAccounts(true);
68 acc = new LedgerAccount(task.getProfile(), accName, parent);
69 map.put(accName, acc);
71 String lastCurrency = null;
72 float lastCurrencyAmount = 0;
73 for (ParsedBalance b : parsedAccount.getAibalance()) {
74 task.throwIfCancelled();
75 final String currency = b.getAcommodity();
76 final float amount = b.getAquantity()
78 if (currency.equals(lastCurrency)) {
79 lastCurrencyAmount += amount;
82 if (lastCurrency != null) {
83 acc.addAmount(lastCurrencyAmount, lastCurrency);
85 lastCurrency = currency;
86 lastCurrencyAmount = amount;
89 if (lastCurrency != null) {
90 acc.addAmount(lastCurrencyAmount, lastCurrency);
92 for (LedgerAccount p : createdParents)
93 acc.propagateAmountsTo(p);