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 net.ktnx.mobileledger.async.RetrieveTransactionsTask;
21 import net.ktnx.mobileledger.model.LedgerAccount;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
27 public abstract class ParsedLedgerAccount {
29 private int anumpostings;
30 public abstract List<SimpleBalance> getSimpleBalance();
31 public String getAname() {
34 public void setAname(String aname) {
37 public int getAnumpostings() {
40 public void setAnumpostings(int anumpostings) {
41 this.anumpostings = anumpostings;
43 public LedgerAccount toLedgerAccount(RetrieveTransactionsTask task,
44 HashMap<String, LedgerAccount> map) {
45 task.addNumberOfPostings(getAnumpostings());
46 final String accName = getAname();
47 LedgerAccount acc = map.get(accName);
49 throw new RuntimeException(
50 String.format("Account '%s' already present", acc.getName()));
51 String parentName = LedgerAccount.extractParentName(accName);
52 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
54 if (parentName == null) {
58 parent = task.ensureAccountExists(parentName, map, createdParents);
59 parent.setHasSubAccounts(true);
61 acc = new LedgerAccount(task.getProfile(), accName, parent);
62 map.put(accName, acc);
64 String lastCurrency = null;
65 float lastCurrencyAmount = 0;
66 for (SimpleBalance b : getSimpleBalance()) {
67 task.throwIfCancelled();
68 final String currency = b.getCommodity();
69 final float amount = b.getAmount();
70 if (currency.equals(lastCurrency)) {
71 lastCurrencyAmount += amount;
74 if (lastCurrency != null) {
75 acc.addAmount(lastCurrencyAmount, lastCurrency);
77 lastCurrency = currency;
78 lastCurrencyAmount = amount;
81 if (lastCurrency != null) {
82 acc.addAmount(lastCurrencyAmount, lastCurrency);
84 for (LedgerAccount p : createdParents)
85 acc.propagateAmountsTo(p);
90 static public class SimpleBalance {
91 private String commodity;
93 public SimpleBalance(String commodity, float amount) {
94 this.commodity = commodity;
97 public String getCommodity() {
100 public void setCommodity(String commodity) {
101 this.commodity = commodity;
103 public float getAmount() {
106 public void setAmount(float amount) {
107 this.amount = amount;