django-importexport-flow 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.
Files changed (55) hide show
  1. django_importexport_flow-0.1.0/LICENSE +22 -0
  2. django_importexport_flow-0.1.0/PKG-INFO +80 -0
  3. django_importexport_flow-0.1.0/README.md +39 -0
  4. django_importexport_flow-0.1.0/pyproject.toml +84 -0
  5. django_importexport_flow-0.1.0/setup.cfg +4 -0
  6. django_importexport_flow-0.1.0/src/django_importexport_flow/__init__.py +81 -0
  7. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/__init__.py +23 -0
  8. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/export_definition.py +90 -0
  9. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/export_request.py +47 -0
  10. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/generate_export.py +133 -0
  11. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/import_config.py +57 -0
  12. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/import_data.py +158 -0
  13. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/import_definition.py +154 -0
  14. django_importexport_flow-0.1.0/src/django_importexport_flow/admin/import_request.py +72 -0
  15. django_importexport_flow-0.1.0/src/django_importexport_flow/apps.py +8 -0
  16. django_importexport_flow-0.1.0/src/django_importexport_flow/engine/__init__.py +12 -0
  17. django_importexport_flow-0.1.0/src/django_importexport_flow/engine/core.py +106 -0
  18. django_importexport_flow-0.1.0/src/django_importexport_flow/engine/pdf.py +20 -0
  19. django_importexport_flow-0.1.0/src/django_importexport_flow/engine/table.py +233 -0
  20. django_importexport_flow-0.1.0/src/django_importexport_flow/forms.py +184 -0
  21. django_importexport_flow-0.1.0/src/django_importexport_flow/managers.py +16 -0
  22. django_importexport_flow-0.1.0/src/django_importexport_flow/migrations/0001_initial.py +148 -0
  23. django_importexport_flow-0.1.0/src/django_importexport_flow/migrations/__init__.py +0 -0
  24. django_importexport_flow-0.1.0/src/django_importexport_flow/models/__init__.py +15 -0
  25. django_importexport_flow-0.1.0/src/django_importexport_flow/models/config_pdf.py +37 -0
  26. django_importexport_flow-0.1.0/src/django_importexport_flow/models/config_table.py +62 -0
  27. django_importexport_flow-0.1.0/src/django_importexport_flow/models/export_definition.py +121 -0
  28. django_importexport_flow-0.1.0/src/django_importexport_flow/models/export_request.py +85 -0
  29. django_importexport_flow-0.1.0/src/django_importexport_flow/models/import_definition.py +160 -0
  30. django_importexport_flow-0.1.0/src/django_importexport_flow/models/import_request.py +94 -0
  31. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/__init__.py +6 -0
  32. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/export.py +154 -0
  33. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/filter_form.py +103 -0
  34. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/helpers.py +355 -0
  35. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/http.py +21 -0
  36. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/import_tabular.py +1199 -0
  37. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/serialization.py +361 -0
  38. django_importexport_flow-0.1.0/src/django_importexport_flow/utils/validation.py +313 -0
  39. django_importexport_flow-0.1.0/src/django_importexport_flow.egg-info/PKG-INFO +80 -0
  40. django_importexport_flow-0.1.0/src/django_importexport_flow.egg-info/SOURCES.txt +53 -0
  41. django_importexport_flow-0.1.0/src/django_importexport_flow.egg-info/dependency_links.txt +1 -0
  42. django_importexport_flow-0.1.0/src/django_importexport_flow.egg-info/requires.txt +12 -0
  43. django_importexport_flow-0.1.0/src/django_importexport_flow.egg-info/top_level.txt +1 -0
  44. django_importexport_flow-0.1.0/tests/test_admin_import_config.py +140 -0
  45. django_importexport_flow-0.1.0/tests/test_engine.py +258 -0
  46. django_importexport_flow-0.1.0/tests/test_export_definition_queryset.py +27 -0
  47. django_importexport_flow-0.1.0/tests/test_export_generate.py +124 -0
  48. django_importexport_flow-0.1.0/tests/test_export_json.py +174 -0
  49. django_importexport_flow-0.1.0/tests/test_filter_mandatory.py +52 -0
  50. django_importexport_flow-0.1.0/tests/test_import_json.py +123 -0
  51. django_importexport_flow-0.1.0/tests/test_json_engine.py +78 -0
  52. django_importexport_flow-0.1.0/tests/test_report_import.py +408 -0
  53. django_importexport_flow-0.1.0/tests/test_report_import_ask.py +40 -0
  54. django_importexport_flow-0.1.0/tests/test_sample_report_fixtures.py +54 -0
  55. django_importexport_flow-0.1.0/tests/test_validation.py +72 -0
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Octolo
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.
22
+
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-importexport-flow
3
+ Version: 0.1.0
4
+ Summary: Declarative export and import definitions for Django (queryset, tabular/PDF, hooks).
5
+ Author-email: Octolo <dev@octolo.tech>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/octolo/django-importexport-flow
8
+ Project-URL: Repository, https://github.com/octolo/django-importexport-flow
9
+ Project-URL: Documentation, https://github.com/octolo/django-importexport-flow/blob/main/docs/README.md
10
+ Project-URL: Issues, https://github.com/octolo/django-importexport-flow/issues
11
+ Keywords: django,reporting,export,csv,excel,pdf,contenttypes
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: Django :: 3.2
16
+ Classifier: Framework :: Django :: 4.0
17
+ Classifier: Framework :: Django :: 4.1
18
+ Classifier: Framework :: Django :: 4.2
19
+ Classifier: Framework :: Django :: 5.0
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
26
+ Requires-Python: >=3.10
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: Django>=3.2
30
+ Requires-Dist: django-boosted>=1.0.0
31
+ Requires-Dist: openpyxl>=3.1.5
32
+ Requires-Dist: pandas>=3.0.1
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=8.3; extra == "dev"
35
+ Requires-Dist: pytest-django>=4.5; extra == "dev"
36
+ Requires-Dist: ruff>=0.5; extra == "dev"
37
+ Requires-Dist: mypy>=1.0; extra == "dev"
38
+ Requires-Dist: django-stubs>=5.0.0; extra == "dev"
39
+ Requires-Dist: weasyprint>=62.0; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # django-importexport-flow
43
+
44
+ Declarative reporting for Django: **target model** (`ContentType`), **manager** path, **`filter_config` / `filter_request` / `filter_mandatory`**, **`order_by`**, and **columns** on **`ExportConfigTable`**. Optional **PDF** (`ExportConfigPdf`) and **CSV / XLSX / JSON** export from the admin.
45
+
46
+ **Documentation:** [docs/README.md](docs/README.md)
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install django-importexport-flow
52
+ ```
53
+
54
+ ```python
55
+ INSTALLED_APPS = [
56
+ # ...
57
+ "django.contrib.contenttypes",
58
+ "django_boosted",
59
+ "django_importexport_flow",
60
+ ]
61
+ ```
62
+
63
+ ```bash
64
+ python manage.py migrate django_importexport_flow
65
+ ```
66
+
67
+ ## Documentation index
68
+
69
+ | Topic | Doc |
70
+ |-------|-----|
71
+ | Install & settings | [docs/installation.md](docs/installation.md) |
72
+ | Purpose | [docs/purpose.md](docs/purpose.md) |
73
+ | Repository layout | [docs/structure.md](docs/structure.md) |
74
+ | Filters & admin export | [docs/filters-and-export.md](docs/filters-and-export.md) |
75
+ | Development | [docs/development.md](docs/development.md) |
76
+ | AI / tooling notes | [docs/AI.md](docs/AI.md) |
77
+
78
+ ## License
79
+
80
+ MIT
@@ -0,0 +1,39 @@
1
+ # django-importexport-flow
2
+
3
+ Declarative reporting for Django: **target model** (`ContentType`), **manager** path, **`filter_config` / `filter_request` / `filter_mandatory`**, **`order_by`**, and **columns** on **`ExportConfigTable`**. Optional **PDF** (`ExportConfigPdf`) and **CSV / XLSX / JSON** export from the admin.
4
+
5
+ **Documentation:** [docs/README.md](docs/README.md)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install django-importexport-flow
11
+ ```
12
+
13
+ ```python
14
+ INSTALLED_APPS = [
15
+ # ...
16
+ "django.contrib.contenttypes",
17
+ "django_boosted",
18
+ "django_importexport_flow",
19
+ ]
20
+ ```
21
+
22
+ ```bash
23
+ python manage.py migrate django_importexport_flow
24
+ ```
25
+
26
+ ## Documentation index
27
+
28
+ | Topic | Doc |
29
+ |-------|-----|
30
+ | Install & settings | [docs/installation.md](docs/installation.md) |
31
+ | Purpose | [docs/purpose.md](docs/purpose.md) |
32
+ | Repository layout | [docs/structure.md](docs/structure.md) |
33
+ | Filters & admin export | [docs/filters-and-export.md](docs/filters-and-export.md) |
34
+ | Development | [docs/development.md](docs/development.md) |
35
+ | AI / tooling notes | [docs/AI.md](docs/AI.md) |
36
+
37
+ ## License
38
+
39
+ MIT
@@ -0,0 +1,84 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "django-importexport-flow"
7
+ version = "0.1.0"
8
+ description = "Declarative export and import definitions for Django (queryset, tabular/PDF, hooks)."
9
+ readme = "README.md"
10
+ authors = [{ name = "Octolo", email = "dev@octolo.tech" }]
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ requires-python = ">=3.10"
14
+ keywords = [
15
+ "django",
16
+ "reporting",
17
+ "export",
18
+ "csv",
19
+ "excel",
20
+ "pdf",
21
+ "contenttypes",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Intended Audience :: Developers",
26
+ "Framework :: Django",
27
+ "Framework :: Django :: 3.2",
28
+ "Framework :: Django :: 4.0",
29
+ "Framework :: Django :: 4.1",
30
+ "Framework :: Django :: 4.2",
31
+ "Framework :: Django :: 5.0",
32
+ "Programming Language :: Python :: 3",
33
+ "Programming Language :: Python :: 3.10",
34
+ "Programming Language :: Python :: 3.11",
35
+ "Programming Language :: Python :: 3.12",
36
+ "Topic :: Software Development :: Libraries :: Python Modules",
37
+ "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
38
+ ]
39
+ dependencies = [
40
+ "Django>=3.2",
41
+ "django-boosted>=1.0.0",
42
+ "openpyxl>=3.1.5",
43
+ "pandas>=3.0.1",
44
+ ]
45
+
46
+ [project.urls]
47
+ Homepage = "https://github.com/octolo/django-importexport-flow"
48
+ Repository = "https://github.com/octolo/django-importexport-flow"
49
+ Documentation = "https://github.com/octolo/django-importexport-flow/blob/main/docs/README.md"
50
+ Issues = "https://github.com/octolo/django-importexport-flow/issues"
51
+
52
+ [project.optional-dependencies]
53
+ dev = [
54
+ "pytest>=8.3",
55
+ "pytest-django>=4.5",
56
+ "ruff>=0.5",
57
+ "mypy>=1.0",
58
+ "django-stubs>=5.0.0",
59
+ "weasyprint>=62.0",
60
+ ]
61
+
62
+
63
+ [tool.setuptools.packages.find]
64
+ where = ["src"]
65
+ include = ["django_importexport_flow*"]
66
+ exclude = ["tests*"]
67
+
68
+ [tool.pytest.ini_options]
69
+ DJANGO_SETTINGS_MODULE = "tests.settings"
70
+ testpaths = ["tests"]
71
+ pythonpath = ["src"]
72
+
73
+ [tool.mypy]
74
+ python_version = "3.10"
75
+ warn_return_any = true
76
+ plugins = ["mypy_django_plugin.main"]
77
+ mypy_path = "src"
78
+
79
+ [tool.django-stubs]
80
+ django_settings_module = "tests.settings"
81
+
82
+ [tool.ruff]
83
+ line-length = 100
84
+ target-version = "py310"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,81 @@
1
+ """django-importexport-flow package."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("django-importexport-flow")
7
+ except PackageNotFoundError:
8
+ __version__ = "0.0.0"
9
+
10
+ __all__ = [
11
+ "ExportConfigPdf",
12
+ "ExportConfigTable",
13
+ "ExportDefinition",
14
+ "ImportDefinition",
15
+ "ImportRequest",
16
+ "ExportRequest",
17
+ "ExportManager",
18
+ "__version__",
19
+ "get_export_definitions",
20
+ "serialize_export_configuration",
21
+ "serialize_import_definition",
22
+ "import_import_definition",
23
+ "serialize_report_import",
24
+ "import_report_import",
25
+ ]
26
+
27
+
28
+ def __getattr__(name: str):
29
+ if name == "ExportManager":
30
+ from .managers import ExportManager
31
+
32
+ return ExportManager
33
+ if name == "serialize_export_configuration":
34
+ from .utils.serialization import serialize_export_configuration
35
+
36
+ return serialize_export_configuration
37
+ if name == "serialize_import_definition":
38
+ from .utils.serialization import serialize_import_definition
39
+
40
+ return serialize_import_definition
41
+ if name == "import_import_definition":
42
+ from .utils.serialization import import_import_definition
43
+
44
+ return import_import_definition
45
+ if name == "serialize_report_import":
46
+ from .utils.serialization import serialize_report_import
47
+
48
+ return serialize_report_import
49
+ if name == "import_report_import":
50
+ from .utils.serialization import import_report_import
51
+
52
+ return import_report_import
53
+ if name == "get_export_definitions":
54
+ from .utils import get_export_definitions
55
+
56
+ return get_export_definitions
57
+ if name == "ExportDefinition":
58
+ from .models import ExportDefinition
59
+
60
+ return ExportDefinition
61
+ if name == "ExportConfigPdf":
62
+ from .models import ExportConfigPdf
63
+
64
+ return ExportConfigPdf
65
+ if name == "ExportConfigTable":
66
+ from .models import ExportConfigTable
67
+
68
+ return ExportConfigTable
69
+ if name == "ImportDefinition":
70
+ from .models import ImportDefinition
71
+
72
+ return ImportDefinition
73
+ if name == "ImportRequest":
74
+ from .models import ImportRequest
75
+
76
+ return ImportRequest
77
+ if name == "ExportRequest":
78
+ from .models import ExportRequest
79
+
80
+ return ExportRequest
81
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,23 @@
1
+ """Django admin registration for django-importexport-flow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Load modules so @admin.register runs.
6
+ from . import export_definition # noqa: F401
7
+ from . import import_definition # noqa: F401
8
+ from . import import_request # noqa: F401
9
+ from . import export_request # noqa: F401
10
+
11
+ from .export_definition import (
12
+ ExportConfigPdfInline,
13
+ ExportConfigTableInline,
14
+ ExportDefinitionAdmin,
15
+ )
16
+ from .import_definition import ImportDefinitionAdmin
17
+
18
+ __all__ = [
19
+ "ExportConfigPdfInline",
20
+ "ExportConfigTableInline",
21
+ "ExportDefinitionAdmin",
22
+ "ImportDefinitionAdmin",
23
+ ]
@@ -0,0 +1,90 @@
1
+ from __future__ import annotations
2
+
3
+ from django.contrib import admin
4
+ from django.contrib import messages
5
+ from django.core.exceptions import PermissionDenied
6
+ from django.urls import reverse
7
+ from django.utils.translation import gettext_lazy as _
8
+
9
+ from django_boosted import AdminBoostModel, admin_boost_view
10
+
11
+ from ..forms import ExportConfigurationImportForm
12
+ from ..models import ExportConfigPdf, ExportConfigTable, ExportDefinition
13
+ from ..utils.serialization import import_export_configuration, serialize_export_configuration
14
+ from .generate_export import GenerateExportMixin
15
+ from .import_config import run_json_configuration_import
16
+
17
+
18
+ class ExportConfigPdfInline(admin.StackedInline):
19
+ model = ExportConfigPdf
20
+ extra = 0
21
+ classes = ("collapse",)
22
+ fields = ("template", "configuration")
23
+
24
+
25
+ class ExportConfigTableInline(admin.StackedInline):
26
+ model = ExportConfigTable
27
+ extra = 0
28
+ classes = ("collapse",)
29
+ fields = ("columns", "configuration")
30
+
31
+
32
+ @admin.register(ExportDefinition)
33
+ class ExportDefinitionAdmin(GenerateExportMixin, AdminBoostModel):
34
+ list_display = ("name", "target", "manager", "uuid")
35
+ search_fields = ("name", "description", "uuid")
36
+ readonly_fields = (
37
+ "uuid",
38
+ "created_by",
39
+ "updated_by",
40
+ "created_at",
41
+ "updated_at",
42
+ )
43
+ inlines = (ExportConfigPdfInline, ExportConfigTableInline)
44
+ fieldsets = (
45
+ (None, {"fields": ("name", "uuid", "description")}),
46
+ (
47
+ _("Model and queryset"),
48
+ {"fields": ("target", "manager", "order_by")},
49
+ ),
50
+ (
51
+ _("Filters"),
52
+ {"fields": ("filter_config", "filter_request", "filter_mandatory")},
53
+ ),
54
+ (
55
+ _("Audit"),
56
+ {"fields": ("created_by", "updated_by", "created_at", "updated_at")},
57
+ ),
58
+ )
59
+
60
+ @admin_boost_view("json", _("Export configuration (JSON)"))
61
+ def export_configuration_json(self, request, obj):
62
+ return serialize_export_configuration(obj)
63
+
64
+ @admin_boost_view("adminform", _("Import configuration (JSON)"))
65
+ def import_configuration_json(self, request, form=None):
66
+ if not self.has_add_permission(request) and not self.has_change_permission(
67
+ request
68
+ ):
69
+ raise PermissionDenied
70
+ if form is None:
71
+ return {"form": ExportConfigurationImportForm()}
72
+ imported = run_json_configuration_import(
73
+ request,
74
+ form,
75
+ import_export_configuration,
76
+ log_label="import_export_configuration",
77
+ )
78
+ if imported is None:
79
+ return {"form": form}
80
+ messages.success(
81
+ request,
82
+ _("Imported export “%(name)s”.") % {"name": imported.name},
83
+ )
84
+ opts = self.model._meta
85
+ url = reverse(
86
+ f"admin:{opts.app_label}_{opts.model_name}_change",
87
+ args=[imported.pk],
88
+ current_app=self.admin_site.name,
89
+ )
90
+ return {"redirect_url": url}
@@ -0,0 +1,47 @@
1
+ """Admin for :class:`~django_importexport_flow.models.ExportRequest` (export audit)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django.contrib import admin
6
+ from django.utils.translation import gettext_lazy as _
7
+
8
+ from ..models import ExportRequest
9
+
10
+
11
+ @admin.register(ExportRequest)
12
+ class ExportRequestAdmin(admin.ModelAdmin):
13
+ list_display = (
14
+ "uuid",
15
+ "export_definition",
16
+ "export_format",
17
+ "status",
18
+ "output_bytes",
19
+ "created_at",
20
+ "completed_at",
21
+ "initiated_by",
22
+ "created_by",
23
+ "updated_by",
24
+ "updated_at",
25
+ )
26
+ list_filter = ("status", "export_format", "created_at")
27
+ search_fields = ("uuid",)
28
+ readonly_fields = (
29
+ "uuid",
30
+ "export_definition",
31
+ "export_format",
32
+ "filter_payload",
33
+ "status",
34
+ "output_bytes",
35
+ "error_trace",
36
+ "created_at",
37
+ "completed_at",
38
+ "initiated_by",
39
+ "created_by",
40
+ "updated_by",
41
+ "updated_at",
42
+ )
43
+ ordering = ("-created_at",)
44
+
45
+ def has_add_permission(self, request):
46
+ """Rows are created by *Generate export* only."""
47
+ return False
@@ -0,0 +1,133 @@
1
+ """Admin mixin: generate table export with filter_request (GET) + filter_config merge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import re
8
+ import traceback
9
+ from typing import Any
10
+
11
+ from django.contrib import messages
12
+ from django.core.exceptions import PermissionDenied, ValidationError
13
+ from django.http import HttpResponse
14
+ from django.utils import timezone
15
+ from django.utils.translation import gettext_lazy as _
16
+
17
+ from django_boosted import admin_boost_view
18
+ from django_boosted.decorators import AdminBoostViewConfig
19
+
20
+ from ..utils.export import definition_has_table_config, run_table_export
21
+ from ..forms import make_export_form_class
22
+ from ..models import ExportRequest
23
+ from ..utils.http import content_disposition_attachment
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ def safe_download_stem(
29
+ raw_name: str | None,
30
+ *,
31
+ fallback: str = "export",
32
+ max_len: int = 80,
33
+ ) -> str:
34
+ """Sanitize a title or name for use as a download filename stem (no extension)."""
35
+ base = re.sub(r"[^\w\-.]+", "_", raw_name or "").strip("_") or fallback
36
+ return base[:max_len]
37
+
38
+
39
+ def _safe_export_filename(name: str) -> str:
40
+ return safe_download_stem(name, fallback="export")
41
+
42
+
43
+ def _export_timestamp_for_filename() -> str:
44
+ """Local time, second precision, safe for filenames (e.g. ``20260329_143045``)."""
45
+ return timezone.localtime(timezone.now()).strftime("%Y%m%d_%H%M%S")
46
+
47
+
48
+ def _filter_payload_snapshot(cleaned_data: dict[str, Any]) -> dict[str, Any]:
49
+ """JSON-safe subset: ``export_format`` and ``fr_*`` keys only."""
50
+ subset = {
51
+ k: v
52
+ for k, v in cleaned_data.items()
53
+ if k == "export_format" or k.startswith("fr_")
54
+ }
55
+ return json.loads(json.dumps(subset, default=str))
56
+
57
+
58
+ def dated_export_filename(safe_stem: str, ext: str) -> str:
59
+ """
60
+ ``safe_stem`` = basename without extension (already sanitized).
61
+ ``ext`` must include the leading dot (e.g. ``.csv``).
62
+ """
63
+ return f"{safe_stem}_{_export_timestamp_for_filename()}{ext}"
64
+
65
+
66
+ class GenerateExportMixin:
67
+ @admin_boost_view(
68
+ "adminform",
69
+ _("Generate export"),
70
+ config=AdminBoostViewConfig(permission="change"),
71
+ )
72
+ def generate_export(self, request, obj, form=None):
73
+ if not self.has_change_permission(request, obj):
74
+ raise PermissionDenied
75
+ FormClass = make_export_form_class(obj)
76
+ if form is None:
77
+ return {"form": FormClass()}
78
+ if not form.is_valid():
79
+ return {"form": form}
80
+ if not definition_has_table_config(obj):
81
+ messages.error(
82
+ request,
83
+ _("Add a table configuration (columns) before exporting."),
84
+ )
85
+ return {"form": form}
86
+ cleaned = form.cleaned_data
87
+ payload = _filter_payload_snapshot(cleaned)
88
+ export_fmt = str(cleaned.get("export_format") or "")
89
+ user = (
90
+ request.user
91
+ if getattr(request.user, "is_authenticated", False)
92
+ else None
93
+ )
94
+ try:
95
+ content, content_type, ext = run_table_export(obj, cleaned)
96
+ except (ValidationError, ValueError) as exc:
97
+ ExportRequest.objects.create(
98
+ export_definition=obj,
99
+ export_format=export_fmt,
100
+ filter_payload=payload,
101
+ status=ExportRequest.Status.FAILURE,
102
+ error_trace=str(exc),
103
+ completed_at=timezone.now(),
104
+ initiated_by=user,
105
+ )
106
+ messages.error(request, str(exc))
107
+ return {"form": form}
108
+ except Exception:
109
+ logger.exception("Table export failed for export definition %r", getattr(obj, "pk", None))
110
+ ExportRequest.objects.create(
111
+ export_definition=obj,
112
+ export_format=export_fmt,
113
+ filter_payload=payload,
114
+ status=ExportRequest.Status.FAILURE,
115
+ error_trace=traceback.format_exc(),
116
+ completed_at=timezone.now(),
117
+ initiated_by=user,
118
+ )
119
+ messages.error(request, _("Export failed."))
120
+ return {"form": form}
121
+ ExportRequest.objects.create(
122
+ export_definition=obj,
123
+ export_format=export_fmt,
124
+ filter_payload=payload,
125
+ status=ExportRequest.Status.SUCCESS,
126
+ output_bytes=len(content),
127
+ completed_at=timezone.now(),
128
+ initiated_by=user,
129
+ )
130
+ filename = dated_export_filename(_safe_export_filename(obj.name), ext)
131
+ response = HttpResponse(content, content_type=content_type)
132
+ response["Content-Disposition"] = content_disposition_attachment(filename)
133
+ return response
@@ -0,0 +1,57 @@
1
+ """Shared admin logic for JSON report configuration import."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ from django.contrib import messages
10
+ from django.core.exceptions import ValidationError
11
+ from django.core.serializers.base import DeserializationError
12
+ from django.db import IntegrityError
13
+ from django.http import HttpRequest
14
+ from django.utils.translation import gettext_lazy as _
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def run_json_configuration_import(
20
+ request: HttpRequest,
21
+ form: Any,
22
+ import_fn: Callable[[dict[str, Any]], Any],
23
+ *,
24
+ log_label: str,
25
+ ) -> Any | None:
26
+ """
27
+ Call ``import_fn(form.import_data)`` and surface errors via messages.
28
+
29
+ Returns the imported instance on success, or ``None`` on failure (the view
30
+ should then return ``{"form": form}``).
31
+ """
32
+ try:
33
+ return import_fn(form.import_data)
34
+ except (ValueError, ValidationError) as exc:
35
+ messages.error(request, str(exc))
36
+ return None
37
+ except DeserializationError as exc:
38
+ logger.warning("%s JSON deserialize failed: %s", log_label, exc)
39
+ messages.error(
40
+ request,
41
+ _("Could not read the configuration from this file."),
42
+ )
43
+ return None
44
+ except IntegrityError as exc:
45
+ logger.warning("%s import integrity error: %s", log_label, exc)
46
+ messages.error(
47
+ request,
48
+ _("Import failed: this configuration conflicts with existing data."),
49
+ )
50
+ return None
51
+ except Exception:
52
+ logger.exception("%s failed", log_label)
53
+ messages.error(
54
+ request,
55
+ _("Import failed. Check the file format and try again."),
56
+ )
57
+ return None