python-sedekahje 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.
- python_sedekahje-0.1.0/LICENSE +21 -0
- python_sedekahje-0.1.0/PKG-INFO +69 -0
- python_sedekahje-0.1.0/README.md +39 -0
- python_sedekahje-0.1.0/pyproject.toml +54 -0
- python_sedekahje-0.1.0/setup.cfg +4 -0
- python_sedekahje-0.1.0/src/python_sedekahje.egg-info/PKG-INFO +69 -0
- python_sedekahje-0.1.0/src/python_sedekahje.egg-info/SOURCES.txt +18 -0
- python_sedekahje-0.1.0/src/python_sedekahje.egg-info/dependency_links.txt +1 -0
- python_sedekahje-0.1.0/src/python_sedekahje.egg-info/entry_points.txt +2 -0
- python_sedekahje-0.1.0/src/python_sedekahje.egg-info/requires.txt +6 -0
- python_sedekahje-0.1.0/src/python_sedekahje.egg-info/top_level.txt +1 -0
- python_sedekahje-0.1.0/src/sedekahje/__init__.py +25 -0
- python_sedekahje-0.1.0/src/sedekahje/__main__.py +7 -0
- python_sedekahje-0.1.0/src/sedekahje/cli.py +73 -0
- python_sedekahje-0.1.0/src/sedekahje/client.py +226 -0
- python_sedekahje-0.1.0/src/sedekahje/constants.py +36 -0
- python_sedekahje-0.1.0/src/sedekahje/exceptions.py +14 -0
- python_sedekahje-0.1.0/src/sedekahje/models.py +112 -0
- python_sedekahje-0.1.0/src/sedekahje/qr.py +23 -0
- python_sedekahje-0.1.0/tests/test_client.py +131 -0
|
@@ -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,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,39 @@
|
|
|
1
|
+
# python-sedekahje
|
|
2
|
+
|
|
3
|
+
Asynchronous Python client for the [Sedekah.je](https://sedekah.je) public API, with built-in DuitNow QR PNG rendering.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install python-sedekahje
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import asyncio
|
|
15
|
+
from sedekahje import SedekahJeClient
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def main() -> None:
|
|
19
|
+
async with SedekahJeClient() as client:
|
|
20
|
+
inst = await client.get_random(state="Selangor", category="masjid")
|
|
21
|
+
print(inst.name, inst.city, inst.state, inst.url)
|
|
22
|
+
|
|
23
|
+
png_bytes = await client.get_qr_png(inst)
|
|
24
|
+
if png_bytes:
|
|
25
|
+
with open("sedekah_qr.png", "wb") as f:
|
|
26
|
+
f.write(png_bytes)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
asyncio.run(main())
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Features
|
|
33
|
+
|
|
34
|
+
- `get_random(state=..., category=...)`: Fetch a random institution (uses `/api/random`, or `/api/institutions?mode=markers` when filtered).
|
|
35
|
+
- `get_institutions(search=..., category=..., state=..., page=..., limit=...)`: Paginated search with `category_counts` facets.
|
|
36
|
+
- `get_markers(search=..., category=..., state=...)`: Flat list of institutions with coordinates.
|
|
37
|
+
- `get_nearest(latitude, longitude, limit=..., state=..., category=...)`: Nearest institutions sorted by Haversine distance.
|
|
38
|
+
- `get_category_counts()`: Directory total and per-category breakdown.
|
|
39
|
+
- `get_qr_png(institution)`: Generates crisp PNG QR bytes from `qr_content` via `segno`, with `qr_image` download fallback.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "python-sedekahje"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Asynchronous Python client for the Sedekah.je API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Zubir Jamal" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["sedekahje", "sedekah", "duitnow", "qr", "masjid", "malaysia", "home-assistant"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"License :: OSI Approved :: MIT License",
|
|
23
|
+
"Operating System :: OS Independent",
|
|
24
|
+
"Topic :: Home Automation",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"aiohttp>=3.9.0",
|
|
30
|
+
"segno>=1.6.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
test = [
|
|
35
|
+
"pytest>=8.0.0",
|
|
36
|
+
"pytest-asyncio>=0.23.0",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/zubirjamal/python-sedekahje"
|
|
41
|
+
Repository = "https://github.com/zubirjamal/python-sedekahje"
|
|
42
|
+
Issues = "https://github.com/zubirjamal/python-sedekahje/issues"
|
|
43
|
+
|
|
44
|
+
[project.scripts]
|
|
45
|
+
sedekahje = "sedekahje.cli:main"
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.packages.find]
|
|
48
|
+
where = ["src"]
|
|
49
|
+
|
|
50
|
+
[tool.pytest.ini_options]
|
|
51
|
+
asyncio_mode = "auto"
|
|
52
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
53
|
+
pythonpath = ["src"]
|
|
54
|
+
testpaths = ["tests"]
|
|
@@ -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,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/python_sedekahje.egg-info/PKG-INFO
|
|
5
|
+
src/python_sedekahje.egg-info/SOURCES.txt
|
|
6
|
+
src/python_sedekahje.egg-info/dependency_links.txt
|
|
7
|
+
src/python_sedekahje.egg-info/entry_points.txt
|
|
8
|
+
src/python_sedekahje.egg-info/requires.txt
|
|
9
|
+
src/python_sedekahje.egg-info/top_level.txt
|
|
10
|
+
src/sedekahje/__init__.py
|
|
11
|
+
src/sedekahje/__main__.py
|
|
12
|
+
src/sedekahje/cli.py
|
|
13
|
+
src/sedekahje/client.py
|
|
14
|
+
src/sedekahje/constants.py
|
|
15
|
+
src/sedekahje/exceptions.py
|
|
16
|
+
src/sedekahje/models.py
|
|
17
|
+
src/sedekahje/qr.py
|
|
18
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sedekahje
|
|
@@ -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
|
+
]
|
|
@@ -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))
|
|
@@ -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
|
|
@@ -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."""
|
|
@@ -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
|
+
)
|
|
@@ -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()
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Unit tests for python-sedekahje."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any
|
|
5
|
+
from unittest.mock import AsyncMock, MagicMock
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from sedekahje import (
|
|
10
|
+
Institution,
|
|
11
|
+
SedekahJeClient,
|
|
12
|
+
SedekahJeResponseError,
|
|
13
|
+
generate_qr_png,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
SAMPLE_INSTITUTION = {
|
|
17
|
+
"id": 2688,
|
|
18
|
+
"name": "Masjid Jamiatul Islamiah",
|
|
19
|
+
"slug": "masjid-jamiatul-islamiah",
|
|
20
|
+
"description": None,
|
|
21
|
+
"category": "masjid",
|
|
22
|
+
"state": "Selangor",
|
|
23
|
+
"city": "Teluk Panglima Garang",
|
|
24
|
+
"qrImage": "https://example.com/qr.jpg",
|
|
25
|
+
"qrContent": "00020201021126420014A000000615000101066033460210MD00140522",
|
|
26
|
+
"supportedPayment": ["duitnow"],
|
|
27
|
+
"coords": [2.9302265, 101.4726872],
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _mock_session(payload: Any, status: int = 200) -> MagicMock:
|
|
32
|
+
resp = AsyncMock()
|
|
33
|
+
resp.status = status
|
|
34
|
+
resp.url = "https://sedekah.je/api/test"
|
|
35
|
+
resp.json = AsyncMock(return_value=payload)
|
|
36
|
+
resp.__aenter__ = AsyncMock(return_value=resp)
|
|
37
|
+
resp.__aexit__ = AsyncMock(return_value=False)
|
|
38
|
+
|
|
39
|
+
session = MagicMock()
|
|
40
|
+
session.get = MagicMock(return_value=resp)
|
|
41
|
+
return session
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_institution_model_and_url() -> None:
|
|
45
|
+
inst = Institution.from_dict(SAMPLE_INSTITUTION)
|
|
46
|
+
assert inst.id == 2688
|
|
47
|
+
assert inst.name == "Masjid Jamiatul Islamiah"
|
|
48
|
+
assert inst.latitude == pytest.approx(2.9302265)
|
|
49
|
+
assert inst.longitude == pytest.approx(101.4726872)
|
|
50
|
+
assert inst.supported_payment == ["duitnow"]
|
|
51
|
+
assert inst.url == "https://sedekah.je/masjid/masjid-jamiatul-islamiah"
|
|
52
|
+
|
|
53
|
+
no_slug = Institution.from_dict({**SAMPLE_INSTITUTION, "slug": None})
|
|
54
|
+
assert no_slug.url == "https://sedekah.je"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_generate_qr_png() -> None:
|
|
58
|
+
png = generate_qr_png(SAMPLE_INSTITUTION["qrContent"])
|
|
59
|
+
assert png.startswith(b"\x89PNG\r\n\x1a\n")
|
|
60
|
+
assert len(png) > 100
|
|
61
|
+
|
|
62
|
+
with pytest.raises(ValueError):
|
|
63
|
+
generate_qr_png("")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def test_get_random_unfiltered() -> None:
|
|
67
|
+
session = _mock_session(SAMPLE_INSTITUTION)
|
|
68
|
+
client = SedekahJeClient(session=session)
|
|
69
|
+
inst = await client.get_random()
|
|
70
|
+
assert inst.id == 2688
|
|
71
|
+
session.get.assert_called_once()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def test_get_random_filtered() -> None:
|
|
75
|
+
session = _mock_session([SAMPLE_INSTITUTION])
|
|
76
|
+
client = SedekahJeClient(session=session)
|
|
77
|
+
inst = await client.get_random(state="Selangor", category="masjid")
|
|
78
|
+
assert inst.id == 2688
|
|
79
|
+
_, kwargs = session.get.call_args
|
|
80
|
+
assert kwargs["params"]["mode"] == "markers"
|
|
81
|
+
assert kwargs["params"]["state"] == "Selangor"
|
|
82
|
+
assert kwargs["params"]["category"] == "masjid"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def test_get_institutions_page() -> None:
|
|
86
|
+
payload = {
|
|
87
|
+
"institutions": [SAMPLE_INSTITUTION],
|
|
88
|
+
"pagination": {
|
|
89
|
+
"page": 1,
|
|
90
|
+
"limit": 1,
|
|
91
|
+
"total": 2412,
|
|
92
|
+
"hasMore": True,
|
|
93
|
+
"totalPages": 2412,
|
|
94
|
+
},
|
|
95
|
+
"facets": {
|
|
96
|
+
"categoryCounts": {"masjid": 1412, "surau": 673},
|
|
97
|
+
},
|
|
98
|
+
}
|
|
99
|
+
session = _mock_session(payload)
|
|
100
|
+
client = SedekahJeClient(session=session)
|
|
101
|
+
page = await client.get_institutions(limit=1)
|
|
102
|
+
assert page.pagination.total == 2412
|
|
103
|
+
assert page.category_counts["masjid"] == 1412
|
|
104
|
+
assert len(page.institutions) == 1
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def test_get_nearest_sorts_by_distance() -> None:
|
|
108
|
+
far = {**SAMPLE_INSTITUTION, "id": 1, "name": "Far", "coords": [3.5, 102.0]}
|
|
109
|
+
near = {**SAMPLE_INSTITUTION, "id": 2, "name": "Near", "coords": [2.99, 101.79]}
|
|
110
|
+
session = _mock_session([far, near])
|
|
111
|
+
client = SedekahJeClient(session=session)
|
|
112
|
+
|
|
113
|
+
results = await client.get_nearest(2.992, 101.791, limit=2)
|
|
114
|
+
assert [r.name for r in results] == ["Near", "Far"]
|
|
115
|
+
assert results[0].distance_km is not None
|
|
116
|
+
assert results[0].distance_km < results[1].distance_km
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def test_get_qr_png_from_content() -> None:
|
|
120
|
+
client = SedekahJeClient(session=_mock_session({}))
|
|
121
|
+
inst = Institution.from_dict(SAMPLE_INSTITUTION)
|
|
122
|
+
png = await client.get_qr_png(inst)
|
|
123
|
+
assert png is not None
|
|
124
|
+
assert png.startswith(b"\x89PNG\r\n\x1a\n")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
async def test_http_error_raises_response_error() -> None:
|
|
128
|
+
session = _mock_session({}, status=500)
|
|
129
|
+
client = SedekahJeClient(session=session)
|
|
130
|
+
with pytest.raises(SedekahJeResponseError):
|
|
131
|
+
await client.get_random()
|