ajaflow-sdk 1.0.0__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.
aja/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """AJA order API client."""
2
+
3
+ from .client import Client, VERSION
4
+ from .errors import (
5
+ AjaError,
6
+ ApiError,
7
+ ErrorCode,
8
+ NetworkError,
9
+ ValidationError,
10
+ )
11
+ from .models import Command, OrderInput
12
+ from .money import currency_exponent, from_minor, to_minor
13
+ from .payment import (
14
+ PAYMENT_STATUSES,
15
+ clear_payment_aliases,
16
+ fold_label,
17
+ register_payment_aliases,
18
+ resolve_payment_status,
19
+ )
20
+
21
+ __all__ = [
22
+ "Client",
23
+ "Command",
24
+ "OrderInput",
25
+ "AjaError",
26
+ "ApiError",
27
+ "ErrorCode",
28
+ "NetworkError",
29
+ "ValidationError",
30
+ "VERSION",
31
+ "PAYMENT_STATUSES",
32
+ "register_payment_aliases",
33
+ "clear_payment_aliases",
34
+ "resolve_payment_status",
35
+ "fold_label",
36
+ "currency_exponent",
37
+ "to_minor",
38
+ "from_minor",
39
+ ]
aja/client.py ADDED
@@ -0,0 +1,356 @@
1
+ """HTTP client for the AJA API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import json
7
+ import re
8
+ import time
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from collections.abc import Mapping
13
+ from typing import Any
14
+
15
+ from .errors import ApiError, ErrorCode, NetworkError, ValidationError
16
+ from .models import Command, OrderInput
17
+
18
+ VERSION = "1.0.0"
19
+ USER_AGENT = f"aja-python-sdk/{VERSION}"
20
+ DEFAULT_BASE_URL = "https://api.ajaflow.com"
21
+
22
+ _TRANSIENT_STATUS = {429, 502, 503, 504}
23
+
24
+ _VERIFY_PARAM = "aja_verify"
25
+ _VERIFICATION_CODE = re.compile(r"[A-Za-z0-9_-]{32,128}")
26
+
27
+
28
+ def _is_local_host(host: str) -> bool:
29
+ """A local test server: localhost, a private network address, *.test, *.local."""
30
+ if host in ("localhost", "host.docker.internal") or re.search(r"\.(localhost|local|test)$", host):
31
+ return True
32
+ try:
33
+ address = ipaddress.ip_address(host)
34
+ except ValueError:
35
+ return False
36
+ return address.is_private or address.is_loopback or address.is_link_local
37
+
38
+
39
+ def _assert_safe_base_url(base_url: str) -> None:
40
+ """The API key travels in every request: never in clear text to a public server."""
41
+ parts = urllib.parse.urlsplit(base_url)
42
+ host = (parts.hostname or "").lower()
43
+ if parts.scheme == "https":
44
+ return
45
+ if parts.scheme == "http" and _is_local_host(host):
46
+ return
47
+ raise ValueError(
48
+ f'AJA base URL "{base_url}" must use https: the API key would travel in clear text '
49
+ "(http is only for a local test server)"
50
+ )
51
+
52
+
53
+ class Client:
54
+ """Entry point."""
55
+
56
+ def __init__(
57
+ self,
58
+ api_key: str,
59
+ base_url: str = DEFAULT_BASE_URL,
60
+ timeout: float = 10.0,
61
+ max_attempts: int = 3,
62
+ backoff_ms: int = 200,
63
+ ) -> None:
64
+ self._api_key = api_key
65
+ self._base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
66
+ _assert_safe_base_url(self._base_url)
67
+ self._timeout = timeout
68
+ self._max_attempts = max_attempts
69
+ self._backoff_ms = backoff_ms
70
+ self.orders = OrdersApi(self)
71
+ self.commands = CommandsApi(self)
72
+ self.products = ProductsApi(self)
73
+ self.site = SiteApi(self)
74
+
75
+ def send(
76
+ self,
77
+ method: str,
78
+ path: str,
79
+ body: dict[str, Any] | None = None,
80
+ query: dict[str, str] | None = None,
81
+ retry_transport: bool = True,
82
+ retry_transient: bool = False,
83
+ timeout: float | None = None,
84
+ ) -> dict[str, Any]:
85
+ """Perform one API call, applying the retry policy."""
86
+ url = self._base_url + path
87
+ if query:
88
+ url += "?" + urllib.parse.urlencode(query)
89
+
90
+ payload = None
91
+ headers = {
92
+ "Authorization": f"Bearer {self._api_key}",
93
+ "Accept": "application/json",
94
+ "User-Agent": USER_AGENT,
95
+ }
96
+ if body is not None:
97
+ payload = json.dumps(body, ensure_ascii=False).encode("utf-8")
98
+ headers["Content-Type"] = "application/json"
99
+
100
+ attempt = 0
101
+ while True:
102
+ attempt += 1
103
+ request = urllib.request.Request(
104
+ url, data=payload, headers=headers, method=method
105
+ )
106
+ try:
107
+ with urllib.request.urlopen(request, timeout=timeout if timeout is not None else self._timeout) as response:
108
+ raw = response.read().decode("utf-8")
109
+ status = response.status
110
+ except urllib.error.HTTPError as http_error:
111
+ raw = http_error.read().decode("utf-8", "replace")
112
+ status = http_error.code
113
+ except (urllib.error.URLError, OSError) as transport_error:
114
+ if retry_transport and attempt < self._max_attempts:
115
+ self._sleep(attempt)
116
+ continue
117
+ raise NetworkError(str(transport_error)) from transport_error
118
+
119
+ if status == 204 or not raw:
120
+ return {}
121
+
122
+ try:
123
+ decoded = json.loads(raw)
124
+ except json.JSONDecodeError:
125
+ decoded = {}
126
+ if not isinstance(decoded, dict):
127
+ decoded = {}
128
+
129
+ if 200 <= status < 300:
130
+ return decoded
131
+
132
+ error = _to_api_error(status, decoded)
133
+ transient = (
134
+ ErrorCode.is_retryable(error.code) and status in _TRANSIENT_STATUS
135
+ )
136
+ if retry_transient and transient and attempt < self._max_attempts:
137
+ self._sleep(attempt)
138
+ continue
139
+
140
+ raise error
141
+
142
+ def _sleep(self, attempt: int) -> None:
143
+ """Exponential backoff: 200 ms, 400 ms, 800 ms."""
144
+ time.sleep(self._backoff_ms * (2 ** (attempt - 1)) / 1000)
145
+
146
+
147
+ def _to_api_error(status: int, decoded: dict[str, Any]) -> ApiError:
148
+ """Map an error envelope onto the right exception class."""
149
+ envelope = decoded.get("error") or {}
150
+ if not isinstance(envelope, dict):
151
+ envelope = {}
152
+ code = str(envelope.get("code", ErrorCode.INTERNAL))
153
+ message = str(envelope.get("message", "AJA request failed"))
154
+ details = envelope.get("details") or {}
155
+ request_id = decoded.get("request_id")
156
+ request_id = str(request_id) if request_id is not None else None
157
+
158
+ cls = ValidationError if code == ErrorCode.VALIDATION else ApiError
159
+ return cls(
160
+ status,
161
+ code,
162
+ message,
163
+ request_id,
164
+ details if isinstance(details, dict) else {},
165
+ )
166
+
167
+
168
+ class OrdersApi:
169
+ """Site-facing orders: create (upsert) and patch by the shop's external_id."""
170
+
171
+ def __init__(self, client: Client) -> None:
172
+ self._client = client
173
+
174
+ def create(self, order: OrderInput) -> dict[str, Any]:
175
+ """POST /v1/orders."""
176
+ return self._client.send(
177
+ "POST", "/v1/orders", order.to_dict(), retry_transient=True
178
+ )
179
+
180
+ def update(self, external_id: str, changes: dict[str, Any]) -> dict[str, Any]:
181
+ """PATCH /v1/orders/{external_id} for a change born on the shop side."""
182
+ path = "/v1/orders/" + urllib.parse.quote(external_id, safe="")
183
+ return self._client.send("PATCH", path, changes, retry_transient=True)
184
+
185
+
186
+ class ProductsApi:
187
+ """Site-facing catalogue: declare the form, push the products."""
188
+
189
+ def __init__(self, client: Client) -> None:
190
+ self._client = client
191
+
192
+ def put_schema(self, schema: dict[str, Any]) -> dict[str, Any]:
193
+ """PUT /v1/product-schema — declare the form the shop's admin uses."""
194
+ return self._client.send(
195
+ "PUT", "/v1/product-schema", schema, retry_transient=True
196
+ )
197
+
198
+ def upsert(
199
+ self,
200
+ external_id: str,
201
+ values: dict[str, Any],
202
+ schema_version: int = 0,
203
+ ) -> dict[str, Any]:
204
+ """POST /v1/products — upsert on external_id, exactly like an order."""
205
+ return self._client.send(
206
+ "POST",
207
+ "/v1/products",
208
+ {
209
+ "external_id": external_id,
210
+ "schema_version": schema_version,
211
+ "values": values,
212
+ },
213
+ retry_transient=True,
214
+ )
215
+
216
+ def delete(self, external_id: str) -> None:
217
+ """DELETE /v1/products/{external_id} — drop it from the copy."""
218
+ path = "/v1/products/" + urllib.parse.quote(external_id, safe="")
219
+ self._client.send("DELETE", path, None, retry_transient=True)
220
+
221
+
222
+ class SiteApi:
223
+ """The shop itself, as AJA knows it: the currency it sells in and the time zone it runs in —
224
+ and the proof that its server holds the key.
225
+ """
226
+
227
+ def __init__(self, client: Client) -> None:
228
+ self._client = client
229
+
230
+ def put_profile(
231
+ self,
232
+ currency: str | None = None,
233
+ timezone: str | None = None,
234
+ wake_url: str | None = None,
235
+ ) -> dict[str, Any]:
236
+ """PUT /v1/site-profile — declare the shop's currency and time zone."""
237
+ body: dict[str, Any] = {}
238
+ code = _given(currency, "currency").upper()
239
+ if code:
240
+ if not re.fullmatch("[A-Z]{3}", code):
241
+ raise ValueError(
242
+ f'currency "{code}" is not a three-letter ISO 4217 code such as "XOF" or "EUR"'
243
+ )
244
+ body["currency"] = code
245
+ zone = _given(timezone, "timezone")
246
+ if zone:
247
+ body["timezone"] = zone
248
+ wake = _given(wake_url, "wake_url")
249
+ if wake:
250
+ if not re.match(r"(?i)https?://", wake):
251
+ raise ValueError(
252
+ f'wake URL "{wake}" must be an http(s) address, such as '
253
+ "https://your-shop.com/wp-cron.php?doing_wp_cron"
254
+ )
255
+ body["wake_url"] = wake
256
+ if not body:
257
+ raise ValueError("put_profile needs a currency, a timezone or a wake URL")
258
+
259
+ return self._client.send(
260
+ "PUT", "/v1/site-profile", body, retry_transient=True
261
+ )
262
+
263
+ def handle_wake(self, params: Mapping[str, Any]) -> dict[str, Any] | None:
264
+ """Answer AJA's ownership check — call it first thing in your wake-URL handler."""
265
+ code = params.get(_VERIFY_PARAM)
266
+ if isinstance(code, (list, tuple)):
267
+ code = code[0] if len(code) == 1 else None
268
+ if not _is_verification_code(code):
269
+ return None
270
+
271
+ try:
272
+ return self.confirm_verification(code)
273
+ except ApiError as error:
274
+ if error.code != ErrorCode.VERIFICATION_FAILED:
275
+ raise
276
+ return {"verified": False}
277
+
278
+ def confirm_verification(self, code: str) -> dict[str, Any]:
279
+ """POST /v1/site-verification — send AJA back the code it put on the wake URL."""
280
+ if not isinstance(code, str):
281
+ raise TypeError(f"verification code must be a string, not {type(code).__name__}")
282
+ if not _is_verification_code(code):
283
+ raise ValueError(
284
+ 'verification code must be 32 to 128 characters among A-Z, a-z, 0-9, "_" and "-"'
285
+ )
286
+ return self._client.send(
287
+ "POST", "/v1/site-verification", {"nonce": code}, retry_transient=True
288
+ )
289
+
290
+
291
+ def _is_verification_code(code: Any) -> bool:
292
+ """A string shaped like AJA's codes — fullmatch: no trailing newline either."""
293
+ return isinstance(code, str) and _VERIFICATION_CODE.fullmatch(code) is not None
294
+
295
+
296
+ def _given(value: str | None, name: str) -> str:
297
+ """The text without surrounding spaces, or "" when not given."""
298
+ if value is None:
299
+ return ""
300
+ if not isinstance(value, str):
301
+ raise TypeError(f"{name} must be a string, not {type(value).__name__}")
302
+ return value.strip()
303
+
304
+
305
+ class CommandsApi:
306
+ """The queue the shop polls."""
307
+
308
+ def __init__(self, client: Client) -> None:
309
+ self._client = client
310
+
311
+ def pending(self, limit: int = 20, wait: int = 0) -> list[Command]:
312
+ """GET /v1/commands — oldest pending first."""
313
+ held = max(0, min(wait, 25))
314
+ query = {"limit": str(limit)}
315
+ if held > 0:
316
+ query["wait"] = str(held)
317
+ response = self._client.send(
318
+ "GET",
319
+ "/v1/commands",
320
+ None,
321
+ query,
322
+ retry_transient=True,
323
+ timeout=float(held + 10) if held > 0 else None,
324
+ )
325
+ rows = response.get("commands") or []
326
+ if not isinstance(rows, list):
327
+ return []
328
+ return [Command.from_dict(row) for row in rows if isinstance(row, dict)]
329
+
330
+ def ack(
331
+ self,
332
+ command_id: str,
333
+ ok: bool,
334
+ status: str | None = None,
335
+ allowed_next: list[str] | None = None,
336
+ reason: str | None = None,
337
+ external_id: str | None = None,
338
+ ) -> None:
339
+ """POST /v1/commands/{id}/ack — confirm or refuse an action."""
340
+ body: dict[str, Any] = {"ok": ok}
341
+ if status is not None:
342
+ body["status"] = status
343
+ if allowed_next:
344
+ body["allowed_next"] = list(allowed_next)
345
+ if reason is not None:
346
+ body["reason"] = reason
347
+ if external_id is not None:
348
+ body["external_id"] = external_id
349
+
350
+ path = "/v1/commands/" + urllib.parse.quote(command_id, safe="") + "/ack"
351
+ try:
352
+ self._client.send("POST", path, body, retry_transient=False)
353
+ except ApiError as error:
354
+ if error.code == ErrorCode.COMMAND_ALREADY_ACKED:
355
+ return
356
+ raise
aja/errors.py ADDED
@@ -0,0 +1,102 @@
1
+ """Error catalogue and exception types for the AJA client."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ErrorCode:
7
+ """Closed catalogue of the error codes the AJA API returns."""
8
+
9
+ VALIDATION = "VALIDATION"
10
+ SITE_KEY_INVALID = "SITE_KEY_INVALID"
11
+ SITE_KEY_REVOKED = "SITE_KEY_REVOKED"
12
+ FORBIDDEN = "FORBIDDEN"
13
+ NOT_FOUND = "NOT_FOUND"
14
+ SITE_NOT_FOUND = "SITE_NOT_FOUND"
15
+ ORDER_NOT_FOUND = "ORDER_NOT_FOUND"
16
+ COMMAND_NOT_FOUND = "COMMAND_NOT_FOUND"
17
+ COMMAND_ALREADY_ACKED = "COMMAND_ALREADY_ACKED"
18
+ PRODUCT_NOT_FOUND = "PRODUCT_NOT_FOUND"
19
+ PRODUCT_SYNC_PENDING = "PRODUCT_SYNC_PENDING"
20
+ PRODUCT_SCHEMA_OUTDATED = "PRODUCT_SCHEMA_OUTDATED"
21
+ PRODUCT_SCHEMA_LOCKED = "PRODUCT_SCHEMA_LOCKED"
22
+ SITE_IP_NOT_ALLOWED = "SITE_IP_NOT_ALLOWED"
23
+ VERIFICATION_FAILED = "VERIFICATION_FAILED"
24
+ # The site has not proven its domain yet: its key only serves the link-up.
25
+ SITE_NOT_VERIFIED = "SITE_NOT_VERIFIED"
26
+ # The call came from a server address the merchant has not confirmed yet.
27
+ SITE_IP_NOT_CONFIRMED = "SITE_IP_NOT_CONFIRMED"
28
+ # The merchant's decision has a type this site does not handle.
29
+ COMMAND_UNSUPPORTED_TYPE = "COMMAND_UNSUPPORTED_TYPE"
30
+ # The order cannot move to that status from the one it has.
31
+ ORDER_TRANSITION_NOT_ALLOWED = "ORDER_TRANSITION_NOT_ALLOWED"
32
+ TEST_TRIAL_EXPIRED = "TEST_TRIAL_EXPIRED"
33
+ PROD_NOT_ACTIVE = "PROD_NOT_ACTIVE"
34
+ RATE_LIMITED = "RATE_LIMITED"
35
+ INTERNAL = "INTERNAL"
36
+
37
+ NON_RETRYABLE = frozenset(
38
+ {
39
+ VALIDATION,
40
+ SITE_KEY_INVALID,
41
+ SITE_KEY_REVOKED,
42
+ FORBIDDEN,
43
+ NOT_FOUND,
44
+ SITE_NOT_FOUND,
45
+ ORDER_NOT_FOUND,
46
+ COMMAND_NOT_FOUND,
47
+ PRODUCT_NOT_FOUND,
48
+ PRODUCT_SCHEMA_OUTDATED,
49
+ PRODUCT_SCHEMA_LOCKED,
50
+ SITE_IP_NOT_ALLOWED,
51
+ VERIFICATION_FAILED,
52
+ # Repeating the call changes nothing until the merchant or the
53
+ # site acts: retrying them in a loop hid why a site stayed pending.
54
+ SITE_NOT_VERIFIED,
55
+ SITE_IP_NOT_CONFIRMED,
56
+ COMMAND_UNSUPPORTED_TYPE,
57
+ ORDER_TRANSITION_NOT_ALLOWED,
58
+ TEST_TRIAL_EXPIRED,
59
+ PROD_NOT_ACTIVE,
60
+ }
61
+ )
62
+
63
+ @classmethod
64
+ def is_retryable(cls, code: str) -> bool:
65
+ """True when the SDK should back off and repeat the same call."""
66
+ return code not in cls.NON_RETRYABLE
67
+
68
+
69
+ class AjaError(Exception):
70
+ """Base class, so a checkout can guard every AJA failure in one block."""
71
+
72
+
73
+ class NetworkError(AjaError):
74
+ """Transport failed before AJA produced a JSON envelope: DNS, TLS, timeout."""
75
+
76
+
77
+ class ApiError(AjaError):
78
+ """AJA answered with an error envelope."""
79
+
80
+ def __init__(
81
+ self,
82
+ http_status: int,
83
+ code: str,
84
+ message: str,
85
+ request_id: str | None = None,
86
+ details: dict | None = None,
87
+ ) -> None:
88
+ super().__init__(message)
89
+ self.http_status = http_status
90
+ self.code = code
91
+ self.request_id = request_id
92
+ self.details = details or {}
93
+
94
+
95
+ class ValidationError(ApiError):
96
+ """The payload was rejected (code VALIDATION)."""
97
+
98
+ @property
99
+ def fields(self) -> dict:
100
+ """Offending JSON field -> reason."""
101
+ fields = self.details.get("fields", {})
102
+ return fields if isinstance(fields, dict) else {}
aja/models.py ADDED
@@ -0,0 +1,121 @@
1
+ """Payload types exchanged with AJA."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from .payment import PAYMENT_STATUSES, resolve_payment_status
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class OrderInput:
13
+ """One order as the shop knows it, ready for POST /v1/orders."""
14
+
15
+ external_id: str
16
+ status: str
17
+ allowed_next: list[str]
18
+ payment_status: str
19
+ payment_mode: str | None
20
+ total: int
21
+ currency: str
22
+ customer: dict[str, Any]
23
+ lines: list[dict[str, Any]]
24
+ extras: dict[str, Any] = field(default_factory=dict)
25
+
26
+ def __post_init__(self) -> None:
27
+ if not self.external_id:
28
+ raise ValueError("external_id must not be empty")
29
+ if not self.lines:
30
+ raise ValueError("an order needs at least one line")
31
+ if isinstance(self.total, bool) or not isinstance(self.total, int):
32
+ raise ValueError("total must be an int, not a float")
33
+ if self.total < 0:
34
+ raise ValueError("total must not be negative")
35
+ name = str(self.customer.get("name") or "").strip()
36
+ phone = str(self.customer.get("phone") or "").strip()
37
+ if not name and not phone:
38
+ raise ValueError("customer needs a name or a phone")
39
+ resolved = resolve_payment_status(self.payment_status)
40
+ if resolved is None:
41
+ raise ValueError(
42
+ f"payment_status {self.payment_status!r} is not recognised. It must "
43
+ f"end up as one of {'|'.join(PAYMENT_STATUSES)}. Either pass one of "
44
+ f"those, or teach the SDK your vocabulary once at start-up:\n"
45
+ f' register_payment_aliases({{"{self.payment_status}": "pending"}})'
46
+ )
47
+ object.__setattr__(self, "_resolved_payment_status", resolved)
48
+
49
+ def to_dict(self) -> dict[str, Any]:
50
+ """snake_case body expected by the HTTP contract."""
51
+ return {
52
+ "external_id": self.external_id,
53
+ "status": self.status,
54
+ "allowed_next": list(self.allowed_next),
55
+ "payment_status": self._resolved_payment_status,
56
+ "payment_mode": self.payment_mode,
57
+ "total": self.total,
58
+ "currency": self.currency,
59
+ "customer": self.customer,
60
+ "lines": list(self.lines),
61
+ "extras": self.extras,
62
+ }
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Command:
67
+ """One queued action the merchant took in the app."""
68
+
69
+ TYPE_ORDER_TRANSITION = "order.transition"
70
+ TYPE_PRODUCT_CREATE = "product.create"
71
+ TYPE_PRODUCT_UPDATE = "product.update"
72
+ TYPE_PRODUCT_DELETE = "product.delete"
73
+ TYPE_PRODUCT_STOCK = "product.stock"
74
+ TYPE_PRODUCT_PROBE = "product.probe"
75
+
76
+ id: str
77
+ type: str
78
+ external_id: str | None
79
+ payload: dict[str, Any]
80
+ created_at: str
81
+
82
+ @classmethod
83
+ def from_dict(cls, row: dict[str, Any]) -> Command:
84
+ payload = row.get("payload") or {}
85
+ external_id = row.get("external_id")
86
+ return cls(
87
+ id=str(row.get("id", "")),
88
+ type=str(row.get("type", "")),
89
+ external_id=external_id if isinstance(external_id, str) and external_id else None,
90
+ payload=payload if isinstance(payload, dict) else {},
91
+ created_at=str(row.get("created_at", "")),
92
+ )
93
+
94
+ @property
95
+ def is_product(self) -> bool:
96
+ """True for the catalogue types an orders-only integration can safely refuse."""
97
+ return self.type.startswith("product.")
98
+
99
+ @property
100
+ def target_status(self) -> str | None:
101
+ """Target status for an order.transition, or None for other types."""
102
+ status = self.payload.get("status")
103
+ return status if isinstance(status, str) and status else None
104
+
105
+ @property
106
+ def values(self) -> dict[str, Any]:
107
+ """Fields to write, for a product.create or product.update."""
108
+ values = self.payload.get("values")
109
+ return values if isinstance(values, dict) else {}
110
+
111
+ @property
112
+ def schema_version(self) -> int:
113
+ """Version of the form the merchant filled, so the shop can refuse a stale one."""
114
+ version = self.payload.get("schema_version")
115
+ return version if isinstance(version, int) else 0
116
+
117
+ @property
118
+ def stock(self) -> int | None:
119
+ """New stock level for a product.stock, or None for other types."""
120
+ stock = self.payload.get("stock")
121
+ return stock if isinstance(stock, int) else None
aja/money.py ADDED
@@ -0,0 +1,120 @@
1
+ """Amounts as AJA carries them: integers in the smallest unit of their currency, per ISO 4217."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from decimal import Decimal
8
+
9
+ _ZERO_DECIMAL = frozenset({
10
+ "BIF", "CLP", "DJF", "GNF", "ISK", "JPY", "KMF", "KRW", "PYG",
11
+ "RWF", "UGX", "UYI", "VND", "VUV", "XAF", "XOF", "XPF",
12
+ })
13
+
14
+ _THREE_DECIMAL = frozenset({"BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"})
15
+
16
+ _DECIMAL = re.compile(r"([+-]?)([0-9]*)(?:\.([0-9]*))?")
17
+ _WHOLE = re.compile(r"([+-]?)([0-9]+)")
18
+
19
+ _MAX_SAFE = 2**53 - 1
20
+ _TOO_LARGE = "amount is too large to stay exact"
21
+
22
+
23
+ def currency_exponent(currency: str) -> int:
24
+ """Decimals of a currency's minor unit: 0, 2 (the usual case) or 3."""
25
+ if not isinstance(currency, str):
26
+ raise TypeError(f'currency must be a code such as "EUR", not {type(currency).__name__}')
27
+ code = currency.strip().upper()
28
+ if code in _ZERO_DECIMAL:
29
+ return 0
30
+ if code in _THREE_DECIMAL:
31
+ return 3
32
+ return 2
33
+
34
+
35
+ def to_minor(amount: str | int | float | Decimal | None, currency: str) -> int | None:
36
+ """A decimal amount — "12.50", "15000", 12.5, Decimal("12.50") — as the integer AJA expects."""
37
+ if amount is None:
38
+ return None
39
+ if isinstance(amount, bool):
40
+ raise TypeError("amount must be a decimal string or a number, not a bool")
41
+ if isinstance(amount, int):
42
+ text = str(int(amount))
43
+ elif isinstance(amount, float):
44
+ if not math.isfinite(amount):
45
+ raise ValueError("amount must be a finite number")
46
+ text = format(amount, ".10f")
47
+ elif isinstance(amount, Decimal):
48
+ if not amount.is_finite():
49
+ raise ValueError("amount must be a finite number")
50
+ text = format(amount, "f")
51
+ elif isinstance(amount, str):
52
+ text = amount.strip()
53
+ else:
54
+ raise TypeError(
55
+ f"amount must be a decimal string or a number, not {type(amount).__name__}"
56
+ )
57
+ if text == "":
58
+ return None
59
+
60
+ parts = _DECIMAL.fullmatch(text)
61
+ if parts is None or (parts.group(2) == "" and not parts.group(3)):
62
+ raise ValueError(
63
+ f'"{text}" is not a decimal amount: write it like "12.50", '
64
+ "with a dot and no thousands separator"
65
+ )
66
+ sign, whole, fraction = parts.group(1), parts.group(2), parts.group(3) or ""
67
+
68
+ exponent = currency_exponent(currency)
69
+ digits = whole + fraction.ljust(exponent, "0")[:exponent]
70
+ up = len(fraction) > exponent and fraction[exponent] >= "5"
71
+ return _to_safe_int(sign == "-", digits, up)
72
+
73
+
74
+ def from_minor(minor: int | float | str | None, currency: str) -> str:
75
+ """AJA's integer back to the decimal string a shop stores, with exactly as many decimals as the
76
+ currency has: 1250 EUR is "12.50", 15000 XOF is "15000", 1250 KWD is "1.250".
77
+ """
78
+ if minor is None:
79
+ return ""
80
+ if isinstance(minor, bool):
81
+ raise TypeError("minor must be a whole number of minor units, not a bool")
82
+ if isinstance(minor, int):
83
+ text = str(int(minor))
84
+ elif isinstance(minor, float):
85
+ if not minor.is_integer() or abs(minor) > _MAX_SAFE:
86
+ raise ValueError(f"{minor!r} is not a whole number of minor units")
87
+ text = str(int(minor))
88
+ elif isinstance(minor, str):
89
+ text = minor.strip()
90
+ if text == "":
91
+ return ""
92
+ else:
93
+ raise TypeError(
94
+ f"minor must be a whole number of minor units, not {type(minor).__name__}"
95
+ )
96
+
97
+ parts = _WHOLE.fullmatch(text)
98
+ if parts is None:
99
+ raise ValueError(f'"{text}" is not a whole number of minor units')
100
+
101
+ digits = parts.group(2).lstrip("0")
102
+ negative = parts.group(1) == "-" and digits != ""
103
+ digits = digits or "0"
104
+ exponent = currency_exponent(currency)
105
+ if exponent > 0:
106
+ digits = digits.rjust(exponent + 1, "0")
107
+ digits = f"{digits[:-exponent]}.{digits[-exponent:]}"
108
+
109
+ return f"{'-' if negative else ''}{digits}"
110
+
111
+
112
+ def _to_safe_int(negative: bool, digits: str, up: bool) -> int:
113
+ """The kept digits as an int, one more when rounding up, signed last."""
114
+ significant = digits.lstrip("0")
115
+ if len(significant) > len(str(_MAX_SAFE)):
116
+ raise ValueError(_TOO_LARGE)
117
+ value = int(significant or "0") + (1 if up else 0)
118
+ if value > _MAX_SAFE:
119
+ raise ValueError(_TOO_LARGE)
120
+ return -value if negative else value
aja/payment.py ADDED
@@ -0,0 +1,102 @@
1
+ """Payment vocabulary translation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+
8
+ PAYMENT_STATUSES = ("pending", "paid", "failed", "refunded")
9
+
10
+
11
+ def fold_label(value: str) -> str:
12
+ """Fold a label into a comparable key."""
13
+ stripped = "".join(
14
+ c for c in unicodedata.normalize("NFD", value)
15
+ if unicodedata.category(c) != "Mn"
16
+ )
17
+ key = re.sub(r"[\s./-]+", "_", stripped.lower().strip())
18
+ return re.sub(r"_+", "_", key)
19
+
20
+
21
+ _BUILT_IN: dict[str, str] = {
22
+ "pending": "pending",
23
+ "unpaid": "pending",
24
+ "not_paid": "pending",
25
+ "awaiting_payment": "pending",
26
+ "pending_payment": "pending",
27
+ "payment_pending": "pending",
28
+ "on_delivery": "pending",
29
+ "cash_on_delivery": "pending",
30
+ "cod": "pending",
31
+ "partially_paid": "pending",
32
+ "partial_payment": "pending",
33
+ "deposit": "pending",
34
+ "en_attente": "pending",
35
+ "en_attente_de_paiement": "pending",
36
+ "paiement_en_attente": "pending",
37
+ "impaye": "pending",
38
+ "non_paye": "pending",
39
+ "a_payer": "pending",
40
+ "contre_remboursement": "pending",
41
+ "paiement_a_la_livraison": "pending",
42
+ "partiellement_paye": "pending",
43
+ "paiement_partiel": "pending",
44
+ "acompte": "pending",
45
+ "paid": "paid",
46
+ "captured": "paid",
47
+ "completed": "paid",
48
+ "complete": "paid",
49
+ "settled": "paid",
50
+ "success": "paid",
51
+ "successful": "paid",
52
+ "partially_refunded": "paid",
53
+ "partial_refund": "paid",
54
+ "paye": "paid",
55
+ "regle": "paid",
56
+ "encaisse": "paid",
57
+ "paiement_recu": "paid",
58
+ "paiement_valide": "paid",
59
+ "partiellement_rembourse": "paid",
60
+ "remboursement_partiel": "paid",
61
+ "failed": "failed",
62
+ "declined": "failed",
63
+ "rejected": "failed",
64
+ "denied": "failed",
65
+ "error": "failed",
66
+ "expired": "failed",
67
+ "echoue": "failed",
68
+ "refuse": "failed",
69
+ "rejete": "failed",
70
+ "erreur": "failed",
71
+ "expire": "failed",
72
+ "refunded": "refunded",
73
+ "chargeback": "refunded",
74
+ "reversed": "refunded",
75
+ "rembourse": "refunded",
76
+ "remboursement": "refunded",
77
+ "avoir": "refunded",
78
+ }
79
+
80
+ _custom: dict[str, str] = {}
81
+
82
+
83
+ def register_payment_aliases(aliases: dict[str, str]) -> None:
84
+ """Teach the SDK your own payment vocabulary, once, at start-up."""
85
+ for label, target in aliases.items():
86
+ if target not in PAYMENT_STATUSES:
87
+ raise ValueError(
88
+ f"register_payment_aliases: {label!r} points at {target!r}, "
89
+ f"which is not one of {'|'.join(PAYMENT_STATUSES)}."
90
+ )
91
+ _custom[fold_label(label)] = target
92
+
93
+
94
+ def clear_payment_aliases() -> None:
95
+ """Forget every registered alias."""
96
+ _custom.clear()
97
+
98
+
99
+ def resolve_payment_status(value: str) -> str | None:
100
+ """Translate a shop's own label into one of the four API values."""
101
+ key = fold_label(value)
102
+ return _custom.get(key) or _BUILT_IN.get(key)
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: ajaflow-sdk
3
+ Version: 1.0.0
4
+ Summary: Python client for the AJA order API: the shop sends its orders and polls the merchant's actions.
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # ajaflow-sdk — SDK Python d’AJA
12
+
13
+ Relie une boutique en ligne à AJA : ses commandes arrivent sur le téléphone du marchand, et les statuts qu'il change reviennent à la boutique.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install ajaflow-sdk
19
+ ```
20
+
21
+ Python 3.9 ou plus. Aucune dépendance. Le paquet s'installe sous le nom `ajaflow-sdk` et s'importe sous le nom `aja`.
22
+
23
+ ## La clé
24
+
25
+ Le marchand crée la clé de sa boutique dans son espace AJA, page **Boutiques**. Gardez-la côté serveur, dans une variable d'environnement : jamais dans le navigateur, jamais dans un dépôt.
26
+
27
+ ```python
28
+ import os
29
+
30
+ from aja import Client
31
+
32
+ aja = Client(api_key=os.environ["AJA_KEY"])
33
+ ```
34
+
35
+ ## Brancher votre site (une fois)
36
+
37
+ Tant que ces deux étapes ne sont pas faites, AJA refuse les commandes de votre site (`SITE_NOT_VERIFIED`) et la page de votre boutique reste « en attente ».
38
+
39
+ **1. Une adresse de réveil.** Une route publique, en https, sur le domaine exact que vous avez indiqué dans AJA (`api.maboutique.sn` si votre serveur est séparé de la vitrine ; « www. » ne compte pas). Une adresse sur un autre domaine est refusée (`domain_mismatch`). AJA l'appelle pour vérifier que ce domaine est bien le vôtre, puis à chaque décision du marchand. Répondez tout de suite : AJA n'attend que quelques secondes. Travaillez ensuite.
40
+
41
+ ```python
42
+ @app.get("/aja/wake")
43
+ def aja_wake():
44
+ params = dict(request.args)
45
+ threading.Thread(target=lambda: (aja.site.handle_wake(params), appliquer_les_decisions())).start()
46
+ return "", 204 # répondre d'abord ; le code part et les décisions s'appliquent ensuite
47
+ ```
48
+
49
+ **2. Se présenter à AJA**, au démarrage de votre serveur : la devise, le fuseau horaire et l'adresse de réveil. AJA appelle aussitôt cette adresse, votre site lui renvoie le code, et le domaine est prouvé, sans rien d'autre à faire.
50
+
51
+ ```python
52
+ aja.site.put_profile(
53
+ currency="XOF",
54
+ timezone="Africa/Dakar",
55
+ wake_url="https://api.maboutique.sn/aja/wake",
56
+ )
57
+ ```
58
+
59
+ ## Envoyer une commande
60
+
61
+ Juste après l'enregistrement de la commande chez vous. Une panne d'AJA ne doit jamais bloquer la vente.
62
+
63
+ ```python
64
+ from aja import AjaError, OrderInput
65
+
66
+ try:
67
+ aja.orders.create(OrderInput(
68
+ external_id=str(order.id),
69
+ status="pending",
70
+ allowed_next=["processing", "cancelled"],
71
+ payment_status="paid",
72
+ payment_mode="wave",
73
+ total=44500,
74
+ currency="XOF",
75
+ customer={"name": "Khadija Ndiaye", "phone": "+221770001122"},
76
+ lines=[{"name": "Ensemble bazin riche", "quantity": 1, "unit_price": 42000}],
77
+ ))
78
+ except AjaError as error:
79
+ logger.warning("AJA: %s", error)
80
+ ```
81
+
82
+ ## Appliquer les décisions du marchand
83
+
84
+ Ce code est votre `appliquer_les_decisions()` : l'adresse de réveil l'appelle à chaque décision du marchand. Une tâche planifiée chaque minute reste un filet de sécurité, si un appel d'AJA se perd :
85
+
86
+ ```bash
87
+ * * * * * python3 /var/www/aja_poll.py
88
+ ```
89
+
90
+ ```python
91
+ from aja import Command
92
+
93
+ for command in aja.commands.pending():
94
+ if command.type != Command.TYPE_ORDER_TRANSITION:
95
+ aja.commands.ack(command.id, ok=False, reason="unsupported_type")
96
+ continue
97
+ status = command.target_status
98
+ try:
99
+ apply_status(command.external_id, status)
100
+ aja.commands.ack(command.id, ok=True, status=status,
101
+ allowed_next=next_statuses(command.external_id))
102
+ except ShopRefusal as refusal:
103
+ aja.commands.ack(command.id, ok=False, reason=str(refusal))
104
+ ```
105
+
106
+ ## Documentation
107
+
108
+ Le guide complet (profil de la boutique, catalogue, montants, erreurs, mise en service) est dans votre espace marchand AJA :
109
+ https://www.ajaflow.com/app/documentation
110
+
111
+ ## Licence
112
+
113
+ MIT
@@ -0,0 +1,11 @@
1
+ aja/__init__.py,sha256=FzcpFBeatlRa9XVsyrohEmhrUM9U4pUgxtFF5nfkbZA,779
2
+ aja/client.py,sha256=zhrd9z3cFPK6ZIz9nsoRSLPyZcmSOZT23v4A8EQOqPA,12414
3
+ aja/errors.py,sha256=MXcikgzXah5zGAC7qeJbYmKj901CsgooPmfmZZm55kM,3418
4
+ aja/models.py,sha256=UYBHBSiP5Hzbz2qNhM_JfkuUbyFhnQ_5rKVpz-8lh5k,4456
5
+ aja/money.py,sha256=WheL9FXBAqlfg-Pocd0UuZU9tTdADqetVsjZEp4VFfg,4390
6
+ aja/payment.py,sha256=_XSHArWqXJpPDtkt1NRkjfgeEZIknygViMGxyI8LYRw,2897
7
+ ajaflow_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=lDQXXhFcw6zqhKv1SOeQWXodQoeRV-ph_SS7s6GUegI,1060
8
+ ajaflow_sdk-1.0.0.dist-info/METADATA,sha256=85dB7LP8gS5R3uJ2JrEqfoab3T7pElRsGN-c5yrAo14,3987
9
+ ajaflow_sdk-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ ajaflow_sdk-1.0.0.dist-info/top_level.txt,sha256=cBaMICWcq2qpmLTJMunvNn80mH6txkhwuf8ccgRAfLM,4
11
+ ajaflow_sdk-1.0.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AJA
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 @@
1
+ aja