summaryrefslogtreecommitdiff
path: root/ledger.cc
blob: 7c7823369f68b5fab7ebba1b86ce9f0d5dae2ea6 (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
#include "ledger.h"
#include "report.h"
#include "textual.h"
#include "binary.h"

#include <fstream>
#include <deque>

namespace ledger {

const std::string version = "2.0b";

ledger_t::~ledger_t()
{
  delete master;

  for (commodities_map::iterator i = commodities.begin();
       i != commodities.end();
       i++)
    delete (*i).second;

  // Don't bother unhooking each entry's transactions from the
  // accounts they refer to, because all accounts are about to
  // be deleted.
  for (entries_list::iterator i = entries.begin();
       i != entries.end();
       i++)
    delete *i;
}

commodity_t * ledger_t::find_commodity(const std::string& symbol,
				       bool auto_create)
{
  commodities_map::const_iterator i = commodities.find(symbol);
  if (i != commodities.end())
    return (*i).second;

  if (auto_create) {
    commodity_t * commodity = new commodity_t(symbol);
    add_commodity(commodity);
    return commodity;
  }

  return NULL;
}

bool ledger_t::add_entry(entry_t * entry)
{
  entries.push_back(entry);

  for (transactions_list::const_iterator i = entry->transactions.begin();
       i != entry->transactions.end();
       i++) {
    (*i)->account->add_transaction(*i);

    if ((*i)->amount != (*i)->cost) {
      assert((*i)->amount.commodity);
      (*i)->amount.commodity->add_price(entry->date, (*i)->cost / (*i)->amount);
    }
  }

  return true;
}

bool ledger_t::remove_entry(entry_t * entry)
{
  entries.remove(entry);

  for (transactions_list::const_iterator i
	 = entry->transactions.begin();
       i != entry->transactions.end();
       i++)
    (*i)->account->remove_transaction(*i);

  return true;
}

int parse_ledger_file(char * p, ledger_t * book)
{
  char * sep = std::strrchr(p, '=');
  if (sep) *sep++ = '\0';

  std::ifstream stream(p);

  account_t * master;
  if (sep)
    master = book->find_account(sep);
  else
    master = book->master;

  book->sources.push_back(p);

  unsigned long magic;
  std::istream::pos_type start = stream.tellg();
  stream.read((char *)&magic, sizeof(magic));
  stream.seekg(start);

  if (magic == magic_number)
    return read_binary_ledger(stream, "", book, master);
  else
    return parse_textual_ledger(stream, book, master);
}

} // namespace ledger