resource-engine-devtools 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 (88) hide show
  1. resource_engine_devtools/__init__.py +6 -0
  2. resource_engine_devtools/ai/__init__.py +1 -0
  3. resource_engine_devtools/ai/example.py +66 -0
  4. resource_engine_devtools/ai/installer.py +424 -0
  5. resource_engine_devtools/ai/skill/SKILL.md +130 -0
  6. resource_engine_devtools/ai/skill/examples/README.md +7 -0
  7. resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
  8. resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
  9. resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
  10. resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
  11. resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
  12. resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
  13. resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
  14. resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
  15. resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
  16. resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
  17. resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
  18. resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
  19. resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
  20. resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
  21. resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
  22. resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
  23. resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
  24. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
  25. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
  26. resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
  27. resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
  28. resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
  29. resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
  30. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
  31. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
  32. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
  33. resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
  34. resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
  35. resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
  36. resource_engine_devtools/ai/skill/llms.txt +25 -0
  37. resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
  38. resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
  39. resource_engine_devtools/ai/skill/references/errors.md +81 -0
  40. resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
  41. resource_engine_devtools/ai/skill/references/permissions.md +111 -0
  42. resource_engine_devtools/ai/skill/references/resource.md +301 -0
  43. resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
  44. resource_engine_devtools/ai/skill/references/testing.md +80 -0
  45. resource_engine_devtools/ai/templates/agents_block.md +26 -0
  46. resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
  47. resource_engine_devtools/check.py +67 -0
  48. resource_engine_devtools/cli.py +1112 -0
  49. resource_engine_devtools/consumer_scaffold.py +715 -0
  50. resource_engine_devtools/contracts.py +471 -0
  51. resource_engine_devtools/db.py +132 -0
  52. resource_engine_devtools/declarations_check.py +116 -0
  53. resource_engine_devtools/documentation/__init__.py +10 -0
  54. resource_engine_devtools/documentation/docstrings.py +72 -0
  55. resource_engine_devtools/documentation/generators/__init__.py +9 -0
  56. resource_engine_devtools/documentation/generators/ai_context.py +121 -0
  57. resource_engine_devtools/documentation/generators/api.py +63 -0
  58. resource_engine_devtools/documentation/generators/json.py +12 -0
  59. resource_engine_devtools/documentation/generators/markdown.py +687 -0
  60. resource_engine_devtools/documentation/generators/mermaid.py +22 -0
  61. resource_engine_devtools/documentation/generators/site.py +379 -0
  62. resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
  63. resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
  64. resource_engine_devtools/documentation/i18n.py +185 -0
  65. resource_engine_devtools/documentation/introspector.py +563 -0
  66. resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
  67. resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
  68. resource_engine_devtools/documentation/model.py +311 -0
  69. resource_engine_devtools/documentation/validator.py +128 -0
  70. resource_engine_devtools/emails.py +172 -0
  71. resource_engine_devtools/events_check.py +124 -0
  72. resource_engine_devtools/gates_check.py +133 -0
  73. resource_engine_devtools/hooks_check.py +287 -0
  74. resource_engine_devtools/i18n.py +312 -0
  75. resource_engine_devtools/loader.py +93 -0
  76. resource_engine_devtools/logic_check.py +136 -0
  77. resource_engine_devtools/mcp_server.py +685 -0
  78. resource_engine_devtools/py.typed +0 -0
  79. resource_engine_devtools/scaffold.py +805 -0
  80. resource_engine_devtools/scaffold_parts.py +637 -0
  81. resource_engine_devtools/source_edit.py +424 -0
  82. resource_engine_devtools/templates_check.py +59 -0
  83. resource_engine_devtools/worker.py +68 -0
  84. resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
  85. resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
  86. resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
  87. resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
  88. resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,687 @@
1
+ """MkDocs-compatible Markdown. One page per resource plus an index.
2
+
3
+ The generator's texts are English and go through ``t()``: render inside
4
+ ``docs_locale("ca")`` for another language (see ``documentation.i18n``).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any
11
+
12
+ from resource_engine_devtools.documentation.docstrings import FUNCTIONAL_SECTIONS, DocText
13
+ from resource_engine_devtools.documentation.generators.mermaid import render_state_machine
14
+ from resource_engine_devtools.documentation.i18n import t
15
+ from resource_engine_devtools.documentation.model import DocumentationModel, ResourceDoc
16
+
17
+ _TITLES = {key: title for title, key in FUNCTIONAL_SECTIONS.items()}
18
+
19
+
20
+ def _undocumented() -> str:
21
+ return t("_No description._")
22
+
23
+
24
+ def _yes(value: bool) -> str:
25
+ return t("yes") if value else t("no")
26
+
27
+
28
+ def _on_delete(kind: str) -> str:
29
+ return {
30
+ "restrict": t("refused while referenced"),
31
+ "set_null": t("the field is emptied"),
32
+ "cascade": t("deleted in cascade"),
33
+ }[kind]
34
+
35
+
36
+ def _text(doc: DocText, *, heading: str = "###") -> list[str]:
37
+ out: list[str] = []
38
+ if doc.summary:
39
+ out.append(doc.summary)
40
+ if doc.description:
41
+ out += ["", doc.description]
42
+ for key, body in doc.sections.items():
43
+ out += ["", f"{heading} {t(_TITLES.get(key, key))}", "", body]
44
+ return out or [_undocumented()]
45
+
46
+
47
+ def _cell(value: str | None) -> str:
48
+ return (value or "").replace("|", "\\|").replace("\n", " ")
49
+
50
+
51
+ def _codes(names: Any) -> str:
52
+ return ", ".join(f"`{n}`" for n in names)
53
+
54
+
55
+ def render_resource(r: ResourceDoc, audit_resource: str | None = None) -> str:
56
+ """The Markdown page of one resource."""
57
+ out = [f"# {r.name}", ""]
58
+ out += _text(r.doc, heading="##")
59
+
60
+ out += [
61
+ "",
62
+ f"## {t('Operations')}",
63
+ "",
64
+ f"| {t('Operation')} | {t('Kind')} | {t('Description')} |",
65
+ "|---|---|---|",
66
+ ]
67
+ for op in r.operations:
68
+ out.append(f"| `{op.name}` | {op.kind} | {_cell(op.doc.summary) or '—'} |")
69
+ if r.view == "custom":
70
+ out += ["", t("Read-only view: the records are computed by a query.")]
71
+ elif r.view:
72
+ out += [
73
+ "",
74
+ t(
75
+ "Read-only view computed from [{source}]({source}.md), one row per {groups}:",
76
+ source=r.view,
77
+ groups=_codes(r.view_group_by),
78
+ ),
79
+ "",
80
+ f"| {t('Field')} | {t('Computation')} |",
81
+ "|---|---|",
82
+ *(f"| `{k}` | `{v}` |" for k, v in r.view_values.items()),
83
+ ]
84
+ if r.discriminator:
85
+ kinds = ", ".join(f"`{i}` ([{n}]({n}.md))" for i, n in r.subtypes.items()) or "—"
86
+ out += [
87
+ "",
88
+ t(
89
+ "Base resource: the `{field}` field holds each record's subtype ({kinds}). It "
90
+ "lists and reads every kind; each subtype creates, updates and deletes its own.",
91
+ field=r.discriminator,
92
+ kinds=kinds,
93
+ ),
94
+ ]
95
+ if r.extends:
96
+ out += [
97
+ "",
98
+ t(
99
+ "Subtype of [{base}]({base}.md) (`{identity}`): it shares its ids, common "
100
+ "fields, state machines and hooks.",
101
+ base=r.extends,
102
+ identity=r.identity,
103
+ ),
104
+ ]
105
+ if r.tenant_field:
106
+ out += [
107
+ "",
108
+ t(
109
+ "Multi-tenant: each record belongs to the tenant in `{field}`; operations are "
110
+ "limited to the caller's tenant.",
111
+ field=r.tenant_field,
112
+ ),
113
+ ]
114
+ if r.restricted_fields:
115
+ out += [
116
+ "",
117
+ t(
118
+ "Restricted fields: {fields} — only roles with an explicit grant see or "
119
+ "change them.",
120
+ fields=_codes(r.restricted_fields),
121
+ ),
122
+ ]
123
+ if audit_resource and r.name != audit_resource:
124
+ if not r.audit:
125
+ note = t("not audited.")
126
+ else:
127
+ hidden = sorted({*r.restricted_fields, *r.audit_exclude})
128
+ note = (
129
+ t("changes and refused attempts are audited, reads too")
130
+ if r.audit_reads
131
+ else t("changes and refused attempts are audited")
132
+ )
133
+ if hidden:
134
+ note += t("; without values for {fields}", fields=_codes(hidden))
135
+ note += "."
136
+ out += ["", t("Audit: {note}", note=note)]
137
+
138
+ several = len(r.state_machines) > 1
139
+ for sm in r.state_machines:
140
+ title = t("State machine `{name}`", name=sm.machine) if several else t("State machine")
141
+ out += ["", f"## {title}", ""]
142
+ out += _text(sm.doc)
143
+ out += [
144
+ "",
145
+ "```mermaid",
146
+ render_state_machine(sm),
147
+ "```",
148
+ "",
149
+ f"| {t('State')} | {t('Name')} | {t('Description')} |",
150
+ "|---|---|---|",
151
+ ]
152
+ for s in sm.states:
153
+ flags = f" ({t('initial')})" if s.initial else f" ({t('final')})" if s.final else ""
154
+ out.append(f"| `{s.id}`{flags} | {s.name} | {_cell(s.description) or '—'} |")
155
+ out += [
156
+ "",
157
+ f"| {t('Transition')} | {t('From')} | {t('To')} | {t('Description')} |",
158
+ "|---|---|---|---|",
159
+ ]
160
+ for tr in sm.transitions:
161
+ out.append(
162
+ f"| `{tr.event}` | `{tr.source}` | `{tr.target}` | {_cell(tr.description) or '—'} |"
163
+ )
164
+
165
+ timers = [timer for sm in r.state_machines for timer in sm.timers]
166
+ if timers:
167
+ out += [
168
+ "",
169
+ f"### {t('Automatic transitions')}",
170
+ "",
171
+ f"| {t('Transition')} | {t('After')} | {t('From')} | {t('Counted from')} "
172
+ f"| {t('Description')} |",
173
+ "|---|---|---|---|---|",
174
+ ]
175
+ for timer in timers:
176
+ out.append(
177
+ f"| `{timer.event}` | {timer.after} | {_codes(timer.states)} | `{timer.since}` "
178
+ f"| {_cell(timer.description) or '—'} |"
179
+ )
180
+ out += [
181
+ "",
182
+ t(
183
+ "The worker (`TimerJob`) runs them as the system principal; they appear in "
184
+ "the history and the audit trail like any transition."
185
+ ),
186
+ ]
187
+
188
+ if r.actions:
189
+ out += ["", f"## {t('Actions')}"]
190
+ for a in r.actions:
191
+ out += ["", f"### `{a.name}`", ""]
192
+ out += _text(a.doc, heading="####")
193
+
194
+ if r.reacts:
195
+ out += [
196
+ "",
197
+ f"## {t('Process')}",
198
+ "",
199
+ t(
200
+ "Each record is an instance of the process, one per value of `{field}`. It "
201
+ "reacts to these events:",
202
+ field=r.correlation,
203
+ ),
204
+ "",
205
+ f"| {t('Event')} | {t('When')} | {t('Key')} | {t('Starts')} | {t('What it does')} |",
206
+ "|---|---|---|---|---|",
207
+ ]
208
+ for x in r.reacts:
209
+ out.append(
210
+ f"| `{x.event}` | {x.when or '—'} | `{x.key}` | {_yes(x.start)} "
211
+ f"| {_cell(x.description) or x.handler} |"
212
+ )
213
+
214
+ if r.references:
215
+ out += [
216
+ "",
217
+ f"## {t('References')}",
218
+ "",
219
+ f"| {t('Relation')} | {t('Field')} | {t('Resource')} | {t('When it is deleted')} "
220
+ f"| {t('Description')} |",
221
+ "|---|---|---|---|---|",
222
+ ]
223
+ for ref in r.references:
224
+ out.append(
225
+ f"| `{ref.name}` | `{ref.field}` | [{ref.resource}]({ref.resource}.md) "
226
+ f"| {_on_delete(ref.on_delete)} | {_cell(ref.description) or '—'} |"
227
+ )
228
+ if r.referenced_by:
229
+ refs = ", ".join(
230
+ f"[{ref.field}]({ref.resource}.md) ({_on_delete(ref.on_delete)})"
231
+ for ref in r.referenced_by
232
+ )
233
+ out += ["", t("Referenced by: {refs}.", refs=refs)]
234
+ if r.links:
235
+ out += [
236
+ "",
237
+ f"## {t('Many-to-many relations')}",
238
+ "",
239
+ f"| {t('Relation')} | {t('Records')} | {t('Through')} |",
240
+ "|---|---|---|",
241
+ ]
242
+ for link in r.links:
243
+ out.append(
244
+ f"| `{link.name}` | [{link.resource}]({link.resource}.md) "
245
+ f"| [{link.field}]({link.field}.md) |"
246
+ )
247
+ out += [
248
+ "",
249
+ t(
250
+ "They are linked and unlinked by creating and deleting records of the join "
251
+ "resource; `expand` accepts these relations too."
252
+ ),
253
+ ]
254
+
255
+ if r.events:
256
+ out += ["", f"## {t('Domain events')}"]
257
+ for e in r.events:
258
+ out += ["", f"### `{e.name}`", ""]
259
+ out += _text(e.doc, heading="####")
260
+ out += [
261
+ "",
262
+ f"| {t('Field')} | {t('Type')} | {t('Required')} |",
263
+ "|---|---|---|",
264
+ ]
265
+ for f in e.fields:
266
+ out.append(f"| `{f.name}` | `{_cell(f.type)}` | {_yes(f.required)} |")
267
+
268
+ if r.documents:
269
+ out += [
270
+ "",
271
+ f"## {t('Documents')}",
272
+ "",
273
+ f"| {t('Slot')} | {t('Types')} | {t('Max. size')} | {t('Multiple')} | {t('Upload')} "
274
+ f"| {t('Required by')} | {t('Processing')} | {t('Description')} |",
275
+ "|---|---|---|---|---|---|---|---|",
276
+ ]
277
+ for slot in r.documents:
278
+ out.append(
279
+ f"| `{slot.name}` | {', '.join(slot.content_types)} | {slot.max_bytes} B "
280
+ f"| {_yes(slot.multiple)} | {slot.upload} | {_codes(slot.required_for) or '—'} "
281
+ f"| {_yes(slot.processing)} | {_cell(slot.description) or '—'} |"
282
+ )
283
+
284
+ if r.emails:
285
+ out += [
286
+ "",
287
+ f"## {t('Emails')}",
288
+ "",
289
+ f"| {t('Email')} | {t('When')} | {t('Recipients')} | {t('Language')} |",
290
+ "|---|---|---|---|",
291
+ ]
292
+ for email in r.emails:
293
+ name = (
294
+ f"[`{email.template}`](../emails.md#{_slug(email.template)})"
295
+ if email.template
296
+ else t("_computed at runtime_")
297
+ )
298
+ when = _point_label(email.point)
299
+ out.append(f"| {name} | {when} | `{_cell(email.to)}` | {email.locale or '—'} |")
300
+ out += [
301
+ "",
302
+ t(
303
+ "They are requested inside the transaction and sent once the change is "
304
+ "committed; if the change is rolled back, they are not sent."
305
+ ),
306
+ ]
307
+
308
+ if r.printouts or r.generated:
309
+ out += [
310
+ "",
311
+ f"## {t('Generated documents')}",
312
+ "",
313
+ f"| {t('Document')} | {t('When')} | {t('Formats')} | {t('Description')} |",
314
+ "|---|---|---|---|",
315
+ ]
316
+ for p in r.printouts:
317
+ doc_link = f"[`{p.template}`](../documents.md#{_slug(p.template)})"
318
+ when = t("on request, as `{name}`", name=p.name)
319
+ formats = ", ".join(p.formats)
320
+ out.append(f"| {doc_link} | {when} | {formats} | {_cell(p.description) or '—'} |")
321
+ for g in r.generated:
322
+ doc_link = (
323
+ f"[`{g.template}`](../documents.md#{_slug(g.template)})"
324
+ if g.template
325
+ else t("_computed at runtime_")
326
+ )
327
+ when = _point_label(g.point)
328
+ if g.slot:
329
+ when += " " + t("(kept in `{slot}`)", slot=g.slot)
330
+ out.append(f"| {doc_link} | {when} | {g.format or '—'} | — |")
331
+ if r.printouts:
332
+ out += [
333
+ "",
334
+ t(
335
+ "Documents on request are rendered from the record as it is when asked, "
336
+ "with the fields the person may read, and are not stored."
337
+ ),
338
+ ]
339
+
340
+ out += _lifecycle(r)
341
+
342
+ return "\n".join(out) + "\n"
343
+
344
+
345
+ # ------------------------------------------------- what happens in each operation
346
+
347
+
348
+ def _point_label(point: str) -> str:
349
+ """``after_transition:approve`` → "on the `approve` transition"."""
350
+ if point.startswith("action:"):
351
+ return t("on the `{name}` action", name=point[7:])
352
+ base, _, q = point.partition(":")
353
+ kind = base.split("_", 1)[1] if "_" in base else base
354
+ if kind == "transition":
355
+ return t("on the `{name}` transition", name=q) if q else t("on any transition")
356
+ if kind == "action":
357
+ return t("on the `{name}` action", name=q) if q else t("on any action")
358
+ if kind == "attach":
359
+ return t("when attaching to `{name}`", name=q) if q else t("when attaching a document")
360
+ if kind == "detach":
361
+ return t("when removing from `{name}`", name=q) if q else t("when removing a document")
362
+ labels = {
363
+ "create": t("on create"),
364
+ "update": t("on update"),
365
+ "delete": t("on delete"),
366
+ "validate": t("when validating the input"),
367
+ "commit": t("after any committed change"),
368
+ }
369
+ return labels.get(kind, f"`{point}`")
370
+
371
+
372
+ def _steps_for(r: ResourceDoc) -> list[tuple[str, str, str | None, str | None]]:
373
+ """``(kind, title, qualifier, input schema)`` of every write operation."""
374
+ titles = {"create": t("Create"), "update": t("Update"), "delete": t("Delete")}
375
+ out: list[tuple[str, str, str | None, str | None]] = []
376
+ for op in r.operations:
377
+ if op.kind == "crud" and op.name in titles:
378
+ out.append((op.name, f"{titles[op.name]} (`{op.name}`)", None, op.input_schema))
379
+ elif op.kind == "transition":
380
+ title = t("Transition `{name}`", name=op.name)
381
+ out.append(("transition", title, op.name, op.input_schema))
382
+ elif op.kind == "action":
383
+ out.append(("action", t("Action `{name}`", name=op.name), op.name, op.input_schema))
384
+ for slot in r.documents:
385
+ out.append(("attach", t("Attach to `{name}`", name=slot.name), slot.name, None))
386
+ out.append(("detach", t("Remove from `{name}`", name=slot.name), slot.name, None))
387
+ return out
388
+
389
+
390
+ def _hooks_at(r: ResourceDoc, point: str, qualifier: str | None) -> list[Any]:
391
+ """Generic hooks first, then the qualified ones (the engine's order)."""
392
+ generic = [h for h in r.hooks if h.point == point]
393
+ qualified = [h for h in r.hooks if qualifier and h.point == f"{point}:{qualifier}"]
394
+ return generic + qualified
395
+
396
+
397
+ def _mutation(kind: str) -> tuple[str, str]:
398
+ return {
399
+ "create": (t("The new record is saved."), t("Save")),
400
+ "update": (t("The changes are saved."), t("Save")),
401
+ "delete": (t("The record is deleted."), t("Delete")),
402
+ "transition": (t("The state changes."), t("Change the state")),
403
+ "action": (t("The action runs."), t("Run")),
404
+ "attach": (t("The document is saved."), t("Save the document")),
405
+ "detach": (t("The document is removed."), t("Remove the document")),
406
+ }.get(kind, (t("The change is saved."), t("Save")))
407
+
408
+
409
+ def _commit() -> str:
410
+ return t("Commit")
411
+
412
+
413
+ def _lifecycle(r: ResourceDoc) -> list[str]:
414
+ """What runs in each write operation, in the order of docs/lifecycle.md."""
415
+ if not r.hooks and not r.emails:
416
+ return []
417
+ out = [
418
+ "",
419
+ f"## {t('What happens in each operation')}",
420
+ "",
421
+ t(
422
+ "Steps **before the commit** are inside the transaction: if one fails, the change "
423
+ "is refused and nothing is saved. Steps **after the commit** run with the change "
424
+ "already saved: an error is logged, but it doesn't undo the change."
425
+ ),
426
+ ]
427
+ for kind, title, qualifier, _schema in _steps_for(r):
428
+ validates = kind in ("create", "update", "transition", "action")
429
+ before = _hooks_at(r, f"before_{kind}", qualifier)
430
+ after = _hooks_at(r, f"after_{kind}", qualifier)
431
+ checks = (
432
+ _hooks_at(r, "before_validate", None) + _hooks_at(r, "after_validate", None)
433
+ if validates
434
+ else []
435
+ )
436
+ point_key = f"action:{qualifier}" if kind == "action" else None
437
+ mails = [
438
+ e
439
+ for e in r.emails
440
+ if e.point in {h.point for h in before + after + checks}
441
+ or (point_key and e.point == point_key)
442
+ ]
443
+ required = [s.name for s in r.documents if qualifier and qualifier in s.required_for]
444
+ if not (before or after or checks or mails or required):
445
+ continue
446
+ # (sentence for the list, short label for the diagram)
447
+ steps: list[tuple[str, str]] = []
448
+ if validates:
449
+ text = t("The input is validated")
450
+ steps.append(
451
+ (text + "".join(f"; {_hook_text(h)}" for h in checks) + ".", t("Validate"))
452
+ )
453
+ if required:
454
+ steps.append((
455
+ t("A document must be available in {slots}.", slots=_codes(required)),
456
+ t("Document {slots}", slots=", ".join(required)),
457
+ )) # fmt: skip
458
+ steps += [(t("Before saving: {hook}", hook=_hook_text(h)), _hook_label(h)) for h in before]
459
+ steps.append(_mutation(kind))
460
+ steps += [
461
+ (t("Before the commit: {hook}", hook=_hook_text(h)), _hook_label(h)) for h in after
462
+ ]
463
+ committed = t("The change is committed, with the audit entry and the events.")
464
+ steps.append((committed, _commit()))
465
+ for e in mails:
466
+ link = f"[`{e.template}`](../emails.md#{_slug(e.template)})" if e.template else ""
467
+ sent = t("After the commit: the email {email} is sent to `{to}`.", email=link, to=e.to)
468
+ steps.append((sent, t("Email {name}", name=e.template or "").strip()))
469
+ out += ["", f"### {title}", ""]
470
+ out += [f"{i}. {text}" for i, (text, _) in enumerate(steps, 1)]
471
+ out += ["", "```mermaid", _flow([label for _, label in steps]), "```"]
472
+ commit = [h for h in r.hooks if h.point == "after_commit"]
473
+ if commit:
474
+ out += ["", t("After any committed change of this resource:"), ""]
475
+ out += [f"- {_hook_text(h)}" for h in commit]
476
+ return out
477
+
478
+
479
+ def _hook_label(h: Any) -> str:
480
+ """The hook in a diagram: the start of what it does."""
481
+ summary: str = (h.doc.summary or h.name).rstrip(".")
482
+ return summary if len(summary) <= 40 else summary[:39].rstrip() + "…"
483
+
484
+
485
+ def _hook_text(h: Any) -> str:
486
+ effect = f" ({t('external effect')})" if h.external_effect else ""
487
+ summary = _cell(h.doc.summary) or t("no description")
488
+ return f"{summary}{effect}" # what it does, not the function's name
489
+
490
+
491
+ def _flow(labels: list[str]) -> str:
492
+ """The steps as a left-to-right flowchart; the commit is a hexagon."""
493
+ commit = _commit()
494
+ lines = ["flowchart LR"]
495
+ for i, label in enumerate(labels):
496
+ label = label.replace('"', "'")
497
+ shape = ('{{"', '"}}') if label == commit else ('["', '"]')
498
+ lines.append(f" s{i}{shape[0]}{label}{shape[1]}")
499
+ if i:
500
+ lines.append(f" s{i - 1} --> s{i}")
501
+ return "\n".join(lines)
502
+
503
+
504
+ def _slug(text: str) -> str:
505
+ return re.sub(r"[^\w]+", "-", text.lower()).strip("-")
506
+
507
+
508
+ # ------------------------------------------------------------------ pages
509
+
510
+
511
+ def render_emails(model: DocumentationModel) -> str:
512
+ """Every email template set, with a preview per locale."""
513
+ out = [
514
+ f"# {t('Emails')}",
515
+ "",
516
+ t(
517
+ "The emails the application sends, from its templates. Variables show as "
518
+ "`{{ name }}`: the real content depends on each case."
519
+ ),
520
+ ]
521
+ for e in model.emails:
522
+ out += ["", f"## {e.template}", ""]
523
+ if e.used_by:
524
+ sent = "; ".join(
525
+ t(
526
+ "by [{resource}](resources/{resource}.md) {when}",
527
+ resource=u.split(" ", 1)[0],
528
+ when=_point_label(u.split(" ", 1)[1]),
529
+ )
530
+ for u in e.used_by
531
+ )
532
+ out.append(t("Sent {by}.", by=sent))
533
+ else:
534
+ out.append(t("No resource requests it: it is sent directly (`Mailer.send`)."))
535
+ if e.missing:
536
+ out += ["", "⚠ " + t("Missing templates: {names}.", names=_codes(e.missing))]
537
+ for v in e.variants:
538
+ label = v.locale or t("Other languages (not translated)")
539
+ out += ["", f"### {label}", ""]
540
+ out += [f"**{t('Subject:')}** {_cell(v.subject) or '—'}"]
541
+ if v.text:
542
+ out += ["", "```text", v.text.rstrip("\n"), "```"]
543
+ if v.html:
544
+ out += ["", "```email-html", v.html.rstrip("\n"), "```"]
545
+ return "\n".join(out) + "\n"
546
+
547
+
548
+ def render_documents(model: DocumentationModel) -> str:
549
+ """Every document template, with a preview per locale."""
550
+ out = [
551
+ f"# {t('Documents')}",
552
+ "",
553
+ t(
554
+ "The documents the application generates from its templates: invoices, "
555
+ "delivery notes, certificates. Variables show as `{{ name }}`: the real "
556
+ "content depends on each record."
557
+ ),
558
+ ]
559
+ for d in model.documents:
560
+ out += ["", f"## {d.template}", ""]
561
+ uses = []
562
+ for u in d.used_by:
563
+ resource, _, point = u.partition(" ")
564
+ if point.startswith("printout:"):
565
+ uses.append(
566
+ t(
567
+ "on request by [{resource}](resources/{resource}.md) (`{name}`)",
568
+ resource=resource,
569
+ name=point.removeprefix("printout:"),
570
+ )
571
+ )
572
+ else:
573
+ uses.append(
574
+ t(
575
+ "by [{resource}](resources/{resource}.md) {when}",
576
+ resource=resource,
577
+ when=_point_label(point),
578
+ )
579
+ )
580
+ if uses:
581
+ out.append(t("Generated {uses}.", uses="; ".join(uses)))
582
+ else:
583
+ out.append(t("No resource uses it from the code that was read."))
584
+ for v in d.variants:
585
+ label = v.locale or t("Other languages (not translated)")
586
+ out += ["", f"### {label}"]
587
+ if v.html:
588
+ out += ["", "```email-html", v.html.rstrip("\n"), "```"]
589
+ if v.text:
590
+ out += ["", "```text", v.text.rstrip("\n"), "```"]
591
+ return "\n".join(out) + "\n"
592
+
593
+
594
+ def render_markdown(model: DocumentationModel) -> dict[str, str]:
595
+ """Return ``{relative_path: content}``."""
596
+ pages = {
597
+ f"resources/{r.name}.md": render_resource(r, model.audit_resource) for r in model.resources
598
+ }
599
+ index = [
600
+ f"# {t('Resource catalogue')}",
601
+ "",
602
+ f"| {t('Resource')} | {t('Description')} | {t('Operations')} | {t('State machines')} |",
603
+ "|---|---|---|---|",
604
+ ]
605
+ for r in model.resources:
606
+ ops = _codes(o.name for o in r.operations)
607
+ machines = ", ".join(
608
+ f"[{sm.machine or sm.state_field}](state-machines.md#{_anchor(r.name, sm)})"
609
+ for sm in r.state_machines
610
+ )
611
+ index.append(
612
+ f"| [{r.name}](resources/{r.name}.md) | {_cell(r.doc.summary) or '—'} | {ops} "
613
+ f"| {machines or '—'} |"
614
+ )
615
+ if any(r.state_machines for r in model.resources):
616
+ index += ["", t("Every state diagram: [state machines](state-machines.md).")]
617
+ pages["state-machines.md"] = render_state_machines(model)
618
+ if model.emails:
619
+ index += ["", t("The emails the application sends: [emails](emails.md).")]
620
+ pages["emails.md"] = render_emails(model)
621
+ if model.documents:
622
+ index += ["", t("The documents it generates: [documents](documents.md).")]
623
+ pages["documents.md"] = render_documents(model)
624
+ if model.system_roles:
625
+ index += ["", t("See also the [permission matrix](permissions.md).")]
626
+ pages["permissions.md"] = render_permissions(model)
627
+ pages["index.md"] = "\n".join(index) + "\n"
628
+ return pages
629
+
630
+
631
+ def render_permissions(model: DocumentationModel) -> str:
632
+ """Matrix of system roles × actions. Policies created from the front end are
633
+ data and are listed by the authz_policies resource, not here."""
634
+ roles = model.system_roles
635
+ out = [
636
+ f"# {t('Permission matrix (system roles)')}",
637
+ "",
638
+ t(
639
+ "System roles are defined in the code and can't be changed from the front end. "
640
+ "Policies created from the front end are listed by `authz_policies`."
641
+ ),
642
+ "",
643
+ f"| {t('Role')} | {t('Description')} | {t('Grants')} |",
644
+ "|---|---|---|",
645
+ ]
646
+ for role in roles:
647
+ out.append(f"| `{role.name}` | {_cell(role.description) or '—'} | {_codes(role.grants)} |")
648
+ out += ["", f"| {t('Action')} | " + " | ".join(f"`{role.name}`" for role in roles) + " |"]
649
+ out.append("|---|" + "---|" * len(roles))
650
+ for action in model.actions:
651
+ marks = " | ".join("✓" if action in role.actions else "" for role in roles)
652
+ out.append(f"| `{action}` | {marks} |")
653
+ return "\n".join(out) + "\n"
654
+
655
+
656
+ def _anchor(resource: str, sm: Any) -> str:
657
+ """The heading id of a machine on the state-machines page (``<h2>`` slug)."""
658
+ # the same slug on GitHub and on the site: "invoices: approval" → invoices-approval
659
+ text = f"{resource}: {sm.machine or sm.state_field}".lower()
660
+ return re.sub(r"[^\w]+", "-", text).strip("-")
661
+
662
+
663
+ def render_state_machines(model: DocumentationModel) -> str:
664
+ """Every state machine of the application, with its diagram."""
665
+ out = [
666
+ f"# {t('State machines')}",
667
+ "",
668
+ t(
669
+ "The processes with states of each resource, drawn from the executable "
670
+ "definition of the machine. Each state and transition is described on the "
671
+ "resource's page."
672
+ ),
673
+ ]
674
+ for r in model.resources:
675
+ for sm in r.state_machines:
676
+ where = t("Resource [{name}](resources/{name}.md)", name=r.name)
677
+ out += ["", f"## {r.name}: {sm.machine or sm.state_field}", "", where, ""]
678
+ if sm.doc.summary:
679
+ out += [sm.doc.summary, ""]
680
+ out += ["```mermaid", render_state_machine(sm), "```"]
681
+ if sm.timers:
682
+ timers = ", ".join(
683
+ t("`{event}` after {after}", event=timer.event, after=timer.after)
684
+ for timer in sm.timers
685
+ )
686
+ out += ["", t("Automatic transitions: {timers}.", timers=timers)]
687
+ return "\n".join(out) + "\n"