fajfield-reports 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fajfield
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,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: fajfield-reports
3
+ Version: 0.1.0
4
+ Summary: Render invoices and multi-page reports from Fajfield templates (.fjt) to PDF from Python, through a self-hosted Fajfield report server. RDLC-style reports without Windows.
5
+ Author: Fajfield
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://fajfield.com/developers/reports/
8
+ Project-URL: Source, https://github.com/Fajfield/fajfield-reports-python
9
+ Project-URL: Issues, https://github.com/Fajfield/fajfield-reports-python/issues
10
+ Project-URL: Designer, https://fajfield.com/designer/report/
11
+ Keywords: pdf,report,invoice,rdlc,crystal-reports,erp,django,flask,fastapi
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Office/Business
14
+ Classifier: Topic :: Printing
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # fajfield-reports (Python)
22
+
23
+ Render invoices, statements and multi-page reports to **PDF from Python**: Django, Flask, FastAPI, Odoo add-ons, scripts and scheduled jobs. Design the template in the free [Fajfield report designer](https://fajfield.com/designer/report/), export it as `.fjt`, and render it with your data.
24
+
25
+ Think *RDLC or Crystal Reports for Python*, without Windows. Tables continue across pages with the header repeated, groups get subtotals, and "Page 2 of 5" is always right.
26
+
27
+ The package talks to a **[Fajfield report server](https://github.com/Fajfield/fajfield-reports-server)** you run yourself, so your data stays on your network. No dependencies: only the Python standard library.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pip install fajfield-reports
33
+ ```
34
+
35
+ Start a report server (once, on any machine your app can reach):
36
+
37
+ ```sh
38
+ docker run -p 8080:8080 -e API_KEYS=change-me -v ./templates:/templates fajfield/reports-server
39
+ # or, with Node 18+:
40
+ npx @fajfield/reports-server serve --templates ./templates
41
+ ```
42
+
43
+ ## Render a report
44
+
45
+ ```python
46
+ from fajfield_reports import ReportClient
47
+
48
+ client = ReportClient("http://localhost:8080", api_key="change-me")
49
+
50
+ client.render_to_file("invoice", {
51
+ "company": {"name": "Harbour Foods Co."},
52
+ "customer": {"name": "Fresh Mart", "address": "Dubai"},
53
+ "invoice": {"no": "INV-0452", "date": date.today()},
54
+ "items": [{"name": l.product, "qty": l.qty, "rate": l.price, "taxRate": 0.05} for l in order.lines],
55
+ }, "invoice.pdf")
56
+ ```
57
+
58
+ - **Template:** the name of a template stored on the server (`"invoice"`), a path to a `.fjt` file, or the template as a dict.
59
+ - **Data:** one key per dataset in the template: a list for rows, a dict for single records. `Decimal`, `date`, `datetime`, `UUID`, dataclasses and named tuples are converted for you.
60
+
61
+ ### Django
62
+
63
+ ```python
64
+ from django.http import HttpResponse
65
+
66
+ def invoice_pdf(request, pk):
67
+ pdf = client.render("invoice", invoice_data(pk))
68
+ return HttpResponse(pdf, content_type="application/pdf")
69
+ ```
70
+
71
+ ### FastAPI
72
+
73
+ ```python
74
+ from fastapi.responses import Response
75
+
76
+ @app.get("/invoices/{pk}.pdf")
77
+ def invoice_pdf(pk: int):
78
+ return Response(client.render("invoice", invoice_data(pk)), media_type="application/pdf")
79
+ ```
80
+
81
+ ## Warnings and errors
82
+
83
+ ```python
84
+ r = client.render_result("invoice", data)
85
+ r.pdf, r.pages, r.warnings # e.g. ['No data for "customer". Pass it as data: { customer: { ... } }.']
86
+ ```
87
+
88
+ Problems the report can live with (missing data, bad barcode data) come back as `warnings`; the PDF is still made. Real errors raise `ReportError` with a plain message and the HTTP status: 400 bad request or template, 401 wrong API key, 404 unknown template, 0 server not reachable.
89
+
90
+ ## Settings
91
+
92
+ `ReportClient()` with no arguments reads `FAJFIELD_REPORTS_URL` (default `http://localhost:8080`) and `FAJFIELD_REPORTS_KEY` from the environment.
93
+
94
+ ## Also from Fajfield
95
+
96
+ [Report designer](https://fajfield.com/designer/report/) · [JavaScript](https://www.npmjs.com/package/@fajfield/reports) · [Flutter](https://pub.dev/packages/fajfield_reports_flutter) · [.NET](https://www.nuget.org/packages/Fajfield.Reports) · [Report server](https://github.com/Fajfield/fajfield-reports-server)
97
+
98
+ MIT license. Made by [Fajfield](https://fajfield.com): research and development for ERP, warehouse, POS and business data.
@@ -0,0 +1,78 @@
1
+ # fajfield-reports (Python)
2
+
3
+ Render invoices, statements and multi-page reports to **PDF from Python**: Django, Flask, FastAPI, Odoo add-ons, scripts and scheduled jobs. Design the template in the free [Fajfield report designer](https://fajfield.com/designer/report/), export it as `.fjt`, and render it with your data.
4
+
5
+ Think *RDLC or Crystal Reports for Python*, without Windows. Tables continue across pages with the header repeated, groups get subtotals, and "Page 2 of 5" is always right.
6
+
7
+ The package talks to a **[Fajfield report server](https://github.com/Fajfield/fajfield-reports-server)** you run yourself, so your data stays on your network. No dependencies: only the Python standard library.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pip install fajfield-reports
13
+ ```
14
+
15
+ Start a report server (once, on any machine your app can reach):
16
+
17
+ ```sh
18
+ docker run -p 8080:8080 -e API_KEYS=change-me -v ./templates:/templates fajfield/reports-server
19
+ # or, with Node 18+:
20
+ npx @fajfield/reports-server serve --templates ./templates
21
+ ```
22
+
23
+ ## Render a report
24
+
25
+ ```python
26
+ from fajfield_reports import ReportClient
27
+
28
+ client = ReportClient("http://localhost:8080", api_key="change-me")
29
+
30
+ client.render_to_file("invoice", {
31
+ "company": {"name": "Harbour Foods Co."},
32
+ "customer": {"name": "Fresh Mart", "address": "Dubai"},
33
+ "invoice": {"no": "INV-0452", "date": date.today()},
34
+ "items": [{"name": l.product, "qty": l.qty, "rate": l.price, "taxRate": 0.05} for l in order.lines],
35
+ }, "invoice.pdf")
36
+ ```
37
+
38
+ - **Template:** the name of a template stored on the server (`"invoice"`), a path to a `.fjt` file, or the template as a dict.
39
+ - **Data:** one key per dataset in the template: a list for rows, a dict for single records. `Decimal`, `date`, `datetime`, `UUID`, dataclasses and named tuples are converted for you.
40
+
41
+ ### Django
42
+
43
+ ```python
44
+ from django.http import HttpResponse
45
+
46
+ def invoice_pdf(request, pk):
47
+ pdf = client.render("invoice", invoice_data(pk))
48
+ return HttpResponse(pdf, content_type="application/pdf")
49
+ ```
50
+
51
+ ### FastAPI
52
+
53
+ ```python
54
+ from fastapi.responses import Response
55
+
56
+ @app.get("/invoices/{pk}.pdf")
57
+ def invoice_pdf(pk: int):
58
+ return Response(client.render("invoice", invoice_data(pk)), media_type="application/pdf")
59
+ ```
60
+
61
+ ## Warnings and errors
62
+
63
+ ```python
64
+ r = client.render_result("invoice", data)
65
+ r.pdf, r.pages, r.warnings # e.g. ['No data for "customer". Pass it as data: { customer: { ... } }.']
66
+ ```
67
+
68
+ Problems the report can live with (missing data, bad barcode data) come back as `warnings`; the PDF is still made. Real errors raise `ReportError` with a plain message and the HTTP status: 400 bad request or template, 401 wrong API key, 404 unknown template, 0 server not reachable.
69
+
70
+ ## Settings
71
+
72
+ `ReportClient()` with no arguments reads `FAJFIELD_REPORTS_URL` (default `http://localhost:8080`) and `FAJFIELD_REPORTS_KEY` from the environment.
73
+
74
+ ## Also from Fajfield
75
+
76
+ [Report designer](https://fajfield.com/designer/report/) · [JavaScript](https://www.npmjs.com/package/@fajfield/reports) · [Flutter](https://pub.dev/packages/fajfield_reports_flutter) · [.NET](https://www.nuget.org/packages/Fajfield.Reports) · [Report server](https://github.com/Fajfield/fajfield-reports-server)
77
+
78
+ MIT license. Made by [Fajfield](https://fajfield.com): research and development for ERP, warehouse, POS and business data.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fajfield-reports"
7
+ version = "0.1.0"
8
+ description = "Render invoices and multi-page reports from Fajfield templates (.fjt) to PDF from Python, through a self-hosted Fajfield report server. RDLC-style reports without Windows."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Fajfield" }]
13
+ requires-python = ">=3.8"
14
+ dependencies = []
15
+ keywords = ["pdf", "report", "invoice", "rdlc", "crystal-reports", "erp", "django", "flask", "fastapi"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Office/Business",
19
+ "Topic :: Printing",
20
+ "Intended Audience :: Developers",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://fajfield.com/developers/reports/"
25
+ Source = "https://github.com/Fajfield/fajfield-reports-python"
26
+ Issues = "https://github.com/Fajfield/fajfield-reports-python/issues"
27
+ Designer = "https://fajfield.com/designer/report/"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,14 @@
1
+ """Fajfield reports for Python: render Fajfield report templates (.fjt) to PDF through a Fajfield report server.
2
+
3
+ from fajfield_reports import ReportClient
4
+
5
+ client = ReportClient("http://localhost:8080", api_key="change-me")
6
+ client.render_to_file("invoice", {"invoice": {"no": "INV-0452"}, "items": items}, "invoice.pdf")
7
+
8
+ Run the server with Docker or `npx @fajfield/reports-server serve`. Design templates at
9
+ https://fajfield.com/designer/report/
10
+ """
11
+ from .client import ReportClient, RenderResult, ReportError
12
+
13
+ __all__ = ["ReportClient", "RenderResult", "ReportError"]
14
+ __version__ = "0.1.0"
@@ -0,0 +1,129 @@
1
+ """A small client for the Fajfield report server. No dependencies: only the Python standard library."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import datetime as _dt
6
+ import decimal
7
+ import json
8
+ import os
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ import uuid
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import Any, Mapping, Optional, Union
16
+
17
+ Template = Union[str, Path, Mapping[str, Any]]
18
+
19
+
20
+ class ReportError(Exception):
21
+ """The server could not render the report. `message` says what to fix; `status` is the HTTP status (0 if the server could not be reached)."""
22
+
23
+ def __init__(self, status: int, message: str):
24
+ super().__init__(f"{message} (HTTP {status})" if status else message)
25
+ self.status = status
26
+ self.message = message
27
+
28
+
29
+ @dataclass
30
+ class RenderResult:
31
+ pdf: bytes
32
+ pages: int
33
+ warnings: list = field(default_factory=list)
34
+ ms: int = 0
35
+
36
+ def save(self, path: Union[str, Path]) -> Path:
37
+ p = Path(path)
38
+ p.write_bytes(self.pdf)
39
+ return p
40
+
41
+
42
+ def _plain(o: Any) -> Any:
43
+ """Makes typical ERP values JSON-friendly: Decimal, date and datetime, UUID, sets, dataclasses and objects."""
44
+ if isinstance(o, decimal.Decimal):
45
+ return float(o)
46
+ if isinstance(o, (_dt.datetime, _dt.date, _dt.time)):
47
+ return o.isoformat()
48
+ if isinstance(o, uuid.UUID):
49
+ return str(o)
50
+ if isinstance(o, (set, frozenset, tuple)):
51
+ return list(o)
52
+ if hasattr(o, "__dataclass_fields__"):
53
+ return {k: getattr(o, k) for k in o.__dataclass_fields__}
54
+ if hasattr(o, "_asdict"):
55
+ return o._asdict()
56
+ if hasattr(o, "__dict__"):
57
+ return {k: v for k, v in vars(o).items() if not k.startswith("_")}
58
+ raise TypeError(f"{type(o).__name__} cannot be sent as report data")
59
+
60
+
61
+ class ReportClient:
62
+ """Talks to a Fajfield report server.
63
+
64
+ `base_url` defaults to the FAJFIELD_REPORTS_URL environment variable (or http://localhost:8080), and
65
+ `api_key` to FAJFIELD_REPORTS_KEY.
66
+ """
67
+
68
+ def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None, timeout: float = 60):
69
+ self.base_url = (base_url or os.environ.get("FAJFIELD_REPORTS_URL") or "http://localhost:8080").rstrip("/")
70
+ self.api_key = api_key if api_key is not None else os.environ.get("FAJFIELD_REPORTS_KEY")
71
+ self.timeout = timeout
72
+
73
+ # ---- reports ----
74
+ def render(self, template: Template, data: Optional[Mapping[str, Any]] = None, *, fill_missing_with_sample: bool = False) -> bytes:
75
+ """Renders and returns the PDF bytes. `template` is the name of a template stored on the server,
76
+ a path to a .fjt file, or the template itself as a dict."""
77
+ return self.render_result(template, data, fill_missing_with_sample=fill_missing_with_sample).pdf
78
+
79
+ def render_result(self, template: Template, data: Optional[Mapping[str, Any]] = None, *, fill_missing_with_sample: bool = False) -> RenderResult:
80
+ """Like render(), and also returns the page count and warnings (missing data, bad barcodes, …)."""
81
+ body: dict = {"template": self._template(template)}
82
+ if data is not None:
83
+ body["data"] = data
84
+ if fill_missing_with_sample:
85
+ body["fillMissingWithSample"] = True
86
+ res = self._call("POST", "/render?format=json", body)
87
+ return RenderResult(base64.b64decode(res["pdf"]), int(res.get("pages", 0)), list(res.get("warnings", [])), int(res.get("ms", 0)))
88
+
89
+ def render_to_file(self, template: Template, data: Optional[Mapping[str, Any]], path: Union[str, Path], **kw: Any) -> RenderResult:
90
+ """Renders and saves the PDF to `path`."""
91
+ r = self.render_result(template, data, **kw)
92
+ r.save(path)
93
+ return r
94
+
95
+ # ---- server ----
96
+ def templates(self) -> list:
97
+ """Names of the templates stored on the server."""
98
+ return list(self._call("GET", "/templates").get("templates", []))
99
+
100
+ def health(self) -> dict:
101
+ return self._call("GET", "/health")
102
+
103
+ # ---- internals ----
104
+ @staticmethod
105
+ def _template(t: Template) -> Any:
106
+ if isinstance(t, Path) or (isinstance(t, str) and t.lower().endswith(".fjt")):
107
+ return json.loads(Path(t).read_text(encoding="utf-8"))
108
+ return t
109
+
110
+ def _call(self, method: str, path: str, body: Any = None) -> dict:
111
+ headers = {"Accept": "application/json"}
112
+ data = None
113
+ if body is not None:
114
+ data = json.dumps(body, default=_plain, ensure_ascii=False).encode("utf-8")
115
+ headers["Content-Type"] = "application/json"
116
+ if self.api_key:
117
+ headers["Authorization"] = f"Bearer {self.api_key}"
118
+ req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
119
+ try:
120
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
121
+ return json.loads(r.read().decode("utf-8"))
122
+ except urllib.error.HTTPError as e:
123
+ try:
124
+ msg = json.loads(e.read().decode("utf-8")).get("error") or e.reason
125
+ except Exception:
126
+ msg = str(e.reason)
127
+ raise ReportError(e.code, msg) from None
128
+ except urllib.error.URLError as e:
129
+ raise ReportError(0, f"Could not reach the report server at {self.base_url}: {e.reason}. Is it running?") from None
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: fajfield-reports
3
+ Version: 0.1.0
4
+ Summary: Render invoices and multi-page reports from Fajfield templates (.fjt) to PDF from Python, through a self-hosted Fajfield report server. RDLC-style reports without Windows.
5
+ Author: Fajfield
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://fajfield.com/developers/reports/
8
+ Project-URL: Source, https://github.com/Fajfield/fajfield-reports-python
9
+ Project-URL: Issues, https://github.com/Fajfield/fajfield-reports-python/issues
10
+ Project-URL: Designer, https://fajfield.com/designer/report/
11
+ Keywords: pdf,report,invoice,rdlc,crystal-reports,erp,django,flask,fastapi
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Office/Business
14
+ Classifier: Topic :: Printing
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # fajfield-reports (Python)
22
+
23
+ Render invoices, statements and multi-page reports to **PDF from Python**: Django, Flask, FastAPI, Odoo add-ons, scripts and scheduled jobs. Design the template in the free [Fajfield report designer](https://fajfield.com/designer/report/), export it as `.fjt`, and render it with your data.
24
+
25
+ Think *RDLC or Crystal Reports for Python*, without Windows. Tables continue across pages with the header repeated, groups get subtotals, and "Page 2 of 5" is always right.
26
+
27
+ The package talks to a **[Fajfield report server](https://github.com/Fajfield/fajfield-reports-server)** you run yourself, so your data stays on your network. No dependencies: only the Python standard library.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pip install fajfield-reports
33
+ ```
34
+
35
+ Start a report server (once, on any machine your app can reach):
36
+
37
+ ```sh
38
+ docker run -p 8080:8080 -e API_KEYS=change-me -v ./templates:/templates fajfield/reports-server
39
+ # or, with Node 18+:
40
+ npx @fajfield/reports-server serve --templates ./templates
41
+ ```
42
+
43
+ ## Render a report
44
+
45
+ ```python
46
+ from fajfield_reports import ReportClient
47
+
48
+ client = ReportClient("http://localhost:8080", api_key="change-me")
49
+
50
+ client.render_to_file("invoice", {
51
+ "company": {"name": "Harbour Foods Co."},
52
+ "customer": {"name": "Fresh Mart", "address": "Dubai"},
53
+ "invoice": {"no": "INV-0452", "date": date.today()},
54
+ "items": [{"name": l.product, "qty": l.qty, "rate": l.price, "taxRate": 0.05} for l in order.lines],
55
+ }, "invoice.pdf")
56
+ ```
57
+
58
+ - **Template:** the name of a template stored on the server (`"invoice"`), a path to a `.fjt` file, or the template as a dict.
59
+ - **Data:** one key per dataset in the template: a list for rows, a dict for single records. `Decimal`, `date`, `datetime`, `UUID`, dataclasses and named tuples are converted for you.
60
+
61
+ ### Django
62
+
63
+ ```python
64
+ from django.http import HttpResponse
65
+
66
+ def invoice_pdf(request, pk):
67
+ pdf = client.render("invoice", invoice_data(pk))
68
+ return HttpResponse(pdf, content_type="application/pdf")
69
+ ```
70
+
71
+ ### FastAPI
72
+
73
+ ```python
74
+ from fastapi.responses import Response
75
+
76
+ @app.get("/invoices/{pk}.pdf")
77
+ def invoice_pdf(pk: int):
78
+ return Response(client.render("invoice", invoice_data(pk)), media_type="application/pdf")
79
+ ```
80
+
81
+ ## Warnings and errors
82
+
83
+ ```python
84
+ r = client.render_result("invoice", data)
85
+ r.pdf, r.pages, r.warnings # e.g. ['No data for "customer". Pass it as data: { customer: { ... } }.']
86
+ ```
87
+
88
+ Problems the report can live with (missing data, bad barcode data) come back as `warnings`; the PDF is still made. Real errors raise `ReportError` with a plain message and the HTTP status: 400 bad request or template, 401 wrong API key, 404 unknown template, 0 server not reachable.
89
+
90
+ ## Settings
91
+
92
+ `ReportClient()` with no arguments reads `FAJFIELD_REPORTS_URL` (default `http://localhost:8080`) and `FAJFIELD_REPORTS_KEY` from the environment.
93
+
94
+ ## Also from Fajfield
95
+
96
+ [Report designer](https://fajfield.com/designer/report/) · [JavaScript](https://www.npmjs.com/package/@fajfield/reports) · [Flutter](https://pub.dev/packages/fajfield_reports_flutter) · [.NET](https://www.nuget.org/packages/Fajfield.Reports) · [Report server](https://github.com/Fajfield/fajfield-reports-server)
97
+
98
+ MIT license. Made by [Fajfield](https://fajfield.com): research and development for ERP, warehouse, POS and business data.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/fajfield_reports/__init__.py
5
+ src/fajfield_reports/client.py
6
+ src/fajfield_reports.egg-info/PKG-INFO
7
+ src/fajfield_reports.egg-info/SOURCES.txt
8
+ src/fajfield_reports.egg-info/dependency_links.txt
9
+ src/fajfield_reports.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ fajfield_reports
@@ -0,0 +1,59 @@
1
+ """Runs against a real report server: FAJFIELD_SERVER_DIR points at a checkout of fajfield-reports-server
2
+ (default: ../fajfield-reports-server) with `npm install` done."""
3
+ import datetime, decimal, os, socket, subprocess, sys, time, unittest
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
7
+ from fajfield_reports import ReportClient, ReportError # noqa: E402
8
+
9
+ SERVER = Path(os.environ.get("FAJFIELD_SERVER_DIR", Path(__file__).resolve().parents[2] / "fajfield-reports-server"))
10
+
11
+
12
+ def free_port():
13
+ s = socket.socket(); s.bind(("", 0)); p = s.getsockname()[1]; s.close(); return p
14
+
15
+
16
+ class ClientTest(unittest.TestCase):
17
+ @classmethod
18
+ def setUpClass(cls):
19
+ cls.port = free_port()
20
+ env = dict(os.environ, PORT=str(cls.port), TEMPLATES_DIR=str(SERVER / "templates"), API_KEYS="k1")
21
+ cls.proc = subprocess.Popen(["node", "bin/fajfield-reports.js", "serve"], cwd=SERVER, env=env, stdout=subprocess.DEVNULL)
22
+ cls.client = ReportClient(f"http://localhost:{cls.port}", api_key="k1")
23
+ for _ in range(50):
24
+ try: cls.client.health(); break
25
+ except ReportError: time.sleep(0.1)
26
+
27
+ @classmethod
28
+ def tearDownClass(cls):
29
+ cls.proc.terminate(); cls.proc.wait()
30
+
31
+ def test_stored_template_with_erp_values(self):
32
+ r = self.client.render_result("invoice", {
33
+ "company": {"name": "Harbour Foods Co."}, "customer": {"name": "Fresh Mart", "address": "Dubai"},
34
+ "invoice": {"no": "INV-1", "date": datetime.date(2026, 11, 30), "due": datetime.date(2026, 12, 14), "terms": "14 days"},
35
+ "items": [{"name": "Rice", "qty": 4, "rate": decimal.Decimal("18.50"), "taxRate": decimal.Decimal("0.05")}],
36
+ })
37
+ self.assertTrue(r.pdf.startswith(b"%PDF-"))
38
+ self.assertEqual(r.pages, 1)
39
+ self.assertEqual(r.warnings, [])
40
+
41
+ def test_template_file_and_sample(self):
42
+ r = self.client.render_result(SERVER / "templates" / "sales.fjt", fill_missing_with_sample=True)
43
+ self.assertEqual(r.pages, 2)
44
+
45
+ def test_templates_and_errors(self):
46
+ self.assertEqual(self.client.templates(), ["invoice", "sales"])
47
+ with self.assertRaises(ReportError) as e:
48
+ self.client.render("nope")
49
+ self.assertEqual(e.exception.status, 404)
50
+ with self.assertRaises(ReportError) as e:
51
+ ReportClient(f"http://localhost:{self.port}", api_key="wrong").render("invoice")
52
+ self.assertEqual(e.exception.status, 401)
53
+ with self.assertRaises(ReportError) as e:
54
+ ReportClient(f"http://localhost:{free_port()}").health()
55
+ self.assertEqual(e.exception.status, 0)
56
+
57
+
58
+ if __name__ == "__main__":
59
+ unittest.main()