stapel-forms 0.6.3__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 (55) hide show
  1. stapel_forms/CONFIG.MD +81 -0
  2. stapel_forms/__init__.py +31 -0
  3. stapel_forms/_capabilities.py +216 -0
  4. stapel_forms/_codegen.py +117 -0
  5. stapel_forms/_codegen_settings.py +165 -0
  6. stapel_forms/actions.py +179 -0
  7. stapel_forms/admin.py +440 -0
  8. stapel_forms/apps.py +31 -0
  9. stapel_forms/authz.py +137 -0
  10. stapel_forms/checks.py +188 -0
  11. stapel_forms/codegen_urls.py +15 -0
  12. stapel_forms/conf.py +131 -0
  13. stapel_forms/conftest.py +141 -0
  14. stapel_forms/docs/capabilities.json +536 -0
  15. stapel_forms/docs/errors.json +668 -0
  16. stapel_forms/docs/flows.json +1 -0
  17. stapel_forms/docs/llms.txt +253 -0
  18. stapel_forms/docs/schema.json +1514 -0
  19. stapel_forms/dto.py +110 -0
  20. stapel_forms/errors.py +148 -0
  21. stapel_forms/events.py +59 -0
  22. stapel_forms/export.py +151 -0
  23. stapel_forms/functions.py +13 -0
  24. stapel_forms/gdpr.py +82 -0
  25. stapel_forms/management/__init__.py +0 -0
  26. stapel_forms/management/commands/__init__.py +0 -0
  27. stapel_forms/management/commands/forms_purge_expired.py +22 -0
  28. stapel_forms/migrations/0001_initial.py +88 -0
  29. stapel_forms/migrations/__init__.py +0 -0
  30. stapel_forms/models.py +157 -0
  31. stapel_forms/notifications.py +231 -0
  32. stapel_forms/presenters.py +469 -0
  33. stapel_forms/py.typed +0 -0
  34. stapel_forms/schema.py +393 -0
  35. stapel_forms/schemas/emits/form.closed.json +12 -0
  36. stapel_forms/schemas/emits/form.published.json +13 -0
  37. stapel_forms/schemas/emits/form.submission.received.json +14 -0
  38. stapel_forms/serializers.py +163 -0
  39. stapel_forms/services.py +520 -0
  40. stapel_forms/static/stapel_forms/forms-builder.js +320 -0
  41. stapel_forms/tasks.py +78 -0
  42. stapel_forms/templates/admin/forms/change_form.html +32 -0
  43. stapel_forms/templates/admin/forms/responses.html +125 -0
  44. stapel_forms/templates/admin/forms/submission_answers.html +24 -0
  45. stapel_forms/translations/.state.json +174 -0
  46. stapel_forms/translations/errors.es.json +23 -0
  47. stapel_forms/translations/errors.ru.json +23 -0
  48. stapel_forms/urls.py +18 -0
  49. stapel_forms/urls_v1.py +93 -0
  50. stapel_forms/views.py +843 -0
  51. stapel_forms-0.6.3.dist-info/METADATA +211 -0
  52. stapel_forms-0.6.3.dist-info/RECORD +55 -0
  53. stapel_forms-0.6.3.dist-info/WHEEL +5 -0
  54. stapel_forms-0.6.3.dist-info/licenses/LICENSE +21 -0
  55. stapel_forms-0.6.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,179 @@
1
+ """Action subscriptions of stapel-forms.
2
+
3
+ Handlers are idempotent-minded (delivery is at-least-once — outbox retries,
4
+ broker redelivery). Transport is chosen by ``STAPEL_COMM`` (in-process in a
5
+ monolith, bus consumer in microservices); the handler code is identical.
6
+
7
+ Three consumers:
8
+
9
+ - ``user.deleted`` → the GDPR provider's erasure of an authenticated
10
+ respondent's answers;
11
+ - ``user.merged`` → the other half of that account life cycle: a guest
12
+ folded into an existing account has its rows re-parented, not erased;
13
+ - this module's OWN ``form.submission.received`` → the notify subscriber.
14
+ Reacting to our own event rather than calling the notifier inline is
15
+ what makes the auto-notify survive the transaction: the row is committed
16
+ before anybody is told about it, and a notification service outage can
17
+ never roll back a respondent's answer.
18
+ """
19
+ import logging
20
+
21
+ from django.core.exceptions import ValidationError
22
+ from stapel_core.comm import on_action
23
+
24
+ from .events import FORM_SUBMISSION_RECEIVED
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class MergeTargetNotReady(RuntimeError):
30
+ """A ``user.merged`` arrived before the surviving account exists here.
31
+
32
+ Transient, not a bug: the guest has forms or answers to carry over but
33
+ there is no local user row to point their FKs at yet. Raising is the
34
+ comm layer's retry signal — ``deliver()`` wraps a failing handler in
35
+ ``ActionDeliveryError`` and the outbox redelivers — so the transfer
36
+ completes once the survivor's user projection lands. An operator seeing
37
+ this in a redelivery loop is looking at an ordering lag, not a defect.
38
+ """
39
+
40
+
41
+ @on_action("user.deleted")
42
+ def handle_user_deleted(event):
43
+ """Erase a user's form answers (GDPR Art. 17)."""
44
+ from .gdpr import FormsGDPRProvider
45
+
46
+ user_id = event.payload.get("user_id")
47
+ if not user_id:
48
+ logger.error("user.deleted event without user_id: %s", event.event_id)
49
+ return
50
+ FormsGDPRProvider().delete(user_id)
51
+
52
+
53
+ @on_action("user.merged")
54
+ def handle_user_merged(event):
55
+ """Carry a merged-away account's forms and answers over to the survivor.
56
+
57
+ Re-parents the three columns this module keys by a user, in one
58
+ transaction:
59
+
60
+ * :class:`~stapel_forms.models.Form` ``created_by`` and
61
+ :class:`~stapel_forms.models.FormVersion` ``created_by`` — who built
62
+ the questionnaire and who published each immutable version;
63
+ * :class:`~stapel_forms.models.Submission` ``submitted_by`` — the
64
+ answers a signed-in respondent gave. An answer belongs to the person
65
+ who typed it, and after the merge that person is the survivor.
66
+
67
+ The opposite instruction to ``user.deleted``, which *destroys* the same
68
+ answers: an account erasure means "this is my data, delete it", a merge
69
+ means "this is still my data, under my other account". Answering only
70
+ the first would leave a guest's responses attributed to an id that can
71
+ no longer sign in — outside the survivor's export, and outside any
72
+ future erasure request too, because none is ever made for a merged-away
73
+ account.
74
+
75
+ A submission already erased under the GDPR path carries
76
+ ``submitted_by = None`` (the tombstone) and is therefore untouched here:
77
+ a merge does not resurrect an attribution its owner asked to have
78
+ removed.
79
+
80
+ Two different "unknown id" situations, and conflating them loses data:
81
+
82
+ * the guest owns nothing here (never answered, or a previous delivery
83
+ already moved it all) — a genuine no-op, returned quietly;
84
+ * the guest owns rows but the survivor has no user row here yet — NOT a
85
+ no-op. :class:`MergeTargetNotReady` is raised so the event is
86
+ redelivered, because returning success would let the outbox mark it
87
+ delivered and strand the answers.
88
+ """
89
+ from django.contrib.auth import get_user_model
90
+ from django.db import transaction
91
+
92
+ from .models import Form, FormVersion, Submission
93
+
94
+ payload = event.payload or {}
95
+ from_user_id = payload.get("from_user_id")
96
+ into_user_id = payload.get("into_user_id")
97
+ if not from_user_id or not into_user_id:
98
+ logger.error("user.merged without from/into user id: %s", event.event_id)
99
+ return
100
+ if str(from_user_id) == str(into_user_id):
101
+ return
102
+
103
+ #: model -> the column naming a user on it.
104
+ owned = (
105
+ (Form, "created_by_id"),
106
+ (FormVersion, "created_by_id"),
107
+ (Submission, "submitted_by"),
108
+ )
109
+
110
+ with transaction.atomic():
111
+ # Both reads and the decision they feed happen inside the transaction
112
+ # and before the first write, so the "not yet" path below can never
113
+ # leave half the rows moved.
114
+ try:
115
+ owns_something = any(
116
+ model.objects.filter(**{column: from_user_id}).exists()
117
+ for model, column in owned
118
+ )
119
+ # The survivor probe is read here, under the same guard, because a
120
+ # malformed *into* id must not escape as a poison pill either.
121
+ survivor_exists = (
122
+ get_user_model().objects.filter(pk=into_user_id).exists()
123
+ )
124
+ except (ValidationError, ValueError, TypeError):
125
+ # Django raises ValidationError (not ValueError) for a malformed
126
+ # UUID; an id that cannot address a row here names nothing, and an
127
+ # escaping exception is a poison pill no redelivery repairs.
128
+ logger.warning("user.merged with unusable user ids: %s", event.event_id)
129
+ return
130
+ if not owns_something:
131
+ # Quiet by design — this is also the at-least-once idempotency
132
+ # path: a redelivery finds nothing left under the guest.
133
+ return
134
+ if not survivor_exists:
135
+ raise MergeTargetNotReady(
136
+ f"user.merged {from_user_id} -> {into_user_id}: the surviving "
137
+ f"account has no user row in stapel-forms yet; redeliver once "
138
+ f"its projection has landed"
139
+ )
140
+
141
+ moved = {
142
+ model.__name__: model.objects.filter(**{column: from_user_id}).update(
143
+ **{column: into_user_id}
144
+ )
145
+ for model, column in owned
146
+ }
147
+
148
+ logger.info(
149
+ "user.merged %s -> %s: forms rows carried over (%s)",
150
+ from_user_id, into_user_id, moved,
151
+ )
152
+
153
+
154
+ @on_action(FORM_SUBMISSION_RECEIVED)
155
+ def handle_submission_received(event):
156
+ """Notify the form's configured recipients, behind the cooldown."""
157
+ from .models import Form, Submission
158
+ from .notifications import notify_submission_received
159
+
160
+ form_id = event.payload.get("form_id")
161
+ form = Form.objects.filter(id=form_id).first()
162
+ if form is None:
163
+ return
164
+ # The event carries ids only (outbox canon: answers never ride the bus).
165
+ # The row is fetched here, inside the subscriber, so the report can be
166
+ # built from storage under this service's own authority rather than
167
+ # from a payload a fan-out topic delivered to every subscriber.
168
+ submission = Submission.objects.filter(
169
+ id=event.payload.get("submission_id")
170
+ ).select_related("version").first()
171
+ notify_submission_received(form, submission)
172
+
173
+
174
+ __all__ = [
175
+ "MergeTargetNotReady",
176
+ "handle_submission_received",
177
+ "handle_user_deleted",
178
+ "handle_user_merged",
179
+ ]
stapel_forms/admin.py ADDED
@@ -0,0 +1,440 @@
1
+ """Django admin for stapel-forms — the operator's working surface.
2
+
3
+ Through 0.5.0 this file was a deliberate peephole: three read-only
4
+ ``ModelAdmin``s, on the argument that workspace admins are not Django staff
5
+ and reach forms through the capability-gated REST surface instead. That
6
+ argument holds for a deployment whose form authors ARE workspace members.
7
+ It does not hold for the shape most hosts actually run first — a public
8
+ form on a marketing site, answered by strangers, read by staff. There is no
9
+ workspace member to be; there is an operator, a table, and (before this
10
+ release) a ``JSONField`` rendered as its ``repr``.
11
+
12
+ So the peephole became a surface, with the trust boundary unchanged:
13
+
14
+ **This is the STAFF door.** It is gated by Django model permissions
15
+ computed from the ``@access`` declaration by ``stapel_core.access``
16
+ (``Submission`` is ``@access.sensitive`` — view MID, mutate HIGH). It asks
17
+ for **no workspace capability**, deliberately: the capability layer in
18
+ ``authz.py`` gates the REST product surface, and requiring a workspace
19
+ membership here would lock a staff reviewer out of exactly the deployment
20
+ that needs this most — a public form nobody is a member of. Two doors,
21
+ still independent, each shut by default.
22
+
23
+ What the surface adds over a raw model view, and why each is a mechanism
24
+ rather than a decoration:
25
+
26
+ - **the answers table** is driven by the schema (``present_response_table``),
27
+ so columns are labelled questions in the form's current order and every
28
+ stored answer has a column to land in;
29
+ - **the builder** publishes a new version of the SAME form. Form identity
30
+ is what a host embedded (``public_id`` lives in someone's HTML), so an
31
+ edit may never mint a new form, and the page says so;
32
+ - **versions are not a top-level object.** ``FormVersion`` stays registered
33
+ (its change page is reachable and is the audit trail) but is hidden from
34
+ the app index, and in the table it is one subtle marker on the row where
35
+ the schema changed. The model split is right; making an operator reason
36
+ about it before they can read a response is not.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import json
41
+
42
+ from django.contrib import admin, messages
43
+ from django.http import Http404
44
+ from django.shortcuts import redirect
45
+ from django.template.response import TemplateResponse
46
+ from django.urls import path, reverse
47
+ from django.utils.dateparse import parse_date, parse_datetime
48
+ from django.utils.html import format_html
49
+ from django.utils.safestring import mark_safe
50
+ from django.utils.translation import gettext_lazy as _
51
+
52
+ from .models import Form, FormVersion, Submission
53
+
54
+ #: Rows per admin page. Independent of ``MAX_PAGE_SIZE`` (the API's keyset
55
+ #: cap): this is a rendering choice about a browser table, not a contract
56
+ #: with a client.
57
+ DEFAULT_PER_PAGE = 50
58
+ MAX_PER_PAGE = 200
59
+
60
+
61
+ class _ReadOnlyAdmin(admin.ModelAdmin):
62
+ def has_add_permission(self, request):
63
+ return False
64
+
65
+ def has_change_permission(self, request, obj=None):
66
+ return False
67
+
68
+
69
+ def _parse_moment(raw, *, end_of_day=False):
70
+ """Accept either a date (from ``<input type=date>``) or a timestamp.
71
+
72
+ The filter inputs are dates, but a caller pasting an ISO timestamp out
73
+ of the API should not get a silent empty page.
74
+
75
+ Two traps, both of which produce a filter that looks like it works:
76
+
77
+ - **`parse_date` is tried first.** On Python 3.11+ `parse_datetime`
78
+ delegates to `datetime.fromisoformat`, which happily accepts a bare
79
+ `2026-09-01` and returns midnight — so asking it first would swallow
80
+ every date input and silently ignore `end_of_day`, making an
81
+ inclusive "to" bound exclusive and hiding a whole day of responses.
82
+ - **the result is always made aware.** A naive datetime handed to a
83
+ filter under `USE_TZ` is interpreted in the current zone with a
84
+ warning, not an error, so the boundary quietly moves by the UTC
85
+ offset.
86
+ """
87
+ if not raw:
88
+ return None
89
+
90
+ import datetime as dt
91
+
92
+ from django.utils import timezone
93
+
94
+ day = parse_date(raw)
95
+ if day is not None:
96
+ moment = dt.datetime.combine(day, dt.time.max if end_of_day else dt.time.min)
97
+ else:
98
+ moment = parse_datetime(raw)
99
+ if moment is None:
100
+ return None
101
+ if timezone.is_naive(moment):
102
+ moment = timezone.make_aware(moment)
103
+ return moment
104
+
105
+
106
+ @admin.register(Form)
107
+ class FormAdmin(admin.ModelAdmin):
108
+ """The primary object. A form, its responses, and its schema."""
109
+
110
+ list_display = ("title", "state", "schema_version", "responses_link", "public_link", "updated_at")
111
+ list_filter = ("state",)
112
+ search_fields = ("id", "title", "workspace_id", "public_id")
113
+ readonly_fields = ("public_id", "created_at", "updated_at")
114
+ fieldsets = (
115
+ (None, {"fields": ("title", "state", "public_id")}),
116
+ (_("Notifications and retention"), {"fields": ("settings",)}),
117
+ (_("Advanced"), {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}),
118
+ )
119
+
120
+ # ── list columns ──────────────────────────────────────────────────
121
+ #
122
+ # Note what is NOT here: any answer content. `Form` is `standard`
123
+ # (view=LOW) and `Submission` is `sensitive` (view=MID), so a preview
124
+ # column of "the latest response" would hand respondent PII to staff
125
+ # the mandate does not clear for it. A COUNT is not content.
126
+
127
+ @admin.display(description=_("Schema"), ordering="active_version__version")
128
+ def schema_version(self, obj):
129
+ if not obj.active_version_id:
130
+ return format_html('<span style="color:#999">{}</span>', _("not published"))
131
+ return f"v{obj.active_version.version}"
132
+
133
+ @admin.display(description=_("Responses"))
134
+ def responses_link(self, obj):
135
+ count = obj.submissions.count()
136
+ return format_html(
137
+ '<a href="{}"><b>{}</b></a>',
138
+ reverse("admin:forms_form_responses", args=[obj.id]),
139
+ count,
140
+ )
141
+
142
+ @admin.display(description=_("Public link"))
143
+ def public_link(self, obj):
144
+ return format_html('<code>{}</code>', obj.public_id)
145
+
146
+ # ── extra views ───────────────────────────────────────────────────
147
+
148
+ def get_urls(self):
149
+ return [
150
+ path(
151
+ "<uuid:form_id>/responses/",
152
+ self.admin_site.admin_view(self.responses_view),
153
+ name="forms_form_responses",
154
+ ),
155
+ path(
156
+ "<uuid:form_id>/publish/",
157
+ self.admin_site.admin_view(self.publish_view),
158
+ name="forms_form_publish",
159
+ ),
160
+ ] + super().get_urls()
161
+
162
+ def _submission_admin(self):
163
+ return self.admin_site._registry[Submission]
164
+
165
+ def responses_view(self, request, form_id):
166
+ """The answers table.
167
+
168
+ Gated on the SUBMISSION's view permission, not the form's: it is
169
+ submissions that are `@access.sensitive`, and gating this on
170
+ `forms.view_form` (LOW) would render respondent PII to staff the
171
+ declaration puts a level above.
172
+ """
173
+ from . import services
174
+ from .presenters import present_response_table
175
+ from .schema import version_history
176
+
177
+ if not self._submission_admin().has_view_permission(request):
178
+ return self._denied(request)
179
+
180
+ form = Form.objects.filter(id=form_id).first()
181
+ if form is None:
182
+ raise Http404
183
+
184
+ since = _parse_moment(request.GET.get("since"))
185
+ until = _parse_moment(request.GET.get("until"), end_of_day=True)
186
+ query = (request.GET.get("q") or "").strip()
187
+ field = (request.GET.get("field") or "").strip() or None
188
+ before = _parse_moment(request.GET.get("before"))
189
+ try:
190
+ pinned = int(request.GET["version"]) if request.GET.get("version") else None
191
+ except (TypeError, ValueError):
192
+ pinned = None
193
+ try:
194
+ per_page = min(int(request.GET.get("per_page") or DEFAULT_PER_PAGE), MAX_PER_PAGE)
195
+ except (TypeError, ValueError):
196
+ per_page = DEFAULT_PER_PAGE
197
+
198
+ try:
199
+ # One row over the page size: the cheap "is there a next page"
200
+ # answer that a keyset cursor gives without a COUNT(*), which
201
+ # is the whole reason this survives thousands of rows.
202
+ rows = services.list_submissions(
203
+ form,
204
+ before=before,
205
+ since=since,
206
+ until=until,
207
+ q=query or None,
208
+ field=field,
209
+ version=pinned,
210
+ limit=per_page + 1,
211
+ )
212
+ invalid_field = None
213
+ except services.FormsError as exc:
214
+ rows, invalid_field = [], exc.params.get("field", field)
215
+
216
+ has_next = len(rows) > per_page
217
+ rows = rows[:per_page]
218
+
219
+ # Default: columns are the union across every version, led by the
220
+ # active schema's order — the reviewer picks a form and gets a
221
+ # table, never a version prompt.
222
+ #
223
+ # Pinned: columns are EXACTLY that version's, which is the case the
224
+ # picker exists for. A field ADDED later can be shown under the
225
+ # current schema as blank for older rows; a field REMOVED later
226
+ # cannot be shown at all, because the current schema no longer
227
+ # knows it. Pinning the version is the only way those answers are
228
+ # readable, which is why the picker is reachable rather than gone.
229
+ versions = list(form.versions.all().order_by("-version"))
230
+ if pinned is not None:
231
+ versions = [v for v in versions if v.version == pinned]
232
+ table = present_response_table(form, rows, versions=versions or None)
233
+
234
+ next_url = None
235
+ if has_next and rows:
236
+ params = request.GET.copy()
237
+ params["before"] = rows[-1].submitted_at.isoformat()
238
+ next_url = f"{request.path}?{params.urlencode()}"
239
+
240
+ context = {
241
+ **self.admin_site.each_context(request),
242
+ "title": _("Responses — %(form)s") % {"form": form.title},
243
+ "opts": self.model._meta,
244
+ "form_obj": form,
245
+ "columns": table["columns"],
246
+ "rows": table["rows"],
247
+ "has_next": has_next,
248
+ "next_url": next_url,
249
+ "per_page": per_page,
250
+ "filter_since": request.GET.get("since", ""),
251
+ "filter_until": request.GET.get("until", ""),
252
+ "filter_q": request.GET.get("q", ""),
253
+ "filter_field": field or "",
254
+ "invalid_field": invalid_field,
255
+ "field_choices": services.form_answer_slugs(form),
256
+ # The optional picker. Defaults to the current schema (empty
257
+ # selection), lists every version with when it went live, what
258
+ # it changed and how many responses it holds — so an empty
259
+ # version is visibly skippable.
260
+ "history": version_history(form),
261
+ "pinned_version": pinned,
262
+ "can_manage": self._submission_admin().has_delete_permission(request),
263
+ }
264
+ return TemplateResponse(request, "admin/forms/responses.html", context)
265
+
266
+ def publish_view(self, request, form_id):
267
+ """Publish the edited schema as the next version of THIS form."""
268
+ from . import services
269
+ from .schema import SchemaInvalid
270
+
271
+ form = Form.objects.filter(id=form_id).first()
272
+ if form is None:
273
+ raise Http404
274
+ if not self.has_change_permission(request, form):
275
+ return self._denied(request)
276
+ if request.method != "POST":
277
+ return redirect(reverse("admin:forms_form_change", args=[form.id]))
278
+
279
+ try:
280
+ schema = json.loads(request.POST.get("schema") or "{}")
281
+ except ValueError:
282
+ self.message_user(request, _("The schema is not valid JSON."), messages.ERROR)
283
+ return redirect(reverse("admin:forms_form_change", args=[form.id]))
284
+
285
+ try:
286
+ services.save_draft(form, schema)
287
+ version = services.publish(form, user=request.user)
288
+ except (SchemaInvalid, services.FormsError) as exc:
289
+ detail = getattr(exc, "error_key", str(exc))
290
+ fields = getattr(exc, "field_errors", None) or []
291
+ if fields:
292
+ detail += " — " + "; ".join(f"{f.field}: {f.message or f.code}" for f in fields)
293
+ self.message_user(
294
+ request,
295
+ _("Nothing was published: %(detail)s") % {"detail": detail},
296
+ messages.ERROR,
297
+ )
298
+ return redirect(reverse("admin:forms_form_change", args=[form.id]))
299
+
300
+ self.message_user(
301
+ request,
302
+ _(
303
+ "Published v%(version)s. The public link is unchanged and "
304
+ "older responses stay readable under the schema they answered."
305
+ )
306
+ % {"version": version.version},
307
+ messages.SUCCESS,
308
+ )
309
+ return redirect(reverse("admin:forms_form_change", args=[form.id]))
310
+
311
+ def _denied(self, request):
312
+ from django.core.exceptions import PermissionDenied
313
+
314
+ raise PermissionDenied
315
+
316
+ # ── the builder on the change page ────────────────────────────────
317
+
318
+ change_form_template = "admin/forms/change_form.html"
319
+
320
+ def render_change_form(self, request, context, *args, **kwargs):
321
+ """Feed the builder, and let stapel-attributes feed its own half.
322
+
323
+ ``attributes_probe`` is a real ``ConfigEditorWidget`` rendered with
324
+ no value. Its inline script no-ops (it bails when the config has no
325
+ ``type``), but its ``json_script`` block publishes the declarations,
326
+ the resolved locale and the merged message catalogues — the exact
327
+ payload the shipped editor expects. The builder reads THAT rather
328
+ than assembling its own copy, so this module imports no private
329
+ helper, keeps no second catalogue, and a kind or a translation
330
+ added upstream reaches the builder with no release here.
331
+
332
+ This is the same reuse `stapel-categories` gets by putting the
333
+ widget on a `config` field; the builder just needs it for fields
334
+ that do not exist until somebody clicks "add".
335
+ """
336
+ from django.templatetags.static import static
337
+ from stapel_attributes import get_config_editor_widget
338
+
339
+ from .conf import forms_settings
340
+
341
+ obj = kwargs.get("obj") or context.get("original")
342
+ schema = None
343
+ if obj is not None and obj.pk:
344
+ schema = obj.draft_schema or (
345
+ obj.active_version.schema if obj.active_version_id else None
346
+ )
347
+ context["attributes_probe"] = get_config_editor_widget("config")().render(
348
+ "__stapel_forms_probe", None, attrs={"id": "id___stapel_forms_probe"}
349
+ )
350
+ # A DICT, not `json.dumps(...)`. The template hands this to
351
+ # `json_script`, which serializes it — so pre-dumping would encode it
352
+ # twice and `JSON.parse` in the browser would hand the builder a
353
+ # string, every `payload.x` undefined and the editor silently empty.
354
+ context["builder_payload"] = {
355
+ "schema": schema or {"fields": [], "meta": {}},
356
+ # The same bundle the attributes widget imports. Named from
357
+ # `static()` rather than hardcoded so a hashed-manifest
358
+ # storage resolves it the same way for both mounts.
359
+ "attributesBundle": static("stapel_attributes/attributes-admin.js"),
360
+ "allowedKinds": list(forms_settings.FIELD_KINDS or []),
361
+ "maxFields": int(forms_settings.MAX_FIELDS_PER_FORM),
362
+ "activeVersion": (
363
+ obj.active_version.version
364
+ if obj is not None and obj.pk and obj.active_version_id
365
+ else None
366
+ ),
367
+ "publishUrl": (
368
+ reverse("admin:forms_form_publish", args=[obj.id])
369
+ if obj is not None and obj.pk
370
+ else None
371
+ ),
372
+ "responsesUrl": (
373
+ reverse("admin:forms_form_responses", args=[obj.id])
374
+ if obj is not None and obj.pk
375
+ else None
376
+ ),
377
+ }
378
+ return super().render_change_form(request, context, *args, **kwargs)
379
+
380
+
381
+ @admin.register(FormVersion)
382
+ class FormVersionAdmin(_ReadOnlyAdmin):
383
+ """Registered but hidden from the app index.
384
+
385
+ The rows are the audit trail of what respondents were asked and must
386
+ stay reachable (a link from a response opens one). What must NOT happen
387
+ — the owner's ruling — is an operator meeting "Form versions" as a
388
+ top-level table they have to reason about before they can read an
389
+ answer. `get_model_perms` returning empty is Django's own idiom for
390
+ exactly that: URLs live, index entry gone.
391
+ """
392
+
393
+ list_display = ("form", "version", "published_at")
394
+ search_fields = ("id", "form__id")
395
+
396
+ def get_model_perms(self, request):
397
+ return {}
398
+
399
+
400
+ @admin.register(Submission)
401
+ class SubmissionAdmin(_ReadOnlyAdmin):
402
+ """One response, rendered against the schema it answered.
403
+
404
+ `@access.sensitive` gates this at MID to view and HIGH to delete; the
405
+ class only removes add/change, which are not operations on a response
406
+ at all — a stored answer is what a respondent said, and editing it
407
+ would be forging a record rather than correcting one.
408
+ """
409
+
410
+ list_display = ("id", "form", "schema_version", "submitted_at", "submitted_by", "erased_at")
411
+ list_filter = ("form",)
412
+ search_fields = ("id", "form__id", "workspace_id")
413
+ readonly_fields = ("answers_table", "form", "submitted_at", "submitted_by", "erased_at")
414
+ # `answers` and `client_meta` are deliberately excluded: the table below
415
+ # is the same content, readable. Leaving the raw field alongside it
416
+ # re-creates the thing this release removed.
417
+ exclude = ("answers", "client_meta", "version", "workspace_id")
418
+
419
+ @admin.display(description=_("Schema"))
420
+ def schema_version(self, obj):
421
+ return f"v{obj.version.version}"
422
+
423
+ @admin.display(description=_("Answers"))
424
+ def answers_table(self, obj):
425
+ from django.template.loader import render_to_string
426
+
427
+ from .presenters import present_answer_rows
428
+
429
+ if obj is None or obj.pk is None:
430
+ return ""
431
+ return mark_safe(
432
+ render_to_string(
433
+ "admin/forms/submission_answers.html",
434
+ {
435
+ "rows": present_answer_rows(obj),
436
+ "erased": obj.erased_at is not None,
437
+ "version": obj.version.version,
438
+ },
439
+ )
440
+ )
stapel_forms/apps.py ADDED
@@ -0,0 +1,31 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class FormsConfig(AppConfig):
5
+ name = "stapel_forms"
6
+ label = "forms"
7
+ verbose_name = "Forms: admin-defined schemas, anonymous submissions, response review"
8
+ default_auto_field = "django.db.models.BigAutoField"
9
+
10
+ def ready(self):
11
+ # Import-time side effects: system checks, error-key registration,
12
+ # comm providers. Keep each in its own module.
13
+ from . import checks # noqa: F401
14
+ from . import errors # noqa: F401
15
+ from . import functions # noqa: F401
16
+
17
+ # Action subscriptions (in-process in a monolith, bus consumer in
18
+ # microservices — same code, transport chosen by STAPEL_COMM):
19
+ # user.deleted, plus this module's own submission event driving the
20
+ # notify subscriber.
21
+ from . import actions # noqa: F401
22
+
23
+ # GDPR provider registration (monolith mode). Hosts must ALSO list
24
+ # "forms" in STAPEL_GDPR["DATA_OWNERS"] — registering without
25
+ # declaring is gdpr.E002, and the erasure closure never completes.
26
+ from stapel_core.gdpr import gdpr_registry
27
+
28
+ from .gdpr import FormsGDPRProvider
29
+
30
+ if FormsGDPRProvider().section not in gdpr_registry.sections:
31
+ gdpr_registry.register(FormsGDPRProvider())