2013-12-17 14:41:30 +00:00
|
|
|
# Part of accounting-api project:
|
|
|
|
# https://gitorious.org/conservancy/accounting-api
|
|
|
|
# License: AGPLv3-or-later
|
|
|
|
|
2013-12-10 23:25:16 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
2013-12-10 22:22:57 +00:00
|
|
|
from flask import json
|
|
|
|
|
2013-12-20 23:24:37 +00:00
|
|
|
from accounting.exceptions import AccountingException
|
2013-12-11 08:23:44 +00:00
|
|
|
from accounting.models import Amount, Transaction, Posting, Account
|
2013-12-10 22:22:57 +00:00
|
|
|
|
2013-12-16 06:33:56 +00:00
|
|
|
|
2013-12-10 22:22:57 +00:00
|
|
|
class AccountingEncoder(json.JSONEncoder):
|
|
|
|
def default(self, o):
|
|
|
|
if isinstance(o, Account):
|
|
|
|
return dict(
|
|
|
|
__type__=o.__class__.__name__,
|
|
|
|
name=o.name,
|
|
|
|
amounts=o.amounts,
|
|
|
|
accounts=o.accounts
|
|
|
|
)
|
|
|
|
elif isinstance(o, Transaction):
|
|
|
|
return dict(
|
|
|
|
__type__=o.__class__.__name__,
|
2013-12-16 06:33:56 +00:00
|
|
|
id=o.id,
|
2013-12-10 22:22:57 +00:00
|
|
|
date=o.date.strftime('%Y-%m-%d'),
|
|
|
|
payee=o.payee,
|
2013-12-11 14:12:08 +00:00
|
|
|
postings=o.postings,
|
|
|
|
metadata=o.metadata
|
2013-12-10 22:22:57 +00:00
|
|
|
)
|
|
|
|
elif isinstance(o, Posting):
|
|
|
|
return dict(
|
|
|
|
__type__=o.__class__.__name__,
|
|
|
|
account=o.account,
|
|
|
|
amount=o.amount,
|
2013-12-11 14:12:08 +00:00
|
|
|
metadata=o.metadata
|
2013-12-10 22:22:57 +00:00
|
|
|
)
|
|
|
|
elif isinstance(o, Amount):
|
|
|
|
return dict(
|
|
|
|
__type__=o.__class__.__name__,
|
2013-12-11 08:23:44 +00:00
|
|
|
amount=str(o.amount),
|
2013-12-10 22:22:57 +00:00
|
|
|
symbol=o.symbol
|
|
|
|
)
|
2013-12-20 23:24:37 +00:00
|
|
|
elif isinstance(o, AccountingException):
|
2013-12-10 23:25:16 +00:00
|
|
|
return dict(
|
2013-12-20 23:24:37 +00:00
|
|
|
type=o.__class__.__name__,
|
2013-12-26 20:48:45 +00:00
|
|
|
message=o.message,
|
|
|
|
transaction=getattr(o, 'transaction', None)
|
2013-12-10 23:25:16 +00:00
|
|
|
)
|
2013-12-10 22:22:57 +00:00
|
|
|
|
|
|
|
return json.JSONEncoder.default(self, o)
|
|
|
|
|
2013-12-16 06:33:56 +00:00
|
|
|
|
2013-12-10 22:22:57 +00:00
|
|
|
class AccountingDecoder(json.JSONDecoder):
|
|
|
|
def __init__(self):
|
|
|
|
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)
|
|
|
|
|
|
|
|
def dict_to_object(self, d):
|
|
|
|
if '__type__' not in d:
|
|
|
|
return d
|
|
|
|
|
2013-12-16 06:33:56 +00:00
|
|
|
types = {c.__name__: c for c in [Amount, Transaction, Posting,
|
2013-12-20 23:24:37 +00:00
|
|
|
Account, AccountingException]}
|
2013-12-10 22:22:57 +00:00
|
|
|
|
|
|
|
_type = d.pop('__type__')
|
|
|
|
|
2013-12-10 23:25:16 +00:00
|
|
|
if _type == 'Transaction':
|
|
|
|
d['date'] = datetime.strptime(d['date'], '%Y-%m-%d')
|
|
|
|
|
2013-12-10 22:22:57 +00:00
|
|
|
return types[_type](**d)
|