rowbind 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rowbind/__init__.py +22 -0
- rowbind/_catalog.py +73 -0
- rowbind/_generated_catalog.py +32 -0
- rowbind/_generated_raw.py +59 -0
- rowbind/_invoice_sync.py +166 -0
- rowbind/_raw.py +103 -0
- rowbind/_transport.py +224 -0
- rowbind/_wire.py +21 -0
- rowbind/client.py +388 -0
- rowbind/examples/__init__.py +1 -0
- rowbind/examples/catalog_invoice.py +42 -0
- rowbind/examples/first_invoice.py +28 -0
- rowbind/examples/invoice_pages.py +21 -0
- rowbind/models.py +316 -0
- rowbind/py.typed +0 -0
- rowbind-0.1.0a1.dist-info/METADATA +5 -0
- rowbind-0.1.0a1.dist-info/RECORD +19 -0
- rowbind-0.1.0a1.dist-info/WHEEL +5 -0
- rowbind-0.1.0a1.dist-info/top_level.txt +1 -0
rowbind/_transport.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""HTTP transport shared by the synchronous and asynchronous invoice clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import http.client
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import random
|
|
10
|
+
import re
|
|
11
|
+
import socket
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from email.utils import parsedate_to_datetime
|
|
15
|
+
from typing import Any, Literal, Mapping, Optional, Union, overload
|
|
16
|
+
from urllib.parse import quote, urlencode, urlsplit
|
|
17
|
+
|
|
18
|
+
from ._wire import OPERATIONS
|
|
19
|
+
|
|
20
|
+
RETRYABLE_STATUSES = (408, 429, 500, 502, 503, 504)
|
|
21
|
+
DEFAULT_BASE_URL = "https://api.rowbind.com"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RowbindError(Exception):
|
|
25
|
+
def __init__(self, code: str, message: str, *, request_id: Optional[str] = None, status: Optional[int] = None):
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.code = code
|
|
28
|
+
self.request_id = request_id
|
|
29
|
+
self.status = status
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _seconds(value: float) -> float:
|
|
33
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value) or value <= 0:
|
|
34
|
+
raise RowbindError("invalid_input", "Set a positive, finite timeout in seconds.")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _retry_after(value: Optional[str]) -> float:
|
|
39
|
+
if value:
|
|
40
|
+
try:
|
|
41
|
+
if value.isascii() and value.isdigit():
|
|
42
|
+
return float(value)
|
|
43
|
+
return max(0.0, parsedate_to_datetime(value).timestamp() - time.time())
|
|
44
|
+
except (TypeError, ValueError, OverflowError):
|
|
45
|
+
pass
|
|
46
|
+
return 0.0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _header(value: object) -> bool:
|
|
50
|
+
return isinstance(value, str) and bool(value.strip()) and value.isascii() and value.isprintable()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _remaining(deadline: float) -> float:
|
|
54
|
+
remaining = deadline - time.monotonic()
|
|
55
|
+
if remaining <= 0:
|
|
56
|
+
raise TimeoutError("HTTP deadline exceeded")
|
|
57
|
+
return remaining
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _interrupt(sock: socket.socket) -> None:
|
|
61
|
+
# getresponse() parses headers internally. A peer sending them one byte at
|
|
62
|
+
# a time can otherwise keep the socket alive past its inactivity timeout.
|
|
63
|
+
try:
|
|
64
|
+
sock.shutdown(socket.SHUT_RDWR)
|
|
65
|
+
except OSError:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _read_body(response: http.client.HTTPResponse, sock: socket.socket, deadline: float) -> bytearray:
|
|
70
|
+
data = bytearray()
|
|
71
|
+
while response.length != 0:
|
|
72
|
+
sock.settimeout(_remaining(deadline))
|
|
73
|
+
chunk = response.read1(64 * 1024)
|
|
74
|
+
if not chunk:
|
|
75
|
+
if response.length:
|
|
76
|
+
raise http.client.IncompleteRead(bytes(data), response.length)
|
|
77
|
+
break
|
|
78
|
+
data.extend(chunk)
|
|
79
|
+
return data
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _credentials(base_url: Optional[str], api_key: Optional[str]) -> tuple[str, str]:
|
|
83
|
+
if base_url is not None and api_key is not None:
|
|
84
|
+
return base_url, api_key
|
|
85
|
+
legacy_url = os.environ.get("ROWBIND_SANDBOX_URL")
|
|
86
|
+
legacy_key = os.environ.get("ROWBIND_SANDBOX_API_KEY")
|
|
87
|
+
if legacy_url is not None or legacy_key is not None:
|
|
88
|
+
if (not legacy_url or not legacy_key or base_url is not None or api_key is not None or
|
|
89
|
+
"ROWBIND_BASE_URL" in os.environ or "ROWBIND_API_KEY" in os.environ):
|
|
90
|
+
raise RowbindError("invalid_configuration", "Use ROWBIND_API_KEY or the complete legacy sandbox pair. "
|
|
91
|
+
"Keep the two configurations separate.")
|
|
92
|
+
if legacy_key.startswith("rb_live_"):
|
|
93
|
+
raise RowbindError("invalid_configuration", "Use a sandbox key with the legacy sandbox variables.")
|
|
94
|
+
return legacy_url, legacy_key
|
|
95
|
+
return (os.environ.get("ROWBIND_BASE_URL", DEFAULT_BASE_URL) if base_url is None else base_url,
|
|
96
|
+
os.environ.get("ROWBIND_API_KEY", "") if api_key is None else api_key)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Transport:
|
|
100
|
+
def __init__(self, base_url: Optional[str], api_key: Optional[str], *, timeout: float = 15.0):
|
|
101
|
+
base_url, api_key = _credentials(base_url, api_key)
|
|
102
|
+
try:
|
|
103
|
+
origin = urlsplit(base_url)
|
|
104
|
+
host, port = origin.hostname, origin.port
|
|
105
|
+
if (not host or origin.username is not None or origin.password is not None or
|
|
106
|
+
origin.path not in ("", "/") or origin.query or origin.fragment or
|
|
107
|
+
not base_url.isprintable() or any(c.isspace() for c in base_url) or "\\" in base_url or
|
|
108
|
+
not (origin.scheme == "https" or (origin.scheme == "http" and host in ("localhost", "127.0.0.1", "::1")))):
|
|
109
|
+
raise ValueError
|
|
110
|
+
except (TypeError, AttributeError, ValueError):
|
|
111
|
+
raise RowbindError("invalid_configuration", "Set an HTTPS Rowbind origin, or use HTTP on loopback.") from None
|
|
112
|
+
if not _header(api_key):
|
|
113
|
+
raise RowbindError("invalid_configuration", "Set ROWBIND_API_KEY in your backend or pass api_key.")
|
|
114
|
+
self._connection = http.client.HTTPSConnection if origin.scheme == "https" else http.client.HTTPConnection
|
|
115
|
+
self._host, self._port = host, port
|
|
116
|
+
self._key = api_key
|
|
117
|
+
self._timeout = _seconds(timeout)
|
|
118
|
+
|
|
119
|
+
@overload
|
|
120
|
+
def request(self, operation_id: Literal["listConnections"], *, timeout: Optional[float] = None) -> list[dict[str, Any]]: ...
|
|
121
|
+
|
|
122
|
+
@overload
|
|
123
|
+
def request(self, operation_id: Literal["checkConnectionHealth", "retrieveConnectionHealth", "createCompany", "createConnectSession", "createInvoice", "retrieveConnection",
|
|
124
|
+
"retrieveConnectSession", "retrieveInvoiceRecovery", "retrieveOperation",
|
|
125
|
+
"enableInvoiceSync", "retrieveInvoiceSync", "listSyncedInvoices", "searchCatalog", "linkCatalog"],
|
|
126
|
+
*, path: Optional[Mapping[str, str]] = None, query: Optional[Mapping[str, Any]] = None,
|
|
127
|
+
body: Optional[Mapping[str, Any]] = None, idempotency_key: Optional[str] = None,
|
|
128
|
+
timeout: Optional[float] = None) -> dict[str, Any]: ...
|
|
129
|
+
|
|
130
|
+
@overload
|
|
131
|
+
def request(self, operation_id: Literal["readRaw", "queryRaw"], *, path: Mapping[str, str], body: Mapping[str, Any],
|
|
132
|
+
include_request_id: Literal[True]) -> tuple[dict[str, Any], Optional[str]]: ...
|
|
133
|
+
|
|
134
|
+
def request(self, operation_id: str, *, path: Optional[Mapping[str, str]] = None,
|
|
135
|
+
query: Optional[Mapping[str, Any]] = None, body: Optional[Mapping[str, Any]] = None,
|
|
136
|
+
idempotency_key: Optional[str] = None, timeout: Optional[float] = None, include_request_id: bool = False
|
|
137
|
+
) -> Union[dict[str, Any], list[dict[str, Any]], tuple[dict[str, Any], Optional[str]]]:
|
|
138
|
+
method, target, keyed, query_names, returns_list = OPERATIONS[operation_id]
|
|
139
|
+
names = re.findall(r"{(\w+)}", target)
|
|
140
|
+
values = path or {}
|
|
141
|
+
if set(values) != set(names):
|
|
142
|
+
raise RowbindError("invalid_input", "Provide the path parameters for this Rowbind resource.")
|
|
143
|
+
for name in names:
|
|
144
|
+
value = values[name]
|
|
145
|
+
if not isinstance(value, str) or value in ("", ".", ".."):
|
|
146
|
+
raise RowbindError("invalid_input", "Provide a valid Rowbind resource ID.")
|
|
147
|
+
target = target.replace("{" + name + "}", quote(value, safe=""))
|
|
148
|
+
if query:
|
|
149
|
+
if set(query) - set(query_names):
|
|
150
|
+
raise RowbindError("invalid_input", "Unexpected query parameters.")
|
|
151
|
+
target += "?" + urlencode(query)
|
|
152
|
+
headers = {"Authorization": "Bearer " + self._key, "Accept": "application/json"}
|
|
153
|
+
if keyed:
|
|
154
|
+
if idempotency_key is None or not _header(idempotency_key) or len(idempotency_key) > 255:
|
|
155
|
+
raise RowbindError("invalid_input", "Provide a valid, stable idempotency key of up to 255 characters.")
|
|
156
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
157
|
+
elif idempotency_key is not None:
|
|
158
|
+
raise RowbindError("invalid_input", "This operation does not accept an idempotency key.")
|
|
159
|
+
payload = None
|
|
160
|
+
if body is not None:
|
|
161
|
+
try:
|
|
162
|
+
payload = json.dumps(body, allow_nan=False, separators=(",", ":")).encode()
|
|
163
|
+
except (TypeError, ValueError):
|
|
164
|
+
raise RowbindError("invalid_input", "Provide a JSON-serializable request.") from None
|
|
165
|
+
headers["Content-Type"] = "application/json"
|
|
166
|
+
attempts = 3 if method in ("GET", "PUT") or keyed else 1
|
|
167
|
+
deadline = time.monotonic() + (self._timeout if timeout is None else _seconds(timeout))
|
|
168
|
+
last_error = RowbindError("transport_unavailable", "Rowbind did not return a result within the HTTP retry budget.")
|
|
169
|
+
for index in range(attempts):
|
|
170
|
+
remaining = deadline - time.monotonic()
|
|
171
|
+
if remaining <= 0:
|
|
172
|
+
break
|
|
173
|
+
attempt_deadline = min(deadline, time.monotonic() + 8.0)
|
|
174
|
+
connection = self._connection(self._host, self._port, timeout=min(8.0, remaining))
|
|
175
|
+
alarm = None
|
|
176
|
+
request_id = status = None
|
|
177
|
+
delay = 0.0
|
|
178
|
+
try:
|
|
179
|
+
connection.connect()
|
|
180
|
+
sock = connection.sock
|
|
181
|
+
if sock is None:
|
|
182
|
+
raise OSError("Connection closed.")
|
|
183
|
+
alarm = threading.Timer(_remaining(attempt_deadline), _interrupt, args=(sock,))
|
|
184
|
+
alarm.daemon = True
|
|
185
|
+
alarm.start()
|
|
186
|
+
connection.request(method, target, body=payload, headers=headers)
|
|
187
|
+
with connection.getresponse() as response:
|
|
188
|
+
_remaining(attempt_deadline)
|
|
189
|
+
status = response.status
|
|
190
|
+
request_id = response.getheader("X-Request-Id")
|
|
191
|
+
raw = _read_body(response, sock, attempt_deadline)
|
|
192
|
+
try:
|
|
193
|
+
result = json.loads(raw)
|
|
194
|
+
except (ValueError, UnicodeError):
|
|
195
|
+
result = None
|
|
196
|
+
_remaining(attempt_deadline)
|
|
197
|
+
if 200 <= status < 300:
|
|
198
|
+
if returns_list and isinstance(result, list) and all(isinstance(item, dict) for item in result):
|
|
199
|
+
return result
|
|
200
|
+
if not returns_list and isinstance(result, dict):
|
|
201
|
+
if include_request_id:
|
|
202
|
+
return result, request_id
|
|
203
|
+
return result
|
|
204
|
+
raise RowbindError("invalid_response", "Unexpected JSON response for this operation.",
|
|
205
|
+
request_id=request_id, status=status)
|
|
206
|
+
if isinstance(result, dict) and isinstance(result.get("code"), str) and isinstance(result.get("message"), str):
|
|
207
|
+
last_error = RowbindError(result["code"], result["message"], request_id=request_id, status=status)
|
|
208
|
+
else:
|
|
209
|
+
last_error = RowbindError("http_error", f"Rowbind HTTP {status}.", request_id=request_id, status=status)
|
|
210
|
+
if status not in RETRYABLE_STATUSES:
|
|
211
|
+
raise last_error
|
|
212
|
+
delay = _retry_after(response.getheader("Retry-After"))
|
|
213
|
+
except (OSError, http.client.HTTPException):
|
|
214
|
+
last_error = RowbindError("transport_unavailable", "Rowbind did not return a complete response.",
|
|
215
|
+
request_id=request_id, status=status)
|
|
216
|
+
finally:
|
|
217
|
+
if alarm is not None:
|
|
218
|
+
alarm.cancel()
|
|
219
|
+
connection.close()
|
|
220
|
+
delay = max(delay, random.uniform(0, 0.2 * 2 ** index))
|
|
221
|
+
if index + 1 == attempts or time.monotonic() + delay >= deadline:
|
|
222
|
+
break
|
|
223
|
+
time.sleep(delay)
|
|
224
|
+
raise last_error
|
rowbind/_wire.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Generated by scripts/generate_wire.py from packages/api-contract/openapi.json.
|
|
2
|
+
# method, path, requires Idempotency-Key, query parameters, returns a list
|
|
3
|
+
OPERATIONS = {
|
|
4
|
+
'checkConnectionHealth': ('POST', '/v1/connections/{id}/health/check', False, (), False),
|
|
5
|
+
'createCompany': ('POST', '/v1/companies', False, (), False),
|
|
6
|
+
'createConnectSession': ('POST', '/v1/connect/sessions', False, (), False),
|
|
7
|
+
'createInvoice': ('POST', '/v1/invoices', True, (), False),
|
|
8
|
+
'enableInvoiceSync': ('PUT', '/v1/connections/{id}/sync/invoices', False, (), False),
|
|
9
|
+
'linkCatalog': ('PUT', '/v1/connections/{id}/catalog/{kind}/links', False, (), False),
|
|
10
|
+
'listConnections': ('GET', '/v1/connections', False, (), True),
|
|
11
|
+
'listSyncedInvoices': ('GET', '/v1/connections/{id}/invoices', False, ('after', 'limit'), False),
|
|
12
|
+
'queryRaw': ('POST', '/v1/connections/{id}/raw/query', False, (), False),
|
|
13
|
+
'readRaw': ('POST', '/v1/connections/{id}/raw/read', False, (), False),
|
|
14
|
+
'retrieveConnectSession': ('GET', '/v1/connect/sessions/{id}', False, (), False),
|
|
15
|
+
'retrieveConnection': ('GET', '/v1/connections/{id}', False, (), False),
|
|
16
|
+
'retrieveConnectionHealth': ('GET', '/v1/connections/{id}/health', False, (), False),
|
|
17
|
+
'retrieveInvoiceRecovery': ('GET', '/v1/operations/{id}/recovery', False, ('after',), False),
|
|
18
|
+
'retrieveInvoiceSync': ('GET', '/v1/connections/{id}/sync/invoices', False, (), False),
|
|
19
|
+
'retrieveOperation': ('GET', '/v1/operations/{id}', False, (), False),
|
|
20
|
+
'searchCatalog': ('GET', '/v1/connections/{id}/catalog/{kind}', False, ('query', 'after'), False),
|
|
21
|
+
}
|
rowbind/client.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""Sync and async clients for the sandbox invoice flow."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from typing import AsyncIterator, Iterator, Literal, Optional, Sequence, overload
|
|
9
|
+
|
|
10
|
+
from ._generated_catalog import AsyncCatalog, Catalog
|
|
11
|
+
from ._generated_raw import _AsyncRawProviders, _RawProviders
|
|
12
|
+
from ._invoice_sync import AsyncSync, Sync, SyncedInvoicePage, invoice_page
|
|
13
|
+
from ._transport import RETRYABLE_STATUSES, RowbindError, Transport
|
|
14
|
+
from .models import (
|
|
15
|
+
Company, Connection, ConnectionHealth, ConnectSession, CreatedConnectSession, FailedOperation,
|
|
16
|
+
InvoiceLine, InvoiceRecord, NetSuiteConnection, Operation, OperationReceipt,
|
|
17
|
+
Provider, QuickBooksConnection, RecoveryEntry, RecoveryPage, VerifiedOperation,
|
|
18
|
+
_array, _company, _connection, _health, _invalid, _object, _operation, _receipt,
|
|
19
|
+
_recovery_page, _session, _string,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class OperationWaitError(RowbindError):
|
|
24
|
+
"""Waiting stopped. Keep the operation ID to read its eventual outcome."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, code: str, message: str, operation_id: str, diagnosis: Optional[RecoveryEntry],
|
|
27
|
+
*, request_id: Optional[str] = None, status: Optional[int] = None) -> None:
|
|
28
|
+
super().__init__(code, message, request_id=request_id, status=status)
|
|
29
|
+
self.operation_id = operation_id
|
|
30
|
+
self.diagnosis = diagnosis
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _required(value: str, field: str) -> str:
|
|
34
|
+
if not isinstance(value, str) or not value:
|
|
35
|
+
raise RowbindError("invalid_input", f"Provide a nonempty {field}.")
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Connections:
|
|
40
|
+
def __init__(self, transport: Transport) -> None:
|
|
41
|
+
self._transport = transport
|
|
42
|
+
|
|
43
|
+
def list(self) -> list[Connection]:
|
|
44
|
+
return [_connection(row) for row in _array(self._transport.request("listConnections"))]
|
|
45
|
+
|
|
46
|
+
def retrieve(self, connection_id: str) -> Connection:
|
|
47
|
+
key = _required(connection_id, "connection ID")
|
|
48
|
+
connection = _connection(self._transport.request("retrieveConnection", path={"id": key}))
|
|
49
|
+
if connection.id != key:
|
|
50
|
+
raise _invalid("connection ID")
|
|
51
|
+
return connection
|
|
52
|
+
|
|
53
|
+
def health(self, connection_id: str) -> ConnectionHealth:
|
|
54
|
+
key = _required(connection_id, "connection ID")
|
|
55
|
+
return _health(self._transport.request("retrieveConnectionHealth", path={"id": key}), key)
|
|
56
|
+
|
|
57
|
+
def check_health(self, connection_id: str) -> ConnectionHealth:
|
|
58
|
+
key = _required(connection_id, "connection ID")
|
|
59
|
+
return _health(self._transport.request("checkConnectionHealth", path={"id": key}), key)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _Companies:
|
|
63
|
+
def __init__(self, transport: Transport) -> None:
|
|
64
|
+
self._transport = transport
|
|
65
|
+
|
|
66
|
+
def create(self, *, external_id: str, name: str) -> Company:
|
|
67
|
+
body = {"externalId": _required(external_id, "company external ID"), "name": _required(name, "company name")}
|
|
68
|
+
company = _company(self._transport.request("createCompany", body=body))
|
|
69
|
+
if company.external_id != external_id:
|
|
70
|
+
raise _invalid("company external ID")
|
|
71
|
+
return company
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _Sessions:
|
|
75
|
+
def __init__(self, transport: Transport) -> None:
|
|
76
|
+
self._transport = transport
|
|
77
|
+
|
|
78
|
+
def create(self, *, company_id: str, provider: Provider, allow_native_queries: bool = False) -> CreatedConnectSession:
|
|
79
|
+
if provider not in ("quickbooksDesktop", "netsuite"):
|
|
80
|
+
raise RowbindError("invalid_input", "Choose quickbooksDesktop or netsuite.")
|
|
81
|
+
if not isinstance(allow_native_queries, bool):
|
|
82
|
+
raise RowbindError("invalid_input", "allow_native_queries must be a boolean.")
|
|
83
|
+
body: dict[str, object] = {"companyId": _required(company_id, "company ID"), "provider": provider}
|
|
84
|
+
if allow_native_queries:
|
|
85
|
+
body["allowNativeQueries"] = True
|
|
86
|
+
data = _object(self._transport.request("createConnectSession", body=body))
|
|
87
|
+
session = _session(data)
|
|
88
|
+
if session.company_id != company_id or session.provider != provider or session.status != "pending":
|
|
89
|
+
raise _invalid("new Connect session")
|
|
90
|
+
return CreatedConnectSession(session.id, company_id, provider, session.expires_at,
|
|
91
|
+
"pending", session.connection_id, _string(data, "url"))
|
|
92
|
+
|
|
93
|
+
def retrieve(self, session_id: str) -> ConnectSession:
|
|
94
|
+
key = _required(session_id, "session ID")
|
|
95
|
+
session = _session(self._transport.request("retrieveConnectSession", path={"id": key}))
|
|
96
|
+
if session.id != key:
|
|
97
|
+
raise _invalid("session ID")
|
|
98
|
+
return session
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _Connect:
|
|
102
|
+
def __init__(self, transport: Transport) -> None:
|
|
103
|
+
self.sessions = _Sessions(transport)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class _Platform:
|
|
107
|
+
def __init__(self, transport: Transport) -> None:
|
|
108
|
+
self.companies = _Companies(transport)
|
|
109
|
+
self.connect = _Connect(transport)
|
|
110
|
+
self.connections = _Connections(transport)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _Invoices:
|
|
114
|
+
def __init__(self, transport: Transport) -> None:
|
|
115
|
+
self._transport = transport
|
|
116
|
+
|
|
117
|
+
def list(self, connection_id: str, *, after: Optional[str] = None, limit: Optional[int] = None) -> SyncedInvoicePage:
|
|
118
|
+
"""Read one page. Save its next_cursor to continue the same snapshot."""
|
|
119
|
+
query: dict[str, object] = {}
|
|
120
|
+
if after is not None:
|
|
121
|
+
query["after"] = _required(after, "invoice cursor")
|
|
122
|
+
if limit is not None:
|
|
123
|
+
if type(limit) is not int or not 1 <= limit <= 100:
|
|
124
|
+
raise RowbindError("invalid_input", "limit must be an integer from 1 to 100.")
|
|
125
|
+
query["limit"] = limit
|
|
126
|
+
value = self._transport.request("listSyncedInvoices", path={"id": connection_id}, query=query)
|
|
127
|
+
page = invoice_page(value, connection_id)
|
|
128
|
+
if len(page.invoices) > (limit or 20) or (after is not None and page.next_cursor == after):
|
|
129
|
+
raise _invalid("invoice page length or continuation")
|
|
130
|
+
return page
|
|
131
|
+
|
|
132
|
+
def iter_pages(self, connection_id: str, *, after: Optional[str] = None, limit: Optional[int] = None) -> Iterator[SyncedInvoicePage]:
|
|
133
|
+
"""Fetch the next page only when the caller advances this iterator."""
|
|
134
|
+
seen = {after} if after is not None else set()
|
|
135
|
+
snapshot = None
|
|
136
|
+
while True:
|
|
137
|
+
page = self.list(connection_id, after=after, limit=limit)
|
|
138
|
+
cutoff = (page.snapshot_revision, page.covered_through)
|
|
139
|
+
if snapshot is not None and cutoff != snapshot:
|
|
140
|
+
raise _invalid("changed invoice snapshot")
|
|
141
|
+
snapshot = cutoff
|
|
142
|
+
if page.next_cursor is not None and page.next_cursor in seen:
|
|
143
|
+
raise _invalid("repeated invoice cursor")
|
|
144
|
+
yield page
|
|
145
|
+
if page.next_cursor is None:
|
|
146
|
+
return
|
|
147
|
+
after = page.next_cursor
|
|
148
|
+
seen.add(after)
|
|
149
|
+
|
|
150
|
+
@overload
|
|
151
|
+
def create(self, target: Connection, *, external_reference: str, customer_external_id: str,
|
|
152
|
+
lines: Sequence[InvoiceLine], idempotency_key: str, currency: Literal["USD"] = "USD") -> OperationReceipt: ...
|
|
153
|
+
|
|
154
|
+
@overload
|
|
155
|
+
def create(self, target: NetSuiteConnection, *, external_reference: str, customer_external_id: str,
|
|
156
|
+
lines: Sequence[InvoiceLine], idempotency_key: str, department_id: str,
|
|
157
|
+
currency: Literal["USD"] = "USD") -> OperationReceipt: ...
|
|
158
|
+
|
|
159
|
+
def create(self, target: Connection, *, external_reference: str, customer_external_id: str,
|
|
160
|
+
lines: Sequence[InvoiceLine], idempotency_key: str, department_id: Optional[str] = None,
|
|
161
|
+
currency: Literal["USD"] = "USD") -> OperationReceipt:
|
|
162
|
+
return self._submit(target, external_reference, customer_external_id, lines, idempotency_key, department_id, currency)
|
|
163
|
+
|
|
164
|
+
def _submit(self, target: Connection, reference: str, customer: str, lines: Sequence[InvoiceLine],
|
|
165
|
+
key: str, department_id: Optional[str], currency: Literal["USD"]) -> OperationReceipt:
|
|
166
|
+
if not isinstance(target, (QuickBooksConnection, NetSuiteConnection)):
|
|
167
|
+
raise RowbindError("invalid_input", "Use the connection returned for the intended book.")
|
|
168
|
+
if department_id is not None and not isinstance(target, NetSuiteConnection):
|
|
169
|
+
raise RowbindError("provider_mismatch", "department_id requires a NetSuite connection.")
|
|
170
|
+
if currency != "USD" or not isinstance(lines, Sequence) or not lines:
|
|
171
|
+
raise RowbindError("invalid_input", "Provide invoice lines and sandbox currency USD.")
|
|
172
|
+
wire_lines = []
|
|
173
|
+
for line in lines:
|
|
174
|
+
if (not isinstance(line, InvoiceLine) or type(line.quantity) is not int or not 1 <= line.quantity <= 9007199254740991
|
|
175
|
+
or not isinstance(line.unit_price, str) or not re.fullmatch(r"[0-9]+\.[0-9]{2}", line.unit_price)):
|
|
176
|
+
raise RowbindError("invalid_input", "Use InvoiceLine with a positive whole quantity and a two-decimal unit price.")
|
|
177
|
+
wire_lines.append({"itemRef": {"externalId": _required(line.item_external_id, "item reference")},
|
|
178
|
+
"quantity": line.quantity, "unitPrice": line.unit_price})
|
|
179
|
+
body: dict[str, object] = {
|
|
180
|
+
"connectionId": _required(target.id, "connection ID"), "externalReference": _required(reference, "invoice reference"),
|
|
181
|
+
"customerRef": {"externalId": _required(customer, "customer reference")}, "currency": currency, "lines": wire_lines,
|
|
182
|
+
}
|
|
183
|
+
if isinstance(target, NetSuiteConnection):
|
|
184
|
+
native = {"subsidiaryId": _required(target.subsidiary_id, "NetSuite subsidiary")}
|
|
185
|
+
if department_id is not None:
|
|
186
|
+
if not isinstance(department_id, str) or not re.fullmatch(r"[1-9][0-9]*", department_id):
|
|
187
|
+
raise RowbindError("invalid_input", "department_id must be a positive NetSuite internal ID.")
|
|
188
|
+
native["departmentId"] = department_id
|
|
189
|
+
body["providerOptions"] = {"netsuite": native}
|
|
190
|
+
return _receipt(self._transport.request("createInvoice", body=body, idempotency_key=_required(key, "idempotency key")))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class _InvoiceWait:
|
|
194
|
+
def __init__(self, operation_id: str, timeout: float) -> None:
|
|
195
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (float, int)) or not math.isfinite(timeout) or timeout <= 0:
|
|
196
|
+
raise RowbindError("invalid_input", "timeout must be a positive number of seconds.")
|
|
197
|
+
self.id = _required(operation_id, "operation ID")
|
|
198
|
+
self.deadline = time.monotonic() + timeout
|
|
199
|
+
self.detail = "The invoice has not been verified yet."
|
|
200
|
+
self.diagnosis: Optional[RecoveryEntry] = None
|
|
201
|
+
|
|
202
|
+
def remaining(self) -> float:
|
|
203
|
+
remaining = self.deadline - time.monotonic()
|
|
204
|
+
if remaining <= 0:
|
|
205
|
+
raise self.timeout_error()
|
|
206
|
+
return remaining
|
|
207
|
+
|
|
208
|
+
def timeout_error(self) -> OperationWaitError:
|
|
209
|
+
return OperationWaitError("verification_pending", f"{self.detail} Resume with operation {self.id}.",
|
|
210
|
+
self.id, self.diagnosis)
|
|
211
|
+
|
|
212
|
+
def read(self, transport: Transport) -> Operation:
|
|
213
|
+
try:
|
|
214
|
+
value = transport.request("retrieveOperation", path={"id": self.id}, timeout=self.remaining())
|
|
215
|
+
except RowbindError as error:
|
|
216
|
+
if error.code not in ("transport_unavailable", "core_storage_unavailable") and error.status not in RETRYABLE_STATUSES:
|
|
217
|
+
raise
|
|
218
|
+
raise OperationWaitError(error.code, f"{error} Resume with operation {self.id}.", self.id, self.diagnosis,
|
|
219
|
+
request_id=error.request_id, status=error.status) from error
|
|
220
|
+
return _operation(value, self.id)
|
|
221
|
+
|
|
222
|
+
def record_if_verified(self, operation: Operation) -> Optional[InvoiceRecord]:
|
|
223
|
+
self.remaining()
|
|
224
|
+
if isinstance(operation, VerifiedOperation):
|
|
225
|
+
return operation.record
|
|
226
|
+
if isinstance(operation, FailedOperation):
|
|
227
|
+
raise RowbindError(operation.code, f"{operation.message} (operation {self.id})")
|
|
228
|
+
if operation.detail:
|
|
229
|
+
self.detail = operation.detail
|
|
230
|
+
if operation.diagnosis:
|
|
231
|
+
self.diagnosis = operation.diagnosis
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class _Operations:
|
|
236
|
+
def __init__(self, transport: Transport) -> None:
|
|
237
|
+
self._transport = transport
|
|
238
|
+
|
|
239
|
+
def retrieve(self, operation_id: str) -> Operation:
|
|
240
|
+
key = _required(operation_id, "operation ID")
|
|
241
|
+
return _operation(self._transport.request("retrieveOperation", path={"id": key}), key)
|
|
242
|
+
|
|
243
|
+
def recovery(self, operation_id: str, *, after: Optional[int] = None) -> RecoveryPage:
|
|
244
|
+
key = _required(operation_id, "operation ID")
|
|
245
|
+
if after is not None and (type(after) is not int or not 1 <= after <= 9007199254740991):
|
|
246
|
+
raise RowbindError("invalid_input", "after must be a positive recovery sequence.")
|
|
247
|
+
value = self._transport.request("retrieveInvoiceRecovery", path={"id": key},
|
|
248
|
+
query=None if after is None else {"after": after})
|
|
249
|
+
return _recovery_page(value, key, after)
|
|
250
|
+
|
|
251
|
+
def wait_for_verified_record(self, operation_id: str, *, timeout: float = 60.0) -> InvoiceRecord:
|
|
252
|
+
wait = _InvoiceWait(operation_id, timeout)
|
|
253
|
+
while True:
|
|
254
|
+
record = wait.record_if_verified(wait.read(self._transport))
|
|
255
|
+
if record is not None:
|
|
256
|
+
return record
|
|
257
|
+
time.sleep(min(0.5, wait.remaining()))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class Rowbind(_RawProviders):
|
|
261
|
+
def __init__(self, *, base_url: Optional[str] = None, api_key: Optional[str] = None) -> None:
|
|
262
|
+
self._transport = Transport(base_url, api_key)
|
|
263
|
+
self.platform = _Platform(self._transport)
|
|
264
|
+
self.companies = self.platform.companies
|
|
265
|
+
self.connect = self.platform.connect
|
|
266
|
+
self.connections = self.platform.connections
|
|
267
|
+
super().__init__(self._transport)
|
|
268
|
+
self.invoices = _Invoices(self._transport)
|
|
269
|
+
self.catalog = Catalog(self._transport)
|
|
270
|
+
self.sync = Sync(self._transport)
|
|
271
|
+
self.operations = _Operations(self._transport)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class _AsyncConnections:
|
|
275
|
+
def __init__(self, sync: _Connections) -> None:
|
|
276
|
+
self._sync = sync
|
|
277
|
+
|
|
278
|
+
async def list(self) -> list[Connection]:
|
|
279
|
+
return await asyncio.to_thread(self._sync.list)
|
|
280
|
+
|
|
281
|
+
async def retrieve(self, connection_id: str) -> Connection:
|
|
282
|
+
return await asyncio.to_thread(self._sync.retrieve, connection_id)
|
|
283
|
+
|
|
284
|
+
async def health(self, connection_id: str) -> ConnectionHealth:
|
|
285
|
+
return await asyncio.to_thread(self._sync.health, connection_id)
|
|
286
|
+
|
|
287
|
+
async def check_health(self, connection_id: str) -> ConnectionHealth:
|
|
288
|
+
return await asyncio.to_thread(self._sync.check_health, connection_id)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class _AsyncCompanies:
|
|
292
|
+
def __init__(self, sync: _Companies) -> None:
|
|
293
|
+
self._sync = sync
|
|
294
|
+
|
|
295
|
+
async def create(self, *, external_id: str, name: str) -> Company:
|
|
296
|
+
return await asyncio.to_thread(self._sync.create, external_id=external_id, name=name)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class _AsyncSessions:
|
|
300
|
+
def __init__(self, sync: _Sessions) -> None:
|
|
301
|
+
self._sync = sync
|
|
302
|
+
|
|
303
|
+
async def create(self, *, company_id: str, provider: Provider, allow_native_queries: bool = False) -> CreatedConnectSession:
|
|
304
|
+
return await asyncio.to_thread(self._sync.create, company_id=company_id, provider=provider, allow_native_queries=allow_native_queries)
|
|
305
|
+
|
|
306
|
+
async def retrieve(self, session_id: str) -> ConnectSession:
|
|
307
|
+
return await asyncio.to_thread(self._sync.retrieve, session_id)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class _AsyncConnect:
|
|
311
|
+
def __init__(self, sync: _Connect) -> None:
|
|
312
|
+
self.sessions = _AsyncSessions(sync.sessions)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class _AsyncPlatform:
|
|
316
|
+
def __init__(self, sync: _Platform) -> None:
|
|
317
|
+
self.companies = _AsyncCompanies(sync.companies)
|
|
318
|
+
self.connect = _AsyncConnect(sync.connect)
|
|
319
|
+
self.connections = _AsyncConnections(sync.connections)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class _AsyncInvoices:
|
|
323
|
+
def __init__(self, sync: _Invoices) -> None:
|
|
324
|
+
self._sync = sync
|
|
325
|
+
|
|
326
|
+
async def list(self, connection_id: str, *, after: Optional[str] = None, limit: Optional[int] = None) -> SyncedInvoicePage:
|
|
327
|
+
return await asyncio.to_thread(self._sync.list, connection_id, after=after, limit=limit)
|
|
328
|
+
|
|
329
|
+
async def iter_pages(self, connection_id: str, *, after: Optional[str] = None, limit: Optional[int] = None) -> AsyncIterator[SyncedInvoicePage]:
|
|
330
|
+
pages = self._sync.iter_pages(connection_id, after=after, limit=limit)
|
|
331
|
+
while True:
|
|
332
|
+
page = await asyncio.to_thread(next, pages, None)
|
|
333
|
+
if page is None:
|
|
334
|
+
return
|
|
335
|
+
yield page
|
|
336
|
+
|
|
337
|
+
@overload
|
|
338
|
+
async def create(self, target: Connection, *, external_reference: str, customer_external_id: str,
|
|
339
|
+
lines: Sequence[InvoiceLine], idempotency_key: str, currency: Literal["USD"] = "USD") -> OperationReceipt: ...
|
|
340
|
+
|
|
341
|
+
@overload
|
|
342
|
+
async def create(self, target: NetSuiteConnection, *, external_reference: str, customer_external_id: str,
|
|
343
|
+
lines: Sequence[InvoiceLine], idempotency_key: str, department_id: str,
|
|
344
|
+
currency: Literal["USD"] = "USD") -> OperationReceipt: ...
|
|
345
|
+
|
|
346
|
+
async def create(self, target: Connection, *, external_reference: str, customer_external_id: str,
|
|
347
|
+
lines: Sequence[InvoiceLine], idempotency_key: str, department_id: Optional[str] = None,
|
|
348
|
+
currency: Literal["USD"] = "USD") -> OperationReceipt:
|
|
349
|
+
return await asyncio.to_thread(self._sync._submit, target, external_reference, customer_external_id,
|
|
350
|
+
lines, idempotency_key, department_id, currency)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class _AsyncOperations:
|
|
354
|
+
def __init__(self, sync: _Operations) -> None:
|
|
355
|
+
self._sync = sync
|
|
356
|
+
|
|
357
|
+
async def retrieve(self, operation_id: str) -> Operation:
|
|
358
|
+
return await asyncio.to_thread(self._sync.retrieve, operation_id)
|
|
359
|
+
|
|
360
|
+
async def recovery(self, operation_id: str, *, after: Optional[int] = None) -> RecoveryPage:
|
|
361
|
+
return await asyncio.to_thread(self._sync.recovery, operation_id, after=after)
|
|
362
|
+
|
|
363
|
+
async def wait_for_verified_record(self, operation_id: str, *, timeout: float = 60.0) -> InvoiceRecord:
|
|
364
|
+
wait = _InvoiceWait(operation_id, timeout)
|
|
365
|
+
while True:
|
|
366
|
+
remaining = wait.remaining()
|
|
367
|
+
try:
|
|
368
|
+
operation = await asyncio.wait_for(asyncio.to_thread(wait.read, self._sync._transport), remaining)
|
|
369
|
+
except asyncio.TimeoutError:
|
|
370
|
+
raise wait.timeout_error() from None
|
|
371
|
+
record = wait.record_if_verified(operation)
|
|
372
|
+
if record is not None:
|
|
373
|
+
return record
|
|
374
|
+
await asyncio.sleep(min(0.5, wait.remaining()))
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class AsyncRowbind(_AsyncRawProviders):
|
|
378
|
+
def __init__(self, *, base_url: Optional[str] = None, api_key: Optional[str] = None) -> None:
|
|
379
|
+
sync = Rowbind(base_url=base_url, api_key=api_key)
|
|
380
|
+
self.platform = _AsyncPlatform(sync.platform)
|
|
381
|
+
self.companies = self.platform.companies
|
|
382
|
+
self.connect = self.platform.connect
|
|
383
|
+
self.connections = self.platform.connections
|
|
384
|
+
super().__init__(sync)
|
|
385
|
+
self.invoices = _AsyncInvoices(sync.invoices)
|
|
386
|
+
self.catalog = AsyncCatalog(sync.catalog)
|
|
387
|
+
self.sync = AsyncSync(sync.sync)
|
|
388
|
+
self.operations = _AsyncOperations(sync.operations)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Runnable examples for an authorized sandbox book."""
|