@@ -128,96 +128,108 @@ class Ledger(Storage):
:class:`~accounting.models.Transaction` instance in
:data:`transaction`.
'''
if transaction.id is None:
_log.debug('No ID found. Generating an ID.')
transaction.generate_id()
exists = self.get_transaction(transaction.id)
if exists is not None:
raise TransactionIDCollision(
'A transaction with the id %s already exists: %s' %
(transaction.id, exists))
transaction.metadata.update({'Id': transaction.id})
transaction_template = ('\n{date} {t.payee}\n'
'{metadata}'
'{postings}')
metadata_template = ' ;{0}: {1}\n'
# TODO: Generate metadata for postings
posting_template = (' {account} {p.amount.symbol}'
' {p.amount.amount}\n')
output = b''
# XXX: Even I hardly understands what this does, however I indent it it
# stays unreadable.
output += transaction_template.format(
date=transaction.date.strftime('%Y-%m-%d'),
t=transaction,
metadata=''.join([
metadata_template.format(k, v)
for k, v in transaction.metadata.items()]),
postings=''.join([posting_template.format(
p=p,
account=p.account + ' ' * (
80 - (len(p.account) + len(p.amount.symbol) +
len(str(p.amount.amount)) + 1 + 2)
)) for p in transaction.postings
])
).encode('utf8')
with open(self.ledger_file, 'ab') as f:
f.write(output)
# Check to see that no errors were introduced
try:
self.get_transactions()
except AccountingException as exc:
# TODO: Do a hard reset on the repository using Repository.reset,
# this is on hold because of
# https://github.com/libgit2/pygit2/issues/271.
# This solution will work in the meantime
self.delete_transaction(transaction.id)
setattr(exc, 'transaction', transaction)
raise exc
self.commit_changes('Added transaction %s' % transaction.id)
_log.info('Added transaction %s', transaction.id)
_log.debug('written to file: %s', output)
return transaction.id
def bal(self):
output = self.send_command('xml')
if output is None:
raise RuntimeError('bal call returned no output')
accounts = []
xml = ElementTree.fromstring(output.decode('utf8'))
accounts = self._recurse_accounts(xml.find('./accounts'))
return accounts
def _recurse_accounts(self, root):
for account in root.findall('./account'):
name = account.find('./fullname').text
amounts = []
# Try to find an account total value, then try to find the account
# balance
account_amounts = account.findall(
'./account-total/balance/amount') or \
account.findall('./account-amount/amount') or \
account.findall('./account-total/amount')
if account_amounts:
for amount in account_amounts:
quantity = amount.find('./quantity').text
symbol = amount.find('./commodity/symbol').text
amounts.append(Amount(amount=quantity, symbol=symbol))
else:
_log.warning('Account %s does not have any amounts', name)
accounts.append(Account(name=name,
amounts=amounts,