perfectpanel-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 w3radar
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,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: perfectpanel-client
3
+ Version: 0.1.0
4
+ Summary: Typed, dependency-light Python client for the Perfect Panel v2 SMM API
5
+ Author: w3radar
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/w3radar/perfectpanel-client
8
+ Project-URL: Documentation, https://github.com/w3radar/perfectpanel-client#readme
9
+ Project-URL: Panel API docs, https://talonpanel.com/api-docs
10
+ Project-URL: Issues, https://github.com/w3radar/perfectpanel-client/issues
11
+ Keywords: smm,api-client,perfect-panel,panel,httpx
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: httpx>=0.24
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7; extra == "dev"
25
+ Requires-Dist: pytest-cov>=4; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # perfectpanel-client
29
+
30
+ Typed, dependency-light Python client for the **Perfect Panel v2** SMM API — the
31
+ same `POST /api/v2` + `action=` shape that most SMM panels speak.
32
+
33
+ [![tests](https://github.com/w3radar/perfectpanel-client/actions/workflows/tests.yml/badge.svg)](https://github.com/w3radar/perfectpanel-client/actions/workflows/tests.yml)
34
+ [![python](https://img.shields.io/badge/python-3.9%2B-blue)](https://github.com/w3radar/perfectpanel-client)
35
+ [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
36
+
37
+ - Seven methods, typed results, one exception base class.
38
+ - Money is **never a float**: exact integer micro-units, like the panel's own
39
+ `cheapest_micro`.
40
+ - Retries with exponential backoff and `Retry-After` support.
41
+ - The API key is never logged and is redacted from `repr()`.
42
+ - 150+ tests, 100% line and branch coverage, no network in CI.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install "git+https://github.com/w3radar/perfectpanel-client.git"
48
+ # or, during development:
49
+ pip install -e ".[dev]"
50
+ ```
51
+
52
+ Requires Python 3.9+. The only runtime dependency is `httpx`.
53
+
54
+ ## 60-second quickstart
55
+
56
+ Every panel publishes a sandbox key so you can integrate before spending
57
+ anything. It reads the real catalogue and writes nothing:
58
+
59
+ ```python
60
+ from perfectpanel import PerfectPanelClient
61
+
62
+ with PerfectPanelClient("sandbox") as panel:
63
+ for service in panel.services()[:3]:
64
+ print(service.service, service.name, service.rate, service.min, service.max)
65
+
66
+ order = panel.add(service_id, "https://instagram.com/p/example", 1000)
67
+ print(order.order, order.charge, order.balance) # exact Money, not floats
68
+
69
+ print(panel.status(order.order).status) # "Pending" / "In progress" / "Completed"
70
+ ```
71
+
72
+ Swap `"sandbox"` for your live key when you are ready — or keep it out of the
73
+ code entirely:
74
+
75
+ ```bash
76
+ export PERFECTPANEL_API_KEY="…"
77
+ ```
78
+
79
+ ```python
80
+ panel = PerfectPanelClient.from_env()
81
+ ```
82
+
83
+ ### Waiting for delivery
84
+
85
+ `add` returns immediately. `wait_for` polls until the order reaches a terminal
86
+ state (`Completed`, `Partial`, `Canceled`) and returns the last status even on
87
+ timeout — an order still in progress is not an error:
88
+
89
+ ```python
90
+ final = panel.wait_for(order.order, timeout=600, poll_interval=10)
91
+ if not final.completed:
92
+ print("still running or partial:", final.status, final.remains)
93
+ ```
94
+
95
+ ### Several orders at once
96
+
97
+ ```python
98
+ for s in panel.multi_status([101, 102, 103]):
99
+ print(s.order, s.status, s.remains)
100
+ ```
101
+
102
+ The panel's batch form takes `orders=101,102,103`. Panels that only implement
103
+ single-order status are detected automatically and asked one by one, so the
104
+ same call works everywhere.
105
+
106
+ ## Endpoints
107
+
108
+ One URL, one form body, `action` selects the operation.
109
+
110
+ | Method | `action` | Parameters | Returns |
111
+ | --- | --- | --- | --- |
112
+ | `services()` | `services` | — | `tuple[Service, ...]` |
113
+ | `add(service, link, quantity, …)` | `add` | `service`, `link`, `quantity`, optional `comments`, `runs`, `interval` | `OrderPlaced(order, charge, balance)` |
114
+ | `status(order)` | `status` | `order` | `OrderStatus` |
115
+ | `multi_status([ids])` | `status` | `orders` (comma-joined) | `tuple[OrderStatus, ...]` |
116
+ | `balance()` | `balance` | — | `Balance(balance, currency)` |
117
+ | `cancel(order)` | `cancel` | `order` | `ActionAck(ok, order)` |
118
+ | `refill(order)` | `refill` | `order` | `ActionAck(ok, order)` |
119
+
120
+ Responses are parsed into frozen dataclasses. Fields a panel adds later are
121
+ kept in `.raw` instead of breaking your integration.
122
+
123
+ ## Error model
124
+
125
+ Every failure inherits from `PerfectPanelError`, so one `except` is enough:
126
+
127
+ ```python
128
+ from perfectpanel import PerfectPanelError
129
+ try:
130
+ panel.add(12, "https://instagram.com/p/x", 1000)
131
+ except PerfectPanelError as exc:
132
+ print(type(exc).__name__, getattr(exc, "error_code", None))
133
+ ```
134
+
135
+ | Exception | When |
136
+ | --- | --- |
137
+ | `InvalidAPIKeyError` | HTTP 401 / `API_KEY_INVALID` |
138
+ | `ServiceNotFoundError` | `SERVICE_NOT_FOUND` |
139
+ | `OrderRejectedError` | `ORDER_REJECTED` — bad link, quantity out of range, no balance |
140
+ | `OrderNotFoundError` | `ORDER_NOT_FOUND` |
141
+ | `CancelRejectedError` | `CANCEL_REJECTED` — too late to cancel |
142
+ | `RefillRejectedError` | `REFILL_REJECTED` |
143
+ | `UnknownActionError` | `ACTION_UNKNOWN` — panel does not implement that action |
144
+ | `TransportError` | DNS, connection or timeout, after all retries |
145
+ | `ResponseParseError` | the answer was not JSON (proxy or HTML error page) |
146
+
147
+ The important detail: **a rejected action comes back as HTTP 200** with an
148
+ `error_code`, for compatibility with older reseller panels. Catch the exception
149
+ type, not the status code. `error_code` is the stable contract; the human
150
+ `message` may be reworded by any panel.
151
+
152
+ ## Money
153
+
154
+ Panel charges arrive as decimal strings (`"0.6327"`). Summing floats over
155
+ thousands of orders drifts by fractions of a cent, so every amount is stored as
156
+ an `int` number of micro-units (`1_000_000 = 1.00 USD`, the same unit the panel's
157
+ public price API uses for `cheapest_micro`):
158
+
159
+ ```python
160
+ from perfectpanel import Money, to_micro, from_micro
161
+
162
+ Money.parse("0.6327").micro # 632700
163
+ Money.parse("0.1") + Money.parse("0.2") == Money.parse("0.3") # True, exactly
164
+ str(Money.parse("1.5")) # "1.5 USD"
165
+ to_micro("0.0000005") # 1 (half-up, never truncated)
166
+ ```
167
+
168
+ `Money + Money` refuses to mix currencies instead of adding dollars to rubles.
169
+
170
+ ## Retries
171
+
172
+ `max_retries=3` by default, on timeouts, connection errors, `429`, `500`,
173
+ `502`, `503` and `504`. Backoff is `backoff_factor * 2 ** (n - 1)` with jitter,
174
+ capped by `max_backoff`, and `Retry-After` wins when the panel sends it. Input
175
+ is validated before any request is made, so a bad `quantity` costs zero calls.
176
+
177
+ ```python
178
+ panel = PerfectPanelClient(key, timeout=20, max_retries=5, backoff_factor=0.4)
179
+ ```
180
+
181
+ ## What a panel API is, honestly
182
+
183
+ An SMM panel resells social-media services — followers, views, likes — placed
184
+ against a link or username. The v2 API is a thin order desk: list the catalogue,
185
+ place an order with your prepaid balance, poll its status, occasionally cancel
186
+ or refill. It is not a social-network API and it cannot guarantee that a
187
+ platform will keep the numbers; it can only tell you what was ordered and what
188
+ the panel says it delivered. That is exactly why this client returns the
189
+ panel's raw status strings unchanged, keeps your balance exact to the micro-unit,
190
+ and never pretends a `Partial` is a `Completed`.
191
+
192
+ ## Who publishes this and why
193
+
194
+ Built and maintained by the team behind [Talon](https://talonpanel.com) — a
195
+ panel that publishes its prices and its methodology instead of hiding them.
196
+
197
+ - The API contract this client implements: <https://talonpanel.com/api-docs>
198
+ - How Talon measures itself against other panels: <https://talonpanel.com/compare/>
199
+
200
+ The client is deliberately panel-agnostic: it speaks the shared v2 shape, so it
201
+ works against any panel that follows it. Talon is only the default URL.
202
+
203
+ ## Development
204
+
205
+ ```bash
206
+ python -m venv .venv && . .venv/bin/activate
207
+ pip install -e ".[dev]"
208
+ pytest # 100% coverage, no network
209
+ ```
210
+
211
+ The tests inject an `httpx.MockTransport`, so nothing touches the network and
212
+ no key is required.
213
+
214
+ ## License
215
+
216
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,189 @@
1
+ # perfectpanel-client
2
+
3
+ Typed, dependency-light Python client for the **Perfect Panel v2** SMM API — the
4
+ same `POST /api/v2` + `action=` shape that most SMM panels speak.
5
+
6
+ [![tests](https://github.com/w3radar/perfectpanel-client/actions/workflows/tests.yml/badge.svg)](https://github.com/w3radar/perfectpanel-client/actions/workflows/tests.yml)
7
+ [![python](https://img.shields.io/badge/python-3.9%2B-blue)](https://github.com/w3radar/perfectpanel-client)
8
+ [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
9
+
10
+ - Seven methods, typed results, one exception base class.
11
+ - Money is **never a float**: exact integer micro-units, like the panel's own
12
+ `cheapest_micro`.
13
+ - Retries with exponential backoff and `Retry-After` support.
14
+ - The API key is never logged and is redacted from `repr()`.
15
+ - 150+ tests, 100% line and branch coverage, no network in CI.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install "git+https://github.com/w3radar/perfectpanel-client.git"
21
+ # or, during development:
22
+ pip install -e ".[dev]"
23
+ ```
24
+
25
+ Requires Python 3.9+. The only runtime dependency is `httpx`.
26
+
27
+ ## 60-second quickstart
28
+
29
+ Every panel publishes a sandbox key so you can integrate before spending
30
+ anything. It reads the real catalogue and writes nothing:
31
+
32
+ ```python
33
+ from perfectpanel import PerfectPanelClient
34
+
35
+ with PerfectPanelClient("sandbox") as panel:
36
+ for service in panel.services()[:3]:
37
+ print(service.service, service.name, service.rate, service.min, service.max)
38
+
39
+ order = panel.add(service_id, "https://instagram.com/p/example", 1000)
40
+ print(order.order, order.charge, order.balance) # exact Money, not floats
41
+
42
+ print(panel.status(order.order).status) # "Pending" / "In progress" / "Completed"
43
+ ```
44
+
45
+ Swap `"sandbox"` for your live key when you are ready — or keep it out of the
46
+ code entirely:
47
+
48
+ ```bash
49
+ export PERFECTPANEL_API_KEY="…"
50
+ ```
51
+
52
+ ```python
53
+ panel = PerfectPanelClient.from_env()
54
+ ```
55
+
56
+ ### Waiting for delivery
57
+
58
+ `add` returns immediately. `wait_for` polls until the order reaches a terminal
59
+ state (`Completed`, `Partial`, `Canceled`) and returns the last status even on
60
+ timeout — an order still in progress is not an error:
61
+
62
+ ```python
63
+ final = panel.wait_for(order.order, timeout=600, poll_interval=10)
64
+ if not final.completed:
65
+ print("still running or partial:", final.status, final.remains)
66
+ ```
67
+
68
+ ### Several orders at once
69
+
70
+ ```python
71
+ for s in panel.multi_status([101, 102, 103]):
72
+ print(s.order, s.status, s.remains)
73
+ ```
74
+
75
+ The panel's batch form takes `orders=101,102,103`. Panels that only implement
76
+ single-order status are detected automatically and asked one by one, so the
77
+ same call works everywhere.
78
+
79
+ ## Endpoints
80
+
81
+ One URL, one form body, `action` selects the operation.
82
+
83
+ | Method | `action` | Parameters | Returns |
84
+ | --- | --- | --- | --- |
85
+ | `services()` | `services` | — | `tuple[Service, ...]` |
86
+ | `add(service, link, quantity, …)` | `add` | `service`, `link`, `quantity`, optional `comments`, `runs`, `interval` | `OrderPlaced(order, charge, balance)` |
87
+ | `status(order)` | `status` | `order` | `OrderStatus` |
88
+ | `multi_status([ids])` | `status` | `orders` (comma-joined) | `tuple[OrderStatus, ...]` |
89
+ | `balance()` | `balance` | — | `Balance(balance, currency)` |
90
+ | `cancel(order)` | `cancel` | `order` | `ActionAck(ok, order)` |
91
+ | `refill(order)` | `refill` | `order` | `ActionAck(ok, order)` |
92
+
93
+ Responses are parsed into frozen dataclasses. Fields a panel adds later are
94
+ kept in `.raw` instead of breaking your integration.
95
+
96
+ ## Error model
97
+
98
+ Every failure inherits from `PerfectPanelError`, so one `except` is enough:
99
+
100
+ ```python
101
+ from perfectpanel import PerfectPanelError
102
+ try:
103
+ panel.add(12, "https://instagram.com/p/x", 1000)
104
+ except PerfectPanelError as exc:
105
+ print(type(exc).__name__, getattr(exc, "error_code", None))
106
+ ```
107
+
108
+ | Exception | When |
109
+ | --- | --- |
110
+ | `InvalidAPIKeyError` | HTTP 401 / `API_KEY_INVALID` |
111
+ | `ServiceNotFoundError` | `SERVICE_NOT_FOUND` |
112
+ | `OrderRejectedError` | `ORDER_REJECTED` — bad link, quantity out of range, no balance |
113
+ | `OrderNotFoundError` | `ORDER_NOT_FOUND` |
114
+ | `CancelRejectedError` | `CANCEL_REJECTED` — too late to cancel |
115
+ | `RefillRejectedError` | `REFILL_REJECTED` |
116
+ | `UnknownActionError` | `ACTION_UNKNOWN` — panel does not implement that action |
117
+ | `TransportError` | DNS, connection or timeout, after all retries |
118
+ | `ResponseParseError` | the answer was not JSON (proxy or HTML error page) |
119
+
120
+ The important detail: **a rejected action comes back as HTTP 200** with an
121
+ `error_code`, for compatibility with older reseller panels. Catch the exception
122
+ type, not the status code. `error_code` is the stable contract; the human
123
+ `message` may be reworded by any panel.
124
+
125
+ ## Money
126
+
127
+ Panel charges arrive as decimal strings (`"0.6327"`). Summing floats over
128
+ thousands of orders drifts by fractions of a cent, so every amount is stored as
129
+ an `int` number of micro-units (`1_000_000 = 1.00 USD`, the same unit the panel's
130
+ public price API uses for `cheapest_micro`):
131
+
132
+ ```python
133
+ from perfectpanel import Money, to_micro, from_micro
134
+
135
+ Money.parse("0.6327").micro # 632700
136
+ Money.parse("0.1") + Money.parse("0.2") == Money.parse("0.3") # True, exactly
137
+ str(Money.parse("1.5")) # "1.5 USD"
138
+ to_micro("0.0000005") # 1 (half-up, never truncated)
139
+ ```
140
+
141
+ `Money + Money` refuses to mix currencies instead of adding dollars to rubles.
142
+
143
+ ## Retries
144
+
145
+ `max_retries=3` by default, on timeouts, connection errors, `429`, `500`,
146
+ `502`, `503` and `504`. Backoff is `backoff_factor * 2 ** (n - 1)` with jitter,
147
+ capped by `max_backoff`, and `Retry-After` wins when the panel sends it. Input
148
+ is validated before any request is made, so a bad `quantity` costs zero calls.
149
+
150
+ ```python
151
+ panel = PerfectPanelClient(key, timeout=20, max_retries=5, backoff_factor=0.4)
152
+ ```
153
+
154
+ ## What a panel API is, honestly
155
+
156
+ An SMM panel resells social-media services — followers, views, likes — placed
157
+ against a link or username. The v2 API is a thin order desk: list the catalogue,
158
+ place an order with your prepaid balance, poll its status, occasionally cancel
159
+ or refill. It is not a social-network API and it cannot guarantee that a
160
+ platform will keep the numbers; it can only tell you what was ordered and what
161
+ the panel says it delivered. That is exactly why this client returns the
162
+ panel's raw status strings unchanged, keeps your balance exact to the micro-unit,
163
+ and never pretends a `Partial` is a `Completed`.
164
+
165
+ ## Who publishes this and why
166
+
167
+ Built and maintained by the team behind [Talon](https://talonpanel.com) — a
168
+ panel that publishes its prices and its methodology instead of hiding them.
169
+
170
+ - The API contract this client implements: <https://talonpanel.com/api-docs>
171
+ - How Talon measures itself against other panels: <https://talonpanel.com/compare/>
172
+
173
+ The client is deliberately panel-agnostic: it speaks the shared v2 shape, so it
174
+ works against any panel that follows it. Talon is only the default URL.
175
+
176
+ ## Development
177
+
178
+ ```bash
179
+ python -m venv .venv && . .venv/bin/activate
180
+ pip install -e ".[dev]"
181
+ pytest # 100% coverage, no network
182
+ ```
183
+
184
+ The tests inject an `httpx.MockTransport`, so nothing touches the network and
185
+ no key is required.
186
+
187
+ ## License
188
+
189
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "perfectpanel-client"
7
+ version = "0.1.0"
8
+ description = "Typed, dependency-light Python client for the Perfect Panel v2 SMM API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "w3radar" }]
13
+ keywords = ["smm", "api-client", "perfect-panel", "panel", "httpx"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = ["httpx>=0.24"]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=7", "pytest-cov>=4"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/w3radar/perfectpanel-client"
30
+ Documentation = "https://github.com/w3radar/perfectpanel-client#readme"
31
+ "Panel API docs" = "https://talonpanel.com/api-docs"
32
+ Issues = "https://github.com/w3radar/perfectpanel-client/issues"
33
+
34
+ [tool.setuptools]
35
+ package-dir = { "" = "src" }
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.setuptools.package-data]
41
+ perfectpanel = ["py.typed"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+ pythonpath = ["src"]
46
+ addopts = "-q --strict-markers"
47
+
48
+ [tool.coverage.run]
49
+ source = ["perfectpanel"]
50
+ branch = true
51
+
52
+ [tool.coverage.report]
53
+ show_missing = true
54
+ skip_empty = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,66 @@
1
+ """perfectpanel — a small, typed client for the Perfect Panel v2 API.
2
+
3
+ from perfectpanel import PerfectPanelClient
4
+
5
+ with PerfectPanelClient("sandbox") as client:
6
+ for service in client.services()[:3]:
7
+ print(service.service, service.name, service.rate)
8
+
9
+ Seven methods cover the whole public API: :meth:`services`, :meth:`add`,
10
+ :meth:`status`, :meth:`multi_status`, :meth:`balance`, :meth:`cancel`,
11
+ :meth:`refill`. Every failure raises a subclass of
12
+ :class:`perfectpanel.PerfectPanelError`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from ._money import MICRO, Money, from_micro, to_micro
18
+ from .client import DEFAULT_BASE_URL, PerfectPanelClient
19
+ from .exceptions import (
20
+ APIError,
21
+ CancelRejectedError,
22
+ InvalidAPIKeyError,
23
+ OrderNotFoundError,
24
+ OrderRejectedError,
25
+ PerfectPanelError,
26
+ RefillRejectedError,
27
+ ResponseParseError,
28
+ ServiceNotFoundError,
29
+ TransportError,
30
+ UnknownActionError,
31
+ )
32
+ from .models import (
33
+ ActionAck,
34
+ Balance,
35
+ OrderPlaced,
36
+ OrderStatus,
37
+ Service,
38
+ )
39
+
40
+ __version__ = "0.1.0"
41
+
42
+ __all__ = [
43
+ "__version__",
44
+ "PerfectPanelClient",
45
+ "DEFAULT_BASE_URL",
46
+ "MICRO",
47
+ "Money",
48
+ "to_micro",
49
+ "from_micro",
50
+ "Service",
51
+ "OrderPlaced",
52
+ "OrderStatus",
53
+ "Balance",
54
+ "ActionAck",
55
+ "PerfectPanelError",
56
+ "APIError",
57
+ "TransportError",
58
+ "ResponseParseError",
59
+ "InvalidAPIKeyError",
60
+ "ServiceNotFoundError",
61
+ "OrderRejectedError",
62
+ "OrderNotFoundError",
63
+ "CancelRejectedError",
64
+ "RefillRejectedError",
65
+ "UnknownActionError",
66
+ ]
@@ -0,0 +1,128 @@
1
+ """Integer-safe money handling.
2
+
3
+ Panels return money as decimal strings (``"0.5050"``). Binary floats quietly
4
+ lose fractions of a cent once you sum a few thousand orders, so every amount
5
+ here is parsed with :class:`decimal.Decimal` and then carried as an integer
6
+ number of **micro-units** (one millionth of the currency unit), the same unit
7
+ used by Talon's public price API (``cheapest_micro``).
8
+
9
+ Integer micro-units add, subtract and compare exactly, so a wallet
10
+ reconciliation never drifts by ``0.0000000000001``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
17
+ from typing import Union
18
+
19
+ MICRO = 1_000_000
20
+ """Micro-units per currency unit."""
21
+
22
+ Number = Union[int, float, str, Decimal]
23
+
24
+
25
+ def to_micro(value: Number, *, places: int = 6) -> int:
26
+ """Convert a panel money value to integer micro-units.
27
+
28
+ Accepts the decimal strings panels actually send (``"0.5050"``), plus
29
+ ints, floats and :class:`~decimal.Decimal`. Rounds half-up to six decimal
30
+ places rather than truncating, so ``0.1234565`` becomes ``123457``.
31
+
32
+ Raises:
33
+ ValueError: if the value is not a finite number.
34
+ """
35
+ if isinstance(value, bool): # bool is an int subclass; never money
36
+ raise ValueError("money value must be numeric, got bool")
37
+ try:
38
+ amount = Decimal(str(value).strip())
39
+ except (InvalidOperation, AttributeError, ValueError) as exc:
40
+ raise ValueError(f"money value is not numeric: {value!r}") from exc
41
+ if not amount.is_finite():
42
+ raise ValueError(f"money value is not finite: {value!r}")
43
+ scaled = amount * MICRO
44
+ quantized = scaled.quantize(Decimal(1), rounding=ROUND_HALF_UP)
45
+ if places != 6: # pragma: no cover - kept for callers that pre-round
46
+ step = Decimal(10) ** (6 - places)
47
+ quantized = (quantized / step).quantize(Decimal(1), rounding=ROUND_HALF_UP) * step
48
+ return int(quantized)
49
+
50
+
51
+ def from_micro(micro: int, *, trim: bool = True) -> str:
52
+ """Render integer micro-units back to a plain decimal string.
53
+
54
+ ``125000`` becomes ``"0.125"``; with ``trim=False`` it keeps all six
55
+ places (``"0.125000"``), which is handy for CSV exports.
56
+ """
57
+ if isinstance(micro, bool) or not isinstance(micro, int):
58
+ raise TypeError("micro must be an int")
59
+ sign = "-" if micro < 0 else ""
60
+ whole, frac = divmod(abs(micro), MICRO)
61
+ text = f"{sign}{whole}.{frac:06d}"
62
+ if trim:
63
+ text = text.rstrip("0").rstrip(".") if "." in text else text
64
+ return text
65
+
66
+
67
+ @dataclass(frozen=True, order=True)
68
+ class Money:
69
+ """An exact amount of money, stored as integer micro-units.
70
+
71
+ ``Money`` never holds a float. Two amounts are equal only when both the
72
+ number of micro-units and the currency match, and ``+``/``-`` refuse to
73
+ mix currencies instead of silently adding dollars to rubles.
74
+ """
75
+
76
+ micro: int
77
+ currency: str = "USD"
78
+
79
+ def __post_init__(self) -> None:
80
+ if isinstance(self.micro, bool) or not isinstance(self.micro, int):
81
+ raise TypeError("micro must be an int; use Money.parse for strings")
82
+ object.__setattr__(self, "currency", (self.currency or "USD").upper())
83
+
84
+ @classmethod
85
+ def parse(cls, value: Number, currency: str = "USD") -> "Money":
86
+ """Build a :class:`Money` from any panel value (string, int, float)."""
87
+ return cls(micro=to_micro(value), currency=currency)
88
+
89
+ @classmethod
90
+ def zero(cls, currency: str = "USD") -> "Money":
91
+ return cls(0, currency)
92
+
93
+ @property
94
+ def amount(self) -> Decimal:
95
+ """The exact amount as a :class:`~decimal.Decimal`."""
96
+ return Decimal(self.micro) / MICRO
97
+
98
+ def format(self, places: int = 2, *, trim: bool = False) -> str:
99
+ """Format for display, e.g. ``"1.23"`` (banker-friendly 2 places)."""
100
+ if places < 0:
101
+ raise ValueError("places must be >= 0")
102
+ text = from_micro(self.micro, trim=trim)
103
+ if places == 6:
104
+ return text
105
+ quantized = self.amount.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
106
+ return f"{quantized:.{places}f}"
107
+
108
+ def _same_currency(self, other: "Money") -> None:
109
+ if not isinstance(other, Money):
110
+ raise TypeError(f"expected Money, got {type(other).__name__}")
111
+ if other.currency != self.currency:
112
+ raise ValueError(
113
+ f"currency mismatch: {self.currency} vs {other.currency}"
114
+ )
115
+
116
+ def __add__(self, other: "Money") -> "Money":
117
+ self._same_currency(other)
118
+ return Money(self.micro + other.micro, self.currency)
119
+
120
+ def __sub__(self, other: "Money") -> "Money":
121
+ self._same_currency(other)
122
+ return Money(self.micro - other.micro, self.currency)
123
+
124
+ def __neg__(self) -> "Money":
125
+ return Money(-self.micro, self.currency)
126
+
127
+ def __str__(self) -> str:
128
+ return f"{self.format(6, trim=True)} {self.currency}"