beancount-gocardless 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.3
2
+ Name: beancount-gocardless
3
+ Version: 0.1.0
4
+ Summary:
5
+ License: MIT
6
+ Requires-Python: >=3.12
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: beancount
12
+ Requires-Dist: beangulp
13
+ Requires-Dist: pyyaml
14
+ Requires-Dist: requests
15
+ Requires-Dist: requests-cache
16
+ Description-Content-Type: text/markdown
17
+
18
+
File without changes
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "beancount-gocardless"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = []
6
+ readme = "README.md"
7
+ requires-python = ">=3.12"
8
+ dependencies = [
9
+ "requests",
10
+ "requests-cache",
11
+ "beancount",
12
+ "beangulp",
13
+ "pyyaml",
14
+ ]
15
+ license = "MIT"
16
+ license-files = ["LICENSE"]
17
+
18
+ [tool.poetry]
19
+ packages = [{include = "beancount_gocardless", from = "src"}]
20
+
21
+
22
+ [build-system]
23
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
24
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,71 @@
1
+ import argparse
2
+ import sys
3
+ import os
4
+ from .client import NordigenClient
5
+
6
+
7
+ def parse_args():
8
+ parser = argparse.ArgumentParser(description="Nordigen CLI Utility")
9
+ parser.add_argument(
10
+ "mode",
11
+ choices=["list_banks", "create_link", "list_accounts", "delete_link"],
12
+ help="Operation mode",
13
+ )
14
+ parser.add_argument(
15
+ "--secret_id",
16
+ default=os.getenv("NORDIGEN_SECRET_ID"),
17
+ help="API secret ID (defaults to env var NORDIGEN_SECRET_ID)",
18
+ )
19
+ parser.add_argument(
20
+ "--secret_key",
21
+ default=os.getenv("NORDIGEN_SECRET_KEY"),
22
+ help="API secret key (defaults to env var NORDIGEN_SECRET_KEY)",
23
+ )
24
+ parser.add_argument(
25
+ "--country", default="GB", help="Country code for listing banks"
26
+ )
27
+ parser.add_argument(
28
+ "--reference", default="beancount", help="Unique reference for bank linking"
29
+ )
30
+ parser.add_argument("--bank", help="Bank ID for linking")
31
+ return parser.parse_args()
32
+
33
+
34
+ def main():
35
+ args = parse_args()
36
+
37
+ if not args.secret_id or not args.secret_key:
38
+ print(
39
+ "Error: Secret ID and Secret Key are required (pass as args or set env vars NORDIGEN_SECRET_ID and NORDIGEN_SECRET_KEY)",
40
+ file=sys.stderr,
41
+ )
42
+ sys.exit(1)
43
+
44
+ client = NordigenClient(
45
+ args.secret_id,
46
+ args.secret_key,
47
+ {"expire_after": 3600 * 24},
48
+ )
49
+
50
+ if args.mode == "list_banks":
51
+ banks = client.list_banks(args.country)
52
+ for b in banks:
53
+ print(b["name"] + ": " + b["id"])
54
+ elif args.mode == "create_link":
55
+ if not args.bank:
56
+ print("--bank is required for create_link", file=sys.stderr)
57
+ sys.exit(1)
58
+ print(client.create_link(args.reference, args.bank))
59
+ elif args.mode == "list_accounts":
60
+ accounts = client.list_accounts()
61
+ for a in accounts:
62
+ print(
63
+ f"{a["institution_id"]} {a['name']}: {a['iban']} {a['currency']} ({a['reference']}/{a['id']})"
64
+ )
65
+
66
+ elif args.mode == "delete_link":
67
+ print(client.delete_link(args.reference))
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
@@ -0,0 +1,173 @@
1
+ from datetime import date, timedelta, datetime
2
+ import requests_cache
3
+ import requests
4
+ from typing import Protocol, TypedDict, Optional
5
+
6
+
7
+ class CacheOptions(TypedDict, total=False):
8
+ cache_name: requests_cache.StrOrPath
9
+ backend: Optional[requests_cache.BackendSpecifier]
10
+ expire_after: requests_cache.ExpirationTime
11
+ old_data_on_error: bool
12
+
13
+
14
+ class HttpServiceException(Exception):
15
+ """Exception raised for HTTP service errors."""
16
+
17
+ def __init__(self, error, response_text=None):
18
+ self.error = error
19
+ self.response_text = response_text
20
+ super().__init__(f"{error}: {response_text}")
21
+
22
+
23
+ class BaseService:
24
+ """Base class for HTTP services handling authentication and requests."""
25
+
26
+ BASE_URL = "https://bankaccountdata.gocardless.com/api/v2"
27
+
28
+ DEFAULT_CACHE_OPTIONS: CacheOptions = {
29
+ "cache_name": "nordigen",
30
+ "backend": "sqlite",
31
+ "expire_after": 3600 * 24,
32
+ "old_data_on_error": False,
33
+ }
34
+
35
+ def __init__(
36
+ self,
37
+ secret_id: str,
38
+ secret_key: str,
39
+ cache_options: Optional[CacheOptions],
40
+ ):
41
+ self.secret_id = secret_id
42
+ self.secret_key = secret_key
43
+ self.token = None
44
+ merged_options = {**self.DEFAULT_CACHE_OPTIONS, **(cache_options or {})}
45
+ self.session = requests_cache.CachedSession(**merged_options)
46
+
47
+ def _ensure_token_valid(self):
48
+ """Ensure a valid token exists (no-op here as Nordigen doesn't provide refresh tokens)."""
49
+ if not self.token:
50
+ self.get_token()
51
+
52
+ def get_token(self):
53
+ """Fetch a new API token using credentials."""
54
+ response = requests.post(
55
+ f"{self.BASE_URL}/token/new/",
56
+ data={"secret_id": self.secret_id, "secret_key": self.secret_key},
57
+ )
58
+ self._handle_response(response)
59
+ self.token = response.json()["access"]
60
+
61
+ def _handle_response(self, response):
62
+ """Check response status and handle errors."""
63
+ try:
64
+ response.raise_for_status()
65
+ except requests.exceptions.HTTPError as e:
66
+ raise HttpServiceException(str(e), response.text)
67
+
68
+ def _request(self, method, endpoint, params=None, data=None):
69
+ """Execute an HTTP request with token handling."""
70
+ url = f"{self.BASE_URL}{endpoint}"
71
+ self._ensure_token_valid()
72
+ headers = {"Authorization": f"Bearer {self.token}"}
73
+
74
+ response = self.session.request(
75
+ method, url, headers=headers, params=params, data=data
76
+ )
77
+
78
+ # Retry once if token expired
79
+ if response.status_code == 401:
80
+ self.get_token()
81
+ headers = {"Authorization": f"Bearer {self.token}"}
82
+ response = self.session.request(
83
+ method, url, headers=headers, params=params, data=data
84
+ )
85
+
86
+ self._handle_response(response)
87
+ return response
88
+
89
+ def _get(self, endpoint, params=None):
90
+ return self._request("GET", endpoint, params=params).json()
91
+
92
+ def _post(self, endpoint, data=None):
93
+ return self._request("POST", endpoint, data=data).json()
94
+
95
+ def _delete(self, endpoint):
96
+ return self._request("DELETE", endpoint).json()
97
+
98
+
99
+ class NordigenClient(BaseService):
100
+ """Client for interacting with the Nordigen API."""
101
+
102
+ def list_banks(self, country="GB"):
103
+ """List available institutions for a country."""
104
+ return [
105
+ {"name": bank["name"], "id": bank["id"]}
106
+ for bank in self._get("/institutions/", params={"country": country})
107
+ ]
108
+
109
+ def find_requisition_id(self, reference):
110
+ """Find requisition ID by reference."""
111
+ requisitions = self._get("/requisitions/")["results"]
112
+ return next(
113
+ (req["id"] for req in requisitions if req["reference"] == reference), None
114
+ )
115
+
116
+ def create_link(self, reference, bank_id, redirect_url="http://localhost"):
117
+ """Create a new bank link requisition."""
118
+ if self.find_requisition_id(reference):
119
+ return {"status": "exists", "message": f"Link {reference} exists"}
120
+
121
+ response = self._post(
122
+ "/requisitions/",
123
+ data={
124
+ "redirect": redirect_url,
125
+ "institution_id": bank_id,
126
+ "reference": reference,
127
+ },
128
+ )
129
+ return {
130
+ "status": "created",
131
+ "link": response["link"],
132
+ "message": f"Complete linking at: {response['link']}",
133
+ }
134
+
135
+ def list_accounts(self):
136
+ """List all connected accounts with details."""
137
+ accounts = []
138
+ for req in self._get("/requisitions/")["results"]:
139
+ for account_id in req["accounts"]:
140
+ account = self._get(f"/accounts/{account_id}")
141
+ details = self._get(f"/accounts/{account_id}/details")["account"]
142
+
143
+ accounts.append(
144
+ {
145
+ "id": account_id,
146
+ "institution_id": req.get("institution_id", ""),
147
+ "reference": req["reference"],
148
+ "iban": account.get("iban", ""),
149
+ "currency": details.get("currency", ""),
150
+ "name": details.get("name", "Unknown"),
151
+ }
152
+ )
153
+ return accounts
154
+
155
+ def delete_link(self, reference):
156
+ """Delete a bank link by reference."""
157
+ req_id = self.find_requisition_id(reference)
158
+ if not req_id:
159
+ return {"status": "not_found", "message": f"Link {reference} not found"}
160
+
161
+ self._delete(f"/requisitions/{req_id}")
162
+ return {"status": "deleted", "message": f"Link {reference} removed"}
163
+
164
+ def get_transactions(self, account_id, days_back=180):
165
+ """Retrieve transactions for an account."""
166
+ date_from = (datetime.now() - timedelta(days=days_back)).strftime("%Y-%m-%d")
167
+ return self._get(
168
+ f"/accounts/{account_id}/transactions/",
169
+ params={
170
+ "date_from": date_from,
171
+ "date_to": datetime.now().strftime("%Y-%m-%d"),
172
+ },
173
+ ).get("transactions", [])
@@ -0,0 +1,183 @@
1
+ from datetime import date, timedelta, datetime
2
+ from os import path
3
+ import beangulp
4
+ import yaml
5
+ from beancount.core import amount, data, flags
6
+ from beancount.core.number import D
7
+ from .client import NordigenClient
8
+
9
+
10
+ class NordigenImporter(beangulp.Importer):
11
+ """An importer for Nordigen API with improved structure and extensibility."""
12
+
13
+ def __init__(self):
14
+ self.config = None
15
+ self._client = None
16
+
17
+ @property
18
+ def client(self):
19
+ if not self._client:
20
+ self._client = NordigenClient(
21
+ self.config["secret_id"],
22
+ self.config["secret_key"],
23
+ cache_options={"expire_after": 3600 * 24, "old_data_on_error": True},
24
+ )
25
+
26
+ return self._client
27
+
28
+ def identify(self, filepath: str) -> bool:
29
+ return path.basename(filepath).endswith("nordigen.yaml")
30
+
31
+ def account(self, filepath: str) -> str:
32
+ return ""
33
+
34
+ def load_config(self, filepath: str):
35
+ """Load configuration from YAML file."""
36
+ with open(filepath, "r") as f:
37
+ raw_config = f.read()
38
+ expanded_config = path.expandvars(raw_config)
39
+ self.config = yaml.safe_load(expanded_config)
40
+
41
+ return self.config
42
+
43
+ def get_transactions_data(self, account_id):
44
+ """Get transactions data either from API or debug files."""
45
+ transactions_data = self.client.get_transactions(account_id)
46
+
47
+ return transactions_data
48
+
49
+ def get_all_transactions(self, transactions_data):
50
+ """Combine and sort booked and pending transactions."""
51
+ all_transactions = [
52
+ (tx, "booked") for tx in transactions_data.get("booked", [])
53
+ ] + [(tx, "pending") for tx in transactions_data.get("pending", [])]
54
+ return sorted(
55
+ all_transactions,
56
+ key=lambda x: x[0].get("valueDate") or x[0].get("bookingDate"),
57
+ )
58
+
59
+ def add_metadata(self, transaction, filing_account: str):
60
+ """Extract metadata from transaction - overridable method."""
61
+ metakv = {}
62
+
63
+ # Transaction ID
64
+ if "transactionId" in transaction:
65
+ metakv["nordref"] = transaction["transactionId"]
66
+
67
+ # Names
68
+ if "creditorName" in transaction:
69
+ metakv["creditorName"] = transaction["creditorName"]
70
+ if "debtorName" in transaction:
71
+ metakv["debtorName"] = transaction["debtorName"]
72
+
73
+ # Currency exchange
74
+ if "currencyExchange" in transaction:
75
+ instructedAmount = transaction["currencyExchange"]["instructedAmount"]
76
+ metakv["original"] = (
77
+ f"{instructedAmount['currency']} {instructedAmount['amount']}"
78
+ )
79
+
80
+ # Booking date if different from value date
81
+ if (
82
+ transaction.get("bookingDate")
83
+ and transaction.get("valueDate")
84
+ and transaction["bookingDate"] != transaction["valueDate"]
85
+ ):
86
+ metakv["bookingDate"] = transaction["bookingDate"]
87
+
88
+ if filing_account:
89
+ metakv["filing_account"] = filing_account
90
+
91
+ return metakv
92
+
93
+ def get_narration(self, transaction):
94
+ """Extract narration from transaction - overridable method."""
95
+ narration = ""
96
+
97
+ if "remittanceInformationUnstructured" in transaction:
98
+ narration += transaction["remittanceInformationUnstructured"]
99
+
100
+ if "remittanceInformationUnstructuredArray" in transaction:
101
+ narration += " ".join(transaction["remittanceInformationUnstructuredArray"])
102
+
103
+ return narration
104
+
105
+ def get_payee(self, transaction):
106
+ """Extract payee from transaction - overridable method."""
107
+ return ""
108
+
109
+ def get_transaction_date(self, transaction):
110
+ """Extract transaction date - overridable method."""
111
+ date_str = transaction.get("valueDate") or transaction.get("bookingDate")
112
+ return date.fromisoformat(date_str) if date_str else None
113
+
114
+ def get_transaction_status(self, status):
115
+ """Determine transaction status flag - overridable method."""
116
+ # Could be configured to use "!" for pending transactions status == 'pending'
117
+ return flags.FLAG_OKAY
118
+
119
+ def create_transaction_entry(
120
+ self, transaction, status, asset_account, filing_account
121
+ ):
122
+ """Create a Beancount transaction entry - overridable method."""
123
+ metakv = self.add_metadata(transaction, filing_account)
124
+ meta = data.new_metadata("", 0, metakv)
125
+
126
+ trx_date = self.get_transaction_date(transaction)
127
+ narration = self.get_narration(transaction)
128
+ payee = self.get_payee(transaction)
129
+ flag = self.get_transaction_status(status)
130
+
131
+ # Get transaction amount
132
+ tx_amount = amount.Amount(
133
+ D(str(transaction["transactionAmount"]["amount"])),
134
+ transaction["transactionAmount"]["currency"],
135
+ )
136
+
137
+ return data.Transaction(
138
+ meta,
139
+ trx_date,
140
+ flag,
141
+ payee,
142
+ narration,
143
+ data.EMPTY_SET,
144
+ data.EMPTY_SET,
145
+ [
146
+ data.Posting(
147
+ asset_account,
148
+ tx_amount,
149
+ None,
150
+ None,
151
+ None,
152
+ None,
153
+ ),
154
+ ],
155
+ )
156
+
157
+ def extract(self, filepath: str, existing: data.Entries) -> data.Entries:
158
+ """Extract entries from Nordigen transactions."""
159
+ self.load_config(filepath)
160
+
161
+ entries = []
162
+ for account in self.config["accounts"]:
163
+ account_id = account["id"]
164
+ asset_account = account["asset_account"]
165
+ filing_account = account.get("filing_account", None)
166
+
167
+ transactions_data = self.get_transactions_data(account_id)
168
+ all_transactions = self.get_all_transactions(transactions_data)
169
+
170
+ for transaction, status in all_transactions:
171
+ entry = self.create_transaction_entry(
172
+ transaction, status, asset_account, filing_account
173
+ )
174
+ entries.append(entry)
175
+
176
+ return entries
177
+
178
+ def cmp(self, entry1: data.Transaction, entry2: data.Transaction):
179
+ return (
180
+ "nordref" in entry1.meta
181
+ and "nordref" in entry2.meta
182
+ and entry1.meta["nordref"] == entry2.meta["nordref"]
183
+ )