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.
@@ -0,0 +1,42 @@
1
+ """Find and link records once, then invoice using the SaaS references."""
2
+ import argparse
3
+ from dataclasses import asdict
4
+ import json
5
+
6
+ from rowbind import InvoiceLine, Rowbind
7
+
8
+
9
+ def main() -> None:
10
+ parser = argparse.ArgumentParser(description=__doc__)
11
+ actions = parser.add_subparsers(dest="action", required=True)
12
+ search = actions.add_parser("search")
13
+ link = actions.add_parser("link")
14
+ for command in (search, link):
15
+ command.add_argument("connection_id")
16
+ command.add_argument("kind", choices=("customer", "item"))
17
+ search.add_argument("query")
18
+ search.add_argument("after", nargs="?")
19
+ link.add_argument("external_id")
20
+ link.add_argument("native_id")
21
+ invoice = actions.add_parser("invoice")
22
+ for name in ("connection_id", "sale_reference", "customer_reference", "sku"):
23
+ invoice.add_argument(name)
24
+ args = parser.parse_args()
25
+ rb = Rowbind()
26
+
27
+ if args.action == "search":
28
+ page = rb.catalog.search(args.connection_id, kind=args.kind, query=args.query, after=args.after)
29
+ print(json.dumps(asdict(page, dict_factory=lambda fields: {k: v for k, v in fields if k != "sku" or v is not None})))
30
+ elif args.action == "link":
31
+ result = rb.catalog.link(args.connection_id, kind=args.kind, external_id=args.external_id, native_id=args.native_id)
32
+ print(json.dumps(asdict(result)))
33
+ else:
34
+ book = rb.connections.retrieve(args.connection_id)
35
+ op = rb.invoices.create(book, external_reference=args.sale_reference, customer_external_id=args.customer_reference,
36
+ lines=[InvoiceLine(args.sku, 2, "60.00")], idempotency_key="sale/" + args.sale_reference)
37
+ record = rb.operations.wait_for_verified_record(op.id)
38
+ print(json.dumps({"operation_id": op.id, "invoice": asdict(record)}))
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
@@ -0,0 +1,28 @@
1
+ """Submit the same two-line sale to the selected sandbox connection."""
2
+ import argparse
3
+ import json
4
+
5
+ from rowbind import InvoiceLine, Rowbind
6
+
7
+ LINES = (InvoiceLine("mano-de-obra", 1, "80.00"), InvoiceLine("material", 1, "40.00"))
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser(description=__doc__)
12
+ parser.add_argument("connection_id")
13
+ parser.add_argument("reference")
14
+ args = parser.parse_args()
15
+ client = Rowbind()
16
+ book = client.connections.retrieve(args.connection_id)
17
+ submitted = client.invoices.create(
18
+ book, external_reference=args.reference, customer_external_id="tienda-norte",
19
+ lines=LINES, idempotency_key="example-" + args.reference,
20
+ )
21
+ print(json.dumps({"operationId": submitted.id}), flush=True)
22
+ record = client.operations.wait_for_verified_record(submitted.id)
23
+ print(json.dumps({"invoiceId": record.id, "total": record.total,
24
+ "balanceDue": record.balance_due, "currency": record.currency}))
25
+
26
+
27
+ if __name__ == "__main__":
28
+ main()
@@ -0,0 +1,21 @@
1
+ """Print one JSON object per page of an authorized book's invoice snapshot."""
2
+ import argparse
3
+ from dataclasses import asdict
4
+ import json
5
+
6
+ from rowbind import Rowbind
7
+
8
+
9
+ def main() -> None:
10
+ parser = argparse.ArgumentParser(description=__doc__)
11
+ parser.add_argument("connection_id")
12
+ parser.add_argument("--after", help="Resume with the next_cursor from the last committed page.")
13
+ parser.add_argument("--limit", type=int, help="Invoices per page.")
14
+ args = parser.parse_args()
15
+ pages = Rowbind().invoices.iter_pages(args.connection_id, after=args.after, limit=args.limit)
16
+ for page in pages:
17
+ print(json.dumps(asdict(page)), flush=True)
18
+
19
+
20
+ if __name__ == "__main__":
21
+ main()
rowbind/models.py ADDED
@@ -0,0 +1,316 @@
1
+ """Values returned by the sandbox invoice API."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import re
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+ from typing import ClassVar, Literal, NewType, Optional, Union, cast
9
+
10
+ from ._transport import RowbindError
11
+
12
+ Provider = Literal["quickbooksDesktop", "netsuite"]
13
+ InvoiceOperationId = NewType("InvoiceOperationId", str)
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class QuickBooksConnection:
18
+ id: str
19
+ provider: ClassVar[Literal["quickbooksDesktop"]] = "quickbooksDesktop"
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class NetSuiteConnection:
24
+ id: str
25
+ subsidiary_id: str
26
+ provider: ClassVar[Literal["netsuite"]] = "netsuite"
27
+
28
+
29
+ Connection = Union[QuickBooksConnection, NetSuiteConnection]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ConnectionHealth:
34
+ connection_id: str
35
+ provider: Provider
36
+ status: str
37
+ capability: str
38
+ authorization: str
39
+ authorized_at: Optional[str]
40
+ checked_at: Optional[str]
41
+ last_verified_at: Optional[str]
42
+ next_action: str
43
+ divergence: Optional[dict[str, object]]
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Company:
48
+ id: str
49
+ external_id: str
50
+ name: str
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class ConnectSession:
55
+ id: str
56
+ company_id: str
57
+ provider: Provider
58
+ expires_at: str
59
+ status: Literal["pending", "connected", "expired"]
60
+ connection_id: Optional[str]
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class CreatedConnectSession(ConnectSession):
65
+ url: str
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class InvoiceLine:
70
+ item_external_id: str
71
+ quantity: int
72
+ unit_price: str
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class InvoiceLineRecord:
77
+ item_id: str
78
+ quantity: Union[int, float]
79
+ unit_price: str
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class InvoiceRecord:
84
+ id: str
85
+ connection_id: str
86
+ customer_id: str
87
+ external_reference: str
88
+ currency: Literal["USD"]
89
+ lines: tuple[InvoiceLineRecord, ...]
90
+ total: str
91
+ balance_due: str
92
+ subsidiary_id: Optional[str]
93
+ department_id: Optional[str]
94
+ kind: ClassVar[Literal["invoice"]] = "invoice"
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class OperationReceipt:
99
+ id: InvoiceOperationId
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class RecoveryEntry:
104
+ sequence: int
105
+ code: str
106
+ phase: str
107
+ certainty: str
108
+ owner: str
109
+ next_action: str
110
+ occurred_at: str
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class RecoveryPage:
115
+ operation_id: str
116
+ entries: tuple[RecoveryEntry, ...]
117
+ next_cursor: Optional[int]
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class PendingOperation:
122
+ id: str
123
+ detail: Optional[str]
124
+ diagnosis: Optional[RecoveryEntry]
125
+ status: ClassVar[Literal["pending"]] = "pending"
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class VerifiedOperation:
130
+ id: str
131
+ record: InvoiceRecord
132
+ status: ClassVar[Literal["verified"]] = "verified"
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class FailedOperation:
137
+ id: str
138
+ status: Literal["rejected", "verification_mismatch"]
139
+ code: str
140
+ message: str
141
+
142
+
143
+ Operation = Union[PendingOperation, VerifiedOperation, FailedOperation]
144
+
145
+
146
+ def _invalid(field: str) -> RowbindError:
147
+ return RowbindError("invalid_response", f"Rowbind returned an invalid {field}.")
148
+
149
+
150
+ def _object(value: object) -> dict[str, object]:
151
+ if not isinstance(value, dict):
152
+ raise _invalid("response object")
153
+ return value
154
+
155
+
156
+ def _array(value: object) -> list[object]:
157
+ if not isinstance(value, list):
158
+ raise _invalid("response array")
159
+ return value
160
+
161
+
162
+ def _string(data: dict[str, object], key: str) -> str:
163
+ value = data.get(key)
164
+ if not isinstance(value, str) or not value:
165
+ raise _invalid(key)
166
+ return value
167
+
168
+
169
+ def _optional_string(data: dict[str, object], key: str) -> Optional[str]:
170
+ return _string(data, key) if key in data else None
171
+
172
+
173
+ def _sequence(value: object) -> int:
174
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 9007199254740991:
175
+ raise _invalid("sequence")
176
+ return value
177
+
178
+
179
+ def _date_time(data: dict[str, object], key: str) -> str:
180
+ value = _string(data, key)
181
+ try:
182
+ observed = datetime.fromisoformat(value.removesuffix("Z") + ("+00:00" if value.endswith("Z") else ""))
183
+ if observed.tzinfo is None:
184
+ raise ValueError()
185
+ except ValueError:
186
+ raise _invalid(key) from None
187
+ return value
188
+
189
+
190
+ def _provider(data: dict[str, object]) -> Provider:
191
+ provider = data.get("provider")
192
+ if provider == "quickbooksDesktop":
193
+ return "quickbooksDesktop"
194
+ if provider == "netsuite":
195
+ return "netsuite"
196
+ raise _invalid("provider")
197
+
198
+
199
+ def _connection(value: object) -> Connection:
200
+ data = _object(value)
201
+ if _provider(data) == "quickbooksDesktop":
202
+ return QuickBooksConnection(_string(data, "id"))
203
+ return NetSuiteConnection(_string(data, "id"), _string(data, "subsidiaryId"))
204
+
205
+
206
+ def _health(value: object, connection_id: str) -> ConnectionHealth:
207
+ data = _object(value)
208
+ if data.get("connectionId") != connection_id:
209
+ raise _invalid("health connection ID")
210
+
211
+ def timestamp(key: str) -> Optional[str]:
212
+ if key not in data:
213
+ raise _invalid(key)
214
+ return None if data[key] is None else _date_time(data, key)
215
+
216
+ return ConnectionHealth(connection_id, _provider(data), _string(data, "status"), _string(data, "capability"),
217
+ _string(data, "authorization"), timestamp("authorizedAt"), timestamp("checkedAt"),
218
+ timestamp("lastVerifiedAt"), _string(data, "nextAction"),
219
+ _object(data["divergence"]) if "divergence" in data else None)
220
+
221
+
222
+ def _company(value: object) -> Company:
223
+ data = _object(value)
224
+ return Company(_string(data, "id"), _string(data, "externalId"), _string(data, "name"))
225
+
226
+
227
+ def _session(value: object) -> ConnectSession:
228
+ data = _object(value)
229
+ status = data.get("status")
230
+ if status != "connected" and status != "pending" and status != "expired":
231
+ raise _invalid("Connect session status")
232
+ connection_id = _string(data, "connectionId") if status == "connected" else _optional_string(data, "connectionId")
233
+ return ConnectSession(_string(data, "id"), _string(data, "companyId"), _provider(data),
234
+ _date_time(data, "expiresAt"), cast(Literal["connected", "pending", "expired"], status), connection_id)
235
+
236
+
237
+ def _receipt(value: object) -> OperationReceipt:
238
+ return OperationReceipt(InvoiceOperationId(_string(_object(value), "id")))
239
+
240
+
241
+ def _recovery_entry(value: object) -> RecoveryEntry:
242
+ data = _object(value)
243
+ return RecoveryEntry(_sequence(data.get("sequence")), _string(data, "code"), _string(data, "phase"),
244
+ _string(data, "certainty"), _string(data, "owner"), _string(data, "nextAction"),
245
+ _date_time(data, "occurredAt"))
246
+
247
+
248
+ def _recovery_page(value: object, operation_id: str, after: Optional[int]) -> RecoveryPage:
249
+ data = _object(value)
250
+ if data.get("operationId") != operation_id:
251
+ raise _invalid("recovery operation ID")
252
+ rows = _array(data.get("entries"))
253
+ if len(rows) > 50:
254
+ raise _invalid("recovery page size")
255
+ entries = tuple(_recovery_entry(entry) for entry in rows)
256
+ previous = after or 0
257
+ for entry in entries:
258
+ if entry.sequence <= previous:
259
+ raise _invalid("recovery sequence")
260
+ previous = entry.sequence
261
+ if "nextCursor" not in data:
262
+ raise _invalid("recovery cursor")
263
+ cursor = None if data["nextCursor"] is None else _sequence(data["nextCursor"])
264
+ if cursor is not None and (not entries or cursor != entries[-1].sequence):
265
+ raise _invalid("recovery cursor")
266
+ return RecoveryPage(operation_id, entries, cursor)
267
+
268
+
269
+ def _money(data: dict[str, object], key: str) -> str:
270
+ value = _string(data, key)
271
+ if not re.fullmatch(r"[0-9]+\.[0-9]{2}", value):
272
+ raise _invalid(key)
273
+ return value
274
+
275
+
276
+ def _invoice_record(value: object) -> InvoiceRecord:
277
+ data = _object(value)
278
+ if data.get("kind") in ("received_payment", "credit_memo", "credit_application"):
279
+ raise RowbindError("unsupported_record", "This SDK invoice flow requires an invoice operation ID.")
280
+ if data.get("kind") != "invoice":
281
+ raise _invalid("record kind")
282
+ if data.get("currency") != "USD":
283
+ raise _invalid("invoice currency")
284
+ lines: list[InvoiceLineRecord] = []
285
+ for line in _array(data.get("lines")):
286
+ item = _object(line)
287
+ quantity = item.get("quantity")
288
+ if (isinstance(quantity, bool) or not isinstance(quantity, (float, int)) or quantity <= 0
289
+ or (isinstance(quantity, float) and not math.isfinite(quantity))):
290
+ raise _invalid("invoice quantity")
291
+ lines.append(InvoiceLineRecord(_string(item, "itemId"), quantity, _money(item, "unitPrice")))
292
+ if not lines:
293
+ raise _invalid("invoice lines")
294
+ return InvoiceRecord(_string(data, "id"), _string(data, "connectionId"), _string(data, "customerId"),
295
+ _string(data, "externalReference"), "USD", tuple(lines), _money(data, "total"),
296
+ _money(data, "balanceDue"), _optional_string(data, "subsidiaryId"),
297
+ _optional_string(data, "departmentId"))
298
+
299
+
300
+ def _operation(value: object, operation_id: str) -> Operation:
301
+ data = _object(value)
302
+ if data.get("id") != operation_id:
303
+ raise _invalid("operation ID")
304
+ status = data.get("status")
305
+ if status == "pending":
306
+ diagnosis = _recovery_entry(data["diagnosis"]) if "diagnosis" in data else None
307
+ detail = data.get("detail")
308
+ if detail is not None and not isinstance(detail, str):
309
+ raise _invalid("operation detail")
310
+ return PendingOperation(operation_id, detail, diagnosis)
311
+ if status == "verified":
312
+ return VerifiedOperation(operation_id, _invoice_record(data.get("record")))
313
+ if status == "rejected" or status == "verification_mismatch":
314
+ return FailedOperation(operation_id, cast(Literal["rejected", "verification_mismatch"], status),
315
+ _string(data, "code"), _string(data, "message"))
316
+ raise _invalid("operation status")
rowbind/py.typed ADDED
File without changes
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: rowbind
3
+ Version: 0.1.0a1
4
+ Summary: Type-safe Python client for the Rowbind sandbox invoice API
5
+ Requires-Python: >=3.9
@@ -0,0 +1,19 @@
1
+ rowbind/__init__.py,sha256=xFta3ZbLvIMFxbJefGpRcaXfyaSUPjpghcUs0RBuUSc,1503
2
+ rowbind/_catalog.py,sha256=7d1zvyZxqZfllHzED2OVs_qySvxj-o1KiCUF2Ql45dI,2804
3
+ rowbind/_generated_catalog.py,sha256=vSc82yVsW7UAZMgX1ydSRnlomyvpuCtrqupEv0qUMqo,1578
4
+ rowbind/_generated_raw.py,sha256=eRmk1LhYcasNB_hpi21Auc_-zDMAx5eHzLyEJaZBmDc,2529
5
+ rowbind/_invoice_sync.py,sha256=bYg6Ia3WXbjbIg51L3kSZU0XWKevR2yS2wKxeFtKTps,6608
6
+ rowbind/_raw.py,sha256=dBaIP4K9QDjqZ7DboOa89VyysLtITpFiUjw6vaTh0qw,5274
7
+ rowbind/_transport.py,sha256=-MWJuVt3dVePh5mcqDG8VKiekyGQocmb4T1EnBoSoRY,11379
8
+ rowbind/_wire.py,sha256=rM0pZESLdEKI-2WGl2JW99HTLulDpBTPG6CsxSBY3Mk,1603
9
+ rowbind/client.py,sha256=GR6YyHCvWLcNmEVEb1AGUV4RWRKAM_9_soU6FwLUEFY,19177
10
+ rowbind/models.py,sha256=Z_dkb1Eek1ZAet7310L_KAtdPIh7pPZNkw5qZgFJhEA,10068
11
+ rowbind/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ rowbind/examples/__init__.py,sha256=_fSAyn9ZVf38qiYGYVt2np-Z9KTgWJzAv8v05jqu1-U,56
13
+ rowbind/examples/catalog_invoice.py,sha256=4N7DdyJ1jTAX0cLvhtNG-Z8zdDU0TtRSpQf7pzM4gMQ,1868
14
+ rowbind/examples/first_invoice.py,sha256=OCKZd8vaOs0eiQ8Vw29WEHIRMnVxH9Ad_f7sVcy_Umo,1030
15
+ rowbind/examples/invoice_pages.py,sha256=_tDweBMhJi9hzBlo7cRtFWhvsESypPWx72BGPwrYLJo,705
16
+ rowbind-0.1.0a1.dist-info/METADATA,sha256=JsD0Q2QDmcW3PfEMF8uFSvczpdazHSYPEK09AweQJLo,145
17
+ rowbind-0.1.0a1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
18
+ rowbind-0.1.0a1.dist-info/top_level.txt,sha256=sGX4QzxJA8wSsUkEa4Vbvis_1Jg_oRfI10RKjt3VYf8,8
19
+ rowbind-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ rowbind