summaryrefslogtreecommitdiff
path: root/balance.cc
blob: dedbc4e1bf7d1678c3341fb190272801c984efcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#include "ledger.h"

#include <fstream>
#include <unistd.h>
#include <pcre.h>               // Perl regular expression library

namespace ledger {

static bool show_current  = false;
static bool show_cleared  = false;
static bool show_children = false;
static bool show_empty    = false;
static bool no_subtotals  = false;

struct mask
{
  bool   exclude;
  pcre * regexp;

  mask(bool exc, pcre * re) : exclude(exc), regexp(re) {}
};

static inline bool matches(const std::list<mask>& regexps,
			   const std::string& str)
{
  // If the first pattern is an exclude, we assume all patterns match
  // if they don't match the exclude.  If the first pattern is an
  // include, then only accounts matching the include will match.

  bool match = (*regexps.begin()).exclude;

  for (std::list<mask>::const_iterator r = regexps.begin();
       r != regexps.end();
       r++) {
    int ovec[3];
    if (pcre_exec((*r).regexp, NULL, str.c_str(), str.length(),
		  0, 0, ovec, 3) >= 0)
      match = ! (*r).exclude;
  }

  return match;
}

static void display_total(std::ostream& out, totals& total_balance,
			  const account * acct,
			  const std::map<account *, totals *>& balances,
			  const std::list<mask>& regexps)
{
  std::map<account *, totals *>::const_iterator b =
    balances.find(const_cast<account *>(acct));
  if (b != balances.end()) {
    totals * balance = (*b).second;

    if (balance && (show_empty || *balance)) {
      bool match = true;
      if (! regexps.empty()) {
	if (show_children) {
	  match = false;
	  for (const account * a = acct; a; a = a->parent) {
	    if (matches(regexps, a->name)) {
	      match = true;
	      break;
	    }
	  }
	} else {
	  match = matches(regexps, acct->name);
	}
      }

      if (match) {
	out << *balance;

	if (acct->parent) {
	  for (const account * a = acct; a; a = a->parent)
	    out << "  ";
	  out << acct->name << std::endl;
	} else {
	  out << "  " << *acct << std::endl;

	  // For top-level accounts, update the total running balance
	  total_balance.credit(*balance);
	}
      }
    }
  }

  // Display balances for all child accounts

  for (account::const_iterator i = acct->children.begin();
       i != acct->children.end();
       i++)
    display_total(out, total_balance, (*i).second, balances, regexps);
}

static void record_price(char * setting,
			 std::map<const std::string, amount *>& prices)
{
  char * c = setting;
  char * p = std::strchr(setting, '=');
  if (! p) {
    std::cerr << "Warning: Invalid price setting: " << setting << std::endl;
  } else {
    *p++ = '\0';
    amount * price = create_amount(p);
    prices.insert(std::pair<const std::string, amount *>(c, price));
  }
}

static void record_regexp(char * pattern, std::list<mask>& regexps)
{
  bool exclude = false;

  char * pat = pattern;
  if (*pat == '-') {
    exclude = true;
    pat++;
    while (std::isspace(*pat))
      pat++;
  }
  else if (*pat == '+') {
    pat++;
    while (std::isspace(*pat))
      pat++;
  }

  const char *error;
  int erroffset;
  pcre * re = pcre_compile(pat, PCRE_CASELESS, &error, &erroffset, NULL);
  if (! re)
    std::cerr << "Warning: Failed to compile regexp: " << pattern
	      << std::endl;
  else
    regexps.push_back(mask(exclude, re));
}

//////////////////////////////////////////////////////////////////////
//
// Balance reporting code
//

void report_balances(int argc, char **argv, std::ostream& out)
{
  std::map<const std::string, amount *> prices;
  std::list<mask> regexps;

  int c;
  optind = 1;
  while (-1 != (c = getopt(argc, argv, "cCsSni:p:"))) {
    switch (char(c)) {
    case 'c': show_current  = true; break;
    case 'C': show_cleared  = true; break;
    case 's': show_children = true; break;
    case 'S': show_empty    = true; break;
    case 'n': no_subtotals  = true; break;

    // -i path-to-file-of-regexps
    case 'i':
      if (access(optarg, R_OK) != -1) {
	std::ifstream include(optarg);

	while (! include.eof()) {
	  char buf[80];
	  include.getline(buf, 79);
	  if (*buf && ! std::isspace(*buf))
	    record_regexp(buf, regexps);
	}
      }
      break;

    // -p "COMMODITY=PRICE"
    // -p path-to-price-database
    case 'p':
      if (access(optarg, R_OK) != -1) {
	std::ifstream pricedb(optarg);

	while (! pricedb.eof()) {
	  char buf[80];
	  pricedb.getline(buf, 79);
	  if (*buf && ! std::isspace(*buf))
	    record_price(buf, prices);
	}
      } else {
	record_price(optarg, prices);
      }
      break;
    }
  }

  // Compile the list of specified regular expressions, which can be
  // specified on the command line, or using an include/exclude file

  for (; optind < argc; optind++)
    record_regexp(argv[optind], regexps);

  // Walk through all of the ledger entries, computing the account
  // totals

  std::map<account *, totals *> balances;
  std::time_t now = std::time(NULL);

  for (ledger_iterator i = ledger.begin(); i != ledger.end(); i++) {
    for (std::list<transaction *>::iterator x = (*i)->xacts.begin();
	 x != (*i)->xacts.end();
	 x++) {
      account * acct = (*x)->acct;

      for (; acct; acct = no_subtotals ? NULL : acct->parent) {
	if (! show_children && acct->parent)
	  continue;

	totals * balance = NULL;

	std::map<account *, totals *>::iterator t = balances.find(acct);
	if (t == balances.end()) {
	  balance = new totals;
	  balances.insert(std::pair<account *, totals *>(acct, balance));
	} else {
	  balance = (*t).second;
	}

	bool do_credit = false;

	if (show_current) {
	  if (difftime((*i)->date, now) < 0)
	    do_credit = true;
	}
	else if (show_cleared) {
	  if ((*i)->cleared)
	    do_credit = true;
	}
	else {
	  do_credit = true;
	}

	if (! do_credit)
	  continue;

	std::map<const std::string, amount *>::iterator pi
	  = prices.find((*x)->cost->comm_symbol());

	if (pi == prices.end()) {
	  balance->credit((*x)->cost);
	} else {
	  amount * value = (*x)->cost->value((*pi).second);
	  balance->credit(value);
	  delete value;
	}
      }
    }
  }

  // Walk through all the top-level accounts, giving the balance
  // report for each, and then for each of their children.

  totals total_balance;

  for (accounts_iterator i = accounts.begin(); i != accounts.end(); i++)
    display_total(out, total_balance, (*i).second, balances, regexps);

  // Print the total of all the balances shown

  if (! no_subtotals)
    out << "--------------------" << std::endl
	<< total_balance << std::endl;

  // Free up temporary variables created on the heap

  for (std::map<account *, totals *>::iterator i = balances.begin();
       i != balances.end();
       i++)
    delete (*i).second;

  for (std::map<const std::string, amount *>::iterator i = prices.begin();
       i != prices.end();
       i++)
    delete (*i).second;
}

} // namespace ledger