python-sedekahje 0.1.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.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-sedekahje
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for the Sedekah.je API
5
+ Author: Zubir Jamal
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/zubirjamal/python-sedekahje
8
+ Project-URL: Repository, https://github.com/zubirjamal/python-sedekahje
9
+ Project-URL: Issues, https://github.com/zubirjamal/python-sedekahje/issues
10
+ Keywords: sedekahje,sedekah,duitnow,qr,masjid,malaysia,home-assistant
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Topic :: Home Automation
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Intended Audience :: Developers
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: aiohttp>=3.9.0
25
+ Requires-Dist: segno>=1.6.0
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest>=8.0.0; extra == "test"
28
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
29
+ Dynamic: license-file
30
+
31
+ # python-sedekahje
32
+
33
+ Asynchronous Python client for the [Sedekah.je](https://sedekah.je) public API, with built-in DuitNow QR PNG rendering.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install python-sedekahje
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```python
44
+ import asyncio
45
+ from sedekahje import SedekahJeClient
46
+
47
+
48
+ async def main() -> None:
49
+ async with SedekahJeClient() as client:
50
+ inst = await client.get_random(state="Selangor", category="masjid")
51
+ print(inst.name, inst.city, inst.state, inst.url)
52
+
53
+ png_bytes = await client.get_qr_png(inst)
54
+ if png_bytes:
55
+ with open("sedekah_qr.png", "wb") as f:
56
+ f.write(png_bytes)
57
+
58
+
59
+ asyncio.run(main())
60
+ ```
61
+
62
+ ## Features
63
+
64
+ - `get_random(state=..., category=...)`: Fetch a random institution (uses `/api/random`, or `/api/institutions?mode=markers` when filtered).
65
+ - `get_institutions(search=..., category=..., state=..., page=..., limit=...)`: Paginated search with `category_counts` facets.
66
+ - `get_markers(search=..., category=..., state=...)`: Flat list of institutions with coordinates.
67
+ - `get_nearest(latitude, longitude, limit=..., state=..., category=...)`: Nearest institutions sorted by Haversine distance.
68
+ - `get_category_counts()`: Directory total and per-category breakdown.
69
+ - `get_qr_png(institution)`: Generates crisp PNG QR bytes from `qr_content` via `segno`, with `qr_image` download fallback.
@@ -0,0 +1,14 @@
1
+ python_sedekahje-0.1.0.dist-info/licenses/LICENSE,sha256=CV9UcjHZBMuVjUPCSgOJpqCp8L0ekkcK1UAomLpdW9Y,1068
2
+ sedekahje/__init__.py,sha256=b4Yt3NOlfnos8Jxw1OTowr1YXjQCzPAVD_5usZOlVDo,609
3
+ sedekahje/__main__.py,sha256=_SKZmZz0RcnrFXHFLe-QAY9y2Ww2_wWOr89hvmvcbiw,140
4
+ sedekahje/cli.py,sha256=UrTCAnUXZFNg4L10VIfrlJ5rM1KvdPZReplc1r-yCPs,2460
5
+ sedekahje/client.py,sha256=lZj7LSlDoegNXz_O9quh0EyiFRDS1RV7H2Bi9ATFxoQ,7778
6
+ sedekahje/constants.py,sha256=eqs4hBJelR0zr9zgIAxuJn5Sf5nIu_EvvWRJZErE5tw,692
7
+ sedekahje/exceptions.py,sha256=BiPIV3CZG9qXBS1Z6_UazfXXtMeGsrgk9ZWL6yGIKW0,379
8
+ sedekahje/models.py,sha256=0_QHQUSLBf7otqPPpb2kxSuwdAmiRMAkNPHwkXZ88Bw,3689
9
+ sedekahje/qr.py,sha256=6d-9c6WuvU4YT_BmnzuX53_TNmWeIeGpl-GcW67xNaY,585
10
+ python_sedekahje-0.1.0.dist-info/METADATA,sha256=Q_esby6e_6gDmKtQarLmEHQFwJ0fa6QlGM0iDEngWzE,2598
11
+ python_sedekahje-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ python_sedekahje-0.1.0.dist-info/entry_points.txt,sha256=sgYexk5BP8EUexwc0vW_v3gFbieR9HWys_QHdBtQZRk,49
13
+ python_sedekahje-0.1.0.dist-info/top_level.txt,sha256=qlmYmC7oZTwWLHdpez2EC6lUaiKo8eizq2rCQ0s-xPU,10
14
+ python_sedekahje-0.1.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,2 @@
1
+ [console_scripts]
2
+ sedekahje = sedekahje.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zubir Jamal
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
+ sedekahje
sedekahje/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Asynchronous Python client for the Sedekah.je API."""
2
+ from __future__ import annotations
3
+
4
+ from .client import SedekahJeClient
5
+ from .constants import CATEGORIES, STATES
6
+ from .exceptions import (
7
+ SedekahJeConnectionError,
8
+ SedekahJeError,
9
+ SedekahJeResponseError,
10
+ )
11
+ from .models import Institution, InstitutionsPage, Pagination
12
+ from .qr import generate_qr_png
13
+
14
+ __all__ = [
15
+ "CATEGORIES",
16
+ "STATES",
17
+ "Institution",
18
+ "InstitutionsPage",
19
+ "Pagination",
20
+ "SedekahJeClient",
21
+ "SedekahJeConnectionError",
22
+ "SedekahJeError",
23
+ "SedekahJeResponseError",
24
+ "generate_qr_png",
25
+ ]
sedekahje/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Allow running `python -m sedekahje`."""
2
+ from __future__ import annotations
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ main()
sedekahje/cli.py ADDED
@@ -0,0 +1,73 @@
1
+ """Command-line interface for python-sedekahje."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ from dataclasses import asdict
8
+
9
+ from .client import SedekahJeClient
10
+
11
+
12
+ async def _run(args: argparse.Namespace) -> None:
13
+ async with SedekahJeClient() as client:
14
+ if args.command == "random":
15
+ inst = await client.get_random(
16
+ state=args.state, category=args.category
17
+ )
18
+ print(json.dumps(asdict(inst), indent=2, ensure_ascii=False))
19
+ elif args.command == "search":
20
+ page = await client.get_institutions(
21
+ search=args.query,
22
+ state=args.state,
23
+ category=args.category,
24
+ limit=args.limit,
25
+ )
26
+ print(
27
+ json.dumps(
28
+ [asdict(i) for i in page.institutions],
29
+ indent=2,
30
+ ensure_ascii=False,
31
+ )
32
+ )
33
+ elif args.command == "nearest":
34
+ items = await client.get_nearest(
35
+ args.lat,
36
+ args.lon,
37
+ limit=args.limit,
38
+ state=args.state,
39
+ category=args.category,
40
+ )
41
+ print(
42
+ json.dumps(
43
+ [asdict(i) for i in items], indent=2, ensure_ascii=False
44
+ )
45
+ )
46
+
47
+
48
+ def main() -> None:
49
+ """Entry point for the sedekahje CLI."""
50
+ parser = argparse.ArgumentParser(
51
+ prog="sedekahje", description="Query the Sedekah.je API"
52
+ )
53
+ sub = parser.add_subparsers(dest="command", required=True)
54
+
55
+ p_rand = sub.add_parser("random", help="Fetch a random institution")
56
+ p_rand.add_argument("--state", default="")
57
+ p_rand.add_argument("--category", default="")
58
+
59
+ p_search = sub.add_parser("search", help="Search institutions")
60
+ p_search.add_argument("query", nargs="?", default="")
61
+ p_search.add_argument("--state", default="")
62
+ p_search.add_argument("--category", default="")
63
+ p_search.add_argument("--limit", type=int, default=5)
64
+
65
+ p_near = sub.add_parser("nearest", help="Find nearest institutions")
66
+ p_near.add_argument("lat", type=float)
67
+ p_near.add_argument("lon", type=float)
68
+ p_near.add_argument("--state", default="")
69
+ p_near.add_argument("--category", default="")
70
+ p_near.add_argument("--limit", type=int, default=5)
71
+
72
+ args = parser.parse_args()
73
+ asyncio.run(_run(args))
sedekahje/client.py ADDED
@@ -0,0 +1,226 @@
1
+ """Asynchronous client for the Sedekah.je API."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import math
6
+ import random
7
+ from typing import Any
8
+
9
+ import aiohttp
10
+
11
+ from .constants import (
12
+ DEFAULT_TIMEOUT_SECONDS,
13
+ DEFAULT_USER_AGENT,
14
+ INSTITUTIONS_URL,
15
+ RANDOM_URL,
16
+ )
17
+ from .exceptions import (
18
+ SedekahJeConnectionError,
19
+ SedekahJeError,
20
+ SedekahJeResponseError,
21
+ )
22
+ from .models import Institution, InstitutionsPage
23
+ from .qr import generate_qr_png
24
+
25
+
26
+ def _haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
27
+ """Compute great-circle distance in kilometers between two coordinates."""
28
+ radius_km = 6371.0
29
+ phi1, phi2 = math.radians(lat1), math.radians(lat2)
30
+ dphi = math.radians(lat2 - lat1)
31
+ dlambda = math.radians(lon2 - lon1)
32
+ a = (
33
+ math.sin(dphi / 2) ** 2
34
+ + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
35
+ )
36
+ return 2 * radius_km * math.atan2(math.sqrt(a), math.sqrt(1 - a))
37
+
38
+
39
+ class SedekahJeClient:
40
+ """Async client for querying Sedekah.je institutions and QR codes."""
41
+
42
+ def __init__(
43
+ self,
44
+ session: aiohttp.ClientSession | None = None,
45
+ *,
46
+ timeout: int = DEFAULT_TIMEOUT_SECONDS,
47
+ user_agent: str = DEFAULT_USER_AGENT,
48
+ ) -> None:
49
+ self._session = session
50
+ self._owns_session = session is None
51
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
52
+ self._user_agent = user_agent
53
+
54
+ async def __aenter__(self) -> SedekahJeClient:
55
+ if self._session is None:
56
+ self._session = aiohttp.ClientSession(timeout=self._timeout)
57
+ return self
58
+
59
+ async def __aexit__(self, *args: object) -> None:
60
+ await self.close()
61
+
62
+ async def close(self) -> None:
63
+ """Close the internally managed aiohttp session, if any."""
64
+ if self._owns_session and self._session is not None:
65
+ await self._session.close()
66
+ self._session = None
67
+
68
+ def _ensure_session(self) -> aiohttp.ClientSession:
69
+ if self._session is None:
70
+ self._session = aiohttp.ClientSession(timeout=self._timeout)
71
+ self._owns_session = True
72
+ return self._session
73
+
74
+ async def _get_json(
75
+ self, url: str, params: dict[str, Any] | None = None
76
+ ) -> Any:
77
+ session = self._ensure_session()
78
+ headers = {"User-Agent": self._user_agent, "Accept": "application/json"}
79
+ clean_params = (
80
+ {k: v for k, v in params.items() if v is not None and v != ""}
81
+ if params
82
+ else None
83
+ )
84
+ try:
85
+ async with session.get(
86
+ url, params=clean_params, headers=headers, timeout=self._timeout
87
+ ) as resp:
88
+ if resp.status != 200:
89
+ raise SedekahJeResponseError(
90
+ f"Sedekah.je returned HTTP {resp.status} for {resp.url}"
91
+ )
92
+ try:
93
+ return await resp.json()
94
+ except (aiohttp.ContentTypeError, ValueError) as err:
95
+ raise SedekahJeResponseError(
96
+ f"Invalid JSON from Sedekah.je: {err}"
97
+ ) from err
98
+ except (aiohttp.ClientError, asyncio.TimeoutError) as err:
99
+ raise SedekahJeConnectionError(
100
+ f"Failed to connect to Sedekah.je: {err}"
101
+ ) from err
102
+
103
+ async def get_random(
104
+ self,
105
+ *,
106
+ state: str = "",
107
+ category: str = "",
108
+ ) -> Institution:
109
+ """Fetch a random institution, optionally filtered by state or category."""
110
+ if state or category:
111
+ markers = await self.get_markers(state=state, category=category)
112
+ if not markers:
113
+ raise SedekahJeError(
114
+ f"No institutions found for state={state!r}, category={category!r}"
115
+ )
116
+ return random.choice(markers)
117
+
118
+ data = await self._get_json(RANDOM_URL)
119
+ if not isinstance(data, dict) or "id" not in data:
120
+ raise SedekahJeResponseError("Unexpected payload from /api/random")
121
+ return Institution.from_dict(data)
122
+
123
+ async def get_institutions(
124
+ self,
125
+ *,
126
+ search: str = "",
127
+ category: str = "",
128
+ state: str = "",
129
+ page: int = 1,
130
+ limit: int = 15,
131
+ ) -> InstitutionsPage:
132
+ """Fetch a paginated list of institutions and category facets."""
133
+ data = await self._get_json(
134
+ INSTITUTIONS_URL,
135
+ params={
136
+ "search": search,
137
+ "category": category,
138
+ "state": state,
139
+ "mode": "page",
140
+ "page": page,
141
+ "limit": limit,
142
+ },
143
+ )
144
+ if not isinstance(data, dict):
145
+ raise SedekahJeResponseError("Unexpected payload from /api/institutions")
146
+ return InstitutionsPage.from_dict(data)
147
+
148
+ async def get_markers(
149
+ self,
150
+ *,
151
+ search: str = "",
152
+ category: str = "",
153
+ state: str = "",
154
+ ) -> list[Institution]:
155
+ """Fetch all matching institutions (flat list with coordinates)."""
156
+ data = await self._get_json(
157
+ INSTITUTIONS_URL,
158
+ params={
159
+ "search": search,
160
+ "category": category,
161
+ "state": state,
162
+ "mode": "markers",
163
+ },
164
+ )
165
+ if not isinstance(data, list):
166
+ raise SedekahJeResponseError(
167
+ "Expected list payload from /api/institutions?mode=markers"
168
+ )
169
+ return [Institution.from_dict(item) for item in data]
170
+
171
+ async def get_nearest(
172
+ self,
173
+ latitude: float,
174
+ longitude: float,
175
+ *,
176
+ limit: int = 5,
177
+ state: str = "",
178
+ category: str = "",
179
+ ) -> list[Institution]:
180
+ """Find the nearest institutions to the given coordinates."""
181
+ markers = await self.get_markers(state=state, category=category)
182
+ with_distance: list[Institution] = []
183
+ for inst in markers:
184
+ if inst.latitude is None or inst.longitude is None:
185
+ continue
186
+ inst.distance_km = round(
187
+ _haversine_km(latitude, longitude, inst.latitude, inst.longitude), 2
188
+ )
189
+ with_distance.append(inst)
190
+ with_distance.sort(key=lambda item: item.distance_km or 0.0)
191
+ return with_distance[:limit]
192
+
193
+ async def get_category_counts(self) -> tuple[int, dict[str, int]]:
194
+ """Return (total_count, category_counts) from the directory facets."""
195
+ page = await self.get_institutions(page=1, limit=1)
196
+ return page.pagination.total, page.category_counts
197
+
198
+ async def get_qr_png(
199
+ self,
200
+ institution: Institution,
201
+ *,
202
+ scale: int = 8,
203
+ border: int = 2,
204
+ ) -> bytes | None:
205
+ """Return PNG bytes for an institution's QR code.
206
+
207
+ Prefers generating a crisp local QR from ``qr_content``; falls back to
208
+ downloading ``qr_image`` when ``qr_content`` is unavailable.
209
+ """
210
+ if institution.qr_content:
211
+ return generate_qr_png(
212
+ institution.qr_content, scale=scale, border=border
213
+ )
214
+ if institution.qr_image:
215
+ session = self._ensure_session()
216
+ try:
217
+ async with session.get(
218
+ institution.qr_image, timeout=self._timeout
219
+ ) as resp:
220
+ if resp.status == 200:
221
+ return await resp.read()
222
+ except (aiohttp.ClientError, asyncio.TimeoutError) as err:
223
+ raise SedekahJeConnectionError(
224
+ f"Failed to download QR image: {err}"
225
+ ) from err
226
+ return None
sedekahje/constants.py ADDED
@@ -0,0 +1,36 @@
1
+ """Constants for the Sedekah.je client library."""
2
+ from __future__ import annotations
3
+
4
+ BASE_URL = "https://sedekah.je"
5
+ INSTITUTIONS_URL = f"{BASE_URL}/api/institutions"
6
+ RANDOM_URL = f"{BASE_URL}/api/random"
7
+
8
+ DEFAULT_TIMEOUT_SECONDS = 15
9
+ DEFAULT_USER_AGENT = "python-sedekahje/0.1.0"
10
+
11
+ CATEGORIES: tuple[str, ...] = (
12
+ "masjid",
13
+ "surau",
14
+ "tahfiz",
15
+ "kebajikan",
16
+ "lain-lain",
17
+ )
18
+
19
+ STATES: tuple[str, ...] = (
20
+ "Johor",
21
+ "Kedah",
22
+ "Kelantan",
23
+ "Melaka",
24
+ "Negeri Sembilan",
25
+ "Pahang",
26
+ "Perak",
27
+ "Perlis",
28
+ "Pulau Pinang",
29
+ "Sabah",
30
+ "Sarawak",
31
+ "Selangor",
32
+ "Terengganu",
33
+ "W.P. Kuala Lumpur",
34
+ "W.P. Labuan",
35
+ "W.P. Putrajaya",
36
+ )
@@ -0,0 +1,14 @@
1
+ """Exceptions for the Sedekah.je client library."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class SedekahJeError(Exception):
6
+ """Base exception for Sedekah.je API errors."""
7
+
8
+
9
+ class SedekahJeConnectionError(SedekahJeError):
10
+ """Network connection or timeout failure."""
11
+
12
+
13
+ class SedekahJeResponseError(SedekahJeError):
14
+ """Unexpected HTTP status or invalid JSON payload."""
sedekahje/models.py ADDED
@@ -0,0 +1,112 @@
1
+ """Data models for the Sedekah.je client library."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Any
6
+
7
+ from .constants import BASE_URL
8
+
9
+
10
+ @dataclass(slots=True)
11
+ class Institution:
12
+ """Represents a mosque, surau, tahfiz, or welfare institution on Sedekah.je."""
13
+
14
+ id: int
15
+ name: str
16
+ category: str
17
+ state: str
18
+ city: str
19
+ slug: str | None = None
20
+ description: str | None = None
21
+ qr_image: str | None = None
22
+ qr_content: str | None = None
23
+ supported_payment: list[str] = field(default_factory=list)
24
+ latitude: float | None = None
25
+ longitude: float | None = None
26
+ distance_km: float | None = None
27
+
28
+ @property
29
+ def url(self) -> str:
30
+ """Return the canonical Sedekah.je page URL for this institution."""
31
+ if self.slug:
32
+ return f"{BASE_URL}/{self.category}/{self.slug}"
33
+ return BASE_URL
34
+
35
+ @classmethod
36
+ def from_dict(cls, data: dict[str, Any]) -> Institution:
37
+ """Create an Institution instance from a Sedekah.je API JSON object."""
38
+ coords = data.get("coords")
39
+ lat: float | None = None
40
+ lon: float | None = None
41
+ if isinstance(coords, (list, tuple)) and len(coords) >= 2:
42
+ try:
43
+ lat = float(coords[0]) if coords[0] is not None else None
44
+ lon = float(coords[1]) if coords[1] is not None else None
45
+ except (TypeError, ValueError):
46
+ lat = None
47
+ lon = None
48
+
49
+ payments = data.get("supportedPayment") or []
50
+ if not isinstance(payments, list):
51
+ payments = []
52
+
53
+ return cls(
54
+ id=int(data["id"]),
55
+ name=str(data.get("name") or "").strip(),
56
+ slug=data.get("slug"),
57
+ description=data.get("description"),
58
+ category=str(data.get("category") or "").strip(),
59
+ state=str(data.get("state") or "").strip(),
60
+ city=str(data.get("city") or "").strip(),
61
+ qr_image=data.get("qrImage"),
62
+ qr_content=data.get("qrContent"),
63
+ supported_payment=[str(p) for p in payments],
64
+ latitude=lat,
65
+ longitude=lon,
66
+ )
67
+
68
+
69
+ @dataclass(slots=True)
70
+ class Pagination:
71
+ """Pagination metadata returned by /api/institutions."""
72
+
73
+ page: int
74
+ limit: int
75
+ total: int
76
+ has_more: bool
77
+ total_pages: int
78
+
79
+ @classmethod
80
+ def from_dict(cls, data: dict[str, Any]) -> Pagination:
81
+ """Create a Pagination instance from API JSON."""
82
+ return cls(
83
+ page=int(data.get("page", 1)),
84
+ limit=int(data.get("limit", 15)),
85
+ total=int(data.get("total", 0)),
86
+ has_more=bool(data.get("hasMore", False)),
87
+ total_pages=int(data.get("totalPages", 1)),
88
+ )
89
+
90
+
91
+ @dataclass(slots=True)
92
+ class InstitutionsPage:
93
+ """Paginated response from /api/institutions."""
94
+
95
+ institutions: list[Institution]
96
+ pagination: Pagination
97
+ category_counts: dict[str, int] = field(default_factory=dict)
98
+
99
+ @classmethod
100
+ def from_dict(cls, data: dict[str, Any]) -> InstitutionsPage:
101
+ """Create an InstitutionsPage from API JSON."""
102
+ raw_items = data.get("institutions") or []
103
+ institutions = [Institution.from_dict(item) for item in raw_items]
104
+ pagination = Pagination.from_dict(data.get("pagination") or {})
105
+ facets = data.get("facets") or {}
106
+ raw_counts = facets.get("categoryCounts") or {}
107
+ category_counts = {str(k): int(v) for k, v in raw_counts.items()}
108
+ return cls(
109
+ institutions=institutions,
110
+ pagination=pagination,
111
+ category_counts=category_counts,
112
+ )
sedekahje/qr.py ADDED
@@ -0,0 +1,23 @@
1
+ """QR code rendering helpers for Sedekah.je."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+
6
+ import segno
7
+
8
+
9
+ def generate_qr_png(
10
+ content: str,
11
+ *,
12
+ scale: int = 8,
13
+ border: int = 2,
14
+ dark: str = "#000000",
15
+ light: str = "#FFFFFF",
16
+ ) -> bytes:
17
+ """Render a QR payload string (e.g. DuitNow EMVCo) into PNG bytes."""
18
+ if not content:
19
+ raise ValueError("QR content must not be empty")
20
+ qr = segno.make(content, error="m")
21
+ buf = io.BytesIO()
22
+ qr.save(buf, kind="png", scale=scale, border=border, dark=dark, light=light)
23
+ return buf.getvalue()