@cubocicloide/stack-frappe 2.0.5 → 2.2.0

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.
@@ -0,0 +1,229 @@
1
+ ---
2
+ name: create-api-method
3
+ description: Add a whitelisted HTTP endpoint to a custom Frappe app — a @frappe.whitelist() function in api.py, callable at /api/method/<app>.api.<name>, optionally paired with a server-rendered portal page. Surveys api.py for reuse, decides authenticated vs guest deliberately, and verifies with dude lint (PY001/PY002) and dude test.
4
+ disable-model-invocation: false
5
+ allowed-tools: "Read Write Edit Glob Grep Bash(dude *) Bash(find *) Bash(cat *) Bash(grep *) Bash(ls *)"
6
+ ---
7
+
8
+ # Create API Method
9
+
10
+ Guided creation of a whitelisted method — Frappe's RPC endpoint. Any function
11
+ decorated with `@frappe.whitelist()` in an installed app is **immediately**
12
+ reachable at `/api/method/<dotted.path>`; there is no router to register and no
13
+ review gate. That is convenient and it is also the risk, which is why PY001 and
14
+ PY002 exist.
15
+
16
+ The reference is `apps/ticketing/ticketing/api.py` (`ticket_stats`) and the
17
+ portal page that consumes it,
18
+ `apps/ticketing/ticketing/templates/pages/ticket_stats.{py,html}`.
19
+
20
+ > Read `.claude/rules/PY/001.md` and `PY/002.md` once at the start — they are
21
+ > the source of truth. `dude explain PY001` prints the same prose.
22
+
23
+ ---
24
+
25
+ ## Step 0 — Locate the project
26
+
27
+ ```bash
28
+ find . -maxdepth 3 -name "dude.json" | head -1
29
+ ```
30
+
31
+ Set `PROJECT_ROOT` to the directory containing `dude.json`. If missing, stop
32
+ with _"No dude.json found — are you inside a dude project?"_.
33
+
34
+ Read the site host, which you'll need to call the endpoint:
35
+
36
+ ```bash
37
+ grep SITE_NAME "$PROJECT_ROOT"/.env # e.g. my-helpdesk.localhost → port 8000
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Step 1 — Gather requirements
43
+
44
+ Ask only for what the user hasn't already provided:
45
+
46
+ 1. **Target app** — default `ticketing`. Must have a `pyproject.toml` under
47
+ `apps/<app>/` (that is what makes it a real bench app — APP001).
48
+ 2. **What the endpoint does** — and whether it **reads** or **writes**.
49
+ 3. **Parameters** — name and type of each; they arrive as query string or JSON
50
+ body keys, so they are strings unless you coerce them.
51
+ 4. **Return shape** — a dict/list is serialised to JSON automatically.
52
+ 5. **Who may call it** — an authenticated user (the default and almost always
53
+ the right answer), or genuinely anonymous visitors. Do not assume guest.
54
+ 6. **A portal page too?** — if the user wants a human-readable page as well as
55
+ JSON, say so now; Step 5 adds the pair.
56
+
57
+ ---
58
+
59
+ ## Step 2 — Survey the existing API (reuse before create)
60
+
61
+ ```bash
62
+ cat "$PROJECT_ROOT"/apps/<app>/<app>/api.py
63
+ grep -rn "frappe.whitelist" "$PROJECT_ROOT"/apps/<app>/
64
+ ls "$PROJECT_ROOT"/apps/<app>/<app>/templates/pages/ 2>/dev/null
65
+ ```
66
+
67
+ - **An existing method already returns this data?** Call it rather than
68
+ duplicating the query — `templates/pages/ticket_stats.py` does exactly that,
69
+ importing `ticket_stats` instead of re-writing the aggregation.
70
+ - **A DocType controller already owns this logic?** Keep business rules in the
71
+ controller's lifecycle hooks; the API method should be a thin, permission-
72
+ respecting caller.
73
+ - Match the naming and docstring style already in `api.py`.
74
+
75
+ Report what you found and what you intend to reuse.
76
+
77
+ ---
78
+
79
+ ## Step 3 — Write the method
80
+
81
+ Add it to `apps/<app>/<app>/api.py` (tab-indented, Frappe style):
82
+
83
+ ```python
84
+ @frappe.whitelist()
85
+ def ticket_stats() -> dict:
86
+ """Return HD Ticket counts grouped by status."""
87
+ if not frappe.db.table_exists("HD Ticket"):
88
+ return {"helpdesk_installed": False, "by_status": {}, "total": 0}
89
+
90
+ rows = frappe.get_all(
91
+ "HD Ticket",
92
+ fields=["status", "count(name) as total"],
93
+ group_by="status",
94
+ )
95
+ by_status = {row.status: row.total for row in rows}
96
+ return {"helpdesk_installed": True, "by_status": by_status, "total": sum(by_status.values())}
97
+ ```
98
+
99
+ Constraints to honour while writing:
100
+
101
+ - **Query through the ORM** — `frappe.get_all` / `frappe.get_list` /
102
+ `frappe.get_doc` / `frappe.qb`. They apply the DocType permission model and
103
+ escape everything. Raw `frappe.db.sql()` is a PY002 **warning**; raw SQL built
104
+ with an f-string, `%`, `.format()` or concatenation is a PY002 **error**. If
105
+ raw SQL is genuinely unavoidable, parameterise it:
106
+ `frappe.db.sql("… where opening_date < %(cutoff)s", {"cutoff": cutoff})`.
107
+ - **Validate and coerce inputs.** Parameters arrive as strings from HTTP;
108
+ `int(...)`/`frappe.parse_json(...)` them and `frappe.throw(_("…"))` on
109
+ anything unexpected.
110
+ - **Tolerate absent apps.** A method touching another app's DocType should
111
+ degrade rather than 500 — `frappe.db.table_exists(...)`, as above.
112
+ - **Writes need an explicit permission decision.** `ignore_permissions=True`
113
+ turns a whitelisted method into a privilege escalation; only use it after
114
+ checking `frappe.has_permission(...)` yourself, and say why in a comment.
115
+ - **Return the minimum.** The response is JSON to whoever is authenticated —
116
+ don't leak fields the caller didn't ask for.
117
+
118
+ ### Guest access — the deliberate decision
119
+
120
+ `allow_guest=True` makes the method callable by **unauthenticated visitors**.
121
+ PY001 flags every occurrence unless a justification comment sits on the same
122
+ line or the line directly above:
123
+
124
+ ```python
125
+ # guest-ok: public status page, returns only aggregate counts
126
+ @frappe.whitelist(allow_guest=True)
127
+ def public_status() -> dict: ...
128
+ ```
129
+
130
+ The comment is a claim you have to be able to defend. If you cannot write a
131
+ convincing reason, the answer is no `allow_guest` — callers authenticate with a
132
+ session cookie or an API key. Never expose a write or a delete to guests.
133
+
134
+ ---
135
+
136
+ ## Step 4 — Add a test
137
+
138
+ Put `test_api.py` beside `api.py`. `bench run-tests --app <app>` (wrapped by
139
+ `dude test`) discovers any `test_*.py` in the app. Use `FrappeTestCase` — it
140
+ wraps each test in a transaction and rolls it back, so tests never leak data
141
+ into the site. Mirror
142
+ `apps/ticketing/ticketing/ticketing/doctype/ticket_escalation_rule/test_ticket_escalation_rule.py`.
143
+
144
+ Import and call the function directly; cover the empty case, the happy path,
145
+ and every `frappe.throw` branch you added.
146
+
147
+ ---
148
+
149
+ ## Step 5 — Optional: the portal page
150
+
151
+ A server-rendered page is a **file pair** under
152
+ `apps/<app>/<app>/templates/pages/` — no registration anywhere. The route is
153
+ the filename: `ticket_stats.{py,html}` → `/ticket_stats`.
154
+
155
+ ```python
156
+ # <route>.py
157
+ from <app>.api import <method>
158
+
159
+ def get_context(context):
160
+ context.no_cache = 1
161
+ context.stats = <method>()
162
+ return context
163
+ ```
164
+
165
+ ```jinja
166
+ {# <route>.html #}
167
+ {% extends "templates/web.html" %}
168
+ {% block title %}…{% endblock %}
169
+ {% block page_content %}…{% endblock %}
170
+ ```
171
+
172
+ The `.py` should **call the whitelisted method**, not re-implement its query —
173
+ that is the whole point of the shipped example. Set `context.no_cache = 1` for
174
+ anything dynamic. If the page 404s, the website cache is stale:
175
+ `dude site clear-cache`.
176
+
177
+ PY002 applies to the context code too — no interpolated SQL there either.
178
+
179
+ ---
180
+
181
+ ## Step 6 — Validate
182
+
183
+ ```bash
184
+ cd "$PROJECT_ROOT"
185
+ dude lint # PY001/PY002 must pass
186
+ dude lint --format json # machine-readable: file, line, code
187
+ dude explain PY001 # (or PY002) — why, and how to satisfy it
188
+ dude format # ruff format + autofix over apps/
189
+ dude test --app <app>
190
+ ```
191
+
192
+ `dude lint` is a pure filesystem check — it needs no Docker and no running
193
+ bench, so run it first and fix the cause each diagnostic names. Never work
194
+ around a diagnostic.
195
+
196
+ Then call the endpoint for real (the bench must be up — `dude up`; first boot
197
+ provisions the site and takes several minutes):
198
+
199
+ ```bash
200
+ # From the host — SITE_NAME comes from .env, the bench serves it on port 8000
201
+ curl -s "http://$SITE_NAME:8000/api/method/<app>.api.<method>"
202
+ # Unauthenticated: expect a PermissionError unless the method is guest-ok.
203
+
204
+ # Without HTTP, straight through the framework
205
+ dude bench --site all execute <app>.api.<method>
206
+
207
+ # Portal page, if you added one
208
+ open "http://$SITE_NAME:8000/<route>"
209
+ ```
210
+
211
+ ---
212
+
213
+ ## Step 7 — Report
214
+
215
+ ```
216
+ API method created
217
+ ═════════════════════════════════════════
218
+ Method apps/<app>/<app>/api.py :: <method>
219
+ Endpoint /api/method/<app>.api.<method>
220
+ Access authenticated | guest-ok: <reason>
221
+ Params <name: type, …>
222
+ Returns <shape>
223
+ Portal page <apps/<app>/<app>/templates/pages/<route>.{py,html} | n/a>
224
+ Test apps/<app>/<app>/test_api.py
225
+ ─────────────────────────────────────────
226
+ dude lint: ✓ (PY001, PY002)
227
+ dude test --app <app>: ✓
228
+ Called: dude bench --site all execute <app>.api.<method>
229
+ ```
@@ -76,6 +76,17 @@ dude lint # must pass — fix any DT/PY violation and re-run
76
76
  dude test --app <app> # the new tests must pass
77
77
  ```
78
78
 
79
+ `dude lint` is a pure filesystem check — it needs neither Docker nor a running
80
+ bench, so run it even when you cannot migrate. On a violation, get the
81
+ machine-readable form and the prose behind the code rather than guessing:
82
+
83
+ ```bash
84
+ dude lint --format json # file, line and code for every diagnostic
85
+ dude explain DT002 # (or DT001/DT003/DT004/PY003) — why, and how to fix
86
+ ```
87
+
88
+ Fix the cause the rule describes; never work around a diagnostic.
89
+
79
90
  If `dude site migrate` fails on the JSON, compare it field-by-field with
80
91
  `ticket_escalation_rule.json` — missing framework keys are the usual cause.
81
92
 
@@ -0,0 +1,254 @@
1
+ ---
2
+ name: create-hook
3
+ description: Wire a new hook into a custom Frappe app — a scheduled background job (scheduler_events + tasks.py), a document event handler on another app's DocType (doc_events + events/), or a shipped fixture. Surveys the existing hooks.py before adding, writes the handler in the right module, registers the dotted path, and verifies with dude lint (APP002/APP003/APP004) and dude test.
4
+ disable-model-invocation: false
5
+ allowed-tools: "Read Write Edit Glob Grep Bash(dude *) Bash(find *) Bash(cat *) Bash(grep *) Bash(ls *)"
6
+ ---
7
+
8
+ # Create Hook
9
+
10
+ `hooks.py` is the app's contract with the framework. Every entry in it is a
11
+ **dotted path resolved at runtime** — a typo does not fail on install or on
12
+ boot, the job simply never runs. That is why APP002, APP003 and APP004 exist,
13
+ and why this skill always ends by running the linter.
14
+
15
+ The reference app is `apps/ticketing/` — copy its patterns, don't invent new
16
+ ones. Keep `hooks.py` declarative: the logic lives in `tasks.py`, `events/` or
17
+ `fixtures/`, never inline in the hooks dict.
18
+
19
+ > Read `.claude/rules/APP/002.md`, `003.md` and `004.md` once at the start —
20
+ > they are the source of truth. `dude explain APP002` prints the same prose.
21
+
22
+ ---
23
+
24
+ ## Step 0 — Locate the project
25
+
26
+ ```bash
27
+ find . -maxdepth 3 -name "dude.json" | head -1
28
+ ```
29
+
30
+ Set `PROJECT_ROOT` to the directory containing `dude.json`. If missing, stop
31
+ with _"No dude.json found — are you inside a dude project?"_.
32
+
33
+ Confirm which apps are real bench apps (a directory under `apps/` is only an
34
+ app if it has a `pyproject.toml` — that is exactly what the linter checks, see
35
+ APP001):
36
+
37
+ ```bash
38
+ ls -d "$PROJECT_ROOT"/apps/*/pyproject.toml
39
+ ```
40
+
41
+ ---
42
+
43
+ ## Step 1 — Gather requirements
44
+
45
+ Ask only for what the user hasn't already provided:
46
+
47
+ 1. **Target app** — default `ticketing`. Must be one of the apps found above.
48
+ 2. **Which kind of hook**:
49
+ - **Scheduled job** — "run this every hour/day" → `scheduler_events` (APP002)
50
+ - **Document event** — "when an HD Ticket is saved, do X" → `doc_events` (APP003)
51
+ - **Fixture** — "ship this Workflow / these records with the app" → `fixtures` (APP004)
52
+ 3. **The specifics**:
53
+ - scheduled job → the frequency (`all`, `hourly`, `daily`, `weekly`,
54
+ `monthly`, or a `cron` expression) and what the job does
55
+ - document event → the DocType (e.g. `HD Ticket`) and the event
56
+ (`validate`, `before_save`, `after_insert`, `on_update`, `on_submit`,
57
+ `on_trash`, …)
58
+ - fixture → the DocType whose records to ship, and which records
59
+
60
+ ---
61
+
62
+ ## Step 2 — Survey the existing hooks (extend before adding)
63
+
64
+ Read the whole file before touching it — the answer is often "add one line to a
65
+ list that already exists":
66
+
67
+ ```bash
68
+ cat "$PROJECT_ROOT"/apps/<app>/<app>/hooks.py
69
+ ls "$PROJECT_ROOT"/apps/<app>/<app>/tasks.py "$PROJECT_ROOT"/apps/<app>/<app>/events/ 2>/dev/null
70
+ ls "$PROJECT_ROOT"/apps/<app>/<app>/fixtures/ 2>/dev/null
71
+ ```
72
+
73
+ - **Same frequency already declared?** Append to that list, don't add a second
74
+ key for the same frequency.
75
+ - **Same DocType already hooked?** Add the event to its existing dict entry.
76
+ - **A module already covers this area?** `tasks.py` for jobs,
77
+ `events/<scrubbed_doctype>.py` for document events — put the function there
78
+ instead of creating a parallel module.
79
+
80
+ Report what you found and what you intend to extend.
81
+
82
+ ---
83
+
84
+ ## Step 3 — Write the handler
85
+
86
+ ### A. Scheduled job → `apps/<app>/<app>/tasks.py`
87
+
88
+ A plain module-level function, no arguments. Model it on
89
+ `escalate_overdue_tickets` in `apps/ticketing/ticketing/tasks.py`.
90
+
91
+ ```python
92
+ def close_stale_resolved_tickets() -> None:
93
+ """Daily: close tickets that have sat in Resolved for more than 7 days."""
94
+ if not frappe.db.table_exists("HD Ticket"):
95
+ return
96
+ ...
97
+ ```
98
+
99
+ Non-negotiables:
100
+ - **Idempotent.** The scheduler guarantees at-least-once, not exactly-once.
101
+ Guard with a "did I already do this?" check — the shipped example looks for
102
+ its own marker comment before escalating again.
103
+ - **Defensive about other apps.** A job that touches a DocType from another app
104
+ must tolerate that app being absent (`frappe.db.table_exists(...)`), the way
105
+ both shipped jobs do — the example app works with or without Helpdesk.
106
+ - **ORM, not SQL.** `frappe.get_all` / `frappe.get_doc` / `frappe.qb`. An
107
+ f-string inside `frappe.db.sql()` is a PY002 **error**.
108
+ - `frappe.db.commit()` at the end when the job wrote something.
109
+
110
+ ### B. Document event → `apps/<app>/<app>/events/<scrubbed_doctype>.py`
111
+
112
+ One module per hooked DocType, named after the scrubbed DocType
113
+ (`HD Ticket` → `hd_ticket.py`). Handlers are plain functions taking
114
+ `(doc, method=None)`. Model them on
115
+ `apps/ticketing/ticketing/events/hd_ticket.py`.
116
+
117
+ ```python
118
+ def on_update(doc, method=None) -> None:
119
+ before = doc.get_doc_before_save()
120
+ if before is None or before.status == doc.status:
121
+ return
122
+ ...
123
+ ```
124
+
125
+ Notes:
126
+ - `doc.get_doc_before_save()` is the standard way to detect a field change
127
+ inside the same save cycle.
128
+ - New module? Create the `events/` package with an `__init__.py` if it doesn't
129
+ exist yet — the dotted path must import.
130
+ - Handlers run on **every save** of that DocType. Keep them cheap and never let
131
+ one raise for an unrelated reason.
132
+
133
+ ### C. Fixture → `apps/<app>/<app>/fixtures/<scrubbed_dt>.json`
134
+
135
+ Fixtures are **records, not code**: build them in the Desk UI first, then
136
+ export. Do not hand-write the JSON.
137
+
138
+ ---
139
+
140
+ ## Step 4 — Register the dotted path in `hooks.py`
141
+
142
+ This is the step the linter checks. The path is
143
+ `<app>.<module>.<function>` — relative to the app's python package, not the
144
+ repo root.
145
+
146
+ ```python
147
+ # A — scheduler_events (APP002)
148
+ scheduler_events = {
149
+ "hourly": ["ticketing.tasks.escalate_overdue_tickets"],
150
+ "daily": ["ticketing.tasks.close_stale_resolved_tickets"],
151
+ }
152
+
153
+ # B — doc_events (APP003)
154
+ doc_events = {
155
+ "HD Ticket": {
156
+ "after_insert": "ticketing.events.hd_ticket.after_insert",
157
+ "on_update": "ticketing.events.hd_ticket.on_update",
158
+ },
159
+ }
160
+
161
+ # C — fixtures (APP004): linked masters first, and always filtered
162
+ fixtures = [
163
+ {"dt": "Workflow State", "filters": [["name", "in", ["Draft", "Approved", "Rejected"]]]},
164
+ {"dt": "Workflow Action Master", "filters": [["name", "in", ["Approve", "Reject"]]]},
165
+ {"dt": "Workflow", "filters": [["name", "in", ["Ticket Escalation Rule Approval"]]]},
166
+ ]
167
+ ```
168
+
169
+ - `hooks.py` is **tab-indented** (Frappe style, enforced by `dude format`) —
170
+ match the surrounding file.
171
+ - APP004 is checked in **both** directions: a declared fixture with no
172
+ `fixtures/<scrubbed_name>.json` breaks a fresh install, and an undeclared
173
+ JSON file is never imported by anyone. `Workflow State` → `workflow_state.json`.
174
+ - Never declare a fixture without `filters` — `{"dt": "Workflow"}` exports
175
+ *every* workflow on the site, including other apps'.
176
+
177
+ For a fixture, export the records into the app now and commit the JSON:
178
+
179
+ ```bash
180
+ dude bench --site all export-fixtures --app <app>
181
+ ```
182
+
183
+ ---
184
+
185
+ ## Step 5 — Add a test
186
+
187
+ Not mechanically required for hooks (PY003 nudges DocType tests specifically),
188
+ but `bench run-tests --app <app>` discovers any `test_*.py` in the app, so it
189
+ costs one file. Put `test_tasks.py` beside `tasks.py`, or
190
+ `test_<scrubbed_doctype>.py` beside the event module, and use `FrappeTestCase`
191
+ — mirror
192
+ `apps/ticketing/ticketing/ticketing/doctype/ticket_escalation_rule/test_ticket_escalation_rule.py`.
193
+ It wraps each test in a transaction and rolls it back, so tests never leak data
194
+ into the site.
195
+
196
+ Test the handler function directly — do not try to make the scheduler fire.
197
+
198
+ ---
199
+
200
+ ## Step 6 — Load and validate
201
+
202
+ Hooks are cached and the scheduler process reads them at start, so a new hook
203
+ is not live until the bench picks it up:
204
+
205
+ ```bash
206
+ cd "$PROJECT_ROOT"
207
+ dude site clear-cache # drops the cached hooks
208
+ dude down && dude up # restart so `schedule` re-reads scheduler_events
209
+ dude site migrate # ONLY for fixtures — re-imports fixtures/*.json
210
+ ```
211
+
212
+ Then verify, in this order:
213
+
214
+ ```bash
215
+ dude lint # APP002/APP003/APP004 must pass
216
+ dude lint --format json # machine-readable: file, line, code
217
+ dude explain APP002 # (or APP003 / APP004) — why, and how to fix
218
+ dude test --app <app>
219
+ ```
220
+
221
+ `dude lint` is a pure filesystem check — it runs without Docker and will catch
222
+ an unresolvable dotted path or a fixture mismatch immediately. Fix the cause the
223
+ rule describes; never work around a diagnostic.
224
+
225
+ Finally, exercise the hook for real instead of waiting for the schedule:
226
+
227
+ ```bash
228
+ # A — run the job now
229
+ dude bench --site all execute <app>.tasks.<function>
230
+
231
+ # B — trigger the document event by saving a document
232
+ dude site console # then: frappe.get_doc("HD Ticket", "<name>").save()
233
+
234
+ # C — confirm the fixture landed
235
+ dude site console # then: frappe.get_all("Workflow", pluck="name")
236
+ ```
237
+
238
+ ---
239
+
240
+ ## Step 7 — Report
241
+
242
+ ```
243
+ Hook created
244
+ ═════════════════════════════════════════
245
+ Kind <scheduled job | doc event | fixture>
246
+ App <app>
247
+ Handler apps/<app>/<app>/<module>.py :: <function>
248
+ Registered hooks.py → <scheduler_events "<freq>" | doc_events "<DocType>.<event>" | fixtures>
249
+ Test <test file | none>
250
+ ─────────────────────────────────────────
251
+ dude lint: ✓ (APP002/APP003/APP004)
252
+ dude test --app <app>: ✓
253
+ Exercised: dude bench --site all execute <dotted.path>
254
+ ```