stapel-cms 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.
Files changed (76) hide show
  1. stapel_cms/CONFIG.MD +48 -0
  2. stapel_cms/__init__.py +31 -0
  3. stapel_cms/_capabilities.py +32 -0
  4. stapel_cms/_codegen.py +123 -0
  5. stapel_cms/_codegen_settings.py +116 -0
  6. stapel_cms/actions.py +54 -0
  7. stapel_cms/admin.py +91 -0
  8. stapel_cms/apps.py +27 -0
  9. stapel_cms/beat.py +41 -0
  10. stapel_cms/blocks.py +363 -0
  11. stapel_cms/checks.py +120 -0
  12. stapel_cms/codegen_urls.py +6 -0
  13. stapel_cms/conf.py +92 -0
  14. stapel_cms/conftest.py +106 -0
  15. stapel_cms/docs/capabilities.json +212 -0
  16. stapel_cms/docs/errors.json +632 -0
  17. stapel_cms/docs/flows.json +611 -0
  18. stapel_cms/docs/llms.txt +194 -0
  19. stapel_cms/dto.py +195 -0
  20. stapel_cms/errors.py +76 -0
  21. stapel_cms/flows.py +51 -0
  22. stapel_cms/fsm.py +28 -0
  23. stapel_cms/functions.py +50 -0
  24. stapel_cms/gdpr.py +61 -0
  25. stapel_cms/management/__init__.py +0 -0
  26. stapel_cms/management/commands/__init__.py +0 -0
  27. stapel_cms/management/commands/cms_publish_due.py +12 -0
  28. stapel_cms/management/commands/cms_seed.py +25 -0
  29. stapel_cms/migrations/0001_initial.py +211 -0
  30. stapel_cms/migrations/__init__.py +0 -0
  31. stapel_cms/models.py +241 -0
  32. stapel_cms/pagination.py +113 -0
  33. stapel_cms/presenters.py +128 -0
  34. stapel_cms/py.typed +0 -0
  35. stapel_cms/richtext.py +260 -0
  36. stapel_cms/safety.py +65 -0
  37. stapel_cms/schemas/consumes/user.merged.json +19 -0
  38. stapel_cms/schemas/emits/cms.menu.changed.json +30 -0
  39. stapel_cms/schemas/emits/cms.page.published.json +51 -0
  40. stapel_cms/schemas/emits/cms.page.unpublished.json +30 -0
  41. stapel_cms/schemas/emits/cms.post.published.json +60 -0
  42. stapel_cms/schemas/emits/cms.post.unpublished.json +30 -0
  43. stapel_cms/schemas/emits/cms.redirect.created.json +39 -0
  44. stapel_cms/schemas/functions/cms.feed.json +28 -0
  45. stapel_cms/schemas/functions/cms.resolve_path.json +27 -0
  46. stapel_cms/schemas/functions/cms.sitemap_entries.json +36 -0
  47. stapel_cms/schemas/functions/machine_translate.json +48 -0
  48. stapel_cms/serializers.py +470 -0
  49. stapel_cms/services/__init__.py +20 -0
  50. stapel_cms/services/cache.py +74 -0
  51. stapel_cms/services/content.py +436 -0
  52. stapel_cms/services/enrich.py +109 -0
  53. stapel_cms/services/events.py +59 -0
  54. stapel_cms/services/feed.py +43 -0
  55. stapel_cms/services/forms.py +114 -0
  56. stapel_cms/services/media.py +65 -0
  57. stapel_cms/services/menus.py +173 -0
  58. stapel_cms/services/paths.py +162 -0
  59. stapel_cms/services/preview.py +42 -0
  60. stapel_cms/services/public.py +299 -0
  61. stapel_cms/services/redirects.py +38 -0
  62. stapel_cms/services/seed.py +65 -0
  63. stapel_cms/services/sitemaps.py +54 -0
  64. stapel_cms/services/tags.py +53 -0
  65. stapel_cms/services/translate.py +175 -0
  66. stapel_cms/sitekeys.py +62 -0
  67. stapel_cms/translations/errors.es.json +30 -0
  68. stapel_cms/translations/errors.ru.json +30 -0
  69. stapel_cms/urls.py +13 -0
  70. stapel_cms/urls_v1.py +70 -0
  71. stapel_cms/views.py +793 -0
  72. stapel_cms-0.1.0.dist-info/METADATA +163 -0
  73. stapel_cms-0.1.0.dist-info/RECORD +76 -0
  74. stapel_cms-0.1.0.dist-info/WHEEL +5 -0
  75. stapel_cms-0.1.0.dist-info/licenses/LICENSE +21 -0
  76. stapel_cms-0.1.0.dist-info/top_level.txt +1 -0
stapel_cms/CONFIG.MD ADDED
@@ -0,0 +1,48 @@
1
+ # CONFIG.MD — stapel-cms
2
+
3
+ Config registry for **stapel-cms**. One row per configuration key the module
4
+ reads, its **source** (`env` = the process environment / the `STAPEL_CMS`
5
+ settings dict), what it is for, whether it is required, and its default.
6
+
7
+ Every key is read through `cms_settings` (`stapel_cms.conf`, namespace
8
+ `STAPEL_CMS`). Resolution order per key: `settings.STAPEL_CMS` dict → a flat
9
+ Django setting of the same name → environment variable → the default below.
10
+ `BLOG_ENABLED` and `STAFF_AUTHZ` are CTO-facing config axes. `BLOCK_TYPES`
11
+ MERGES over the built-in block types; every other key replaces its default.
12
+
13
+ ## stapel-cms
14
+
15
+ | Key | Source | Purpose | Required | Default |
16
+ |-----|--------|---------|----------|---------|
17
+ | BLOG_ENABLED | env | axis: false unmounts posts, tags, archives and the feed (pages, menus, redirects stay). | no | true |
18
+ | STAFF_AUTHZ | env | axis: `staff` = any staff account edits; `model_perms` = staff plus the @access mandate per model (`has_perm("cms.<action>_<model>")`). Anything else is check E002. | no | staff |
19
+ | LOCALES | settings | locales content may be written in; must contain DEFAULT_LOCALE (E003). | no | ["en"] |
20
+ | DEFAULT_LOCALE | env | last step of every fallback chain; the locale of seed pages. | no | en |
21
+ | LOCALE_FALLBACKS | settings | `{"de-at": ["de"]}`: fallbacks tried before DEFAULT_LOCALE; every name must be in LOCALES (E003). | no | {} |
22
+ | BLOCK_TYPES | settings | `{"<type>": "dotted.path.PydanticModel" or None}` merged over the built-ins (rich_text, hero, faq, gallery, embed, form, listing_rail); None removes one. Checked by E001. | no | {} |
23
+ | EMBED_HOSTS | settings | exact hosts an embed block may use (https only); bare host names (E005). | no | youtube, youtube-nocookie, vimeo, google maps hosts |
24
+ | PAGE_TEMPLATES | settings | template keys a page may name; the frontend maps each to a layout. Empty is E004. | no | ["default", "landing", "legal", "faq"] |
25
+ | BLOG_PATH_PREFIX | env | public path prefix of posts (`/blog/<slug>`); pages may not live under it. | no | /blog |
26
+ | WORDS_PER_MINUTE | env | reading-time divisor. | no | 200 |
27
+ | REVISIONS_KEEP | env | revisions kept per page or post; the live and scheduled ones are never pruned. | no | 50 |
28
+ | PAGE_MAX_DEPTH | env | path segments a page may have. | no | 6 |
29
+ | MENU_MAX_DEPTH | env | nesting levels of a menu. | no | 3 |
30
+ | MENU_MAX_ITEMS | env | items per menu. | no | 200 |
31
+ | MAX_BLOCKS | env | blocks per page or post. | no | 200 |
32
+ | MAX_BLOCKS_BYTES | env | serialized size of a block list. | no | 262144 |
33
+ | PREVIEW_TOKEN_TTL_SECONDS | env | lifetime of a signed preview link. | no | 3600 |
34
+ | PREVIEW_URL_TEMPLATE | env | `https://…?token={token}` returned with a preview token; empty = no url. | no | "" |
35
+ | SITE_ORIGIN | env | absolute origin for feed links when the site registry is empty. | no | "" |
36
+ | FEED_ITEMS | env | posts in the RSS/Atom feed. | no | 20 |
37
+ | CACHE_ALIAS | env | Django cache alias of the public read cache; a per-process cache is warning W002. | no | default |
38
+ | CACHE_TTL_SECONDS | env | lifetime of a cached public body (bounds staleness on a per-process cache). | no | 300 |
39
+ | HTTP_MAX_AGE | env | `Cache-Control: public, max-age` of public reads. | no | 60 |
40
+ | MEDIA_REFS_FUNCTION | env | comm Function told which cdn refs content uses (`cdn.refs_sync` contract); empty disables. | no | cdn.refs_sync |
41
+ | MACHINE_TRANSLATE | env | comm Function `{texts, source, target}` → `{texts}` for machine-translated locale variants; empty = off; unreachable is W001. | no | "" |
42
+ | MACHINE_TRANSLATE_TIMEOUT_SECONDS | env | seconds one MACHINE_TRANSLATE call may take (a page is several sequential calls). | no | 300 |
43
+ | MACHINE_TRANSLATE_MAX_TEXT_CHARS | env | chars per text the translation Function accepts; longer rich-text leaves are split at sentence boundaries and rejoined. | no | 5000 |
44
+ | MACHINE_TRANSLATE_MAX_ITEMS | env | texts per translation call. | no | 2000 |
45
+ | MACHINE_TRANSLATE_MAX_CHARS | env | chars per translation call. | no | 200000 |
46
+ | FORM_EXISTS_FUNCTION | env | comm Function `{public_id}` → `{exists, published}` checking a form block on save (unknown refused) and publish (unpublished refused); unreachable = shape check plus a warning; empty disables. | no | forms.form.exists |
47
+ | MEDIA_DESCRIBE_FUNCTION | env | comm Function `{refs}` → `{items, missing}` (`cdn.describe_many`) describing the images of a public page or post answer (`media`, `seo.og_image_url`); unreachable = bare refs only; empty disables. | no | cdn.describe_many |
48
+ | MEDIA_DESCRIBE_MAX_REFS | env | refs described per public answer (one call); the rest stay bare refs. | no | 50 |
stapel_cms/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """stapel-cms — Public content: pages, blog, menus and SEO for the Stapel framework.
2
+
3
+ Public API (lazily exported, PEP 562 — importing this package never pulls
4
+ in Django or requires configured settings):
5
+
6
+ - ``cms_settings`` — resolved app settings (``stapel_cms.conf``).
7
+ """
8
+
9
+ __all__ = [
10
+ "cms_settings",
11
+ ]
12
+
13
+ # name -> submodule that defines it. Resolution is deferred until first
14
+ # attribute access so that `import stapel_cms` stays Django-free.
15
+ _LAZY_EXPORTS = {
16
+ "cms_settings": ".conf",
17
+ }
18
+
19
+
20
+ def __getattr__(name):
21
+ if name in _LAZY_EXPORTS:
22
+ from importlib import import_module
23
+
24
+ value = getattr(import_module(_LAZY_EXPORTS[name], __name__), name)
25
+ globals()[name] = value # cache for subsequent lookups
26
+ return value
27
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
28
+
29
+
30
+ def __dir__():
31
+ return sorted(set(globals()) | set(__all__))
@@ -0,0 +1,32 @@
1
+ """stapel-cms capabilities.json emitter — thin shim over stapel_tools.capabilities."""
2
+ from pathlib import Path
3
+
4
+ from stapel_tools.capabilities import axis_group_rules, run_capabilities_cli
5
+
6
+
7
+ def main(argv=None):
8
+ from stapel_cms._codegen import _configure
9
+
10
+ _configure()
11
+ from stapel_cms.conf import DEFAULTS
12
+ from stapel_cms.urls import GATE_REGISTRY
13
+
14
+ # CTO-facing axes: BLOG_ENABLED (unmounts the blog routes), STAFF_AUTHZ
15
+ # (who may edit) and EMBED_HOSTS (which embeds render; published to
16
+ # clients in the resolve answer's meta). BLOCK_TYPES is the extension seam.
17
+ axes = {"BLOG_ENABLED", "STAFF_AUTHZ", "EMBED_HOSTS"}
18
+ return run_capabilities_cli(
19
+ argv,
20
+ repo=Path(__file__).resolve().parent,
21
+ canonical_prefix="/cms/api/v1",
22
+ defaults=DEFAULTS,
23
+ registry=GATE_REGISTRY,
24
+ is_axis=lambda k: k in axes,
25
+ axis_group=axis_group_rules(exact={"BLOG_ENABLED": "cms.blog", "STAFF_AUTHZ": "cms.staff",
26
+ "EMBED_HOSTS": "cms.embed"}),
27
+ prog="stapel-cms-capabilities",
28
+ )
29
+
30
+
31
+ if __name__ == "__main__":
32
+ raise SystemExit(main())
stapel_cms/_codegen.py ADDED
@@ -0,0 +1,123 @@
1
+ """stapel-cms contract-emission harness (contract-pipeline.md §2-3).
2
+
3
+ Emits the module's own contract triad into ``docs/`` from a single-module
4
+ ``{cms + core}`` Django instance mounted at the canonical
5
+ ``cms/api/v1/`` prefix:
6
+
7
+ docs/schema.json drf-spectacular OpenAPI, this module only, canonical prefix
8
+ docs/flows.json generate_flow_docs machine artifact ([] — no @flow_step here)
9
+ docs/errors.json generate_error_keys registry
10
+
11
+ The *mechanism* is stapel_tools.codegen (shared, unchanged); this file is the
12
+ thin per-module *config* that wires the module's settings + canonical mount.
13
+
14
+ Usage:
15
+ python -m stapel_cms._codegen --out docs # `make contract`
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import os
21
+ import sys
22
+ from pathlib import Path
23
+
24
+
25
+ def _configure() -> None:
26
+ """Configure + boot the single-module Django instance for emission."""
27
+ repo_root = os.path.dirname(os.path.abspath(__file__))
28
+ sys.path[:] = [p for p in sys.path if os.path.abspath(p or os.getcwd()) != repo_root]
29
+
30
+ from django.conf import settings
31
+
32
+ if not settings.configured:
33
+ from stapel_cms._codegen_settings import settings_kwargs
34
+
35
+ settings.configure(
36
+ **settings_kwargs(root_urlconf="stapel_cms.codegen_urls", contract=True)
37
+ )
38
+
39
+ import django
40
+
41
+ django.setup()
42
+
43
+ from drf_spectacular.settings import spectacular_settings
44
+
45
+ from stapel_cms._codegen_settings import CODEGEN_SCHEMA_PATH_PREFIX
46
+
47
+ spectacular_settings.SCHEMA_PATH_PREFIX = CODEGEN_SCHEMA_PATH_PREFIX
48
+
49
+ # Stable enum component names (stapel-schema-lint SCH004).
50
+ from drf_spectacular.plumbing import _load_enum_name_overrides
51
+
52
+ from stapel_cms._codegen_settings import enum_name_overrides
53
+
54
+ spectacular_settings.ENUM_NAME_OVERRIDES = enum_name_overrides()
55
+ _load_enum_name_overrides.cache_clear()
56
+
57
+ # Register drf-spectacular's JWT cookie-auth extension explicitly (a real
58
+ # host triggers this as a side effect of wiring its Swagger URLs). Without
59
+ # it, the protected endpoints
60
+ # would emit without their `security: [{"JWTCookieAuth": []}]` entry — a
61
+ # real contract gap. Applied per stapel-calendar's precedent.
62
+ from stapel_core.django.openapi.swagger import _register_jwt_auth_extension
63
+
64
+ _register_jwt_auth_extension()
65
+
66
+
67
+ def _require_python_312() -> None:
68
+ """Abort emission if not running the pinned 3.12 interpreter.
69
+
70
+ drf-spectacular's rendering of component descriptions (``Optional[X]`` vs
71
+ ``X | None``) depends on the Python minor version — contracts emitted on
72
+ anything other than 3.12 (the CI/monolith pin) produce false diffs.
73
+ """
74
+ if sys.version_info[:2] != (3, 12):
75
+ got = f"{sys.version_info.major}.{sys.version_info.minor}"
76
+ raise SystemExit(
77
+ f"stapel-cms contract emission ABORTED: running Python {got}, "
78
+ "but contracts must be emitted on Python 3.12 (the CI/monolith "
79
+ "pin). drf-spectacular renders component descriptions (Optional[X] "
80
+ "vs X | None) differently across Python minor versions, so emitting "
81
+ "on any other minor produces false diffs against the committed "
82
+ "docs/*.json. Re-run under a 3.12 interpreter."
83
+ )
84
+
85
+
86
+ def main(argv: list[str] | None = None) -> int:
87
+ _require_python_312()
88
+
89
+ parser = argparse.ArgumentParser(
90
+ prog="stapel-cms-contract",
91
+ description="Emit this module's contract triad (schema.json + flows.json "
92
+ "+ errors.json) into --out, canonical /cms/api/v1/ prefix.",
93
+ )
94
+ parser.add_argument(
95
+ "--out",
96
+ default="docs",
97
+ help="Output directory for the triad (default: docs).",
98
+ )
99
+ args = parser.parse_args(argv)
100
+
101
+ _configure()
102
+
103
+ from stapel_tools.codegen import emit_errors, emit_flows, emit_schema
104
+
105
+ out = Path(args.out)
106
+ out.mkdir(parents=True, exist_ok=True)
107
+ paths = emit_schema(out / "schema.json")
108
+ # Profile 2 goes to its own file: docs/schema.json is what stapel-react's
109
+ # generators read, and stays profile 1.
110
+ emit_schema(out / "schema.v2.json", contract_profile=2)
111
+ flows = emit_flows(out / "flows.json")
112
+ errors = emit_errors(out / "errors.json")
113
+
114
+ print(
115
+ f"stapel-cms contract: {paths} paths, {flows} flows, {errors} error keys "
116
+ f"→ {out}/",
117
+ file=sys.stderr,
118
+ )
119
+ return 0
120
+
121
+
122
+ if __name__ == "__main__":
123
+ raise SystemExit(main())
@@ -0,0 +1,116 @@
1
+ """Single-module Django settings shared by the test suite and contract emission.
2
+
3
+ One copy, so the harness that emits ``docs/schema.json`` and the tests that
4
+ prove it can never drift in INSTALLED_APPS or comm config. The production
5
+ ``REST_FRAMEWORK`` (exception handler, schema class) is used by both: the
6
+ error envelope the tests assert is the one a host serves.
7
+ """
8
+ from __future__ import annotations
9
+
10
+
11
+ def settings_kwargs(
12
+ *,
13
+ root_urlconf: str = "stapel_cms.tests.urls",
14
+ contract: bool = False,
15
+ neighbours: bool = False,
16
+ ) -> dict:
17
+ """``neighbours=True`` (the test suite) also installs whichever neighbour
18
+ modules cms reaches by Function name are importable (stapel-forms,
19
+ stapel-translate), so the seams are proved against the real providers.
20
+ Contract emission never installs them: the contract is cms's alone."""
21
+ rest_framework = {
22
+ "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
23
+ "DEFAULT_SCHEMA_CLASS": "stapel_core.django.openapi.schemas.PermissionAwareAutoSchema",
24
+ "EXCEPTION_HANDLER": "stapel_core.django.api.errors.stapel_exception_handler",
25
+ }
26
+ if contract:
27
+ rest_framework.update({
28
+ "DEFAULT_AUTHENTICATION_CLASSES": [
29
+ "stapel_core.django.jwt.authentication.JWTCookieAuthentication",
30
+ ],
31
+ "DEFAULT_PERMISSION_CLASSES": [
32
+ "stapel_core.django.api.permissions.IsServiceRequest",
33
+ "stapel_core.django.api.permissions.IsSuperUser",
34
+ ],
35
+ "DEFAULT_RENDERER_CLASSES": [
36
+ "rest_framework.renderers.JSONRenderer",
37
+ "rest_framework.renderers.BrowsableAPIRenderer",
38
+ ],
39
+ })
40
+ return dict(
41
+ SECRET_KEY="test-secret-key-not-for-production",
42
+ DEBUG=False,
43
+ INSTALLED_APPS=[
44
+ "django.contrib.contenttypes",
45
+ "django.contrib.auth",
46
+ "django.contrib.sessions",
47
+ "django.contrib.admin",
48
+ "django.contrib.messages",
49
+ "stapel_core.django.apps.CommonDjangoConfig",
50
+ "stapel_core.django.users",
51
+ "rest_framework",
52
+ "drf_spectacular",
53
+ "stapel_cms",
54
+ *(_neighbour_apps() if neighbours and not contract else []),
55
+ ],
56
+ AUTH_USER_MODEL="users.User",
57
+ DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
58
+ DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
59
+ USE_TZ=True,
60
+ ROOT_URLCONF=root_urlconf,
61
+ ALLOWED_HOSTS=["*"],
62
+ CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}},
63
+ STAPEL_BUS_BACKEND="stapel_core.bus.backends.memory.MemoryBus",
64
+ STAPEL_COMM={
65
+ "OUTBOX_ENABLED": False,
66
+ "ACTION_TRANSPORT": "inprocess",
67
+ "VALIDATE_SCHEMAS": True,
68
+ },
69
+ STAPEL_CMS={"LOCALES": ["en", "de"]},
70
+ TEMPLATES=[{
71
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
72
+ "APP_DIRS": True,
73
+ "OPTIONS": {"context_processors": [
74
+ "django.template.context_processors.request",
75
+ "django.contrib.auth.context_processors.auth",
76
+ "django.contrib.messages.context_processors.messages",
77
+ ]},
78
+ }],
79
+ MIDDLEWARE=[
80
+ "django.contrib.sessions.middleware.SessionMiddleware",
81
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
82
+ "django.contrib.messages.middleware.MessageMiddleware",
83
+ ],
84
+ MIGRATION_MODULES={"users": None},
85
+ REST_FRAMEWORK=rest_framework,
86
+ )
87
+
88
+
89
+ def _neighbour_apps() -> list[str]:
90
+ from importlib.util import find_spec
91
+
92
+ apps = []
93
+ if find_spec("stapel_translate") is not None:
94
+ apps += ["stapel_core.django.taskstore", "stapel_translate"]
95
+ if find_spec("stapel_forms") is not None:
96
+ apps.append("stapel_forms")
97
+ return apps
98
+
99
+
100
+ #: Forced on drf-spectacular's singleton so a single-module instance derives
101
+ #: the same operation ids as a multi-module aggregate.
102
+ CODEGEN_SCHEMA_PATH_PREFIX = "/"
103
+
104
+
105
+ def enum_name_overrides() -> dict:
106
+ """Stable enum component names (stapel-schema-lint SCH004)."""
107
+ from stapel_cms.models import RedirectSource, Status, TargetType
108
+ from stapel_cms.serializers import CONTENT_WARNING_CODES
109
+
110
+ return {
111
+ "CmsStatusEnum": Status,
112
+ "CmsResolveKindEnum": [("page", "page"), ("post", "post"), ("redirect", "redirect")],
113
+ "CmsMenuTargetEnum": TargetType,
114
+ "CmsRedirectSourceEnum": RedirectSource,
115
+ "CmsContentWarningCodeEnum": CONTENT_WARNING_CODES,
116
+ }
stapel_cms/actions.py ADDED
@@ -0,0 +1,54 @@
1
+ """Action subscriptions of stapel-cms. Handlers are idempotent.
2
+
3
+ - ``user.merged`` (stapel-auth) — authorship ids follow the surviving
4
+ account. Staff are rarely guests, but a silent answer to a merge is the
5
+ defect class ``stapel_core.comm.lifecycle_checks`` exists for.
6
+ - ``user.deleted`` / ``gdpr.erasure.requested`` are answered by
7
+ ``register_gdpr_owner`` (``apps.py``), not here.
8
+ """
9
+ import json
10
+ import logging
11
+ from pathlib import Path
12
+
13
+ from django.db import transaction
14
+ from stapel_core.comm import on_action
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _CONSUMES = Path(__file__).resolve().parent / "schemas" / "consumes"
19
+
20
+
21
+ def _schema(name: str) -> dict:
22
+ return json.loads((_CONSUMES / f"{name}.json").read_text(encoding="utf-8"))
23
+
24
+
25
+ def reparent_authors(from_user_id: str, into_user_id: str) -> dict:
26
+ """Move every authorship id from one account to another; counts what moved."""
27
+ from .models import Page, Post, Redirect, Revision
28
+
29
+ moved = {}
30
+ for model in (Page, Post):
31
+ moved[f"{model._meta.model_name}_authors"] = model.objects.filter(author_id=from_user_id).update(
32
+ author_id=into_user_id)
33
+ moved[f"{model._meta.model_name}_editors"] = model.objects.filter(updated_by_id=from_user_id).update(
34
+ updated_by_id=into_user_id)
35
+ moved["revisions"] = Revision.objects.filter(created_by_id=from_user_id).update(created_by_id=into_user_id)
36
+ moved["redirects"] = Redirect.objects.filter(created_by_id=from_user_id).update(created_by_id=into_user_id)
37
+ return moved
38
+
39
+
40
+ @on_action("user.merged", schema=_schema("user.merged"))
41
+ def handle_user_merged(event):
42
+ """Re-parent the guest's authorship ids to the surviving account."""
43
+ payload = event.payload or {}
44
+ from_user_id = str(payload.get("from_user_id") or "")
45
+ into_user_id = str(payload.get("into_user_id") or "")
46
+ if not from_user_id or not into_user_id:
47
+ logger.error("user.merged without from/into user id: %s", event.event_id)
48
+ return
49
+ if from_user_id == into_user_id:
50
+ return
51
+ with transaction.atomic():
52
+ moved = reparent_authors(from_user_id, into_user_id)
53
+ if any(moved.values()):
54
+ logger.info("user.merged %s -> %s: %s", from_user_id, into_user_id, moved)
stapel_cms/admin.py ADDED
@@ -0,0 +1,91 @@
1
+ """Admin for stapel-cms.
2
+
3
+ Status moves only through the service (publish/archive actions), never a raw
4
+ field edit, so every move is checked by the FSM, snapshotted and announced.
5
+ Revisions are read-only.
6
+ """
7
+ from django.contrib import admin, messages
8
+
9
+ from .models import Menu, MenuItem, Page, Post, Redirect, Revision, Tag
10
+
11
+ WORKFLOW_FIELDS = ("status", "version", "live_revision", "scheduled_revision", "publish_at", "published_at",
12
+ "last_published_at", "archived_at", "author_id", "updated_by_id", "media_refs",
13
+ "translation_group")
14
+
15
+
16
+ def _transition_action(kind: str, to_status: str):
17
+ def action(modeladmin, request, queryset):
18
+ from .services import CmsError
19
+ from .services.content import transition
20
+
21
+ moved = refused = 0
22
+ for obj in queryset:
23
+ try:
24
+ transition(kind, obj.pk, request.user, to_status)
25
+ moved += 1
26
+ except CmsError:
27
+ refused += 1
28
+ if moved:
29
+ modeladmin.message_user(request, f"{moved} item(s) moved to {to_status}.")
30
+ if refused:
31
+ modeladmin.message_user(request, f"{refused} item(s) cannot move to {to_status}.", messages.WARNING)
32
+
33
+ action.__name__ = f"{kind}_{to_status}"
34
+ action.short_description = f"Move selected to {to_status}"
35
+ return action
36
+
37
+
38
+ @admin.register(Page)
39
+ class PageAdmin(admin.ModelAdmin):
40
+ list_display = ("path", "title", "site", "locale", "status", "last_published_at")
41
+ list_filter = ("status", "site", "locale", "template")
42
+ search_fields = ("title", "path")
43
+ readonly_fields = ("path", *WORKFLOW_FIELDS)
44
+ actions = [_transition_action("page", "published"), _transition_action("page", "archived")]
45
+
46
+
47
+ @admin.register(Post)
48
+ class PostAdmin(admin.ModelAdmin):
49
+ list_display = ("slug", "title", "site", "locale", "status", "published_at")
50
+ list_filter = ("status", "site", "locale")
51
+ search_fields = ("title", "slug")
52
+ readonly_fields = ("reading_time_minutes", *WORKFLOW_FIELDS)
53
+ actions = [_transition_action("post", "published"), _transition_action("post", "archived")]
54
+
55
+
56
+ @admin.register(Tag)
57
+ class TagAdmin(admin.ModelAdmin):
58
+ list_display = ("name", "slug", "site", "locale")
59
+ list_filter = ("site", "locale")
60
+
61
+
62
+ class MenuItemInline(admin.TabularInline):
63
+ model = MenuItem
64
+ extra = 0
65
+ fields = ("parent", "position", "label", "target_type", "page", "post", "url", "route", "new_tab")
66
+
67
+
68
+ @admin.register(Menu)
69
+ class MenuAdmin(admin.ModelAdmin):
70
+ list_display = ("key", "title", "site", "locale", "updated_at")
71
+ list_filter = ("site", "locale")
72
+ inlines = [MenuItemInline]
73
+
74
+
75
+ @admin.register(Redirect)
76
+ class RedirectAdmin(admin.ModelAdmin):
77
+ list_display = ("old_path", "new_path", "site", "locale", "permanent", "source")
78
+ list_filter = ("source", "site", "locale")
79
+ search_fields = ("old_path", "new_path")
80
+
81
+
82
+ @admin.register(Revision)
83
+ class RevisionAdmin(admin.ModelAdmin):
84
+ list_display = ("kind", "object_id", "number", "note", "created_by_id", "created_at")
85
+ list_filter = ("kind",)
86
+
87
+ def has_add_permission(self, request):
88
+ return False
89
+
90
+ def has_change_permission(self, request, obj=None):
91
+ return False
stapel_cms/apps.py ADDED
@@ -0,0 +1,27 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class CmsConfig(AppConfig):
5
+ name = "stapel_cms"
6
+ label = "cms"
7
+ verbose_name = "Public content: pages, blog, menus and SEO"
8
+ default_auto_field = "django.db.models.BigAutoField"
9
+
10
+ def ready(self):
11
+ from . import actions # noqa: F401
12
+ from . import checks # noqa: F401
13
+ from . import errors # noqa: F401
14
+ from . import flows # noqa: F401
15
+ from . import functions # noqa: F401
16
+
17
+ from stapel_core.gdpr import gdpr_registry, register_gdpr_owner
18
+
19
+ from .gdpr import OWNER, SUBJECT_TYPES, CmsGDPRProvider, erase_subject
20
+
21
+ if not any(p.section == OWNER for p in gdpr_registry.providers):
22
+ gdpr_registry.register(CmsGDPRProvider())
23
+ register_gdpr_owner(OWNER, SUBJECT_TYPES, erase_subject)
24
+
25
+ from .services.sitemaps import register_provider
26
+
27
+ register_provider()
stapel_cms/beat.py ADDED
@@ -0,0 +1,41 @@
1
+ """The scheduled-publication pass — shipped by the library.
2
+
3
+ Wire it in the settings module itself::
4
+
5
+ from stapel_cms.beat import get_cms_beat_schedule
6
+
7
+ CELERY_BEAT_SCHEDULE = {**get_cms_beat_schedule(), ...}
8
+
9
+ Every minute, scheduled snapshots whose ``publish_at`` has come are promoted
10
+ (facts emitted, cache invalidated). The public read already serves a due
11
+ snapshot without the beat; the pass makes it durable and announced. Celery
12
+ is optional: ``manage.py cms_publish_due`` runs the same pass.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ PUBLISH_DUE_TASK_NAME = "stapel_cms.beat.publish_due"
17
+ PUBLISH_DUE_BEAT_KEY = "cms-publish-due"
18
+ PUBLISH_DUE_INTERVAL_SECONDS = 60
19
+
20
+
21
+ def publish_due() -> int:
22
+ """One promotion pass. A plain callable for hosts without Celery."""
23
+ from .services.content import promote_due
24
+
25
+ return promote_due()
26
+
27
+
28
+ def get_cms_beat_schedule() -> dict:
29
+ """Beat entry for the pass. Add to ``CELERY_BEAT_SCHEDULE``."""
30
+ return {PUBLISH_DUE_BEAT_KEY: {"task": PUBLISH_DUE_TASK_NAME, "schedule": float(PUBLISH_DUE_INTERVAL_SECONDS)}}
31
+
32
+
33
+ try: # pragma: no cover - exercised by whichever profile the host installs
34
+ from celery import shared_task
35
+ except ImportError:
36
+ pass
37
+ else:
38
+ publish_due = shared_task(name=PUBLISH_DUE_TASK_NAME)(publish_due)
39
+
40
+
41
+ __all__ = ["PUBLISH_DUE_BEAT_KEY", "PUBLISH_DUE_TASK_NAME", "get_cms_beat_schedule", "publish_due"]