beancount-gocardless 0.1.12__py3-none-any.whl → 0.1.14__py3-none-any.whl

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.
@@ -4,7 +4,7 @@ Complete coverage of all schemas from swagger.json
4
4
  """
5
5
 
6
6
  from typing import Optional, List, Dict, Any, TypedDict
7
- from pydantic import BaseModel, Field, ConfigDict, validator
7
+ from pydantic import BaseModel, Field, ConfigDict, field_validator
8
8
  from pydantic.alias_generators import to_camel
9
9
  from enum import Enum
10
10
 
@@ -37,8 +37,10 @@ class StatusEnum(str, Enum):
37
37
  class BalanceAmountSchema(BaseModel):
38
38
  """Balance amount schema."""
39
39
 
40
- amount: str
41
- currency: str
40
+ model_config = ConfigDict(populate_by_name=True)
41
+
42
+ amount: str = Field(default=None)
43
+ currency: str = Field(default=None)
42
44
 
43
45
 
44
46
  class BalanceSchema(BaseModel):
@@ -166,6 +168,8 @@ class AccountDetail(BaseModel):
166
168
  class TransactionAmountSchema(BaseModel):
167
169
  """Transaction amount schema."""
168
170
 
171
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
172
+
169
173
  amount: str
170
174
  currency: str
171
175
 
@@ -173,6 +177,8 @@ class TransactionAmountSchema(BaseModel):
173
177
  class InstructedAmount(BaseModel):
174
178
  """Instructed amount schema."""
175
179
 
180
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
181
+
176
182
  amount: str
177
183
  currency: str
178
184
 
@@ -180,6 +186,8 @@ class InstructedAmount(BaseModel):
180
186
  class CurrencyExchangeSchema(BaseModel):
181
187
  """Currency exchange schema."""
182
188
 
189
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
190
+
183
191
  source_currency: str
184
192
  exchange_rate: Optional[str] = None
185
193
  unit_currency: Optional[str] = None
@@ -192,8 +200,12 @@ class CurrencyExchangeSchema(BaseModel):
192
200
  class BalanceAfterTransactionSchema(BaseModel):
193
201
  """Balance after transaction schema."""
194
202
 
195
- balance_after_transaction: Optional[BalanceAmountSchema] = None
196
- balance_type: Optional[str] = None
203
+ model_config = ConfigDict(populate_by_name=True)
204
+
205
+ balance_amount: Optional[BalanceAmountSchema] = Field(
206
+ default=None, validation_alias="balanceAmount"
207
+ )
208
+ balance_type: Optional[str] = Field(default=None, validation_alias="balanceType")
197
209
 
198
210
 
199
211
  class TransactionSchema(BaseModel):
@@ -206,6 +218,19 @@ class TransactionSchema(BaseModel):
206
218
  value_date_time: Optional[str] = Field(None, description="Value date and time.")
207
219
  transaction_amount: TransactionAmountSchema
208
220
  currency_exchange: Optional[List[CurrencyExchangeSchema]] = None
221
+
222
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
223
+
224
+ @field_validator("currency_exchange", mode="before")
225
+ @classmethod
226
+ def normalize_currency_exchange(cls, v):
227
+ """Normalize currency_exchange to always be a list."""
228
+ if v is None:
229
+ return None
230
+ if isinstance(v, dict):
231
+ return [v]
232
+ return v
233
+
209
234
  creditor_name: Optional[str] = Field(None, description="Creditor name.")
210
235
  creditor_account: Optional[AccountSchema] = None
211
236
  creditor_agent: Optional[str] = Field(None, description="Creditor agent.")
@@ -259,7 +284,21 @@ class BankTransaction(BaseModel):
259
284
  )
260
285
  creditor_name: Optional[str] = Field(None, description="Creditor name.")
261
286
  creditor_account: Optional[AccountSchema] = None
287
+ ultimate_creditor: Optional[str] = Field(
288
+ default=None, description="Ultimate creditor."
289
+ )
262
290
  currency_exchange: Optional[List[CurrencyExchangeSchema]] = None
291
+
292
+ @field_validator("currency_exchange", mode="before")
293
+ @classmethod
294
+ def normalize_currency_exchange(cls, v):
295
+ """Normalize currency_exchange to always be a list."""
296
+ if v is None:
297
+ return None
298
+ if isinstance(v, dict):
299
+ return [v]
300
+ return v
301
+
263
302
  balance_after_transaction: Optional[BalanceAfterTransactionSchema] = None
264
303
  bank_transaction_code: Optional[str] = Field(
265
304
  None, description="Bank transaction code."
@@ -276,11 +315,13 @@ class BankTransaction(BaseModel):
276
315
  booking_date_time: Optional[str] = Field(None, description="Booking date and time.")
277
316
  value_date_time: Optional[str] = Field(None, description="Value date and time.")
278
317
  entry_reference: Optional[str] = Field(None, description="Entry reference.")
279
- additional_information_structured: Optional[str] = Field(
280
- None, description="Additional structured information."
318
+ additional_data_structured: Optional[Dict[str, Any]] = Field(
319
+ default=None,
320
+ description="Additional structured information.",
281
321
  )
282
322
  card_transaction: Optional[Dict[str, Any]] = Field(
283
- None, description="Card transaction details."
323
+ default=None,
324
+ description="Card transaction details.",
284
325
  )
285
326
  merchant_category_code: Optional[str] = Field(
286
327
  None, description="Merchant category code."
@@ -543,8 +584,12 @@ class AccountConfig(BaseModel):
543
584
  asset_account: str
544
585
  metadata: Dict[str, Any] = {}
545
586
  transaction_types: List[str] = ["booked", "pending"]
587
+ preferred_balance_type: Optional[str] = None
588
+ exclude_default_metadata: List[str] = []
589
+ metadata_fields: Optional[Dict[str, str]] = None
546
590
 
547
- @validator("transaction_types")
591
+ @field_validator("transaction_types")
592
+ @classmethod
548
593
  def validate_transaction_types(cls, v):
549
594
  allowed = {"booked", "pending"}
550
595
  if not set(v).issubset(allowed):
@@ -0,0 +1,39 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+
6
+ def load_dotenv(dotenv_path: Optional[str] = None) -> None:
7
+ """
8
+ Simple .env loader that searches in current and parent directories.
9
+ Only handles simple KEY=VALUE pairs and ignores comments.
10
+ """
11
+ if dotenv_path:
12
+ search_paths = [Path(dotenv_path)]
13
+ else:
14
+ # Search in current and parent directories
15
+ current = Path.cwd().resolve()
16
+ search_paths = [current / ".env"] + [p / ".env" for p in current.parents]
17
+
18
+ for path in search_paths:
19
+ if path.exists() and path.is_file():
20
+ try:
21
+ with open(path, "r") as f:
22
+ for line in f:
23
+ line = line.strip()
24
+ # Ignore comments and empty lines
25
+ if not line or line.startswith("#"):
26
+ continue
27
+ # Basic KEY=VALUE parsing
28
+ if "=" in line:
29
+ key, value = line.split("=", 1)
30
+ key = key.strip()
31
+ # Strip quotes and whitespace
32
+ value = value.strip().strip("'\"")
33
+ # Only set if not already present in environment
34
+ if key and key not in os.environ:
35
+ os.environ[key] = value
36
+ return # Stop after the first .env file found and successfully read
37
+ except Exception:
38
+ # Silently fail if we can't read a specific .env file
39
+ continue
@@ -0,0 +1,252 @@
1
+ Metadata-Version: 2.4
2
+ Name: beancount-gocardless
3
+ Version: 0.1.14
4
+ License-Expression: MIT
5
+ License-File: LICENSE
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.12
8
+ Requires-Python: <4,>=3.12
9
+ Requires-Dist: beancount
10
+ Requires-Dist: beangulp
11
+ Requires-Dist: pre-commit>=4.5.1
12
+ Requires-Dist: pydantic>=2.0.0
13
+ Requires-Dist: pyyaml
14
+ Requires-Dist: questionary>=2.0.0
15
+ Requires-Dist: requests
16
+ Requires-Dist: requests-cache
17
+ Requires-Dist: rich
18
+ Provides-Extra: dev
19
+ Requires-Dist: myst-parser; extra == 'dev'
20
+ Requires-Dist: sphinx; extra == 'dev'
21
+ Requires-Dist: sphinx-rtd-theme; extra == 'dev'
22
+ Provides-Extra: lint
23
+ Requires-Dist: ruff>=0.9.8; extra == 'lint'
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == 'test'
26
+ Requires-Dist: pytest-asyncio; extra == 'test'
27
+ Description-Content-Type: text/markdown
28
+
29
+ [![PyPI](https://img.shields.io/pypi/v/beancount-gocardless.svg)](https://pypi.org/project/beancount-gocardless/)
30
+ [![Python versions](https://img.shields.io/pypi/pyversions/beancount-gocardless.svg)](https://pypi.org/project/beancount-gocardless/)
31
+ [![License](https://img.shields.io/pypi/l/beancount-gocardless.svg)](https://pypi.org/project/beancount-gocardless/)
32
+ [![Documentation Status](https://readthedocs.org/projects/beancount-gocardless/badge/?version=latest)](https://beancount-gocardless.readthedocs.io/en/latest/)
33
+ [![Publish](https://github.com/jodoox/beancount-gocardless/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/jodoox/beancount-gocardless/actions/workflows/publish.yml)
34
+
35
+ # beancount-gocardless
36
+
37
+ Python client for the GoCardless Bank Account Data API (formerly Nordigen), with Pydantic models recreated from the OpenAPI/Swagger spec, plus a Beancount importer.
38
+
39
+ Inspired by https://github.com/tarioch/beancounttools.
40
+
41
+ Documentation: https://beancount-gocardless.readthedocs.io/en/latest/
42
+
43
+ ## Key features
44
+
45
+ - API client with typed Pydantic models for endpoints and data structures.
46
+ - Built-in HTTP caching via `requests-cache` (optional).
47
+ - CLI to manage bank authorization (list banks, create links, list accounts, delete links).
48
+ - Beancount importer: a `beangulp.Importer` implementation that fetches transactions and emits Beancount entries.
49
+ - Import-time metadata control (exclude fields, add custom fields), plus subclassing hooks for advanced needs.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install beancount-gocardless
55
+ ```
56
+
57
+ ## Prerequisites (credentials)
58
+
59
+ Create a GoCardless Bank Account Data account to get API credentials:
60
+
61
+ https://bankaccountdata.gocardless.com/overview/
62
+
63
+ You will need:
64
+
65
+ - `GOCARDLESS_SECRET_ID`
66
+ - `GOCARDLESS_SECRET_KEY`
67
+
68
+ ## CLI usage (bank authorization)
69
+
70
+ The importer needs an authorized bank connection first. Use the CLI to create and manage connections.
71
+
72
+ Set credentials as environment variables:
73
+
74
+ ```bash
75
+ export GOCARDLESS_SECRET_ID="..."
76
+ export GOCARDLESS_SECRET_KEY="..."
77
+ ```
78
+
79
+ Launch the CLI:
80
+
81
+ ```bash
82
+ beancount-gocardless
83
+ ```
84
+
85
+ Options:
86
+ - List accounts: view connected accounts with expiry status (EXPIRED badge shown for expired connections), select an account to view details, check balances, or delete the link
87
+ - Add account: add a new bank connection by selecting country, choosing a bank, and creating an authorization link
88
+ - List banks: browse available banks by country and create links
89
+
90
+ Account expiry is shown in the list. Use --mock flag for testing without real credentials.
91
+
92
+ ## Beancount usage
93
+
94
+ ### 1) Create a YAML config
95
+
96
+ Create `gocardless.yaml`:
97
+
98
+ ```yaml
99
+ secret_id: $GOCARDLESS_SECRET_ID
100
+ secret_key: $GOCARDLESS_SECRET_KEY
101
+
102
+ # Note: this project substitutes environment variables in YAML values at runtime.
103
+
104
+ cache_options: # if omitted, caching is disabled
105
+ cache_name: "gocardless"
106
+ backend: "sqlite"
107
+ expire_after: 3600
108
+ old_data_on_error: true
109
+
110
+ accounts:
111
+ - id: "<REDACTED_UUID>"
112
+ asset_account: "Assets:Banks:Revolut:Checking"
113
+ transaction_types: ["booked", "pending"] # optional, defaults to both
114
+ preferred_balance_type: "interimAvailable" # optional
115
+ ```
116
+
117
+ ### 2) Create an import script
118
+
119
+ Create `my.import`:
120
+
121
+ ```python
122
+ #!/usr/bin/env python3
123
+
124
+ import beangulp
125
+ from beancount_gocardless import GoCardLessImporter
126
+ from smart_importer import PredictPayees, PredictPostings
127
+
128
+ importers = [
129
+ GoCardLessImporter(),
130
+ ]
131
+
132
+ hooks = [
133
+ PredictPostings().hook,
134
+ PredictPayees().hook,
135
+ ]
136
+
137
+ if __name__ == "__main__":
138
+ ingest = beangulp.Ingest(importers, hooks=hooks)
139
+ ingest()
140
+ ```
141
+
142
+ ### 3) Run the import
143
+
144
+ ```bash
145
+ python my.import extract ./gocardless.yaml --existing ./ledger.bean
146
+ ```
147
+
148
+ ## Customizing metadata
149
+
150
+ ### Via YAML configuration
151
+
152
+ You can control metadata per account:
153
+
154
+ ```yaml
155
+ accounts:
156
+ - id: "<REDACTED_UUID>"
157
+ asset_account: "Assets:Banks:Revolut:Checking"
158
+
159
+ # Exclude specific default metadata fields.
160
+ exclude_default_metadata: ["bookingDate", "creditorName"]
161
+
162
+ # Add custom metadata fields using dotted paths.
163
+ metadata_fields:
164
+ payee: "creditorName"
165
+ cardScheme: "additionalDataStructured.cardInstrument.cardSchemeName"
166
+ balanceType: "balanceAfterTransaction.balance_type"
167
+ ```
168
+
169
+ Supported options:
170
+
171
+ - `exclude_default_metadata` (default: `[]`) - Exclude specific default metadata fields.
172
+ - Default fields include: `nordref`, `creditorName`, `debtorName`, `bookingDate`
173
+ - `metadata_fields` (default: `null`) - Add or override metadata fields using dotted paths.
174
+ - Specify the output key as the dict key and the GoCardless path as the value.
175
+ - Example: `"cardScheme": "additionalDataStructured.cardInstrument.cardSchemeName"`
176
+
177
+ ### Example configurations
178
+
179
+ **Use defaults with exclusions:**
180
+
181
+ ```yaml
182
+ accounts:
183
+ - id: "<REDACTED_UUID>"
184
+ asset_account: "Assets:Banks:Revolut:Checking"
185
+ exclude_default_metadata: ["bookingDate"] # Keep nordref, creditorName, debtorName
186
+ ```
187
+
188
+ **Full customization with custom keys:**
189
+
190
+ ```yaml
191
+ accounts:
192
+ - id: "<REDACTED_UUID>"
193
+ asset_account: "Assets:Banks:Revolut:Checking"
194
+ exclude_default_metadata: [] # Keep all defaults
195
+ metadata_fields:
196
+ # Rename default field by using custom key name
197
+ payee: "creditorName"
198
+ # Add nested custom fields
199
+ cardScheme: "additionalDataStructured.cardInstrument.cardSchemeName"
200
+ mcc: "merchant_category_code"
201
+ ultimateCreditor: "ultimate_creditor"
202
+ ```
203
+
204
+ ### Via subclassing
205
+
206
+ For advanced customization, subclass `GoCardLessImporter` and override `add_metadata`:
207
+
208
+ ```python
209
+ from beancount_gocardless import GoCardLessImporter
210
+
211
+ class CustomImporter(GoCardLessImporter):
212
+ def add_metadata(self, transaction, custom_metadata, account_config=None):
213
+ metakv = super().add_metadata(transaction, custom_metadata, account_config)
214
+
215
+ if transaction.ultimate_creditor:
216
+ metakv["ultimateCreditor"] = transaction.ultimate_creditor
217
+ if transaction.merchant_category_code:
218
+ metakv["mcc"] = transaction.merchant_category_code
219
+ if transaction.bank_transaction_code:
220
+ metakv["bankCode"] = transaction.bank_transaction_code
221
+
222
+ return metakv
223
+
224
+ importers = [CustomImporter()]
225
+ ```
226
+
227
+ The `BankTransaction` model (see `models.py`) contains many optional fields you can expose as metadata, for example:
228
+
229
+ - `ultimate_creditor`, `ultimate_debtor`
230
+ - `bank_transaction_code`, `proprietary_bank_transaction_code`
231
+ - `merchant_category_code`, `creditor_id`, `mandate_id`
232
+ - `entry_reference`, `account_servicer_reference`
233
+
234
+ ## Development
235
+
236
+ ### API coverage and models
237
+
238
+ The GoCardless client aims to provide full API coverage with typed models for endpoints and data structures.
239
+
240
+ Models are manually recreated from the OpenAPI/Swagger spec to keep strong typing and stable semantics.
241
+
242
+ ### Local development
243
+
244
+ ```bash
245
+ git clone https://github.com/jodoox/beancount-gocardless.git
246
+ cd beancount-gocardless
247
+ python -m venv .venv
248
+ source .venv/bin/activate
249
+ pip install -U pip
250
+ pip install -e ".[dev]"
251
+ pytest
252
+ ```
@@ -0,0 +1,14 @@
1
+ beancount_gocardless/__init__.py,sha256=JVJivGs-o5yY8YGqTYwn1cXY7aiA76lUyc95s1Ye-j0,253
2
+ beancount_gocardless/__main__.py,sha256=0yFL6yq31qI-pf_dp0_0-TgMHlG5QyHQ1wYzi8mhAWI,81
3
+ beancount_gocardless/cli.py,sha256=VlqbJaLRxagaGbV9AKr-oMxwhCkWKoHys3u4gYifdIg,21882
4
+ beancount_gocardless/client.py,sha256=DrbvGN85Pf5Cl20mgC_grLLhhrEk2Jn4ArJJOWQ0wjU,16162
5
+ beancount_gocardless/importer.py,sha256=-sfO0CKNmH9ivUPyU_aY4xFG0y1ohUi3v4Y--rG76hs,18824
6
+ beancount_gocardless/mock_client.py,sha256=WvcKGjpUTzYlqRVz3mUoDWiKKEc_12yi3TLwreMbHC4,7765
7
+ beancount_gocardless/models.py,sha256=jLMPFVW7FiiN2nERPPGSa2sW-r33_DY08wvZT_yYpwA,19765
8
+ beancount_gocardless/utils.py,sha256=DKRG1sm-jyLmGN17oZJ3fGplXPc91ASHhH0f0KCANlc,1613
9
+ beancount_gocardless/openapi/swagger.json,sha256=t8TLbt0l2UOyorZX8JyoG4XO2qtXDRYUlsllM3ckyG4,264957
10
+ beancount_gocardless-0.1.14.dist-info/METADATA,sha256=hiKH5B8ekd9OKuN1LWNiCQxX8aMUUkZI8ok2EOO5mwM,7838
11
+ beancount_gocardless-0.1.14.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
12
+ beancount_gocardless-0.1.14.dist-info/entry_points.txt,sha256=LFBqXX9sLw7EABb1w-2k2T8PqIDgh56F4cwtAvB2hLk,71
13
+ beancount_gocardless-0.1.14.dist-info/licenses/LICENSE,sha256=VR2hkz3p9Sw4hSXc7S5iZTOXGeV4h-i8AO_q0zEmtkE,1074
14
+ beancount_gocardless-0.1.14.dist-info/RECORD,,
@@ -1,3 +1,2 @@
1
1
  [console_scripts]
2
2
  beancount-gocardless = beancount_gocardless.cli:main
3
- beancount-gocardless-tui = beancount_gocardless.tui:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Patrick Ruckstuhl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.