django-reportkit 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.
- django_reportkit/__init__.py +10 -0
- django_reportkit/apps.py +21 -0
- django_reportkit/conf.py +35 -0
- django_reportkit/errors/__init__.py +5 -0
- django_reportkit/errors/exceptions.py +43 -0
- django_reportkit/errors/handlers.py +37 -0
- django_reportkit/errors/messages.py +36 -0
- django_reportkit/exports/__init__.py +5 -0
- django_reportkit/exports/formats.py +60 -0
- django_reportkit/exports/policy.py +49 -0
- django_reportkit/exports/runner.py +32 -0
- django_reportkit/jobs/__init__.py +3 -0
- django_reportkit/jobs/backends/__init__.py +6 -0
- django_reportkit/jobs/backends/base.py +14 -0
- django_reportkit/jobs/backends/celery.py +17 -0
- django_reportkit/jobs/backends/sync.py +15 -0
- django_reportkit/jobs/backends/thread.py +20 -0
- django_reportkit/jobs/cleanup.py +48 -0
- django_reportkit/jobs/models.py +89 -0
- django_reportkit/jobs/service.py +147 -0
- django_reportkit/jobs/storage.py +26 -0
- django_reportkit/jobs/tasks.py +11 -0
- django_reportkit/management/__init__.py +0 -0
- django_reportkit/management/commands/__init__.py +0 -0
- django_reportkit/management/commands/cleanup_report_files.py +17 -0
- django_reportkit/migrations/0001_initial.py +44 -0
- django_reportkit/migrations/__init__.py +0 -0
- django_reportkit/models.py +3 -0
- django_reportkit/reports/__init__.py +7 -0
- django_reportkit/reports/base.py +45 -0
- django_reportkit/reports/columns.py +28 -0
- django_reportkit/reports/mixins/__init__.py +5 -0
- django_reportkit/reports/mixins/access.py +58 -0
- django_reportkit/reports/mixins/document.py +111 -0
- django_reportkit/reports/mixins/filters.py +39 -0
- django_reportkit/reports/model.py +76 -0
- django_reportkit/reports/params.py +65 -0
- django_reportkit/reports/registry.py +44 -0
- django_reportkit/reports/rows.py +17 -0
- django_reportkit/rest/__init__.py +3 -0
- django_reportkit/rest/errors.py +27 -0
- django_reportkit/rest/permissions.py +16 -0
- django_reportkit/rest/serializers.py +147 -0
- django_reportkit/rest/urls.py +28 -0
- django_reportkit/rest/views.py +257 -0
- django_reportkit/templates/django_reportkit/base.html +28 -0
- django_reportkit/templates/django_reportkit/error.html +9 -0
- django_reportkit/templates/django_reportkit/job.html +32 -0
- django_reportkit/templates/django_reportkit/preview.html +35 -0
- django_reportkit/urls.py +10 -0
- django_reportkit/views/__init__.py +5 -0
- django_reportkit/views/export.py +62 -0
- django_reportkit/views/jobs.py +101 -0
- django_reportkit/views/mixins.py +39 -0
- django_reportkit/views/preview.py +75 -0
- django_reportkit/views/urls.py +15 -0
- django_reportkit-0.1.0.dist-info/METADATA +212 -0
- django_reportkit-0.1.0.dist-info/RECORD +61 -0
- django_reportkit-0.1.0.dist-info/WHEEL +5 -0
- django_reportkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- django_reportkit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from datetime import timedelta
|
|
2
|
+
|
|
3
|
+
from django.db import close_old_connections, transaction
|
|
4
|
+
from django.utils import timezone
|
|
5
|
+
from django.utils.module_loading import import_string
|
|
6
|
+
|
|
7
|
+
from ..conf import reportkit_settings
|
|
8
|
+
from ..errors import friendly_message, log_error
|
|
9
|
+
from ..exports import ExportRunner, get_format
|
|
10
|
+
from ..reports.params import ReportParams
|
|
11
|
+
from .models import ReportJob
|
|
12
|
+
from .storage import job_storage, save_export
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ReportJobs:
|
|
16
|
+
"""
|
|
17
|
+
Create background export jobs, hand them to the configured backend and run them.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def start(cls, report, format, rows):
|
|
22
|
+
"""
|
|
23
|
+
Record a job for the report and submit it once the current transaction commits.
|
|
24
|
+
"""
|
|
25
|
+
with transaction.atomic():
|
|
26
|
+
job = cls.create(report, format, rows)
|
|
27
|
+
transaction.on_commit(lambda: cls.submit(job.pk))
|
|
28
|
+
return job
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def create(report, format, rows):
|
|
32
|
+
"""
|
|
33
|
+
Persist the report definition, export format, parameters and requesting user.
|
|
34
|
+
"""
|
|
35
|
+
return ReportJob.objects.create(
|
|
36
|
+
report=report.get_key(),
|
|
37
|
+
title=report.get_title(),
|
|
38
|
+
format=format.name,
|
|
39
|
+
params=report.params.to_json(),
|
|
40
|
+
user_id=report.params.user_id,
|
|
41
|
+
rows=rows,
|
|
42
|
+
filename=format.filename(report.get_slug()),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def submit(cls, job_id):
|
|
47
|
+
"""
|
|
48
|
+
Submit a committed job to the configured background backend.
|
|
49
|
+
"""
|
|
50
|
+
cls.backend().submit(str(job_id))
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def backend():
|
|
54
|
+
"""
|
|
55
|
+
Return the configured job backend.
|
|
56
|
+
"""
|
|
57
|
+
return import_string(reportkit_settings.JOB_BACKEND)()
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def run(cls, job_id):
|
|
61
|
+
"""
|
|
62
|
+
Claim a pending job, generate its export and record the final result.
|
|
63
|
+
"""
|
|
64
|
+
job = cls.claim(job_id)
|
|
65
|
+
if job is None:
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
report = None
|
|
69
|
+
name = None
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
report = cls.build_report(job)
|
|
73
|
+
format = get_format(report, job.format)
|
|
74
|
+
name = cls.export(job, report, format)
|
|
75
|
+
cls.complete(job, name)
|
|
76
|
+
except Exception as error:
|
|
77
|
+
log_error(error, report)
|
|
78
|
+
cls.fail(job, error, name)
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def claim(job_id):
|
|
82
|
+
"""
|
|
83
|
+
Atomically claim a pending job so only one worker can execute it.
|
|
84
|
+
"""
|
|
85
|
+
now = timezone.now()
|
|
86
|
+
claimed = ReportJob.objects.filter(pk=job_id, status=ReportJob.Status.PENDING).update(status=ReportJob.Status.RUNNING, started_at=now)
|
|
87
|
+
|
|
88
|
+
if not claimed:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
return ReportJob.objects.get(pk=job_id)
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def build_report(job):
|
|
95
|
+
"""
|
|
96
|
+
Reconstruct the report using its stored definition and parameters.
|
|
97
|
+
"""
|
|
98
|
+
report_class = import_string(job.report)
|
|
99
|
+
return report_class(ReportParams.from_json(job.params))
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def export(job, report, format):
|
|
103
|
+
"""
|
|
104
|
+
Generate the report and save its output to the configured storage.
|
|
105
|
+
"""
|
|
106
|
+
with ExportRunner.to_temporary_file(report, format) as spool:
|
|
107
|
+
return save_export(job, spool)
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def complete(cls, job, name):
|
|
111
|
+
"""
|
|
112
|
+
Mark the job as completed and record its stored file and expiration time.
|
|
113
|
+
"""
|
|
114
|
+
finished = timezone.now()
|
|
115
|
+
expires = finished + timedelta(hours=reportkit_settings.JOB_TTL_HOURS)
|
|
116
|
+
cls.mark(job, status=ReportJob.Status.DONE, file=name, finished_at=finished, expires_at=expires)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def fail(cls, job, error, name=None):
|
|
120
|
+
"""
|
|
121
|
+
Mark the job as failed and remove any exported file left behind.
|
|
122
|
+
"""
|
|
123
|
+
try:
|
|
124
|
+
if name:
|
|
125
|
+
job_storage().delete(name)
|
|
126
|
+
finally:
|
|
127
|
+
cls.mark(job, status=ReportJob.Status.FAILED, error=friendly_message(error), finished_at=timezone.now())
|
|
128
|
+
|
|
129
|
+
@staticmethod
|
|
130
|
+
def mark(job, **fields):
|
|
131
|
+
"""
|
|
132
|
+
Save the supplied job fields.
|
|
133
|
+
"""
|
|
134
|
+
for name, value in fields.items():
|
|
135
|
+
setattr(job, name, value)
|
|
136
|
+
job.save(update_fields=list(fields))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def run_job(job_id):
|
|
140
|
+
"""
|
|
141
|
+
Run one job outside the request cycle, closing stale database connections around it.
|
|
142
|
+
"""
|
|
143
|
+
close_old_connections()
|
|
144
|
+
try:
|
|
145
|
+
ReportJobs.run(job_id)
|
|
146
|
+
finally:
|
|
147
|
+
close_old_connections()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from django.core.files import File
|
|
2
|
+
from django.core.files.storage import storages
|
|
3
|
+
|
|
4
|
+
from ..conf import reportkit_settings
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def job_storage():
|
|
8
|
+
"""
|
|
9
|
+
Return the storage that keeps finished exports (settings JOB_STORAGE, "default" by default).
|
|
10
|
+
"""
|
|
11
|
+
return storages[reportkit_settings.JOB_STORAGE]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def save_export(job, spool):
|
|
15
|
+
"""
|
|
16
|
+
Store an export file under JOB_DIRECTORY and return its storage name.
|
|
17
|
+
"""
|
|
18
|
+
return job_storage().save(f"{reportkit_settings.JOB_DIRECTORY}/{job.pk}/{job.filename}", File(spool, name=job.filename))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def delete_export(name):
|
|
22
|
+
"""
|
|
23
|
+
Delete a stored export when it exists.
|
|
24
|
+
"""
|
|
25
|
+
if name and job_storage().exists(name):
|
|
26
|
+
job_storage().delete(name)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from django.core.management.base import BaseCommand
|
|
2
|
+
|
|
3
|
+
from ...jobs.cleanup import delete_expired_jobs
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Command(BaseCommand):
|
|
7
|
+
"""
|
|
8
|
+
Delete expired background exports; run it periodically (cron or Celery beat).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
help = "Delete expired report export files and their jobs."
|
|
12
|
+
|
|
13
|
+
def handle(self, *args, **options):
|
|
14
|
+
"""
|
|
15
|
+
Delete the expired jobs and report how many.
|
|
16
|
+
"""
|
|
17
|
+
self.stdout.write(f"Deleted {delete_expired_jobs()} expired report jobs.")
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Generated by Django 6.1.3 on 2026-11-22 02:55
|
|
2
|
+
|
|
3
|
+
import django.db.models.deletion
|
|
4
|
+
import uuid
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
from django.db import migrations, models
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Migration(migrations.Migration):
|
|
10
|
+
|
|
11
|
+
initial = True
|
|
12
|
+
|
|
13
|
+
dependencies = [
|
|
14
|
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
operations = [
|
|
18
|
+
migrations.CreateModel(
|
|
19
|
+
name='ReportJob',
|
|
20
|
+
fields=[
|
|
21
|
+
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
|
22
|
+
('report', models.CharField(max_length=255, verbose_name='report')),
|
|
23
|
+
('title', models.CharField(blank=True, max_length=255, verbose_name='title')),
|
|
24
|
+
('format', models.CharField(max_length=20, verbose_name='format')),
|
|
25
|
+
('params', models.JSONField(default=dict, verbose_name='parameters')),
|
|
26
|
+
('status', models.CharField(choices=[('pending', 'Waiting'), ('running', 'Generating'), ('done', 'Ready'), ('failed', 'Failed')], default='pending', max_length=10, verbose_name='status')),
|
|
27
|
+
('rows', models.PositiveIntegerField(default=0, verbose_name='rows')),
|
|
28
|
+
('file', models.CharField(blank=True, max_length=500, verbose_name='file')),
|
|
29
|
+
('filename', models.CharField(blank=True, max_length=255, verbose_name='file name')),
|
|
30
|
+
('error', models.TextField(blank=True, verbose_name='error')),
|
|
31
|
+
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created')),
|
|
32
|
+
('started_at', models.DateTimeField(blank=True, null=True, verbose_name='started')),
|
|
33
|
+
('finished_at', models.DateTimeField(blank=True, null=True, verbose_name='finished')),
|
|
34
|
+
('expires_at', models.DateTimeField(blank=True, null=True, verbose_name='expires')),
|
|
35
|
+
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='report_jobs', to=settings.AUTH_USER_MODEL)),
|
|
36
|
+
],
|
|
37
|
+
options={
|
|
38
|
+
'verbose_name': 'report job',
|
|
39
|
+
'verbose_name_plural': 'report jobs',
|
|
40
|
+
'ordering': ['-created_at'],
|
|
41
|
+
'indexes': [models.Index(fields=['status', 'expires_at'], name='django_repo_status_ca664d_idx')],
|
|
42
|
+
},
|
|
43
|
+
),
|
|
44
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from ..conf import reportkit_settings
|
|
2
|
+
from .mixins import ReportAccessMixin, ReportDocumentMixin, ReportFilterMixin
|
|
3
|
+
from .params import ReportParams
|
|
4
|
+
|
|
5
|
+
FORMATS = ("pdf", "xlsx", "xlsx-data", "docx")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Report(ReportAccessMixin, ReportFilterMixin, ReportDocumentMixin):
|
|
9
|
+
"""
|
|
10
|
+
Abstract report: subclasses provide prepared rows, their count and optionally totals; this class builds a
|
|
11
|
+
ReportKit document for previews, downloads and background exports. Instances are built from ReportParams, so the
|
|
12
|
+
same report runs in a request or in a background job.
|
|
13
|
+
"""
|
|
14
|
+
formats = FORMATS
|
|
15
|
+
paginate_by = None
|
|
16
|
+
|
|
17
|
+
def __init__(self, params=None):
|
|
18
|
+
"""
|
|
19
|
+
Bind the report to its parameters.
|
|
20
|
+
"""
|
|
21
|
+
self.params = params if params is not None else ReportParams()
|
|
22
|
+
|
|
23
|
+
def get_rows(self):
|
|
24
|
+
"""
|
|
25
|
+
Return every row as mappings keyed by column field; a lazy iterable is best.
|
|
26
|
+
"""
|
|
27
|
+
raise NotImplementedError
|
|
28
|
+
|
|
29
|
+
def count(self):
|
|
30
|
+
"""
|
|
31
|
+
Return the number of rows, used to choose how to export.
|
|
32
|
+
"""
|
|
33
|
+
raise NotImplementedError
|
|
34
|
+
|
|
35
|
+
def get_paginate_by(self):
|
|
36
|
+
"""
|
|
37
|
+
Return the number of rows on one preview page.
|
|
38
|
+
"""
|
|
39
|
+
return self.paginate_by or reportkit_settings.PAGINATE_BY
|
|
40
|
+
|
|
41
|
+
def get_page(self, number):
|
|
42
|
+
"""
|
|
43
|
+
Return a Django Page whose object_list holds the rows of one preview page.
|
|
44
|
+
"""
|
|
45
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from reportkit.components.table import TableColumn
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Column:
|
|
5
|
+
"""
|
|
6
|
+
One report column: the queryset field it reads (a values() path such as "account__name", or an annotation) and how
|
|
7
|
+
pyreportkit shows it. The options are TableColumn's: subtitle, format, currency, decimals, date_format, align, ...
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
def __init__(self, field, title, **options):
|
|
11
|
+
"""
|
|
12
|
+
Keep the field, the title (it may be a lazy translation) and the TableColumn options.
|
|
13
|
+
"""
|
|
14
|
+
if not isinstance(field, str) or not field:
|
|
15
|
+
raise ValueError("Column field must be a non-empty string.")
|
|
16
|
+
self.field, self.title, self.options = field, title, options
|
|
17
|
+
|
|
18
|
+
def table_column(self):
|
|
19
|
+
"""
|
|
20
|
+
Return the pyreportkit column, translating the title in the active language.
|
|
21
|
+
"""
|
|
22
|
+
return TableColumn(key=self.field, title=str(self.title), **{key: str(value) if key == "subtitle" else value for key, value in self.options.items()})
|
|
23
|
+
|
|
24
|
+
def __repr__(self):
|
|
25
|
+
"""
|
|
26
|
+
Show the field and title.
|
|
27
|
+
"""
|
|
28
|
+
return f"Column({self.field!r}, {str(self.title)!r})"
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ReportAccessMixin:
|
|
5
|
+
"""
|
|
6
|
+
Provide report identity, URL patterns and access permissions.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
slug = None
|
|
10
|
+
login_required = True
|
|
11
|
+
permission_required = None
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def get_slug(cls):
|
|
15
|
+
"""
|
|
16
|
+
Return the name the report's URLs are named after: slug, or the class name in kebab case.
|
|
17
|
+
"""
|
|
18
|
+
return cls.slug or re.sub(r"(?<!^)(?=[A-Z])", "-", cls.__name__).lower()
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def get_key(cls):
|
|
22
|
+
"""
|
|
23
|
+
Return the import path a background job uses to find the report class again.
|
|
24
|
+
"""
|
|
25
|
+
return f"{cls.__module__}.{cls.__qualname__}"
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def urls(cls):
|
|
29
|
+
"""
|
|
30
|
+
Return the URL patterns of this report's preview and exports, for include().
|
|
31
|
+
"""
|
|
32
|
+
from ...views.urls import report_urlpatterns # Deferred: views import reports.
|
|
33
|
+
|
|
34
|
+
return report_urlpatterns(cls)
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def api_urls(cls, **view_options):
|
|
38
|
+
"""
|
|
39
|
+
Return the Django REST Framework URL patterns of this report's JSON preview and exports, for include().
|
|
40
|
+
"""
|
|
41
|
+
from ...rest.urls import report_api_urlpatterns # Deferred: optional, needs djangorestframework.
|
|
42
|
+
|
|
43
|
+
return report_api_urlpatterns(cls, **view_options)
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def has_permission(cls, user):
|
|
47
|
+
"""
|
|
48
|
+
Return whether the user may see the report: logged in unless login_required is False, then
|
|
49
|
+
permission_required (a permission name or a list of them).
|
|
50
|
+
"""
|
|
51
|
+
if cls.login_required and not getattr(user, "is_authenticated", False):
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
if cls.permission_required is None:
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
required = (cls.permission_required,) if isinstance(cls.permission_required, str) else cls.permission_required
|
|
58
|
+
return bool(user and user.has_perms(required))
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from django.utils.translation import gettext_lazy as _
|
|
2
|
+
from django.utils.translation import override
|
|
3
|
+
from reportkit.builders import ReportBuilder, TableBuilder
|
|
4
|
+
from reportkit.rendering.context import RenderingContext
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ReportDocumentMixin:
|
|
8
|
+
"""
|
|
9
|
+
Build presentation-only ReportKit documents from prepared report data.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
title = ""
|
|
13
|
+
columns = ()
|
|
14
|
+
total_label = _("Total")
|
|
15
|
+
page = {"margin": "12mm"}
|
|
16
|
+
page_number = "{page} / {pages}"
|
|
17
|
+
table_title = None
|
|
18
|
+
table_style = None
|
|
19
|
+
table_component_style = None
|
|
20
|
+
|
|
21
|
+
def get_title(self):
|
|
22
|
+
"""
|
|
23
|
+
Return the localized report title.
|
|
24
|
+
"""
|
|
25
|
+
return str(self.title)
|
|
26
|
+
|
|
27
|
+
def get_columns(self):
|
|
28
|
+
"""
|
|
29
|
+
Return the configured report columns.
|
|
30
|
+
"""
|
|
31
|
+
return list(self.columns)
|
|
32
|
+
|
|
33
|
+
def get_totals(self):
|
|
34
|
+
"""
|
|
35
|
+
Return the prepared report totals.
|
|
36
|
+
"""
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
def total_row(self):
|
|
40
|
+
"""
|
|
41
|
+
Build the display row from prepared totals.
|
|
42
|
+
"""
|
|
43
|
+
totals = self.get_totals()
|
|
44
|
+
columns = self.get_columns()
|
|
45
|
+
|
|
46
|
+
if not totals or not columns:
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
return {**totals, columns[0].field: str(self.total_label)}
|
|
50
|
+
|
|
51
|
+
def context(self):
|
|
52
|
+
"""
|
|
53
|
+
Build the rendering context for the report language.
|
|
54
|
+
"""
|
|
55
|
+
return RenderingContext(language=self.params.language, direction=self.params.direction)
|
|
56
|
+
|
|
57
|
+
def table(self, rows):
|
|
58
|
+
"""
|
|
59
|
+
Build the report table from prepared data.
|
|
60
|
+
"""
|
|
61
|
+
return self.table_builder(rows).build()
|
|
62
|
+
|
|
63
|
+
def table_builder(self, rows):
|
|
64
|
+
"""
|
|
65
|
+
Configure the table columns, rows, totals, and presentation.
|
|
66
|
+
"""
|
|
67
|
+
columns = (column.table_column() for column in self.get_columns())
|
|
68
|
+
builder = TableBuilder().columns(*columns).rows(rows).totals(self.total_row()).title(self.table_title)
|
|
69
|
+
self.configure_table(builder)
|
|
70
|
+
return builder
|
|
71
|
+
|
|
72
|
+
def configure_table(self, builder):
|
|
73
|
+
"""
|
|
74
|
+
Apply optional table and component styles.
|
|
75
|
+
"""
|
|
76
|
+
if self.table_style is not None:
|
|
77
|
+
builder.table_style(self.table_style)
|
|
78
|
+
|
|
79
|
+
if self.table_component_style is not None:
|
|
80
|
+
builder.style(self.table_component_style)
|
|
81
|
+
|
|
82
|
+
def build(self, builder, table):
|
|
83
|
+
"""
|
|
84
|
+
Compose the report layout with its table and page numbering.
|
|
85
|
+
"""
|
|
86
|
+
return builder.add(table).page_number(self.page_number)
|
|
87
|
+
|
|
88
|
+
def document(self, rows=None):
|
|
89
|
+
"""
|
|
90
|
+
Build the ReportKit document using the supplied or complete rows.
|
|
91
|
+
"""
|
|
92
|
+
with override(self.params.language):
|
|
93
|
+
builder = self.document_builder()
|
|
94
|
+
table = self.table(rows if rows is not None else self.get_rows())
|
|
95
|
+
return self.build(builder, table).build()
|
|
96
|
+
|
|
97
|
+
def document_builder(self):
|
|
98
|
+
"""
|
|
99
|
+
Initialize the report builder with page settings.
|
|
100
|
+
"""
|
|
101
|
+
return ReportBuilder(self.get_title()).page(**self.page)
|
|
102
|
+
|
|
103
|
+
def html(self, rows=None):
|
|
104
|
+
"""
|
|
105
|
+
Render the report document as a complete HTML string.
|
|
106
|
+
"""
|
|
107
|
+
import reportkit.exporters.html # noqa: F401
|
|
108
|
+
from reportkit.exporters.html.exporter import HtmlExporter
|
|
109
|
+
|
|
110
|
+
with override(self.params.language):
|
|
111
|
+
return HtmlExporter().export(self.document(rows), self.context()).decode("utf-8")
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from functools import cached_property
|
|
2
|
+
|
|
3
|
+
from django.contrib.auth import get_user_model
|
|
4
|
+
|
|
5
|
+
from ...errors.exceptions import ReportFilterError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ReportFilterMixin:
|
|
9
|
+
"""
|
|
10
|
+
Resolve the requesting user, bind the filter form and expose the validated filter values.
|
|
11
|
+
"""
|
|
12
|
+
filter_form = None
|
|
13
|
+
|
|
14
|
+
@cached_property
|
|
15
|
+
def user(self):
|
|
16
|
+
"""
|
|
17
|
+
Return the user the report is built for, or None.
|
|
18
|
+
"""
|
|
19
|
+
return get_user_model()._default_manager.filter(pk=self.params.user_id).first() if self.params.user_id else None
|
|
20
|
+
|
|
21
|
+
@cached_property
|
|
22
|
+
def form(self):
|
|
23
|
+
"""
|
|
24
|
+
Return the bound filter form, or None when the report has no filters.
|
|
25
|
+
"""
|
|
26
|
+
return self.filter_form(self.params.querydict() or None) if self.filter_form else None
|
|
27
|
+
|
|
28
|
+
@cached_property
|
|
29
|
+
def filters(self):
|
|
30
|
+
"""
|
|
31
|
+
Return the cleaned filter values; an empty mapping when nothing is filled in.
|
|
32
|
+
"""
|
|
33
|
+
if self.form is None or not self.form.is_bound:
|
|
34
|
+
return {}
|
|
35
|
+
|
|
36
|
+
if not self.form.is_valid():
|
|
37
|
+
raise ReportFilterError(self.form.errors)
|
|
38
|
+
|
|
39
|
+
return {name: value for name, value in self.form.cleaned_data.items() if value not in (None, "", [], ())}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
from functools import cached_property
|
|
2
|
+
|
|
3
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
4
|
+
from django.core.paginator import Paginator
|
|
5
|
+
|
|
6
|
+
from .base import Report
|
|
7
|
+
from .rows import QuerysetRows
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ModelReport(Report):
|
|
11
|
+
"""
|
|
12
|
+
Report over a queryset: the filters narrow it, the rows stream from it with iterator(), and the totals are computed
|
|
13
|
+
by the database over every filtered row (aggregate()), never over one page.
|
|
14
|
+
|
|
15
|
+
Declare model or queryset, columns, totals (column field -> aggregate expression such as Sum("amount")) and
|
|
16
|
+
optionally filter_form with filter_lookups (form field -> ORM lookup such as "date__gte").
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
model = None
|
|
20
|
+
queryset = None
|
|
21
|
+
totals = {}
|
|
22
|
+
filter_lookups = {}
|
|
23
|
+
chunk_size = 2000
|
|
24
|
+
|
|
25
|
+
def get_queryset(self):
|
|
26
|
+
"""
|
|
27
|
+
Return the base queryset; override to scope it to self.user or to add select_related() and annotations.
|
|
28
|
+
"""
|
|
29
|
+
if self.queryset is not None:
|
|
30
|
+
return self.queryset.all()
|
|
31
|
+
if self.model is not None:
|
|
32
|
+
return self.model._default_manager.all()
|
|
33
|
+
raise ImproperlyConfigured(f"{type(self).__name__} needs a model, a queryset or a get_queryset() override.")
|
|
34
|
+
|
|
35
|
+
def filter_queryset(self, queryset, filters):
|
|
36
|
+
"""
|
|
37
|
+
Apply the cleaned filter values through filter_lookups (a field without a lookup filters by its own name).
|
|
38
|
+
"""
|
|
39
|
+
return queryset.filter(**{self.filter_lookups.get(name, name): value for name, value in filters.items()})
|
|
40
|
+
|
|
41
|
+
@cached_property
|
|
42
|
+
def filtered_queryset(self):
|
|
43
|
+
"""
|
|
44
|
+
Return the filtered queryset, built once per report.
|
|
45
|
+
"""
|
|
46
|
+
return self.filter_queryset(self.get_queryset(), self.filters)
|
|
47
|
+
|
|
48
|
+
def fields(self):
|
|
49
|
+
"""
|
|
50
|
+
Return the values() fields the columns read.
|
|
51
|
+
"""
|
|
52
|
+
return [column.field for column in self.get_columns()]
|
|
53
|
+
|
|
54
|
+
def get_rows(self):
|
|
55
|
+
"""
|
|
56
|
+
Return the rows read lazily, in chunks.
|
|
57
|
+
"""
|
|
58
|
+
return QuerysetRows(self.filtered_queryset, self.fields(), self.chunk_size)
|
|
59
|
+
|
|
60
|
+
def count(self):
|
|
61
|
+
"""
|
|
62
|
+
Return the number of filtered rows.
|
|
63
|
+
"""
|
|
64
|
+
return self.filtered_queryset.count()
|
|
65
|
+
|
|
66
|
+
def get_totals(self):
|
|
67
|
+
"""
|
|
68
|
+
Aggregate the totals over every filtered row.
|
|
69
|
+
"""
|
|
70
|
+
return self.filtered_queryset.aggregate(**self.totals) if self.totals else None
|
|
71
|
+
|
|
72
|
+
def get_page(self, number):
|
|
73
|
+
"""
|
|
74
|
+
Return one preview page of rows; the paginator counts the filtered rows once.
|
|
75
|
+
"""
|
|
76
|
+
return Paginator(self.filtered_queryset.values(*self.fields()), self.get_paginate_by()).get_page(number)
|