2022-03-22 21:56:35 +00:00
|
|
|
# Twisted/Klein imports
|
2022-07-15 10:09:54 +00:00
|
|
|
from hashlib import sha256
|
|
|
|
from json import dumps, loads
|
2022-03-22 21:56:35 +00:00
|
|
|
|
2022-02-28 20:02:50 +00:00
|
|
|
# Other library imports
|
|
|
|
import requests
|
2022-05-02 15:33:00 +00:00
|
|
|
import treq
|
2022-07-15 10:09:54 +00:00
|
|
|
import util
|
2023-02-09 07:20:00 +00:00
|
|
|
from lib.serde.nordigen import (
|
|
|
|
AccessToken,
|
|
|
|
AccountBalancesRoot,
|
|
|
|
AccountDetails,
|
|
|
|
Agreement,
|
|
|
|
Institutions,
|
|
|
|
RequisitionResponse,
|
|
|
|
Requisitions,
|
|
|
|
TXRoot,
|
|
|
|
)
|
2022-07-15 10:09:54 +00:00
|
|
|
from serde import ValidationError
|
2023-02-09 07:20:00 +00:00
|
|
|
|
2022-02-28 20:02:50 +00:00
|
|
|
# Project imports
|
|
|
|
from settings import settings
|
2022-07-15 10:09:54 +00:00
|
|
|
from simplejson.errors import JSONDecodeError
|
|
|
|
from twisted.internet.defer import inlineCallbacks
|
|
|
|
from twisted.internet.task import LoopingCall
|
2022-02-28 20:02:50 +00:00
|
|
|
|
|
|
|
|
2022-03-05 21:52:31 +00:00
|
|
|
class Nordigen(util.Base):
|
2022-02-28 20:02:50 +00:00
|
|
|
"""
|
|
|
|
Class to manage calls to Open Banking APIs through Nordigen.
|
|
|
|
"""
|
|
|
|
|
2022-03-22 21:56:35 +00:00
|
|
|
def __init__(self, sinks):
|
2022-03-05 21:52:31 +00:00
|
|
|
super().__init__()
|
2022-03-22 21:56:35 +00:00
|
|
|
self.sinks = sinks
|
2022-03-04 21:06:20 +00:00
|
|
|
self.token = None
|
2022-03-22 21:56:35 +00:00
|
|
|
self.banks = {}
|
|
|
|
self.authed = False
|
2022-05-02 15:33:00 +00:00
|
|
|
self.requisitions = None
|
2022-03-22 21:56:35 +00:00
|
|
|
|
|
|
|
# Get the banks from the config and cache them
|
2022-05-02 15:33:00 +00:00
|
|
|
self.log.debug("Getting mapped accounts.")
|
2022-03-22 21:56:35 +00:00
|
|
|
self.get_mapped_accounts()
|
2022-05-02 15:33:00 +00:00
|
|
|
self.log.debug("Finished getting mapped accounts.")
|
2022-03-22 21:56:35 +00:00
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
self.log.debug("Creating loop to get access token.")
|
2022-03-22 21:56:35 +00:00
|
|
|
self.lc = LoopingCall(self.get_access_token)
|
|
|
|
self.lc.start(int(settings.Nordigen.TokenRefreshSec))
|
2022-05-02 15:33:00 +00:00
|
|
|
self.log.debug("Finished creating loops.")
|
2022-03-22 21:56:35 +00:00
|
|
|
|
|
|
|
def __authed__(self):
|
|
|
|
"""
|
|
|
|
Called when we have received the access token.
|
|
|
|
"""
|
|
|
|
self.log.info("Connection authenticated.")
|
2022-05-02 15:33:00 +00:00
|
|
|
# self.get_requisitions()
|
|
|
|
d = self.get_all_account_info()
|
|
|
|
d.addCallback(self.got_all_account_info)
|
2022-05-05 08:18:35 +00:00
|
|
|
self.sinks.all_sinks_authenticated()
|
2022-03-22 21:56:35 +00:00
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
def got_all_account_info(self, account_infos):
|
2022-03-22 21:56:35 +00:00
|
|
|
# Filter for added accounts since we only do that for TrueLayer
|
|
|
|
account_infos = {
|
2022-04-12 21:06:28 +00:00
|
|
|
bank: accounts
|
|
|
|
for bank, accounts in account_infos.items()
|
|
|
|
for account in accounts
|
|
|
|
if account["account_id"] in self.banks
|
2022-03-22 21:56:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.sinks.got_account_info("nordigen", account_infos)
|
2022-02-28 20:02:50 +00:00
|
|
|
|
2022-03-25 18:46:08 +00:00
|
|
|
self.lc_tx = LoopingCall(self.transaction_loop)
|
|
|
|
self.lc_tx.start(int(settings.Nordigen.RefreshSec))
|
|
|
|
|
|
|
|
def transaction_loop(self):
|
|
|
|
for account_id in self.banks:
|
|
|
|
transactions = self.get_transactions(account_id)
|
2022-05-02 15:33:00 +00:00
|
|
|
transactions.addCallback(self.got_transactions, account_id)
|
2022-03-25 18:46:08 +00:00
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
def got_transactions(self, transactions, account_id):
|
|
|
|
self.sinks.got_transactions("nordigen", account_id, transactions)
|
|
|
|
|
|
|
|
def generic_deferred(self, response, dest_func):
|
|
|
|
"""
|
|
|
|
Generic function to take a treq response and fire a callback with
|
|
|
|
its content to dest_func.
|
|
|
|
:param response: a treq response
|
|
|
|
:param dest_func: function to call with the response data
|
|
|
|
"""
|
|
|
|
self.log.debug(f"Generic deferred received: {response}")
|
|
|
|
content = response.content()
|
|
|
|
content.addCallback(dest_func)
|
|
|
|
|
|
|
|
@inlineCallbacks
|
2022-02-28 20:02:50 +00:00
|
|
|
def get_access_token(self):
|
|
|
|
"""
|
|
|
|
Get an access token.
|
|
|
|
:return: True or False
|
|
|
|
:rtype: bool
|
|
|
|
"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
}
|
2022-02-28 20:02:50 +00:00
|
|
|
data = {
|
|
|
|
"secret_id": settings.Nordigen.ID,
|
|
|
|
"secret_key": settings.Nordigen.Key,
|
|
|
|
}
|
|
|
|
path = f"{settings.Nordigen.Base}/token/new/"
|
2022-05-02 15:33:00 +00:00
|
|
|
self.log.debug("Getting new access token.")
|
|
|
|
d = yield treq.post(path, headers=headers, data=data)
|
|
|
|
content = yield d.content()
|
2022-02-28 20:02:50 +00:00
|
|
|
try:
|
2022-05-02 15:33:00 +00:00
|
|
|
obj = AccessToken.from_json(content)
|
2022-03-25 18:04:17 +00:00
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()
|
|
|
|
self.token = parsed["access"]
|
|
|
|
self.log.info("Refreshed access token")
|
2022-03-22 21:56:35 +00:00
|
|
|
if not self.authed:
|
|
|
|
self.__authed__()
|
|
|
|
self.authed = True
|
2022-02-28 20:02:50 +00:00
|
|
|
|
|
|
|
def get_institutions(self, country, filter_name=None):
|
|
|
|
"""
|
|
|
|
Get a list of supported institutions.
|
2022-03-04 23:22:57 +00:00
|
|
|
:param country: country to query
|
|
|
|
:param filter_name: return only results with this in the name
|
|
|
|
:return: list of institutions
|
|
|
|
:rtype: list
|
2022-02-28 20:02:50 +00:00
|
|
|
"""
|
|
|
|
if not len(country) == 2:
|
|
|
|
return False
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-02-28 20:02:50 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/institutions/?country={country}"
|
|
|
|
r = requests.get(path, headers=headers)
|
|
|
|
try:
|
2022-03-25 18:04:17 +00:00
|
|
|
parsed_pre = r.json()
|
2022-02-28 20:02:50 +00:00
|
|
|
except JSONDecodeError:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.error(f"Error parsing institutions response: {r.content}")
|
2022-02-28 20:02:50 +00:00
|
|
|
return False
|
2022-03-25 18:04:17 +00:00
|
|
|
parsed = {"institutions": parsed_pre}
|
|
|
|
try:
|
|
|
|
obj = Institutions.from_dict(parsed)
|
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()["institutions"]
|
2022-02-28 20:02:50 +00:00
|
|
|
new_list = []
|
|
|
|
if filter_name:
|
|
|
|
for i in parsed:
|
|
|
|
if filter_name in i["name"]:
|
|
|
|
new_list.append(i)
|
|
|
|
return new_list
|
|
|
|
return parsed
|
2022-03-22 21:56:35 +00:00
|
|
|
|
|
|
|
def build_link(self, institution_id):
|
|
|
|
"""Create a link to access an institution.
|
|
|
|
:param institution_id: ID of the institution
|
|
|
|
"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-03-22 21:56:35 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/requisitions/"
|
2022-04-12 21:06:28 +00:00
|
|
|
data = {
|
|
|
|
"institution_id": institution_id,
|
|
|
|
"redirect": settings.Nordigen.CallbackURL,
|
|
|
|
}
|
2022-03-22 21:56:35 +00:00
|
|
|
r = requests.post(path, headers=headers, data=data)
|
|
|
|
try:
|
2022-03-25 18:04:17 +00:00
|
|
|
obj = Agreement.from_json(r.content)
|
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()
|
2022-03-22 21:56:35 +00:00
|
|
|
if "link" in parsed:
|
|
|
|
return parsed["link"]
|
|
|
|
return False
|
|
|
|
|
|
|
|
def create_auth_url(self, country, bank_name):
|
|
|
|
"""Helper to look up a bank and create a link.
|
|
|
|
:param country: country
|
|
|
|
:param bank_name: bank name string to search"""
|
|
|
|
institutions = self.get_institutions(country, filter_name=bank_name)
|
|
|
|
# We were not precise enough to have one result
|
|
|
|
if not len(institutions) == 1:
|
|
|
|
return False
|
|
|
|
institution = institutions[0]
|
|
|
|
link = self.build_link(institution["id"])
|
|
|
|
if not link:
|
|
|
|
return False
|
|
|
|
return link
|
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
@inlineCallbacks
|
2022-03-22 21:56:35 +00:00
|
|
|
def get_requisitions(self):
|
|
|
|
"""
|
|
|
|
Get a list of active accounts.
|
|
|
|
"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-03-22 21:56:35 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/requisitions"
|
2022-05-02 15:33:00 +00:00
|
|
|
d = yield treq.get(path, headers=headers)
|
|
|
|
content = yield d.content()
|
2022-03-22 21:56:35 +00:00
|
|
|
try:
|
2022-05-02 15:33:00 +00:00
|
|
|
obj = Requisitions.from_json(content)
|
2022-03-25 18:04:17 +00:00
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()
|
2022-03-22 21:56:35 +00:00
|
|
|
if "results" in parsed:
|
|
|
|
return parsed["results"]
|
|
|
|
else:
|
|
|
|
self.log.error(f"Results not in requisitions response: {parsed}")
|
2022-03-25 18:04:17 +00:00
|
|
|
|
2022-03-22 21:56:35 +00:00
|
|
|
return False
|
|
|
|
|
2022-04-09 19:18:23 +00:00
|
|
|
def delete_requisition(self, requisition_id):
|
|
|
|
"""
|
|
|
|
Delete a requisision ID.
|
|
|
|
"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-04-09 19:18:23 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/requisitions/{requisition_id}/"
|
|
|
|
r = requests.delete(path, headers=headers)
|
|
|
|
try:
|
|
|
|
obj = RequisitionResponse.from_json(r.content)
|
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()
|
|
|
|
return parsed
|
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
@inlineCallbacks
|
2022-03-22 21:56:35 +00:00
|
|
|
def get_accounts(self, requisition):
|
|
|
|
"""
|
|
|
|
Get a list of accounts for a requisition.
|
|
|
|
:param requisition: requisition ID"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-03-22 21:56:35 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/requisitions/{requisition}/"
|
2022-05-02 15:33:00 +00:00
|
|
|
d = yield treq.get(path, headers=headers)
|
|
|
|
content = yield d.content()
|
2022-03-22 21:56:35 +00:00
|
|
|
try:
|
2022-05-02 15:33:00 +00:00
|
|
|
obj = Agreement.from_json(content)
|
2022-03-25 18:04:17 +00:00
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()
|
2022-03-22 21:56:35 +00:00
|
|
|
if "accounts" in parsed:
|
|
|
|
return parsed["accounts"]
|
|
|
|
return False
|
|
|
|
|
2022-04-29 10:34:01 +00:00
|
|
|
def get_ownernames(self):
|
|
|
|
"""
|
|
|
|
Get list of supplementary owner names.
|
|
|
|
"""
|
|
|
|
ownernames = loads(settings.Nordigen.OwnerNames)
|
|
|
|
return ownernames
|
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
@inlineCallbacks
|
2022-03-22 21:56:35 +00:00
|
|
|
def get_account(self, account_id):
|
|
|
|
"""
|
|
|
|
Get details of an account.
|
|
|
|
:param requisition: requisition ID"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-03-22 21:56:35 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/accounts/{account_id}/details/"
|
2022-05-02 15:33:00 +00:00
|
|
|
d = yield treq.get(path, headers=headers)
|
|
|
|
content = yield d.content()
|
2022-03-22 21:56:35 +00:00
|
|
|
try:
|
2022-05-02 15:33:00 +00:00
|
|
|
obj = AccountDetails.from_json(content)
|
2022-03-25 18:04:17 +00:00
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
2022-04-24 18:21:45 +00:00
|
|
|
parsed_obj = obj.to_dict()
|
|
|
|
if "account" not in parsed_obj:
|
|
|
|
return False
|
|
|
|
parsed = parsed_obj["account"]
|
2022-03-22 21:56:35 +00:00
|
|
|
if "bban" in parsed and parsed["currency"] == "GBP":
|
|
|
|
sort_code = parsed["bban"][0:6]
|
|
|
|
account_number = parsed["bban"][6:]
|
2022-04-24 18:21:45 +00:00
|
|
|
if "ownerName" not in parsed:
|
2022-04-29 10:34:01 +00:00
|
|
|
ownernames = self.get_ownernames()
|
|
|
|
if account_id in ownernames:
|
|
|
|
parsed["ownerName"] = ownernames[account_id]
|
2022-07-15 10:09:54 +00:00
|
|
|
self.log.info(
|
|
|
|
f"Found supplementary owner name for {account_id}: {ownernames[account_id]}"
|
|
|
|
)
|
2022-04-29 10:34:01 +00:00
|
|
|
else:
|
2022-05-09 07:24:04 +00:00
|
|
|
self.log.error(f"No owner name in parsed, cannot use: {account_id}")
|
2022-04-29 10:34:01 +00:00
|
|
|
return False
|
2022-04-21 19:45:27 +00:00
|
|
|
recipient = parsed["ownerName"]
|
2022-03-22 21:56:35 +00:00
|
|
|
del parsed["bban"]
|
2022-04-29 10:34:01 +00:00
|
|
|
if "iban" in parsed:
|
|
|
|
del parsed["iban"]
|
2022-03-22 21:56:35 +00:00
|
|
|
sort_code = "-".join(list(map("".join, zip(*[iter(sort_code)] * 2))))
|
|
|
|
parsed["sort_code"] = sort_code
|
|
|
|
parsed["number"] = account_number
|
2022-04-21 19:45:27 +00:00
|
|
|
parsed["recipient"] = recipient
|
2022-03-22 21:56:35 +00:00
|
|
|
# Let's add the account ID so we can reference it later
|
|
|
|
parsed["account_id"] = account_id
|
|
|
|
return parsed
|
|
|
|
|
|
|
|
def get_mapped_accounts(self):
|
|
|
|
existing_entry = loads(settings.Nordigen.Maps)
|
|
|
|
self.banks = existing_entry
|
|
|
|
|
2022-06-01 08:09:10 +00:00
|
|
|
@inlineCallbacks
|
2022-05-02 15:33:00 +00:00
|
|
|
def map_account(self, account_id): # TODO: inlineCallbacks?
|
2022-03-22 21:56:35 +00:00
|
|
|
"""
|
|
|
|
Map an account_id at a bank to an account_name.
|
|
|
|
This enables the account for fetching.
|
|
|
|
Data type: {"monzo": [account, ids, here],
|
|
|
|
"revolut": [account, ids, here]}
|
|
|
|
"""
|
2022-06-01 08:09:10 +00:00
|
|
|
account_data = yield self.get_account(account_id)
|
2022-03-22 21:56:35 +00:00
|
|
|
currency = account_data["currency"]
|
|
|
|
|
|
|
|
existing_entry = loads(settings.Nordigen.Maps)
|
|
|
|
if account_id in existing_entry:
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
existing_entry.append(account_id)
|
|
|
|
|
|
|
|
settings.Nordigen.Maps = dumps(existing_entry)
|
|
|
|
self.banks = existing_entry
|
|
|
|
settings.write()
|
|
|
|
|
|
|
|
return currency
|
|
|
|
|
2022-04-09 19:18:23 +00:00
|
|
|
def unmap_account(self, account_id):
|
|
|
|
"""
|
|
|
|
Unmap an account_id at a bank to an account_name.
|
|
|
|
This disables the account for fetching.
|
|
|
|
Data type: {"monzo": [account, ids, here],
|
|
|
|
"revolut": [account, ids, here]}
|
|
|
|
"""
|
|
|
|
|
|
|
|
existing_entry = loads(settings.Nordigen.Maps)
|
|
|
|
if account_id not in existing_entry:
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
existing_entry.remove(account_id)
|
|
|
|
|
|
|
|
settings.Nordigen.Maps = dumps(existing_entry)
|
|
|
|
self.banks = existing_entry
|
|
|
|
settings.write()
|
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
@inlineCallbacks
|
2022-03-22 21:56:35 +00:00
|
|
|
def get_all_account_info(self):
|
|
|
|
to_return = {}
|
2022-05-02 15:33:00 +00:00
|
|
|
requisitions = yield self.get_requisitions()
|
2022-03-22 21:56:35 +00:00
|
|
|
if not requisitions:
|
|
|
|
self.log.error("Could not get requisitions.")
|
|
|
|
return {}
|
|
|
|
for req in requisitions:
|
|
|
|
if not req["accounts"]:
|
|
|
|
continue
|
2022-05-02 15:33:00 +00:00
|
|
|
accounts = yield self.get_accounts(req["id"])
|
2022-03-22 21:56:35 +00:00
|
|
|
for account_id in accounts:
|
2022-05-02 15:33:00 +00:00
|
|
|
account_info = yield self.get_account(account_id)
|
2022-03-22 21:56:35 +00:00
|
|
|
if not account_info:
|
|
|
|
continue
|
|
|
|
if req["institution_id"] in to_return:
|
|
|
|
to_return[req["institution_id"]].append(account_info)
|
|
|
|
else:
|
|
|
|
to_return[req["institution_id"]] = [account_info]
|
|
|
|
return to_return
|
2022-03-25 18:04:17 +00:00
|
|
|
|
2022-03-25 18:46:08 +00:00
|
|
|
def normalise_transactions(self, transactions):
|
|
|
|
for transaction in transactions:
|
|
|
|
# Rename ID
|
2022-04-24 18:21:45 +00:00
|
|
|
if "transactionId" in transaction:
|
|
|
|
transaction["transaction_id"] = transaction["transactionId"]
|
|
|
|
del transaction["transactionId"]
|
2022-04-29 10:34:01 +00:00
|
|
|
else:
|
|
|
|
# No transaction ID. This is a problem for our implementation
|
|
|
|
|
2022-07-15 10:09:54 +00:00
|
|
|
tx_hash = sha256(
|
|
|
|
dumps(transaction, sort_keys=True).encode("utf8")
|
|
|
|
).hexdigest()
|
2022-04-29 10:34:01 +00:00
|
|
|
transaction["transaction_id"] = tx_hash
|
2022-03-25 18:46:08 +00:00
|
|
|
|
|
|
|
# Rename timestamp
|
|
|
|
transaction["timestamp"] = transaction["bookingDate"]
|
|
|
|
del transaction["bookingDate"]
|
|
|
|
|
|
|
|
transaction["amount"] = float(transaction["transactionAmount"]["amount"])
|
|
|
|
transaction["currency"] = transaction["transactionAmount"]["currency"]
|
|
|
|
del transaction["transactionAmount"]
|
|
|
|
|
|
|
|
transaction["reference"] = transaction["remittanceInformationUnstructured"]
|
|
|
|
del transaction["remittanceInformationUnstructured"]
|
|
|
|
|
2022-05-02 15:33:00 +00:00
|
|
|
@inlineCallbacks
|
2022-03-25 18:04:17 +00:00
|
|
|
def get_transactions(self, account_id):
|
|
|
|
"""
|
|
|
|
Get all transactions for an account.
|
|
|
|
:param account_id: account to fetch transactions for
|
|
|
|
:return: list of transactions
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-03-25 18:04:17 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/accounts/{account_id}/transactions/"
|
2022-05-02 15:33:00 +00:00
|
|
|
d = yield treq.get(path, headers=headers)
|
|
|
|
content = yield d.content()
|
2022-04-09 18:59:22 +00:00
|
|
|
try:
|
2022-05-02 15:33:00 +00:00
|
|
|
obj = TXRoot.from_json(content)
|
2022-04-09 18:59:22 +00:00
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
2022-04-20 19:46:19 +00:00
|
|
|
parsed_obj = obj.to_dict()
|
|
|
|
if "transactions" not in parsed_obj:
|
|
|
|
self.log.warning(f"No transactions for account: {account_id}")
|
|
|
|
return {}
|
|
|
|
parsed = parsed_obj["transactions"]["booked"]
|
2022-03-25 18:46:08 +00:00
|
|
|
self.normalise_transactions(parsed)
|
|
|
|
return parsed
|
2022-04-09 18:59:22 +00:00
|
|
|
|
|
|
|
def get_balance(self, account_id):
|
|
|
|
"""
|
|
|
|
Get the balance and currency of an account.
|
|
|
|
:param account_id: the account ID
|
|
|
|
:return: tuple of (currency, amount)
|
|
|
|
:rtype: tuple
|
|
|
|
"""
|
2022-04-12 21:06:28 +00:00
|
|
|
headers = {
|
|
|
|
"accept": "application/json",
|
|
|
|
"Authorization": f"Bearer {self.token}",
|
|
|
|
}
|
2022-04-09 18:59:22 +00:00
|
|
|
path = f"{settings.Nordigen.Base}/accounts/{account_id}/balances/"
|
|
|
|
r = requests.get(path, headers=headers)
|
|
|
|
try:
|
|
|
|
obj = AccountBalancesRoot.from_json(r.content)
|
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
2022-06-01 08:09:10 +00:00
|
|
|
return (False, False)
|
2022-06-14 07:19:11 +00:00
|
|
|
parsed = obj.to_dict()
|
2022-04-09 18:59:22 +00:00
|
|
|
total = 0
|
|
|
|
currency = None
|
2022-06-19 17:26:38 +00:00
|
|
|
if "balances" not in parsed:
|
|
|
|
self.log.error(f"No balances: {parsed}")
|
|
|
|
return (False, False)
|
2022-06-14 07:19:11 +00:00
|
|
|
for entry in parsed["balances"]:
|
2022-04-09 18:59:22 +00:00
|
|
|
if currency:
|
|
|
|
if not currency == entry["balanceAmount"]["currency"]:
|
|
|
|
self.log.error("Different currencies in balance query.")
|
2022-06-01 08:09:10 +00:00
|
|
|
return (False, False)
|
2022-06-14 07:19:11 +00:00
|
|
|
if not entry["balanceType"] == "expected":
|
2022-04-23 18:52:42 +00:00
|
|
|
continue
|
2022-04-09 18:59:22 +00:00
|
|
|
total += float(entry["balanceAmount"]["amount"])
|
|
|
|
currency = entry["balanceAmount"]["currency"]
|
|
|
|
return (currency, total)
|
|
|
|
|
|
|
|
def get_total_map(self):
|
|
|
|
"""
|
|
|
|
Return a dictionary keyed by currencies with the amounts as values.
|
|
|
|
:return: dict keyed by currency, values are amounts
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
|
|
|
totals = {}
|
|
|
|
for account_id in self.banks:
|
|
|
|
currency, amount = self.get_balance(account_id)
|
|
|
|
if not amount:
|
|
|
|
continue
|
2022-06-01 08:09:10 +00:00
|
|
|
if not currency:
|
|
|
|
continue
|
2022-04-09 18:59:22 +00:00
|
|
|
if currency in totals:
|
|
|
|
totals[currency] += amount
|
|
|
|
else:
|
|
|
|
totals[currency] = amount
|
|
|
|
return totals
|