purser-client 1.7.1__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.
- purser_client-1.7.1/LICENSE +21 -0
- purser_client-1.7.1/PKG-INFO +117 -0
- purser_client-1.7.1/README.md +91 -0
- purser_client-1.7.1/purser_client/__init__.py +226 -0
- purser_client-1.7.1/purser_client/py.typed +0 -0
- purser_client-1.7.1/purser_client.egg-info/PKG-INFO +117 -0
- purser_client-1.7.1/purser_client.egg-info/SOURCES.txt +10 -0
- purser_client-1.7.1/purser_client.egg-info/dependency_links.txt +1 -0
- purser_client-1.7.1/purser_client.egg-info/top_level.txt +1 -0
- purser_client-1.7.1/pyproject.toml +50 -0
- purser_client-1.7.1/setup.cfg +4 -0
- purser_client-1.7.1/tests/test_client.py +231 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Max Geurtsen
|
|
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.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: purser-client
|
|
3
|
+
Version: 1.7.1
|
|
4
|
+
Summary: Purser's Python client: read the books, propose an invoice's payment, read a proposal's status. It cannot approve: only the CFO's passkey does.
|
|
5
|
+
Author: Max Geurtsen
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/agamemnon-coder/x402-business-agents/tree/main/sdk/python
|
|
8
|
+
Project-URL: Source, https://github.com/agamemnon-coder/x402-business-agents
|
|
9
|
+
Project-URL: Issues, https://github.com/agamemnon-coder/x402-business-agents/issues
|
|
10
|
+
Keywords: purser,accounts-payable,payments,x402
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
<div align="center">
|
|
28
|
+
|
|
29
|
+
<a href="../../README.md"><picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/brand/purser-mark-dark.svg"><img src="../../docs/assets/brand/purser-mark.svg" alt="Purser" width="64" height="64"></picture></a>
|
|
30
|
+
|
|
31
|
+
# Purser Python client
|
|
32
|
+
|
|
33
|
+
**List invoices, propose a payment and read its status from Python; standard library only, and no method approves.**
|
|
34
|
+
|
|
35
|
+
[](https://github.com/agamemnon-coder/x402-business-agents/actions/workflows/python-sdk.yml?query=branch%3Amain) [](pyproject.toml) [](pyproject.toml) [](../../docs/releasing.md#packages) [](#it-cannot-approve) [](#it-cannot-approve)
|
|
36
|
+
|
|
37
|
+
[Install](#install) · [Quickstart](#quickstart) · [It cannot approve](#it-cannot-approve) · [Notes](#notes)
|
|
38
|
+
|
|
39
|
+
</div>
|
|
40
|
+
|
|
41
|
+
<picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/pages/sdk-python-dark.svg"><img src="../../docs/assets/pages/sdk-python-light.svg" alt="Purser's Python client in four steps: list_invoices, propose_payment to PENDING_APPROVAL with terms_sha256, the CFO signs the SHA-256 of the exact terms in Purser Cloud, get_proposal to APPROVED and EXECUTED; no method approves (animated)" width="100%"></picture>
|
|
42
|
+
|
|
43
|
+
A small client for Purser Cloud's API, standard library only (`urllib`, Python 3.10 or later; CI runs its tests on 3.10
|
|
44
|
+
to 3.14). It lists invoices, proposes an invoice's payment for the CFO's approval and reads a proposal's status. It
|
|
45
|
+
calls only the operations of [`openapi/purser.yaml`](../../openapi/purser.yaml), under their `operationId`s
|
|
46
|
+
(`test/sdk-python.test.ts` checks every one).
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
**Not yet published to PyPI**; publishing is the owner's step ([docs/releasing.md](../../docs/releasing.md),
|
|
51
|
+
"Packages"). Until then, install it from a clone, or put `sdk/python` on your path:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
python3 -m pip install ./sdk/python # from a clone; once published: pip install purser-client
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The import name is `purser_client`, not `purser`: the name `purser` on PyPI is an unrelated project that installs its
|
|
58
|
+
own top-level `purser` package, and two packages of one name in one environment overwrite each other.
|
|
59
|
+
|
|
60
|
+
Status: tested locally, against a local mock (`tests/test_client.py`) and against Purser Cloud in-process. Packaged as
|
|
61
|
+
the distribution `purser-client` ([pyproject.toml](pyproject.toml), no runtime dependencies): `test/sdk-packages.test.ts`
|
|
62
|
+
builds the wheel, installs it into a fresh virtual environment and imports it.
|
|
63
|
+
|
|
64
|
+
## Quickstart
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
export PURSER_BASE_URL=https://purser.example.com # your Purser Cloud (PURSER_URL works too)
|
|
68
|
+
export PURSER_API_KEY=pck_... # an owner makes it: scopes read and propose; never in code
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from purser_client import Purser, PurserError # or, in a clone: import sys; sys.path.insert(0, "sdk/python") first
|
|
73
|
+
|
|
74
|
+
purser = Purser.from_env()
|
|
75
|
+
|
|
76
|
+
# 1. List invoices (one page; purser.invoices() walks every page)
|
|
77
|
+
page = purser.list_invoices(status="ready", limit=20)
|
|
78
|
+
for inv in page["items"]:
|
|
79
|
+
print(inv["id"], inv.get("vendor"), inv.get("currency"), inv.get("total"))
|
|
80
|
+
|
|
81
|
+
# 2. Propose a payment for the CFO's approval (a key with the propose scope)
|
|
82
|
+
payable = [i for i in purser.list_payable_invoices() if i["payable"] and not i["proposal"]]
|
|
83
|
+
if payable:
|
|
84
|
+
try:
|
|
85
|
+
proposal = purser.propose_payment(payable[0]["id"])["proposal"]
|
|
86
|
+
print(proposal["id"], "waits for the CFO's passkey") # nothing is paid yet
|
|
87
|
+
except PurserError as e:
|
|
88
|
+
if e.status != 409:
|
|
89
|
+
raise
|
|
90
|
+
print("Purser did not file it:", e)
|
|
91
|
+
|
|
92
|
+
# 3. Read a proposal's status
|
|
93
|
+
print(purser.get_proposal("P-0009")["status"]) # PENDING_APPROVAL, then APPROVED and EXECUTED, or REJECTED or EXPIRED
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## It cannot approve
|
|
97
|
+
|
|
98
|
+
Approving a payment is the CFO's passkey over the exact terms, in Purser Cloud. The API refuses every key there, and
|
|
99
|
+
this client has no method for it (the picture at the top shows the flow). Test money only until a company goes live.
|
|
100
|
+
|
|
101
|
+
## Notes
|
|
102
|
+
|
|
103
|
+
- `base_url` must be https (http only for localhost). The key is sent as `Authorization: Bearer`, and `repr()` never
|
|
104
|
+
shows it.
|
|
105
|
+
- Errors are `PurserError` with `status` and `code`: `forbidden` for a scope the key lacks, `conflict` when Purser
|
|
106
|
+
will not file (held, waiting or paid; the message says why), and `not_found`.
|
|
107
|
+
- `invoices()` follows `next_cursor` page by page. If the server sends a cursor it already gave, or the same page
|
|
108
|
+
again, it raises `PurserError` (`repeated_cursor`, `repeated_page`) before yielding that page, instead of reading
|
|
109
|
+
the same invoices for ever.
|
|
110
|
+
- Every POST carries an `Idempotency-Key`: a new UUID, or yours (`propose_payment(id, idempotency_key=...)`); Purser
|
|
111
|
+
Cloud answers the same key and request within 24 hours with the first answer.
|
|
112
|
+
- A read, or a POST with its key, answered 429 or 5xx is tried again up to `retries` times (2 by default), as
|
|
113
|
+
`Retry-After` says; with `idempotency_keys=False` a POST carries no key and is never tried again.
|
|
114
|
+
- Since 1.7.1: `get_payment_dossier(id)` (a payment's authorisation dossier, by its proposal's or invoice's id),
|
|
115
|
+
`run_shadow_mode(csv_text, alone_limit="2000.00")` (shadow mode: nothing is written) and `get_bank_file(id)` (the
|
|
116
|
+
SEPA file an approved payment was executed as; the CFO's own sign-in only, so every key gets 403).
|
|
117
|
+
- Tests: `python3 sdk/python/tests/test_client.py`.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
<a href="../../README.md"><picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/brand/purser-mark-dark.svg"><img src="../../docs/assets/brand/purser-mark.svg" alt="Purser" width="64" height="64"></picture></a>
|
|
4
|
+
|
|
5
|
+
# Purser Python client
|
|
6
|
+
|
|
7
|
+
**List invoices, propose a payment and read its status from Python; standard library only, and no method approves.**
|
|
8
|
+
|
|
9
|
+
[](https://github.com/agamemnon-coder/x402-business-agents/actions/workflows/python-sdk.yml?query=branch%3Amain) [](pyproject.toml) [](pyproject.toml) [](../../docs/releasing.md#packages) [](#it-cannot-approve) [](#it-cannot-approve)
|
|
10
|
+
|
|
11
|
+
[Install](#install) · [Quickstart](#quickstart) · [It cannot approve](#it-cannot-approve) · [Notes](#notes)
|
|
12
|
+
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
<picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/pages/sdk-python-dark.svg"><img src="../../docs/assets/pages/sdk-python-light.svg" alt="Purser's Python client in four steps: list_invoices, propose_payment to PENDING_APPROVAL with terms_sha256, the CFO signs the SHA-256 of the exact terms in Purser Cloud, get_proposal to APPROVED and EXECUTED; no method approves (animated)" width="100%"></picture>
|
|
16
|
+
|
|
17
|
+
A small client for Purser Cloud's API, standard library only (`urllib`, Python 3.10 or later; CI runs its tests on 3.10
|
|
18
|
+
to 3.14). It lists invoices, proposes an invoice's payment for the CFO's approval and reads a proposal's status. It
|
|
19
|
+
calls only the operations of [`openapi/purser.yaml`](../../openapi/purser.yaml), under their `operationId`s
|
|
20
|
+
(`test/sdk-python.test.ts` checks every one).
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
**Not yet published to PyPI**; publishing is the owner's step ([docs/releasing.md](../../docs/releasing.md),
|
|
25
|
+
"Packages"). Until then, install it from a clone, or put `sdk/python` on your path:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
python3 -m pip install ./sdk/python # from a clone; once published: pip install purser-client
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The import name is `purser_client`, not `purser`: the name `purser` on PyPI is an unrelated project that installs its
|
|
32
|
+
own top-level `purser` package, and two packages of one name in one environment overwrite each other.
|
|
33
|
+
|
|
34
|
+
Status: tested locally, against a local mock (`tests/test_client.py`) and against Purser Cloud in-process. Packaged as
|
|
35
|
+
the distribution `purser-client` ([pyproject.toml](pyproject.toml), no runtime dependencies): `test/sdk-packages.test.ts`
|
|
36
|
+
builds the wheel, installs it into a fresh virtual environment and imports it.
|
|
37
|
+
|
|
38
|
+
## Quickstart
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
export PURSER_BASE_URL=https://purser.example.com # your Purser Cloud (PURSER_URL works too)
|
|
42
|
+
export PURSER_API_KEY=pck_... # an owner makes it: scopes read and propose; never in code
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from purser_client import Purser, PurserError # or, in a clone: import sys; sys.path.insert(0, "sdk/python") first
|
|
47
|
+
|
|
48
|
+
purser = Purser.from_env()
|
|
49
|
+
|
|
50
|
+
# 1. List invoices (one page; purser.invoices() walks every page)
|
|
51
|
+
page = purser.list_invoices(status="ready", limit=20)
|
|
52
|
+
for inv in page["items"]:
|
|
53
|
+
print(inv["id"], inv.get("vendor"), inv.get("currency"), inv.get("total"))
|
|
54
|
+
|
|
55
|
+
# 2. Propose a payment for the CFO's approval (a key with the propose scope)
|
|
56
|
+
payable = [i for i in purser.list_payable_invoices() if i["payable"] and not i["proposal"]]
|
|
57
|
+
if payable:
|
|
58
|
+
try:
|
|
59
|
+
proposal = purser.propose_payment(payable[0]["id"])["proposal"]
|
|
60
|
+
print(proposal["id"], "waits for the CFO's passkey") # nothing is paid yet
|
|
61
|
+
except PurserError as e:
|
|
62
|
+
if e.status != 409:
|
|
63
|
+
raise
|
|
64
|
+
print("Purser did not file it:", e)
|
|
65
|
+
|
|
66
|
+
# 3. Read a proposal's status
|
|
67
|
+
print(purser.get_proposal("P-0009")["status"]) # PENDING_APPROVAL, then APPROVED and EXECUTED, or REJECTED or EXPIRED
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## It cannot approve
|
|
71
|
+
|
|
72
|
+
Approving a payment is the CFO's passkey over the exact terms, in Purser Cloud. The API refuses every key there, and
|
|
73
|
+
this client has no method for it (the picture at the top shows the flow). Test money only until a company goes live.
|
|
74
|
+
|
|
75
|
+
## Notes
|
|
76
|
+
|
|
77
|
+
- `base_url` must be https (http only for localhost). The key is sent as `Authorization: Bearer`, and `repr()` never
|
|
78
|
+
shows it.
|
|
79
|
+
- Errors are `PurserError` with `status` and `code`: `forbidden` for a scope the key lacks, `conflict` when Purser
|
|
80
|
+
will not file (held, waiting or paid; the message says why), and `not_found`.
|
|
81
|
+
- `invoices()` follows `next_cursor` page by page. If the server sends a cursor it already gave, or the same page
|
|
82
|
+
again, it raises `PurserError` (`repeated_cursor`, `repeated_page`) before yielding that page, instead of reading
|
|
83
|
+
the same invoices for ever.
|
|
84
|
+
- Every POST carries an `Idempotency-Key`: a new UUID, or yours (`propose_payment(id, idempotency_key=...)`); Purser
|
|
85
|
+
Cloud answers the same key and request within 24 hours with the first answer.
|
|
86
|
+
- A read, or a POST with its key, answered 429 or 5xx is tried again up to `retries` times (2 by default), as
|
|
87
|
+
`Retry-After` says; with `idempotency_keys=False` a POST carries no key and is never tried again.
|
|
88
|
+
- Since 1.7.1: `get_payment_dossier(id)` (a payment's authorisation dossier, by its proposal's or invoice's id),
|
|
89
|
+
`run_shadow_mode(csv_text, alone_limit="2000.00")` (shadow mode: nothing is written) and `get_bank_file(id)` (the
|
|
90
|
+
SEPA file an approved payment was executed as; the CFO's own sign-in only, so every key gets 403).
|
|
91
|
+
- Tests: `python3 sdk/python/tests/test_client.py`.
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Purser's Python client: read the books, propose an invoice's payment, read a proposal's status.
|
|
2
|
+
|
|
3
|
+
Also, since 1.7.1: a payment's authorisation dossier, its bank file (the CFO's alone: every key is refused), and shadow
|
|
4
|
+
mode, the back-test of past paid invoices.
|
|
5
|
+
|
|
6
|
+
Standard library only (urllib). Its operations are those of openapi/purser.yaml; test/sdk-python.test.ts checks each
|
|
7
|
+
one against the document. Installed as the distribution purser-client (sdk/python/pyproject.toml), imported as
|
|
8
|
+
purser_client: the name "purser" on PyPI is an unrelated project that installs its own top-level "purser" package.
|
|
9
|
+
|
|
10
|
+
What it cannot do, on purpose: approve. Approving a payment is a signed-in person's passkey over the exact terms, in
|
|
11
|
+
Purser Cloud; the API refuses every key there, and this client has no method for it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import random
|
|
19
|
+
import re
|
|
20
|
+
import time
|
|
21
|
+
import uuid
|
|
22
|
+
import urllib.error
|
|
23
|
+
import urllib.parse
|
|
24
|
+
import urllib.request
|
|
25
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
26
|
+
|
|
27
|
+
__all__ = ["Purser", "PurserError", "OPERATIONS"]
|
|
28
|
+
__version__ = "1.7.1"
|
|
29
|
+
|
|
30
|
+
#: The operations this client calls, by OpenAPI operationId: (method, path).
|
|
31
|
+
OPERATIONS: Dict[str, tuple] = {
|
|
32
|
+
"getMe": ("GET", "/v1/me"),
|
|
33
|
+
"listInvoices": ("GET", "/v1/invoices"),
|
|
34
|
+
"getInvoice": ("GET", "/v1/invoices/{id}"),
|
|
35
|
+
"listPayableInvoices": ("GET", "/v1/engine/invoices"),
|
|
36
|
+
"proposePayment": ("POST", "/v1/engine/invoices/{id}/pay"),
|
|
37
|
+
"getProposal": ("GET", "/v1/engine/proposals/{id}"),
|
|
38
|
+
"getBankFile": ("GET", "/v1/engine/proposals/{id}/bank-file"),
|
|
39
|
+
"getPaymentDossier": ("GET", "/v1/engine/proposals/{id}/dossier"),
|
|
40
|
+
"runShadowMode": ("POST", "/v1/engine/shadow"),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_LOCAL = {"localhost", "127.0.0.1", "::1"}
|
|
44
|
+
_ID = re.compile(r"^[A-Za-z0-9_.:-]{1,120}$")
|
|
45
|
+
_KEY = re.compile(r"^[\x21-\x7e]{1,255}$")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _retryable(status: int) -> bool:
|
|
49
|
+
"""Whether an answer is worth asking again: too many requests, or the server's fault."""
|
|
50
|
+
return status == 429 or 500 <= status <= 599
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _delay(attempt: int, retry_after: Optional[str]) -> float:
|
|
54
|
+
"""Seconds before retry n (1 for the first): Retry-After in seconds when given (at most a minute), else backoff with jitter."""
|
|
55
|
+
v = (retry_after or "").strip()
|
|
56
|
+
if v.isdigit():
|
|
57
|
+
return min(int(v), 60)
|
|
58
|
+
base = min(0.5 * 2 ** (attempt - 1), 8.0)
|
|
59
|
+
return base / 2 + random.random() * base / 2
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class PurserError(Exception):
|
|
63
|
+
"""An answer that was not 2xx (the API's sentence for a person and its stable code for a program), or a 2xx answer
|
|
64
|
+
the client cannot use: not_json, or repeated_cursor and repeated_page while paging (invoices())."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, status: int, code: str, message: str) -> None:
|
|
67
|
+
super().__init__(message)
|
|
68
|
+
self.status = status
|
|
69
|
+
self.code = code
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Purser:
|
|
73
|
+
"""A client for one company's Purser Cloud.
|
|
74
|
+
|
|
75
|
+
base_url: your Purser Cloud (https; http only for localhost).
|
|
76
|
+
api_key: an API key (pck_...) from the environment, never from code. read to read; read and propose to file payments.
|
|
77
|
+
retries: how many more times a request is tried after a 429 or a 5xx (2 by default): a read always, a POST only when
|
|
78
|
+
it carries an Idempotency-Key, so the server files it once.
|
|
79
|
+
idempotency_keys: whether each POST carries an Idempotency-Key (a new random UUID, or the call's own): True by
|
|
80
|
+
default. False: no key, and a POST is never tried again.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, base_url: str, api_key: str, timeout: float = 30.0, retries: int = 2, idempotency_keys: bool = True) -> None:
|
|
84
|
+
url = urllib.parse.urlsplit(base_url)
|
|
85
|
+
if not (url.scheme == "https" or (url.scheme == "http" and url.hostname in _LOCAL)) or not url.netloc:
|
|
86
|
+
raise ValueError("base_url must be https (http only for localhost)")
|
|
87
|
+
if not api_key:
|
|
88
|
+
raise ValueError("api_key is empty: read it from the environment (PURSER_API_KEY)")
|
|
89
|
+
self._base = f"{url.scheme}://{url.netloc}"
|
|
90
|
+
self._key = api_key
|
|
91
|
+
self._timeout = timeout
|
|
92
|
+
if not isinstance(retries, int) or retries < 0:
|
|
93
|
+
raise ValueError("retries must be a whole number, 0 or more")
|
|
94
|
+
self._retries = retries
|
|
95
|
+
self._idempotency_keys = idempotency_keys
|
|
96
|
+
|
|
97
|
+
def __repr__(self) -> str: # never the key
|
|
98
|
+
return f"Purser({self._base!r})"
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def from_env(cls, env: Optional[Dict[str, str]] = None) -> "Purser":
|
|
102
|
+
"""A client from PURSER_BASE_URL (or PURSER_URL) and PURSER_API_KEY."""
|
|
103
|
+
e = os.environ if env is None else env
|
|
104
|
+
return cls(e.get("PURSER_BASE_URL") or e.get("PURSER_URL") or "", e.get("PURSER_API_KEY", ""))
|
|
105
|
+
|
|
106
|
+
def _call(self, op: str, id: Optional[str] = None, query: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None,
|
|
107
|
+
body: Optional[bytes] = None, content_type: Optional[str] = None) -> Any:
|
|
108
|
+
method, path = OPERATIONS[op]
|
|
109
|
+
if "{id}" in path:
|
|
110
|
+
if not id or not _ID.match(id):
|
|
111
|
+
raise ValueError(f"{op} needs an id like AP-0004 or P-0009")
|
|
112
|
+
path = path.replace("{id}", urllib.parse.quote(id, safe=""))
|
|
113
|
+
q = {k: str(v) for k, v in (query or {}).items() if v is not None}
|
|
114
|
+
url = self._base + path + (f"?{urllib.parse.urlencode(q)}" if q else "")
|
|
115
|
+
headers = {"authorization": f"Bearer {self._key}", "accept": "application/json", "user-agent": f"purser-python/{__version__}"}
|
|
116
|
+
if body is not None and content_type:
|
|
117
|
+
headers["content-type"] = content_type
|
|
118
|
+
key = None
|
|
119
|
+
if method == "POST":
|
|
120
|
+
key = idempotency_key if idempotency_key is not None else (str(uuid.uuid4()) if self._idempotency_keys else None)
|
|
121
|
+
if key is not None:
|
|
122
|
+
if not _KEY.match(key):
|
|
123
|
+
raise ValueError("idempotency_key is 1 to 255 printable characters without spaces")
|
|
124
|
+
headers["idempotency-key"] = key
|
|
125
|
+
# A read, or a POST under its Idempotency-Key (every try the same key), is tried again after a 429 or a 5xx.
|
|
126
|
+
tries = self._retries + 1 if method == "GET" or key is not None else 1
|
|
127
|
+
attempt = 0
|
|
128
|
+
while True:
|
|
129
|
+
attempt += 1
|
|
130
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
131
|
+
try:
|
|
132
|
+
with urllib.request.urlopen(req, timeout=self._timeout) as res:
|
|
133
|
+
text = res.read().decode("utf-8")
|
|
134
|
+
break
|
|
135
|
+
except urllib.error.HTTPError as e:
|
|
136
|
+
raw = e.read().decode("utf-8", "replace")
|
|
137
|
+
if attempt < tries and _retryable(e.code):
|
|
138
|
+
time.sleep(_delay(attempt, e.headers.get("retry-after")))
|
|
139
|
+
continue
|
|
140
|
+
try:
|
|
141
|
+
body = json.loads(raw)
|
|
142
|
+
except ValueError:
|
|
143
|
+
body = {}
|
|
144
|
+
raise PurserError(e.code, body.get("code", "error"), body.get("error", f"HTTP {e.code}")) from None
|
|
145
|
+
try:
|
|
146
|
+
return json.loads(text)
|
|
147
|
+
except ValueError:
|
|
148
|
+
raise PurserError(200, "not_json", "the answer was not JSON") from None
|
|
149
|
+
|
|
150
|
+
def me(self) -> Dict[str, Any]:
|
|
151
|
+
"""Who is calling: the company and this key's scopes."""
|
|
152
|
+
return self._call("getMe")
|
|
153
|
+
|
|
154
|
+
def list_invoices(self, status: Optional[str] = None, due_from: Optional[str] = None, due_to: Optional[str] = None,
|
|
155
|
+
limit: Optional[int] = None, cursor: Optional[str] = None) -> Dict[str, Any]:
|
|
156
|
+
"""One page of supplier invoices: {"items": [...], "next_cursor": str | None}."""
|
|
157
|
+
return self._call("listInvoices", query={"status": status, "due_from": due_from, "due_to": due_to, "limit": limit, "cursor": cursor})
|
|
158
|
+
|
|
159
|
+
def invoices(self, **query: Any) -> Iterator[Dict[str, Any]]:
|
|
160
|
+
"""Every invoice that matches, page by page.
|
|
161
|
+
|
|
162
|
+
A server that hands back a cursor it gave before, or the same page again, would have this read the same invoices
|
|
163
|
+
for ever: it raises a PurserError (code repeated_cursor or repeated_page) before yielding that page.
|
|
164
|
+
"""
|
|
165
|
+
cursor = None
|
|
166
|
+
seen = set()
|
|
167
|
+
previous = None
|
|
168
|
+
while True:
|
|
169
|
+
page = self.list_invoices(cursor=cursor, **query)
|
|
170
|
+
items = page["items"]
|
|
171
|
+
nxt = page.get("next_cursor")
|
|
172
|
+
if nxt and nxt in seen:
|
|
173
|
+
raise PurserError(200, "repeated_cursor", f"the server sent the cursor {json.dumps(nxt)} again: stopped paging so the same invoices are not read twice")
|
|
174
|
+
if items and items == previous:
|
|
175
|
+
raise PurserError(200, "repeated_page", "the server sent the same page of invoices again under a new cursor: stopped paging so they are not read twice")
|
|
176
|
+
if nxt:
|
|
177
|
+
seen.add(nxt)
|
|
178
|
+
previous = items
|
|
179
|
+
yield from items
|
|
180
|
+
cursor = nxt
|
|
181
|
+
if not cursor:
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
def get_invoice(self, invoice_id: str) -> Dict[str, Any]:
|
|
185
|
+
return self._call("getInvoice", invoice_id)
|
|
186
|
+
|
|
187
|
+
def list_payable_invoices(self) -> List[Dict[str, Any]]:
|
|
188
|
+
"""The engine's invoices: whether each can be proposed (payable) and its proposal, if one was filed."""
|
|
189
|
+
return self._call("listPayableInvoices")["items"]
|
|
190
|
+
|
|
191
|
+
def propose_payment(self, invoice_id: str, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
|
|
192
|
+
"""File an invoice's payment for the CFO's approval (a key with the propose scope).
|
|
193
|
+
|
|
194
|
+
Nothing is paid until the CFO signs these exact terms with their passkey in Purser Cloud. A PurserError with
|
|
195
|
+
status 409 says why Purser would not file it. idempotency_key: your own (an order or job id) instead of a new
|
|
196
|
+
UUID; the same key and request within 24 hours answers as the first time.
|
|
197
|
+
"""
|
|
198
|
+
return self._call("proposePayment", invoice_id, idempotency_key=idempotency_key)
|
|
199
|
+
|
|
200
|
+
def get_proposal(self, proposal_id: str) -> Dict[str, Any]:
|
|
201
|
+
"""Where a proposal stands: PENDING_APPROVAL until the CFO's passkey, then APPROVED and EXECUTED, or REJECTED or EXPIRED."""
|
|
202
|
+
return self._call("getProposal", proposal_id)["proposal"]
|
|
203
|
+
|
|
204
|
+
def get_bank_file(self, proposal_id: str) -> Dict[str, Any]:
|
|
205
|
+
"""The SEPA credit transfer file (pain.001.001.09) an approved bank file payment was executed as.
|
|
206
|
+
|
|
207
|
+
A PurserError with status 404 when none was filed. The API answers it only to a signed-in CFO (the approve
|
|
208
|
+
scope): every API key is refused with 403, so this needs the CFO's own session, never an agent's key.
|
|
209
|
+
"""
|
|
210
|
+
return self._call("getBankFile", proposal_id)["bank_file"]
|
|
211
|
+
|
|
212
|
+
def get_payment_dossier(self, payment_id: str) -> Dict[str, Any]:
|
|
213
|
+
"""One payment's authorisation dossier, by its proposal's id or its invoice's (a read key): the exact terms and
|
|
214
|
+
their hash, who signed them and when, the policy, the checks, the transfers and the audit rows."""
|
|
215
|
+
return self._call("getPaymentDossier", payment_id)["dossier"]
|
|
216
|
+
|
|
217
|
+
def run_shadow_mode(self, csv: str, alone_limit: Optional[str] = None, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
|
|
218
|
+
"""Shadow mode, the back-test (a read key): past paid supplier invoices as CSV text (at most 2 MB; the columns:
|
|
219
|
+
docs/shadow/README.md), replayed through Purser's checks under the company's CFO policy. alone_limit ("2000.00",
|
|
220
|
+
or "none") sets the limit to pay alone for this replay only. Nothing is written; no model, no rail."""
|
|
221
|
+
if not isinstance(csv, str) or not csv.strip():
|
|
222
|
+
raise ValueError("run_shadow_mode needs the CSV's text")
|
|
223
|
+
if alone_limit is not None and alone_limit != "none" and not re.match(r"^\d{1,9}\.\d{2}$", alone_limit):
|
|
224
|
+
raise ValueError('alone_limit is an amount in EUR like "2000.00", or "none"')
|
|
225
|
+
return self._call("runShadowMode", query={"alone_limit": alone_limit}, idempotency_key=idempotency_key,
|
|
226
|
+
body=csv.encode("utf-8"), content_type="text/csv")["report"]
|
|
File without changes
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: purser-client
|
|
3
|
+
Version: 1.7.1
|
|
4
|
+
Summary: Purser's Python client: read the books, propose an invoice's payment, read a proposal's status. It cannot approve: only the CFO's passkey does.
|
|
5
|
+
Author: Max Geurtsen
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/agamemnon-coder/x402-business-agents/tree/main/sdk/python
|
|
8
|
+
Project-URL: Source, https://github.com/agamemnon-coder/x402-business-agents
|
|
9
|
+
Project-URL: Issues, https://github.com/agamemnon-coder/x402-business-agents/issues
|
|
10
|
+
Keywords: purser,accounts-payable,payments,x402
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
<div align="center">
|
|
28
|
+
|
|
29
|
+
<a href="../../README.md"><picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/brand/purser-mark-dark.svg"><img src="../../docs/assets/brand/purser-mark.svg" alt="Purser" width="64" height="64"></picture></a>
|
|
30
|
+
|
|
31
|
+
# Purser Python client
|
|
32
|
+
|
|
33
|
+
**List invoices, propose a payment and read its status from Python; standard library only, and no method approves.**
|
|
34
|
+
|
|
35
|
+
[](https://github.com/agamemnon-coder/x402-business-agents/actions/workflows/python-sdk.yml?query=branch%3Amain) [](pyproject.toml) [](pyproject.toml) [](../../docs/releasing.md#packages) [](#it-cannot-approve) [](#it-cannot-approve)
|
|
36
|
+
|
|
37
|
+
[Install](#install) · [Quickstart](#quickstart) · [It cannot approve](#it-cannot-approve) · [Notes](#notes)
|
|
38
|
+
|
|
39
|
+
</div>
|
|
40
|
+
|
|
41
|
+
<picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/pages/sdk-python-dark.svg"><img src="../../docs/assets/pages/sdk-python-light.svg" alt="Purser's Python client in four steps: list_invoices, propose_payment to PENDING_APPROVAL with terms_sha256, the CFO signs the SHA-256 of the exact terms in Purser Cloud, get_proposal to APPROVED and EXECUTED; no method approves (animated)" width="100%"></picture>
|
|
42
|
+
|
|
43
|
+
A small client for Purser Cloud's API, standard library only (`urllib`, Python 3.10 or later; CI runs its tests on 3.10
|
|
44
|
+
to 3.14). It lists invoices, proposes an invoice's payment for the CFO's approval and reads a proposal's status. It
|
|
45
|
+
calls only the operations of [`openapi/purser.yaml`](../../openapi/purser.yaml), under their `operationId`s
|
|
46
|
+
(`test/sdk-python.test.ts` checks every one).
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
**Not yet published to PyPI**; publishing is the owner's step ([docs/releasing.md](../../docs/releasing.md),
|
|
51
|
+
"Packages"). Until then, install it from a clone, or put `sdk/python` on your path:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
python3 -m pip install ./sdk/python # from a clone; once published: pip install purser-client
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The import name is `purser_client`, not `purser`: the name `purser` on PyPI is an unrelated project that installs its
|
|
58
|
+
own top-level `purser` package, and two packages of one name in one environment overwrite each other.
|
|
59
|
+
|
|
60
|
+
Status: tested locally, against a local mock (`tests/test_client.py`) and against Purser Cloud in-process. Packaged as
|
|
61
|
+
the distribution `purser-client` ([pyproject.toml](pyproject.toml), no runtime dependencies): `test/sdk-packages.test.ts`
|
|
62
|
+
builds the wheel, installs it into a fresh virtual environment and imports it.
|
|
63
|
+
|
|
64
|
+
## Quickstart
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
export PURSER_BASE_URL=https://purser.example.com # your Purser Cloud (PURSER_URL works too)
|
|
68
|
+
export PURSER_API_KEY=pck_... # an owner makes it: scopes read and propose; never in code
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from purser_client import Purser, PurserError # or, in a clone: import sys; sys.path.insert(0, "sdk/python") first
|
|
73
|
+
|
|
74
|
+
purser = Purser.from_env()
|
|
75
|
+
|
|
76
|
+
# 1. List invoices (one page; purser.invoices() walks every page)
|
|
77
|
+
page = purser.list_invoices(status="ready", limit=20)
|
|
78
|
+
for inv in page["items"]:
|
|
79
|
+
print(inv["id"], inv.get("vendor"), inv.get("currency"), inv.get("total"))
|
|
80
|
+
|
|
81
|
+
# 2. Propose a payment for the CFO's approval (a key with the propose scope)
|
|
82
|
+
payable = [i for i in purser.list_payable_invoices() if i["payable"] and not i["proposal"]]
|
|
83
|
+
if payable:
|
|
84
|
+
try:
|
|
85
|
+
proposal = purser.propose_payment(payable[0]["id"])["proposal"]
|
|
86
|
+
print(proposal["id"], "waits for the CFO's passkey") # nothing is paid yet
|
|
87
|
+
except PurserError as e:
|
|
88
|
+
if e.status != 409:
|
|
89
|
+
raise
|
|
90
|
+
print("Purser did not file it:", e)
|
|
91
|
+
|
|
92
|
+
# 3. Read a proposal's status
|
|
93
|
+
print(purser.get_proposal("P-0009")["status"]) # PENDING_APPROVAL, then APPROVED and EXECUTED, or REJECTED or EXPIRED
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## It cannot approve
|
|
97
|
+
|
|
98
|
+
Approving a payment is the CFO's passkey over the exact terms, in Purser Cloud. The API refuses every key there, and
|
|
99
|
+
this client has no method for it (the picture at the top shows the flow). Test money only until a company goes live.
|
|
100
|
+
|
|
101
|
+
## Notes
|
|
102
|
+
|
|
103
|
+
- `base_url` must be https (http only for localhost). The key is sent as `Authorization: Bearer`, and `repr()` never
|
|
104
|
+
shows it.
|
|
105
|
+
- Errors are `PurserError` with `status` and `code`: `forbidden` for a scope the key lacks, `conflict` when Purser
|
|
106
|
+
will not file (held, waiting or paid; the message says why), and `not_found`.
|
|
107
|
+
- `invoices()` follows `next_cursor` page by page. If the server sends a cursor it already gave, or the same page
|
|
108
|
+
again, it raises `PurserError` (`repeated_cursor`, `repeated_page`) before yielding that page, instead of reading
|
|
109
|
+
the same invoices for ever.
|
|
110
|
+
- Every POST carries an `Idempotency-Key`: a new UUID, or yours (`propose_payment(id, idempotency_key=...)`); Purser
|
|
111
|
+
Cloud answers the same key and request within 24 hours with the first answer.
|
|
112
|
+
- A read, or a POST with its key, answered 429 or 5xx is tried again up to `retries` times (2 by default), as
|
|
113
|
+
`Retry-After` says; with `idempotency_keys=False` a POST carries no key and is never tried again.
|
|
114
|
+
- Since 1.7.1: `get_payment_dossier(id)` (a payment's authorisation dossier, by its proposal's or invoice's id),
|
|
115
|
+
`run_shadow_mode(csv_text, alone_limit="2000.00")` (shadow mode: nothing is written) and `get_bank_file(id)` (the
|
|
116
|
+
SEPA file an approved payment was executed as; the CFO's own sign-in only, so every key gets 403).
|
|
117
|
+
- Tests: `python3 sdk/python/tests/test_client.py`.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
purser_client/__init__.py
|
|
5
|
+
purser_client/py.typed
|
|
6
|
+
purser_client.egg-info/PKG-INFO
|
|
7
|
+
purser_client.egg-info/SOURCES.txt
|
|
8
|
+
purser_client.egg-info/dependency_links.txt
|
|
9
|
+
purser_client.egg-info/top_level.txt
|
|
10
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
purser_client
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# purser-client: Purser's Python client as a package (docs/releasing.md, "Packages"). Standard library only, so no
|
|
2
|
+
# runtime dependencies. The distribution is purser-client and the import package purser_client: "purser" on PyPI is an
|
|
3
|
+
# unrelated project that installs its own top-level "purser" package, and two distributions writing the same package
|
|
4
|
+
# in one environment overwrite each other's files without a warning.
|
|
5
|
+
#
|
|
6
|
+
# The build backend is pinned like every other tool in this repository. setuptools 77 or later is needed for the SPDX
|
|
7
|
+
# licence expression below (PEP 639); test/sdk-packages.test.ts builds the wheel with the setuptools this machine has
|
|
8
|
+
# (--no-build-isolation, no registry call) and installs it into a fresh virtual environment.
|
|
9
|
+
[build-system]
|
|
10
|
+
requires = ["setuptools==84.2.1"]
|
|
11
|
+
build-backend = "setuptools.build_meta"
|
|
12
|
+
|
|
13
|
+
[project]
|
|
14
|
+
name = "purser-client"
|
|
15
|
+
dynamic = ["version"]
|
|
16
|
+
description = "Purser's Python client: read the books, propose an invoice's payment, read a proposal's status. It cannot approve: only the CFO's passkey does."
|
|
17
|
+
readme = "README.md"
|
|
18
|
+
license = "MIT"
|
|
19
|
+
license-files = ["LICENSE"]
|
|
20
|
+
requires-python = ">=3.10"
|
|
21
|
+
authors = [{ name = "Max Geurtsen" }]
|
|
22
|
+
keywords = ["purser", "accounts-payable", "payments", "x402"]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 5 - Production/Stable",
|
|
25
|
+
"Intended Audience :: Developers",
|
|
26
|
+
"Programming Language :: Python :: 3",
|
|
27
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
28
|
+
"Programming Language :: Python :: 3.10",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Programming Language :: Python :: 3.13",
|
|
32
|
+
"Programming Language :: Python :: 3.14",
|
|
33
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
34
|
+
"Typing :: Typed",
|
|
35
|
+
]
|
|
36
|
+
dependencies = []
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/agamemnon-coder/x402-business-agents/tree/main/sdk/python"
|
|
40
|
+
Source = "https://github.com/agamemnon-coder/x402-business-agents"
|
|
41
|
+
Issues = "https://github.com/agamemnon-coder/x402-business-agents/issues"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools]
|
|
44
|
+
packages = ["purser_client"]
|
|
45
|
+
|
|
46
|
+
[tool.setuptools.package-data]
|
|
47
|
+
purser_client = ["py.typed"]
|
|
48
|
+
|
|
49
|
+
[tool.setuptools.dynamic]
|
|
50
|
+
version = { attr = "purser_client.__version__" }
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""The Python client against a local mock of Purser Cloud (standard library only; no network beyond 127.0.0.1).
|
|
2
|
+
|
|
3
|
+
Run: python3 sdk/python/tests/test_client.py
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import unittest
|
|
11
|
+
import urllib.parse
|
|
12
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
|
15
|
+
from purser_client import OPERATIONS, Purser, PurserError # noqa: E402
|
|
16
|
+
|
|
17
|
+
KEY = "pck_test_not-a-real-key"
|
|
18
|
+
PROPOSAL = {"id": "P-0001", "kind": "invoice_payment", "status": "PENDING_APPROVAL", "terms_sha256": "a" * 64, "facts": [["Amount", "EUR 1309.00"]], "warnings": []}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _inv(i):
|
|
22
|
+
return {"id": i, "version": 1}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
#: Paging cases for invoices(): each case's pages by the cursor asked for ("" for none).
|
|
26
|
+
PAGING = {
|
|
27
|
+
"paging-two": {"": {"items": [_inv("AP-0001")], "next_cursor": "c1"}, "c1": {"items": [_inv("AP-0002")], "next_cursor": None}},
|
|
28
|
+
"paging-empty": {"": {"items": [], "next_cursor": None}},
|
|
29
|
+
"paging-repeat": {"": {"items": [_inv("AP-0001")], "next_cursor": "c1"}, "c1": {"items": [_inv("AP-0001")], "next_cursor": "c1"}},
|
|
30
|
+
"paging-loop": {"": {"items": [_inv("AP-0001")], "next_cursor": "c1"}, "c1": {"items": [_inv("AP-0002")], "next_cursor": "c2"}, "c2": {"items": [_inv("AP-0003")], "next_cursor": "c1"}},
|
|
31
|
+
"paging-same-page": {"": {"items": [_inv("AP-0001")], "next_cursor": "c1"}, "c1": {"items": [_inv("AP-0001")], "next_cursor": "c2"}},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Mock(BaseHTTPRequestHandler):
|
|
36
|
+
seen = []
|
|
37
|
+
#: The Idempotency-Key of each POST, in order (None when it carried none).
|
|
38
|
+
keys = []
|
|
39
|
+
#: How many times each flaky path was asked: the first answer is a 503, the next ones succeed.
|
|
40
|
+
flaky = {}
|
|
41
|
+
#: The Content-Type and body of each POST, in order.
|
|
42
|
+
bodies = []
|
|
43
|
+
|
|
44
|
+
def log_message(self, *_):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
def _send(self, status, body):
|
|
48
|
+
data = json.dumps(body).encode()
|
|
49
|
+
self.send_response(status)
|
|
50
|
+
if status == 503:
|
|
51
|
+
self.send_header("retry-after", "0")
|
|
52
|
+
self.send_header("content-type", "application/json")
|
|
53
|
+
self.send_header("content-length", str(len(data)))
|
|
54
|
+
self.end_headers()
|
|
55
|
+
self.wfile.write(data)
|
|
56
|
+
|
|
57
|
+
def _route(self, method):
|
|
58
|
+
Mock.seen.append((method, self.path, self.headers.get("authorization")))
|
|
59
|
+
if self.headers.get("authorization") != f"Bearer {KEY}":
|
|
60
|
+
return self._send(401, {"error": "sign in, or send an API key as Authorization: Bearer", "code": "unauthorized"})
|
|
61
|
+
p = self.path
|
|
62
|
+
if method == "POST":
|
|
63
|
+
Mock.keys.append(self.headers.get("idempotency-key"))
|
|
64
|
+
n = int(self.headers.get("content-length") or 0)
|
|
65
|
+
Mock.bodies.append((self.headers.get("content-type"), self.rfile.read(n).decode("utf-8") if n else None))
|
|
66
|
+
if method == "POST" and p.split("?")[0] == "/v1/engine/shadow":
|
|
67
|
+
return self._send(200, {"report": {"format": "purser.shadow/v1", "summary": {"rows": 1, "refused": 0}}})
|
|
68
|
+
if method == "GET" and p == "/v1/engine/proposals/P-0001/dossier":
|
|
69
|
+
return self._send(200, {"dossier": {"format": "purser.payment-dossier/v1", "payment": {"proposal_id": "P-0001"}}})
|
|
70
|
+
if method == "GET" and p == "/v1/engine/proposals/P-0001/bank-file":
|
|
71
|
+
return self._send(403, {"error": "a key never approves: approving is a signed-in CFO's passkey over the exact terms", "code": "forbidden"})
|
|
72
|
+
if p in ("/v1/engine/invoices/AP-0503/pay", "/v1/engine/proposals/P-0503"):
|
|
73
|
+
Mock.flaky[p] = Mock.flaky.get(p, 0) + 1
|
|
74
|
+
return self._send(503, {"error": "busy", "code": "busy"}) if Mock.flaky[p] == 1 else self._send(200, {"proposal": PROPOSAL})
|
|
75
|
+
if method == "GET" and p == "/v1/me":
|
|
76
|
+
return self._send(200, {"tenant": {"id": "t1", "name": "Northwind"}, "kind": "key", "scopes": ["read", "propose"], "role": None})
|
|
77
|
+
if method == "GET" and (p == "/v1/invoices" or p.startswith("/v1/invoices?")):
|
|
78
|
+
# status=paging-<case>: the pages of one paging case (test_paging), keyed by the cursor asked for.
|
|
79
|
+
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(p).query))
|
|
80
|
+
if q.get("status", "").startswith("paging-"):
|
|
81
|
+
page = PAGING[q["status"]].get(q.get("cursor", ""))
|
|
82
|
+
return self._send(200, page) if page else self._send(404, {"error": "no such cursor", "code": "not_found"})
|
|
83
|
+
if "cursor=AP-0001" in p:
|
|
84
|
+
return self._send(200, {"items": [{"id": "AP-0002", "version": 1}], "next_cursor": None})
|
|
85
|
+
return self._send(200, {"items": [{"id": "AP-0001", "version": 1, "vendor": "Bergtex", "total": "1309.00", "currency": "EUR"}], "next_cursor": "AP-0001"})
|
|
86
|
+
if method == "GET" and p == "/v1/invoices/AP-0001":
|
|
87
|
+
return self._send(200, {"id": "AP-0001", "version": 1, "earlier_versions": []})
|
|
88
|
+
if method == "GET" and p == "/v1/engine/invoices":
|
|
89
|
+
return self._send(200, {"items": [{"id": "AP-0001", "status": "ready", "payable": True, "vendor": "Bergtex", "currency": "EUR", "total": "1309.00", "proposal": None}]})
|
|
90
|
+
if method == "POST" and p == "/v1/engine/invoices/AP-0001/pay":
|
|
91
|
+
return self._send(200, {"proposal": PROPOSAL})
|
|
92
|
+
if method == "POST" and p == "/v1/engine/invoices/AP-0009/pay":
|
|
93
|
+
return self._send(409, {"error": "AP-0009 is held for a person", "code": "conflict"})
|
|
94
|
+
if method == "GET" and p == "/v1/engine/proposals/P-0001":
|
|
95
|
+
return self._send(200, {"proposal": PROPOSAL})
|
|
96
|
+
return self._send(404, {"error": "no such route", "code": "not_found"})
|
|
97
|
+
|
|
98
|
+
def do_GET(self):
|
|
99
|
+
self._route("GET")
|
|
100
|
+
|
|
101
|
+
def do_POST(self):
|
|
102
|
+
self._route("POST")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class ClientTest(unittest.TestCase):
|
|
106
|
+
@classmethod
|
|
107
|
+
def setUpClass(cls):
|
|
108
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Mock)
|
|
109
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
110
|
+
cls.base = f"http://127.0.0.1:{cls.server.server_port}"
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def tearDownClass(cls):
|
|
114
|
+
cls.server.shutdown()
|
|
115
|
+
|
|
116
|
+
def setUp(self):
|
|
117
|
+
Mock.seen = []
|
|
118
|
+
Mock.keys = []
|
|
119
|
+
Mock.flaky = {}
|
|
120
|
+
Mock.bodies = []
|
|
121
|
+
self.p = Purser(self.base, KEY)
|
|
122
|
+
|
|
123
|
+
def test_the_v1_7_reads_dossier_shadow_mode_and_the_bank_file(self):
|
|
124
|
+
self.assertEqual(self.p.get_payment_dossier("P-0001")["payment"]["proposal_id"], "P-0001")
|
|
125
|
+
report = self.p.run_shadow_mode("supplier,amount\nBergtex,1850.00\n", alone_limit="2000.00")
|
|
126
|
+
self.assertEqual(report["summary"]["rows"], 1)
|
|
127
|
+
self.assertIn(("POST", "/v1/engine/shadow?alone_limit=2000.00", f"Bearer {KEY}"), Mock.seen)
|
|
128
|
+
self.assertEqual(Mock.bodies, [("text/csv", "supplier,amount\nBergtex,1850.00\n")])
|
|
129
|
+
with self.assertRaises(ValueError):
|
|
130
|
+
self.p.run_shadow_mode("x", alone_limit="2k")
|
|
131
|
+
with self.assertRaises(ValueError):
|
|
132
|
+
self.p.run_shadow_mode(" ")
|
|
133
|
+
# The bank file is the CFO's alone: every key is refused.
|
|
134
|
+
with self.assertRaises(PurserError) as e:
|
|
135
|
+
self.p.get_bank_file("P-0001")
|
|
136
|
+
self.assertEqual((e.exception.status, e.exception.code), (403, "forbidden"))
|
|
137
|
+
|
|
138
|
+
def test_quickstart(self):
|
|
139
|
+
self.assertEqual(self.p.me()["scopes"], ["read", "propose"])
|
|
140
|
+
page = self.p.list_invoices(status="ready", limit=1)
|
|
141
|
+
self.assertEqual(page["items"][0]["id"], "AP-0001")
|
|
142
|
+
self.assertEqual([i["id"] for i in self.p.invoices()], ["AP-0001", "AP-0002"])
|
|
143
|
+
self.assertEqual(self.p.get_invoice("AP-0001")["id"], "AP-0001")
|
|
144
|
+
self.assertTrue(self.p.list_payable_invoices()[0]["payable"])
|
|
145
|
+
out = self.p.propose_payment("AP-0001")
|
|
146
|
+
self.assertEqual(out["proposal"]["status"], "PENDING_APPROVAL")
|
|
147
|
+
self.assertEqual(self.p.get_proposal("P-0001")["status"], "PENDING_APPROVAL")
|
|
148
|
+
self.assertIn(("POST", "/v1/engine/invoices/AP-0001/pay", f"Bearer {KEY}"), Mock.seen)
|
|
149
|
+
self.assertIn(("GET", "/v1/invoices?status=ready&limit=1", f"Bearer {KEY}"), Mock.seen)
|
|
150
|
+
|
|
151
|
+
def _collect(self, case):
|
|
152
|
+
"""The ids invoices() yields for a paging case, and the error it raised (at most 10: a loop must not hang the test)."""
|
|
153
|
+
ids = []
|
|
154
|
+
try:
|
|
155
|
+
for i in self.p.invoices(status=case, limit=1):
|
|
156
|
+
ids.append(i["id"])
|
|
157
|
+
if len(ids) >= 10:
|
|
158
|
+
break
|
|
159
|
+
except PurserError as e:
|
|
160
|
+
return ids, e
|
|
161
|
+
return ids, None
|
|
162
|
+
|
|
163
|
+
def test_paging_reads_the_next_page_and_stops_at_the_end(self):
|
|
164
|
+
self.assertEqual(self._collect("paging-two"), (["AP-0001", "AP-0002"], None))
|
|
165
|
+
self.assertEqual([p for _, p, _ in Mock.seen], ["/v1/invoices?status=paging-two&limit=1", "/v1/invoices?status=paging-two&limit=1&cursor=c1"])
|
|
166
|
+
self.assertEqual(self._collect("paging-empty"), ([], None))
|
|
167
|
+
|
|
168
|
+
def test_paging_refuses_a_repeated_cursor_before_yielding_that_page(self):
|
|
169
|
+
ids, e = self._collect("paging-repeat")
|
|
170
|
+
self.assertEqual(ids, ["AP-0001"])
|
|
171
|
+
self.assertIsNotNone(e)
|
|
172
|
+
self.assertEqual(e.code, "repeated_cursor")
|
|
173
|
+
self.assertIn('cursor "c1" again', str(e))
|
|
174
|
+
ids, e = self._collect("paging-loop")
|
|
175
|
+
self.assertEqual((ids, e and e.code), (["AP-0001", "AP-0002"], "repeated_cursor"))
|
|
176
|
+
|
|
177
|
+
def test_paging_refuses_the_same_page_under_a_new_cursor(self):
|
|
178
|
+
ids, e = self._collect("paging-same-page")
|
|
179
|
+
self.assertEqual((ids, e and e.code), (["AP-0001"], "repeated_page"))
|
|
180
|
+
|
|
181
|
+
def test_errors_carry_status_and_code(self):
|
|
182
|
+
with self.assertRaises(PurserError) as e:
|
|
183
|
+
self.p.propose_payment("AP-0009")
|
|
184
|
+
self.assertEqual((e.exception.status, e.exception.code), (409, "conflict"))
|
|
185
|
+
with self.assertRaises(PurserError) as e:
|
|
186
|
+
Purser(self.base, "pck_wrong").me()
|
|
187
|
+
self.assertEqual(e.exception.status, 401)
|
|
188
|
+
|
|
189
|
+
def test_never_approves(self):
|
|
190
|
+
self.assertFalse([n for n in dir(Purser) if "approv" in n.lower()])
|
|
191
|
+
self.assertFalse([op for op, (_, path) in OPERATIONS.items() if "approve" in path or "approve" in op.lower()])
|
|
192
|
+
|
|
193
|
+
def test_refuses_bad_input_and_hides_the_key(self):
|
|
194
|
+
with self.assertRaises(ValueError):
|
|
195
|
+
Purser("http://purser.example.com", KEY)
|
|
196
|
+
with self.assertRaises(ValueError):
|
|
197
|
+
Purser("https://purser.example.com", "")
|
|
198
|
+
with self.assertRaises(ValueError):
|
|
199
|
+
self.p.get_proposal("../keys")
|
|
200
|
+
self.assertNotIn(KEY, repr(self.p))
|
|
201
|
+
self.assertEqual(Purser.from_env({"PURSER_URL": self.base, "PURSER_API_KEY": KEY}).me()["kind"], "key")
|
|
202
|
+
self.assertEqual(Purser.from_env({"PURSER_BASE_URL": self.base, "PURSER_API_KEY": KEY}).me()["kind"], "key")
|
|
203
|
+
|
|
204
|
+
def test_every_post_carries_an_idempotency_key_and_is_tried_again_under_it(self):
|
|
205
|
+
self.assertEqual(self.p.propose_payment("AP-0503")["proposal"]["id"], "P-0001")
|
|
206
|
+
self.assertEqual(len(Mock.keys), 2)
|
|
207
|
+
self.assertRegex(Mock.keys[0], r"^[0-9a-f-]{36}$")
|
|
208
|
+
self.assertEqual(Mock.keys[1], Mock.keys[0])
|
|
209
|
+
self.p.propose_payment("AP-0001")
|
|
210
|
+
self.p.propose_payment("AP-0001", idempotency_key="order-4711")
|
|
211
|
+
self.assertNotEqual(Mock.keys[2], Mock.keys[0])
|
|
212
|
+
self.assertEqual(Mock.keys[3], "order-4711")
|
|
213
|
+
with self.assertRaises(ValueError):
|
|
214
|
+
self.p.propose_payment("AP-0001", idempotency_key="has spaces")
|
|
215
|
+
|
|
216
|
+
def test_without_a_key_a_post_is_never_tried_again(self):
|
|
217
|
+
with self.assertRaises(PurserError) as e:
|
|
218
|
+
Purser(self.base, KEY, idempotency_keys=False).propose_payment("AP-0503")
|
|
219
|
+
self.assertEqual(e.exception.status, 503)
|
|
220
|
+
self.assertEqual(Mock.keys, [None])
|
|
221
|
+
|
|
222
|
+
def test_a_read_is_tried_again_after_a_5xx(self):
|
|
223
|
+
self.assertEqual(self.p.get_proposal("P-0503")["id"], "P-0001")
|
|
224
|
+
self.assertEqual(Mock.flaky["/v1/engine/proposals/P-0503"], 2)
|
|
225
|
+
Mock.flaky = {}
|
|
226
|
+
with self.assertRaises(PurserError):
|
|
227
|
+
Purser(self.base, KEY, retries=0).get_proposal("P-0503")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
if __name__ == "__main__":
|
|
231
|
+
unittest.main()
|