beangulp-wise 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,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .env
10
+ .DS_Store
11
+ .claude/settings.local.json
@@ -0,0 +1,339 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, write to the Free Software Foundation, Inc.,
308
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
+
310
+ Also add information on how to contact you by electronic and paper mail.
311
+
312
+ If the program is interactive, make it output a short notice like this
313
+ when it starts in an interactive mode:
314
+
315
+ Gnomovision version 69, Copyright (C) year name of author
316
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
+ This is free software, and you are welcome to redistribute it
318
+ under certain conditions; type `show c' for details.
319
+
320
+ The hypothetical commands `show w' and `show c' should show the appropriate
321
+ parts of the General Public License. Of course, the commands you use may
322
+ be called something other than `show w' and `show c'; they could even be
323
+ mouse-clicks or menu items--whatever suits your program.
324
+
325
+ You should also get your employer (if you work as a programmer) or your
326
+ school, if any, to sign a "copyright disclaimer" for the program, if
327
+ necessary. Here is a sample; alter the names:
328
+
329
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
+
332
+ <signature of Ty Coon>, 1 April 1989
333
+ Ty Coon, President of Vice
334
+
335
+ This General Public License does not permit incorporating your program into
336
+ proprietary programs. If your program is a subroutine library, you may
337
+ consider it more useful to permit linking proprietary applications with the
338
+ library. If this is what you want to do, use the GNU Lesser General
339
+ Public License instead of this License.
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: beangulp-wise
3
+ Version: 0.1.0
4
+ Summary: beangulp importer for Wise balance statements (statement.json), with a thin SCA-capable API client: idempotent drafts via referenceNumber, conversion-leg merging, fee splitting, closing-balance assertions
5
+ License: GPL-2.0-only
6
+ License-File: LICENSE
7
+ Keywords: bank-statement,beancount,beangulp,importer,multicurrency,transferwise,wise
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: beancount>=3.0
10
+ Requires-Dist: beangulp>=0.2
11
+ Requires-Dist: requests>=2.28
12
+ Provides-Extra: sca
13
+ Requires-Dist: cryptography>=42; extra == 'sca'
14
+ Description-Content-Type: text/markdown
15
+
16
+ # beangulp-wise
17
+
18
+ [beangulp](https://github.com/beancount/beangulp) importer for **Wise**
19
+ (formerly TransferWise) balance statements, plus a thin, SCA-capable API
20
+ client to fetch them.
21
+
22
+ Wise has no official Python SDK, and the community clients are either
23
+ experimental or AGPL-licensed; the import workflow needs exactly three GET
24
+ endpoints, so this package owns a ~100-line client instead
25
+ (`beangulp_wise.client.WiseClient`).
26
+
27
+ ## Design
28
+
29
+ The importer consumes **`statement.json` files** (one per currency balance),
30
+ not the API directly — fetching writes files to disk first, so every import
31
+ is auditable, replayable, and testable offline.
32
+
33
+ - `referenceNumber` (`CARD-…`, `TRANSFER-…`, `CONVERSION-…`) is stored as
34
+ `wise_id:` metadata and is the idempotency key: `extract()` skips references
35
+ already anywhere in the existing ledger. **Re-imports are always safe.**
36
+ - Payee by detail type: merchant name for card payments, recipient/sender for
37
+ transfers, description otherwise.
38
+ - `totalFees` becomes an explicit posting to `fees_account` — fees stay
39
+ visible instead of dissolving into the counter leg.
40
+ - `payee_rules` (`(regex, account, flag)`) draft the counter leg; unmatched
41
+ entries keep the `!` review flag and the cash leg only.
42
+ - `endOfStatementBalance` → a `balance` assertion the day after the interval.
43
+ - **Conversions**: each leg appears in a different currency's statement,
44
+ sharing one `referenceNumber`. `merge_conversions(entries)` joins them into
45
+ a single two-currency transaction — the incoming leg priced `@@` what left
46
+ the other balance net of fees, so it balances exactly.
47
+
48
+ ## Usage
49
+
50
+ ```python
51
+ from beangulp_wise import Importer, merge_conversions
52
+
53
+ importer = Importer(
54
+ {"EUR": "Assets:Wise:EUR", "USD": "Assets:Wise:USD"},
55
+ fees_account="Expenses:BankFees:Wise",
56
+ holder="My GmbH", # a token may see several profiles
57
+ payee_rules=((r"cloudflare", "Expenses:IT:Hosting", "!"),),
58
+ )
59
+ entries = merge_conversions(
60
+ importer.extract("statement-eur.json", existing=ledger_entries)
61
+ + importer.extract("statement-usd.json", existing=ledger_entries)
62
+ )
63
+ ```
64
+
65
+ ## Fetching statements (SCA)
66
+
67
+ Statement endpoints are protected by Strong Customer Authentication: Wise
68
+ answers 403 with a one-time token in the `x-2fa-approval` header, which must
69
+ be signed (RSA-SHA256, PKCS#1 v1.5) with a private key whose **public half is
70
+ registered on the Wise account** (Settings → API tokens → Manage public keys).
71
+
72
+ ```python
73
+ from beangulp_wise import WiseClient
74
+
75
+ client = WiseClient(token, private_key_pem=open("private.pem", "rb").read())
76
+ pid = client.profile_id("My GmbH")
77
+ for balance in client.balances(pid):
78
+ statement = client.balance_statement(
79
+ pid, balance["id"], balance["currency"],
80
+ "2026-07-01T00:00:00.000Z", "2026-07-31T23:59:59.999Z",
81
+ )
82
+ ```
83
+
84
+ `cryptography` is an optional dependency (`beangulp-wise[sca]`) — importing
85
+ statement files works without it.
@@ -0,0 +1,70 @@
1
+ # beangulp-wise
2
+
3
+ [beangulp](https://github.com/beancount/beangulp) importer for **Wise**
4
+ (formerly TransferWise) balance statements, plus a thin, SCA-capable API
5
+ client to fetch them.
6
+
7
+ Wise has no official Python SDK, and the community clients are either
8
+ experimental or AGPL-licensed; the import workflow needs exactly three GET
9
+ endpoints, so this package owns a ~100-line client instead
10
+ (`beangulp_wise.client.WiseClient`).
11
+
12
+ ## Design
13
+
14
+ The importer consumes **`statement.json` files** (one per currency balance),
15
+ not the API directly — fetching writes files to disk first, so every import
16
+ is auditable, replayable, and testable offline.
17
+
18
+ - `referenceNumber` (`CARD-…`, `TRANSFER-…`, `CONVERSION-…`) is stored as
19
+ `wise_id:` metadata and is the idempotency key: `extract()` skips references
20
+ already anywhere in the existing ledger. **Re-imports are always safe.**
21
+ - Payee by detail type: merchant name for card payments, recipient/sender for
22
+ transfers, description otherwise.
23
+ - `totalFees` becomes an explicit posting to `fees_account` — fees stay
24
+ visible instead of dissolving into the counter leg.
25
+ - `payee_rules` (`(regex, account, flag)`) draft the counter leg; unmatched
26
+ entries keep the `!` review flag and the cash leg only.
27
+ - `endOfStatementBalance` → a `balance` assertion the day after the interval.
28
+ - **Conversions**: each leg appears in a different currency's statement,
29
+ sharing one `referenceNumber`. `merge_conversions(entries)` joins them into
30
+ a single two-currency transaction — the incoming leg priced `@@` what left
31
+ the other balance net of fees, so it balances exactly.
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ from beangulp_wise import Importer, merge_conversions
37
+
38
+ importer = Importer(
39
+ {"EUR": "Assets:Wise:EUR", "USD": "Assets:Wise:USD"},
40
+ fees_account="Expenses:BankFees:Wise",
41
+ holder="My GmbH", # a token may see several profiles
42
+ payee_rules=((r"cloudflare", "Expenses:IT:Hosting", "!"),),
43
+ )
44
+ entries = merge_conversions(
45
+ importer.extract("statement-eur.json", existing=ledger_entries)
46
+ + importer.extract("statement-usd.json", existing=ledger_entries)
47
+ )
48
+ ```
49
+
50
+ ## Fetching statements (SCA)
51
+
52
+ Statement endpoints are protected by Strong Customer Authentication: Wise
53
+ answers 403 with a one-time token in the `x-2fa-approval` header, which must
54
+ be signed (RSA-SHA256, PKCS#1 v1.5) with a private key whose **public half is
55
+ registered on the Wise account** (Settings → API tokens → Manage public keys).
56
+
57
+ ```python
58
+ from beangulp_wise import WiseClient
59
+
60
+ client = WiseClient(token, private_key_pem=open("private.pem", "rb").read())
61
+ pid = client.profile_id("My GmbH")
62
+ for balance in client.balances(pid):
63
+ statement = client.balance_statement(
64
+ pid, balance["id"], balance["currency"],
65
+ "2026-07-01T00:00:00.000Z", "2026-07-31T23:59:59.999Z",
66
+ )
67
+ ```
68
+
69
+ `cryptography` is an optional dependency (`beangulp-wise[sca]`) — importing
70
+ statement files works without it.
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "beangulp-wise"
3
+ version = "0.1.0"
4
+ description = "beangulp importer for Wise balance statements (statement.json), with a thin SCA-capable API client: idempotent drafts via referenceNumber, conversion-leg merging, fee splitting, closing-balance assertions"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { text = "GPL-2.0-only" }
8
+ keywords = ["beancount", "beangulp", "importer", "wise", "transferwise", "bank-statement", "multicurrency"]
9
+ dependencies = [
10
+ "beancount>=3.0",
11
+ "beangulp>=0.2",
12
+ "requests>=2.28",
13
+ ]
14
+
15
+ [project.optional-dependencies]
16
+ # Only needed to sign Wise's SCA (x-2fa-approval) challenge when fetching
17
+ # statements from the API; importing statement.json files works without it.
18
+ sca = ["cryptography>=42"]
19
+
20
+ [dependency-groups]
21
+ dev = ["pytest>=8", "cryptography>=42"]
22
+
23
+ [build-system]
24
+ requires = ["hatchling"]
25
+ build-backend = "hatchling.build"
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["src/beangulp_wise"]
@@ -0,0 +1,285 @@
1
+ """beangulp importer for Wise balance statements (``statement.json``).
2
+
3
+ One statement file covers **one currency balance**; the importer drafts one
4
+ beancount transaction per statement entry:
5
+
6
+ - ``referenceNumber`` (``CARD-…``, ``TRANSFER-…``, …) becomes metadata
7
+ (``wise_id:`` by default) and is the idempotency key — ``extract()`` skips
8
+ references already present anywhere in the existing ledger.
9
+ - Payee comes from the entry's ``details`` by type: merchant name for card
10
+ payments, recipient/sender for transfers, the description otherwise.
11
+ - ``totalFees`` > 0 becomes an explicit posting to ``fees_account`` — Wise
12
+ fees stay visible instead of disappearing into the counter leg.
13
+ - ``payee_rules`` (``(regex, account, flag)``) draft the counter leg; anything
14
+ unmatched keeps the ``!`` review flag and the cash leg only.
15
+ - ``endOfStatementBalance`` becomes a ``balance`` assertion dated the day
16
+ after the statement interval ends.
17
+
18
+ **Conversions** appear once per balance — two statement files, two entries,
19
+ one shared ``referenceNumber``. :func:`merge_conversions` joins them into a
20
+ single two-currency transaction (``@@`` price on the incoming leg, fee kept
21
+ explicit), which is where realized FX differences become visible.
22
+
23
+ The API client (SCA-capable) lives in :mod:`beangulp_wise.client`; the
24
+ importer itself only reads files, so fetching stays auditable and replayable.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import datetime as dt
30
+ import json
31
+ import re
32
+ from collections.abc import Sequence
33
+ from decimal import Decimal
34
+
35
+ import beangulp
36
+ from beancount.core import data, flags
37
+ from beancount.core.amount import Amount
38
+
39
+ from .client import ScaChallenge, WiseClient, WiseError, sign_sca_token # re-export
40
+
41
+ __all__ = [
42
+ "Importer",
43
+ "ScaChallenge",
44
+ "WiseClient",
45
+ "WiseError",
46
+ "merge_conversions",
47
+ "sign_sca_token",
48
+ ]
49
+
50
+
51
+ def _decimal(value) -> Decimal:
52
+ return Decimal(str(value))
53
+
54
+
55
+ def _payee(details: dict) -> str:
56
+ kind = details.get("type", "")
57
+ if kind == "CARD":
58
+ merchant = details.get("merchant") or {}
59
+ if merchant.get("name"):
60
+ return merchant["name"]
61
+ if kind == "TRANSFER":
62
+ recipient = details.get("recipient") or {}
63
+ name = recipient.get("name") or details.get("senderName")
64
+ if name:
65
+ return name
66
+ if kind in ("DEPOSIT", "MONEY_ADDED") and details.get("senderName"):
67
+ return details["senderName"]
68
+ if kind == "CONVERSION":
69
+ return "Wise"
70
+ return (details.get("description") or "").strip()
71
+
72
+
73
+ class Importer(beangulp.Importer):
74
+ """Importer for Wise balance-statement JSON files."""
75
+
76
+ def __init__(
77
+ self,
78
+ account_map: dict[str, str],
79
+ *,
80
+ fees_account: str | None = None,
81
+ holder: str | None = None,
82
+ meta_key: str = "wise_id",
83
+ payee_rules: Sequence[tuple[str, str, str]] = (),
84
+ review_flag: str = flags.FLAG_WARNING,
85
+ ):
86
+ self._accounts = dict(account_map)
87
+ self._fees_account = fees_account
88
+ self._holder = holder
89
+ self._meta_key = meta_key
90
+ self._rules = [
91
+ (re.compile(pattern, re.IGNORECASE), account, flag)
92
+ for pattern, account, flag in payee_rules
93
+ ]
94
+ self._review_flag = review_flag
95
+
96
+ # ── beangulp interface ───────────────────────────────────────────────────
97
+
98
+ def _load(self, filepath: str) -> dict | None:
99
+ try:
100
+ with open(filepath, encoding="utf-8") as f:
101
+ statement = json.load(f)
102
+ except (OSError, ValueError):
103
+ return None
104
+ if not isinstance(statement, dict) or "transactions" not in statement:
105
+ return None
106
+ if (statement.get("query") or {}).get("currency") not in self._accounts:
107
+ return None
108
+ if self._holder:
109
+ holder = statement.get("accountHolder") or {}
110
+ name = holder.get("businessName") or holder.get("fullName")
111
+ if name != self._holder:
112
+ return None
113
+ return statement
114
+
115
+ def identify(self, filepath: str) -> bool:
116
+ return self._load(filepath) is not None
117
+
118
+ def account(self, filepath: str) -> str:
119
+ statement = self._load(filepath)
120
+ return self._accounts[statement["query"]["currency"]] if statement else ""
121
+
122
+ def date(self, filepath: str):
123
+ statement = self._load(filepath)
124
+ if statement and (statement.get("query") or {}).get("intervalEnd"):
125
+ return dt.datetime.fromisoformat(
126
+ statement["query"]["intervalEnd"].replace("Z", "+00:00")
127
+ ).date()
128
+ return None
129
+
130
+ def filename(self, filepath: str) -> str:
131
+ return "statement.json"
132
+
133
+ def extract(self, filepath: str, existing: data.Entries) -> data.Entries:
134
+ statement = self._load(filepath)
135
+ if statement is None:
136
+ return []
137
+ currency = statement["query"]["currency"]
138
+ cash_account = self._accounts[currency]
139
+ seen = _existing_references(existing, self._meta_key)
140
+
141
+ entries: data.Entries = []
142
+ for index, txn in enumerate(statement["transactions"]):
143
+ number = _decimal(txn["amount"]["value"])
144
+ if not number:
145
+ continue
146
+ ref = txn.get("referenceNumber") or ""
147
+ if ref and ref in seen:
148
+ continue
149
+
150
+ details = txn.get("details") or {}
151
+ meta = data.new_metadata(filepath, index)
152
+ if ref:
153
+ meta[self._meta_key] = ref
154
+ if details.get("type") == "CONVERSION":
155
+ meta["conversion"] = "true" # consumed by merge_conversions
156
+
157
+ postings = [
158
+ data.Posting(cash_account, Amount(number, currency), None, None, None, None)
159
+ ]
160
+ fee = _decimal((txn.get("totalFees") or {}).get("value") or 0)
161
+ if fee and self._fees_account:
162
+ fee_ccy = (txn.get("totalFees") or {}).get("currency") or currency
163
+ postings.append(
164
+ data.Posting(self._fees_account, Amount(fee, fee_ccy), None, None, None, None)
165
+ )
166
+
167
+ payee = _payee(details)
168
+ narration = (details.get("description") or "").strip()
169
+ flag = self._review_flag
170
+ if details.get("type") != "CONVERSION":
171
+ haystack = f"{payee}\n{narration}\n{details.get('paymentReference') or ''}"
172
+ for pattern, counter, rule_flag in self._rules:
173
+ if pattern.search(haystack):
174
+ postings.append(
175
+ data.Posting(
176
+ counter, Amount(-number - fee, currency), None, None, None, None
177
+ )
178
+ )
179
+ flag = rule_flag
180
+ break
181
+
182
+ date = dt.datetime.fromisoformat(txn["date"].replace("Z", "+00:00")).date()
183
+ entries.append(
184
+ data.Transaction(
185
+ meta,
186
+ date,
187
+ flag,
188
+ payee,
189
+ narration,
190
+ data.EMPTY_SET,
191
+ data.EMPTY_SET,
192
+ postings,
193
+ )
194
+ )
195
+
196
+ entries.sort(key=lambda e: e.date)
197
+ closing = statement.get("endOfStatementBalance")
198
+ end = (statement.get("query") or {}).get("intervalEnd")
199
+ if closing and end:
200
+ end_date = dt.datetime.fromisoformat(end.replace("Z", "+00:00")).date()
201
+ entries.append(
202
+ data.Balance(
203
+ data.new_metadata(filepath, len(entries)),
204
+ end_date + dt.timedelta(days=1),
205
+ cash_account,
206
+ Amount(_decimal(closing["value"]), closing["currency"]),
207
+ None,
208
+ None,
209
+ )
210
+ )
211
+ return entries
212
+
213
+
214
+ def merge_conversions(entries: data.Entries, meta_key: str = "wise_id") -> data.Entries:
215
+ """Join the two single-currency legs of each Wise conversion.
216
+
217
+ Legs share a ``referenceNumber`` across two statement files. The merged
218
+ transaction keeps both cash postings and any fee postings; the **incoming**
219
+ leg gets an ``@@`` total price of what actually left the other balance net
220
+ of fees, so the transaction balances exactly and the effective rate is the
221
+ booked one.
222
+ """
223
+ by_ref: dict[str, list[int]] = {}
224
+ for i, entry in enumerate(entries):
225
+ if isinstance(entry, data.Transaction) and entry.meta.get("conversion"):
226
+ ref = entry.meta.get(meta_key)
227
+ if ref:
228
+ by_ref.setdefault(ref, []).append(i)
229
+
230
+ merged: data.Entries = []
231
+ drop: set[int] = set()
232
+ for indexes in by_ref.values():
233
+ if len(indexes) != 2:
234
+ continue # counterpart not in this batch; leave the leg for review
235
+ a, b = (entries[i] for i in indexes)
236
+ out_leg, in_leg = (a, b) if a.postings[0].units.number < 0 else (b, a)
237
+ out_cash = out_leg.postings[0]
238
+ fees = list(out_leg.postings[1:] + in_leg.postings[1:])
239
+ fee_total = sum(
240
+ (p.units.number for p in fees if p.units.currency == out_cash.units.currency),
241
+ Decimal("0"),
242
+ )
243
+ in_cash = in_leg.postings[0]
244
+ priced_in = data.Posting(
245
+ in_cash.account,
246
+ in_cash.units,
247
+ None,
248
+ Amount(-out_cash.units.number - fee_total, out_cash.units.currency),
249
+ None,
250
+ None,
251
+ )
252
+ meta = dict(out_leg.meta)
253
+ meta.pop("conversion", None)
254
+ merged.append(
255
+ data.Transaction(
256
+ meta,
257
+ out_leg.date,
258
+ "*",
259
+ "Wise",
260
+ out_leg.narration or in_leg.narration,
261
+ data.EMPTY_SET,
262
+ data.EMPTY_SET,
263
+ [out_cash, priced_in, *fees],
264
+ )
265
+ )
266
+ drop.update(indexes)
267
+
268
+ result = [e for i, e in enumerate(entries) if i not in drop]
269
+ result.extend(merged)
270
+ result.sort(key=lambda e: (e.date, isinstance(e, data.Balance)))
271
+ return result
272
+
273
+
274
+ def _existing_references(existing: data.Entries, meta_key: str) -> set[str]:
275
+ refs: set[str] = set()
276
+ for entry in existing or []:
277
+ meta = getattr(entry, "meta", None) or {}
278
+ value = meta.get(meta_key)
279
+ if isinstance(value, str):
280
+ refs.add(value)
281
+ for posting in getattr(entry, "postings", ()) or ():
282
+ value = (posting.meta or {}).get(meta_key)
283
+ if isinstance(value, str):
284
+ refs.add(value)
285
+ return refs
@@ -0,0 +1,130 @@
1
+ """Thin Wise API client — just what statement imports need.
2
+
3
+ Wise has no official Python SDK; the community clients either carry heavy
4
+ dependencies or AGPL licensing. The import workflow needs exactly three GET
5
+ endpoints, so this stays deliberately small:
6
+
7
+ - ``profiles()`` — GET /v2/profiles
8
+ - ``balances(profile_id)`` — GET /v4/profiles/{id}/balances?types=STANDARD
9
+ - ``balance_statement(...)`` — GET /v1/profiles/{id}/balance-statements/{bid}/statement.json
10
+
11
+ Statement endpoints are protected by Strong Customer Authentication: the API
12
+ answers 403 with a one-time token in the ``x-2fa-approval`` header, which must
13
+ be signed with an RSA private key whose public half is registered on the Wise
14
+ account (Settings → API tokens → Manage public keys). The client signs and
15
+ retries transparently when constructed with ``private_key_pem``; without a
16
+ key it raises :class:`ScaChallenge` so callers can explain the fix.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import base64
22
+ from typing import Any
23
+
24
+ import requests
25
+
26
+ PROD_HOST = "https://api.transferwise.com"
27
+ SANDBOX_HOST = "https://api.sandbox.transferwise.tech"
28
+
29
+
30
+ class WiseError(RuntimeError):
31
+ """Unexpected Wise API response."""
32
+
33
+
34
+ class ScaChallenge(WiseError):
35
+ """The endpoint requires SCA and no private key is configured.
36
+
37
+ Fix: generate an RSA keypair, upload the public key in Wise
38
+ (Settings → API tokens → Manage public keys), and construct the client
39
+ with the private key PEM.
40
+ """
41
+
42
+
43
+ def sign_sca_token(one_time_token: str, private_key_pem: bytes) -> str:
44
+ """RSA-SHA256 (PKCS#1 v1.5) signature of the SCA one-time token, base64."""
45
+ from cryptography.hazmat.primitives import hashes, serialization
46
+ from cryptography.hazmat.primitives.asymmetric import padding
47
+
48
+ key = serialization.load_pem_private_key(private_key_pem, password=None)
49
+ signature = key.sign(one_time_token.encode("ascii"), padding.PKCS1v15(), hashes.SHA256())
50
+ return base64.b64encode(signature).decode("ascii")
51
+
52
+
53
+ class WiseClient:
54
+ def __init__(
55
+ self,
56
+ token: str,
57
+ *,
58
+ private_key_pem: bytes | None = None,
59
+ host: str = PROD_HOST,
60
+ session: requests.Session | None = None,
61
+ ):
62
+ self._host = host
63
+ self._key = private_key_pem
64
+ self._session = session or requests.Session()
65
+ self._session.headers.update(
66
+ {"Authorization": f"Bearer {token}", "User-Agent": "beangulp-wise"}
67
+ )
68
+
69
+ def _get(self, path: str, params: dict | None = None) -> Any:
70
+ response = self._session.get(self._host + path, params=params, timeout=30)
71
+ ott = response.headers.get("x-2fa-approval")
72
+ if response.status_code == 403 and ott:
73
+ if not self._key:
74
+ raise ScaChallenge(
75
+ f"GET {path} requires SCA signing and no private key is configured"
76
+ )
77
+ response = self._session.get(
78
+ self._host + path,
79
+ params=params,
80
+ headers={"x-2fa-approval": ott, "X-Signature": sign_sca_token(ott, self._key)},
81
+ timeout=30,
82
+ )
83
+ if response.status_code == 403:
84
+ raise ScaChallenge(
85
+ f"GET {path}: SCA signature rejected "
86
+ f"({response.headers.get('x-2fa-approval-result', 'no result header')}) — "
87
+ "is this private key's PUBLIC half uploaded in Wise "
88
+ "(Settings → API tokens → Manage public keys)?"
89
+ )
90
+ if response.status_code != 200:
91
+ raise WiseError(f"GET {path} → {response.status_code}: {response.text[:200]}")
92
+ return response.json()
93
+
94
+ def profiles(self) -> list[dict]:
95
+ return self._get("/v2/profiles")
96
+
97
+ def profile_id(self, business_name: str) -> int:
98
+ """Profile id by business name (a token may see several entities)."""
99
+ for profile in self.profiles():
100
+ if profile.get("businessName") == business_name:
101
+ return profile["id"]
102
+ raise WiseError(f"no profile named {business_name!r} visible to this token")
103
+
104
+ def balances(self, profile_id: int) -> list[dict]:
105
+ return self._get(f"/v4/profiles/{profile_id}/balances", {"types": "STANDARD"})
106
+
107
+ def balance_statement(
108
+ self,
109
+ profile_id: int,
110
+ balance_id: int,
111
+ currency: str,
112
+ interval_start: str,
113
+ interval_end: str,
114
+ statement_type: str = "COMPACT",
115
+ ) -> dict:
116
+ """Balance statement JSON for one currency balance.
117
+
118
+ ``interval_start``/``interval_end`` are ISO instants
119
+ (``2026-07-01T00:00:00.000Z``); COMPACT folds fees into ``totalFees``
120
+ per transaction, which is what the importer expects.
121
+ """
122
+ return self._get(
123
+ f"/v1/profiles/{profile_id}/balance-statements/{balance_id}/statement.json",
124
+ {
125
+ "currency": currency,
126
+ "intervalStart": interval_start,
127
+ "intervalEnd": interval_end,
128
+ "type": statement_type,
129
+ },
130
+ )
@@ -0,0 +1,69 @@
1
+ {
2
+ "accountHolder": {"type": "BUSINESS", "businessName": "Test GmbH"},
3
+ "issuer": {"name": "Wise Europe SA"},
4
+ "transactions": [
5
+ {
6
+ "type": "DEBIT",
7
+ "date": "2026-07-03T09:12:41.000Z",
8
+ "amount": {"value": -1.76, "currency": "EUR", "zero": false},
9
+ "totalFees": {"value": 0.00, "currency": "EUR", "zero": true},
10
+ "details": {
11
+ "type": "CARD",
12
+ "description": "Card transaction of 2.00 USD issued by Cloudflare",
13
+ "amount": {"value": 2.00, "currency": "USD"},
14
+ "merchant": {"name": "Cloudflare", "country": "US", "category": "Computer Network Services"}
15
+ },
16
+ "exchangeDetails": {"forAmount": {"value": 2.00, "currency": "USD"}},
17
+ "runningBalance": {"value": 6494.98, "currency": "EUR"},
18
+ "referenceNumber": "CARD-1000001"
19
+ },
20
+ {
21
+ "type": "CREDIT",
22
+ "date": "2026-07-06T14:02:11.000Z",
23
+ "amount": {"value": 878.48, "currency": "EUR", "zero": false},
24
+ "totalFees": {"value": 0.00, "currency": "EUR", "zero": true},
25
+ "details": {
26
+ "type": "TRANSFER",
27
+ "description": "Received money from Acme OU with reference ACM202606",
28
+ "senderName": "Acme OU",
29
+ "paymentReference": "ACM202606"
30
+ },
31
+ "exchangeDetails": null,
32
+ "runningBalance": {"value": 7373.46, "currency": "EUR"},
33
+ "referenceNumber": "TRANSFER-2000002"
34
+ },
35
+ {
36
+ "type": "DEBIT",
37
+ "date": "2026-07-08T08:30:00.000Z",
38
+ "amount": {"value": -100.00, "currency": "EUR", "zero": false},
39
+ "totalFees": {"value": 0.47, "currency": "EUR", "zero": false},
40
+ "details": {
41
+ "type": "CONVERSION",
42
+ "description": "Converted 100.00 EUR to 107.20 USD",
43
+ "sourceAmount": {"value": 100.00, "currency": "EUR"},
44
+ "targetAmount": {"value": 107.20, "currency": "USD"},
45
+ "rate": 1.0771
46
+ },
47
+ "exchangeDetails": null,
48
+ "runningBalance": {"value": 7273.46, "currency": "EUR"},
49
+ "referenceNumber": "CONVERSION-3000003"
50
+ },
51
+ {
52
+ "type": "DEBIT",
53
+ "date": "2026-07-09T00:00:00.000Z",
54
+ "amount": {"value": 0.00, "currency": "EUR", "zero": true},
55
+ "totalFees": {"value": 0.00, "currency": "EUR", "zero": true},
56
+ "details": {"type": "UNKNOWN", "description": "Zero-value adjustment"},
57
+ "exchangeDetails": null,
58
+ "runningBalance": {"value": 7273.46, "currency": "EUR"},
59
+ "referenceNumber": "ADJUSTMENT-4000004"
60
+ }
61
+ ],
62
+ "endOfStatementBalance": {"value": 7273.46, "currency": "EUR"},
63
+ "query": {
64
+ "intervalStart": "2026-07-01T00:00:00.000Z",
65
+ "intervalEnd": "2026-07-10T23:59:59.999Z",
66
+ "currency": "EUR",
67
+ "accountId": 10000001
68
+ }
69
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "accountHolder": {"type": "BUSINESS", "businessName": "Test GmbH"},
3
+ "issuer": {"name": "Wise Europe SA"},
4
+ "transactions": [
5
+ {
6
+ "type": "CREDIT",
7
+ "date": "2026-07-08T08:30:00.000Z",
8
+ "amount": {"value": 107.20, "currency": "USD", "zero": false},
9
+ "totalFees": {"value": 0.00, "currency": "USD", "zero": true},
10
+ "details": {
11
+ "type": "CONVERSION",
12
+ "description": "Converted 100.00 EUR to 107.20 USD",
13
+ "sourceAmount": {"value": 100.00, "currency": "EUR"},
14
+ "targetAmount": {"value": 107.20, "currency": "USD"},
15
+ "rate": 1.0771
16
+ },
17
+ "exchangeDetails": null,
18
+ "runningBalance": {"value": 107.20, "currency": "USD"},
19
+ "referenceNumber": "CONVERSION-3000003"
20
+ }
21
+ ],
22
+ "endOfStatementBalance": {"value": 107.20, "currency": "USD"},
23
+ "query": {
24
+ "intervalStart": "2026-07-01T00:00:00.000Z",
25
+ "intervalEnd": "2026-07-10T23:59:59.999Z",
26
+ "currency": "USD",
27
+ "accountId": 10000002
28
+ }
29
+ }
@@ -0,0 +1,73 @@
1
+ """Tests for the thin Wise API client (no network)."""
2
+
3
+ import pytest
4
+
5
+ from beangulp_wise.client import ScaChallenge, WiseClient, sign_sca_token
6
+
7
+
8
+ def _keypair():
9
+ from cryptography.hazmat.primitives import serialization
10
+ from cryptography.hazmat.primitives.asymmetric import rsa
11
+
12
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
13
+ pem = key.private_bytes(
14
+ serialization.Encoding.PEM,
15
+ serialization.PrivateFormat.TraditionalOpenSSL,
16
+ serialization.NoEncryption(),
17
+ )
18
+ return key, pem
19
+
20
+
21
+ def test_sign_sca_token_produces_verifiable_signature():
22
+ import base64
23
+
24
+ from cryptography.hazmat.primitives import hashes
25
+ from cryptography.hazmat.primitives.asymmetric import padding
26
+
27
+ key, pem = _keypair()
28
+ token = "cca278c6-c24b-4b08-8560-39937b59ae43"
29
+ signature = base64.b64decode(sign_sca_token(token, pem))
30
+ key.public_key().verify( # raises on mismatch
31
+ signature, token.encode("ascii"), padding.PKCS1v15(), hashes.SHA256()
32
+ )
33
+
34
+
35
+ class _Response:
36
+ def __init__(self, status_code, headers=None, payload=None):
37
+ self.status_code = status_code
38
+ self.headers = headers or {}
39
+ self.text = ""
40
+ self._payload = payload
41
+
42
+ def json(self):
43
+ return self._payload
44
+
45
+
46
+ class _Session:
47
+ """Fake requests.Session: first GET returns the SCA 403, then 200."""
48
+
49
+ def __init__(self):
50
+ self.headers = {}
51
+ self.calls = []
52
+
53
+ def get(self, url, params=None, headers=None, timeout=None):
54
+ self.calls.append(headers or {})
55
+ if len(self.calls) == 1:
56
+ return _Response(403, headers={"x-2fa-approval": "OTT-123"})
57
+ return _Response(200, payload={"ok": True})
58
+
59
+
60
+ def test_client_signs_and_retries_sca_challenge():
61
+ _, pem = _keypair()
62
+ session = _Session()
63
+ client = WiseClient("token", private_key_pem=pem, session=session)
64
+ assert client.profiles() == {"ok": True}
65
+ retry_headers = session.calls[1]
66
+ assert retry_headers["x-2fa-approval"] == "OTT-123"
67
+ assert retry_headers["X-Signature"]
68
+
69
+
70
+ def test_client_raises_actionable_error_without_key():
71
+ client = WiseClient("token", session=_Session())
72
+ with pytest.raises(ScaChallenge):
73
+ client.profiles()
@@ -0,0 +1,124 @@
1
+ """Tests for the Wise balance-statement importer."""
2
+
3
+ from datetime import date as Date
4
+ from decimal import Decimal
5
+ from pathlib import Path
6
+
7
+ from beancount.core import data
8
+
9
+ from beangulp_wise import Importer, merge_conversions
10
+
11
+ HERE = Path(__file__).parent
12
+ EUR = str(HERE / "fixture-eur.json")
13
+ USD = str(HERE / "fixture-usd.json")
14
+
15
+ ACCOUNTS = {"EUR": "Assets:Wise:EUR", "USD": "Assets:Wise:USD"}
16
+ RULES = (
17
+ (r"cloudflare", "Expenses:IT:Hosting", "!"),
18
+ (r"acme", "Assets:Receivable", "*"),
19
+ )
20
+
21
+
22
+ def _importer(**kwargs):
23
+ kwargs.setdefault("fees_account", "Expenses:Fees")
24
+ kwargs.setdefault("payee_rules", RULES)
25
+ return Importer(ACCOUNTS, **kwargs)
26
+
27
+
28
+ def test_identify_by_schema_currency_and_holder(tmp_path):
29
+ assert _importer().identify(EUR)
30
+ assert _importer(holder="Test GmbH").identify(EUR)
31
+ assert not _importer(holder="Other AG").identify(EUR)
32
+ assert not Importer({"CHF": "Assets:Wise:CHF"}).identify(EUR)
33
+ other = tmp_path / "other.json"
34
+ other.write_text('{"not": "a statement"}')
35
+ assert not _importer().identify(str(other))
36
+
37
+
38
+ def test_extract_card_transfer_conversion_and_balance():
39
+ entries = _importer().extract(EUR, existing=[])
40
+ txns = [e for e in entries if isinstance(e, data.Transaction)]
41
+ balances = [e for e in entries if isinstance(e, data.Balance)]
42
+ assert len(txns) == 3 # zero-value adjustment skipped
43
+ assert len(balances) == 1
44
+
45
+ card, transfer, conversion = txns
46
+ assert card.date == Date(2026, 7, 3)
47
+ assert card.payee == "Cloudflare"
48
+ assert card.flag == "!"
49
+ assert card.meta["wise_id"] == "CARD-1000001"
50
+ assert [p.account for p in card.postings] == ["Assets:Wise:EUR", "Expenses:IT:Hosting"]
51
+ assert card.postings[1].units.number == Decimal("1.76")
52
+
53
+ assert transfer.payee == "Acme OU"
54
+ assert transfer.flag == "*"
55
+ assert transfer.postings[1].account == "Assets:Receivable"
56
+ assert transfer.postings[1].units.number == Decimal("-878.48")
57
+
58
+ assert conversion.meta["conversion"] == "true"
59
+ assert conversion.payee == "Wise"
60
+ assert conversion.flag == "!" # single leg: incomplete until merged
61
+ assert [p.account for p in conversion.postings] == ["Assets:Wise:EUR", "Expenses:Fees"]
62
+ assert conversion.postings[1].units.number == Decimal("0.47")
63
+
64
+ assert balances[0].date == Date(2026, 7, 11)
65
+ assert balances[0].amount.number == Decimal("7273.46")
66
+
67
+
68
+ def test_merge_conversions_joins_legs_with_priced_incoming_leg():
69
+ importer = _importer()
70
+ entries = importer.extract(EUR, existing=[]) + importer.extract(USD, existing=[])
71
+ merged = merge_conversions(entries)
72
+
73
+ conversions = [
74
+ e
75
+ for e in merged
76
+ if isinstance(e, data.Transaction) and e.meta.get("wise_id") == "CONVERSION-3000003"
77
+ ]
78
+ assert len(conversions) == 1
79
+ txn = conversions[0]
80
+ assert txn.flag == "*"
81
+ accounts = [p.account for p in txn.postings]
82
+ assert accounts == ["Assets:Wise:EUR", "Assets:Wise:USD", "Expenses:Fees"]
83
+ out_leg, in_leg, fee = txn.postings
84
+ assert out_leg.units.number == Decimal("-100.00")
85
+ assert in_leg.units.number == Decimal("107.20")
86
+ # @@ 99.53 EUR: what left the EUR balance net of the 0.47 fee
87
+ assert in_leg.price.number == Decimal("99.53")
88
+ assert in_leg.price.currency == "EUR"
89
+ # weights: -100.00 + 99.53 + 0.47 == 0 — the merged txn balances exactly
90
+ assert out_leg.units.number + in_leg.price.number + fee.units.number == 0
91
+
92
+ # both balance assertions survive the merge
93
+ assert sum(isinstance(e, data.Balance) for e in merged) == 2
94
+
95
+
96
+ def test_merge_leaves_unpaired_leg_for_review():
97
+ entries = _importer().extract(EUR, existing=[])
98
+ merged = merge_conversions(entries)
99
+ unpaired = [
100
+ e
101
+ for e in merged
102
+ if isinstance(e, data.Transaction) and e.meta.get("wise_id") == "CONVERSION-3000003"
103
+ ]
104
+ assert len(unpaired) == 1
105
+ assert unpaired[0].flag == "!"
106
+
107
+
108
+ def test_extract_skips_references_already_in_ledger():
109
+ meta = data.new_metadata("ledger.bean", 1)
110
+ meta["wise_id"] = "CARD-1000001"
111
+ booked = data.Transaction(
112
+ meta,
113
+ Date(2026, 7, 3),
114
+ "*",
115
+ "Cloudflare",
116
+ "already booked",
117
+ data.EMPTY_SET,
118
+ data.EMPTY_SET,
119
+ [],
120
+ )
121
+ entries = _importer().extract(EUR, existing=[booked])
122
+ refs = [e.meta.get("wise_id") for e in entries if isinstance(e, data.Transaction)]
123
+ assert "CARD-1000001" not in refs
124
+ assert len(refs) == 2