45 KiB
Developer's Guide: Extending the Native UI
How to add buttons, dropdowns, and automation to ERPNext without a custom Frappe app — the same three tools used to build every native feature in this project (Tool Kits, QR codes, Damage & Cost Report, maintenance reminders). Everything here is built and stored inside Frappe itself, through the Desk UI — no code deploy, no app, no restart.
Architecture at a glance
One VPS runs one Docker Compose stack — one bench: the shared Frappe/ERPNext containers,
MariaDB, Redis, and the backend-billing Flask service. That bench can hold one client or
several — each client is its own Frappe site (own database, own site folder, same shared
containers/volumes), not its own stack. backend/tenants.json gives each site its own billing
identity (tenant_slug), so one shared backend-billing service, and one shared nightly
backup, safely cover every client on the box at once.
VPS (one bench)
├── backend-billing → tenants.json (one entry per client site)
├── db (MariaDB) → one database per site
├── sites/ → one folder per site
└── backup.sh → one nightly archive of everything above, to R2
Everything in this guide — Customize Form, Client Scripts, Server Scripts — targets one site at
a time (via bench --site <name> console, or by being logged into that site's Desk). Nothing
here is bench-global except Stage 4's server_script_enabled flag in
INSTALLATION_PLAYBOOK.md, which is why that one only needs
setting once per VPS, not once per client. See that playbook's own "Architecture" section for the
full standing-up-a-new-client walkthrough, and
BACKUP_RESTORE.md for how the shared backup/restore actually works.
The three tools, and when to reach for each
| You want to... | Use | Notes |
|---|---|---|
| Add a field to a form | Customize Form | No code. Desk UI → Customize Form → pick a DocType. |
| Add a button, or change form behavior in the browser (show/hide fields, populate values, navigate) | Client Script | Runs in the user's browser. Can call server-side logic, but can't touch the database directly. |
| Run logic on the server — call another service, write files, query/update records beyond the current form | Server Script | Runs on the server, sandboxed (RestrictedPython). Four flavors — see below. |
A Client Script button that needs to do something beyond the browser (attach a file, call the QR backend, delete records) is always a pair: the Client Script adds the button and calls into a Server Script; the Server Script does the actual work. Neither one does both jobs.
Server Script's four flavors
| Script Type | Fires when | Reference fields needed |
|---|---|---|
| DocType Event | Automatically, on a lifecycle event of a specific DocType (After Insert, After Submit, etc.) | Reference Document Type, DocType Event |
| API | On demand, called from a Client Script (or any HTTP client) via /api/method/<name> |
API Method (the name callers use) |
| Scheduler Event | On a schedule (cron-like) | — |
| Permission Query | To compute row-level read permissions for list views | — |
This project uses the first two. Every native automation you'll build is one of these two shapes.
Patching the image itself (last resort)
A small number of things genuinely have no DB-level override point at all — not Website
Settings, not Navbar Settings, not a Client Script (its dt field is mandatory, so there's no way
to register one that runs globally across every Desk page the way some of these render). Confirmed
by reading Frappe/ERPNext's own source each time, not guessed:
| What | Where it actually lives | Confirmed via |
|---|---|---|
| "ERPNext" text under the workspace title, and the Apps-switcher tile's label | erpnext/hooks.py's app_title |
boot.py's load_desktop_data() |
| The Apps-switcher tile's icon, and a couple of erpnext-level branding fallbacks | erpnext/hooks.py's app_logo_url / add_to_apps_screen / website_context |
same |
| The Desk sidebar header's icon (top-left of every workspace page) | a real bundled SVG file, apps/erpnext/erpnext/public/icons/desktop_icons/solid/<workspace>.svg |
sidebar_header.js's set_header_icon() + utils.js's get_desktop_icon() |
Before reaching for this, prove the DB-level path really doesn't exist — check the relevant
DocType's full field list (frappe.get_meta(doctype).fields), not just the fields you already
know about; two of the three rows above were only confirmed after checking Website Settings and
Navbar Settings turned up nothing. This is genuinely a last resort, not a shortcut for skipping
that check.
The mechanism: erpnext-image/Dockerfile — FROM frappe/erpnext:${ERPNEXT_VERSION}, then a
RUN/COPY that patches exactly the file(s) above, with build-time grep checks that fail the
build loudly if a future ERPNEXT_VERSION bump rewords or moves what's being patched, rather than
silently shipping unpatched branding. Wired in via frappe_docker's own CUSTOM_IMAGE/CUSTOM_TAG
mechanism (its compose.yaml already reads
${CUSTOM_IMAGE:-frappe/erpnext}:${CUSTOM_TAG:-$ERPNEXT_VERSION} for every Frappe-image service)
— no edits to frappe_docker/ or this repo's own docker-compose.yml. Build with
erpnext-image/build.sh; see INSTALLATION_PLAYBOOK.md Stage 1 for wiring it into a fresh
deployment.
⚠ Confirmed the hard way, worth knowing before assuming a fix needs an extra step: a locally
built CUSTOM_IMAGE needs PULL_POLICY=never in .env — frappe_docker defaults these services to
pull_policy: always (correct once this image is actually pushed to a registry; wrong for a
local-only build, which fails outright trying to pull something that was never pushed anywhere).
Separately, don't assume every static asset under an app's public/ folder needs a bench build
step after patching — checked directly on a running container
(ls -la /home/frappe/frappe-bench/assets/) before writing that assumption down anywhere:
assets/erpnext is a plain directory symlink straight back to apps/erpnext/erpnext/public, baked
into the image by the entrypoint script on every container start. A Dockerfile COPY into that
source path is picked up immediately — no rebuild step, no extra durability concern.
Building a button (Client Script)
Desk UI → search bar → Client Script → New.
Fields on the form:
- Name — anything descriptive; this is the record's identity, not shown to end users.
- Document Type (
dt) — which DocType the script attaches to, e.g.Serial No. - View — usually
Form. (ListandReportalso exist, for list-view customizations.) - Enabled — check this, or the script silently does nothing.
- Script — the JavaScript itself.
The button-adding pattern:
frappe.ui.form.on("Serial No", {
refresh: function(frm) {
if (frm.doc.name && !frm.is_new()) {
frm.add_custom_button("Regenerate QR Code", function() {
// ... call a Server Script, or do pure client-side work
});
}
}
});
refresh fires every time the form loads or reloads — the right place for buttons, since it
re-adds them after every frm.reload_doc().
Grouping buttons into a dropdown: pass a third argument to add_custom_button() — every call
that shares the same group label collapses into one dropdown button with that label, instead of
each becoming its own top-level button:
frm.add_custom_button("TOOL-00001", function() { ... }, "View Serial Numbers");
frm.add_custom_button("TOOL-00002", function() { ... }, "View Serial Numbers");
// renders as one dropdown button "View Serial Numbers" containing both
Calling a Server Script from a button — for an API-type Server Script named (its API Method)
some_method_name:
frappe.call({
method: "some_method_name",
args: { key: value },
freeze: true, // greys out the form while it runs
freeze_message: "Working...",
callback: function(r) {
if (r.message) { /* r.message is whatever the script returned */ }
}
});
Building the server-side half (API-type Server Script)
Desk UI → search bar → Server Script → New.
Fields on the form:
- Name — descriptive, e.g. "Regenerate Serial No QR Code".
- Script Type —
API. - API Method — the exact string the Client Script's
frappe.call({ method: ... })must match. This is the callable name, not the record's Name field. - Allow Guest — leave unchecked unless this genuinely needs to work for logged-out users.
- Script — the Python.
Reading input, inside the script:
value = frappe.form_dict.get("key") # matches args: { key: value } from the Client Script
Returning output, inside the script:
frappe.flags.some_key = "some value"
⚠ Not frappe.response["message"] = ... — the sandbox only exposes frappe.response as a
real, writable object once a live HTTP request has already populated it. Setting it directly
inside the script throws SyntaxError: Not allowed to write to object ... outside that exact
context. frappe.flags.<key> = value is the one output path that's documented to always work —
Frappe automatically returns the full frappe.flags dict as r.message in the calling
frappe.call's callback.
What's available inside the sandbox (a deliberately restricted subset of Python — this is
RestrictedPython, not a normal script): frappe.get_doc, frappe.new_doc, frappe.delete_doc,
frappe.get_all / frappe.get_list, frappe.db.exists / frappe.db.get_value / frappe.db.sql,
frappe.make_get_request / frappe.make_post_request (and put/patch/delete), frappe.throw,
frappe.form_dict, frappe.flags, frappe.session.user. Notably not available: arbitrary
imports (import os, import base64, etc.) — if you need binary data, use the File doctype's
decode=True + content=<base64 string> mechanism instead of decoding it yourself.
Automatic triggers (DocType Event Server Script)
Same Server Script → New form, but:
- Script Type —
DocType Event. - Reference Document Type — the DocType to watch, e.g.
Stock Entry. - DocType Event — the lifecycle moment:
Before Insert,After Insert,Before Save,After Save,Before Submit,After Submit,Before Cancel,After Cancel, etc.
Inside the script, the triggering document is available as doc:
if doc.some_field == "some_value":
...
⚠ The event only fires for documents created through the normal Document lifecycle —
doc.insert() / doc.save() / doc.submit(). Some ERPNext internals bulk-create records for
performance using frappe.db.bulk_insert(), which writes rows directly to the database and
skips the Document lifecycle entirely — no hooks, no Server Scripts, no Notifications fire for
those records. Serial No is a real example: ERPNext creates Serial No records this way during
Stock Entry submission, so a DocType Event script on Serial No's own "After Insert" will never
fire from that flow. The fix is to trigger on the parent operation that does go through the
normal lifecycle instead — in this case, Stock Entry's "After Submit" — and have that script
iterate over whatever child records it just affected. If a DocType Event script seems to silently
never run (no Error Log entry, nothing happens), suspect this before anything else — check
whether the DocType you're watching is ever bulk-inserted rather than individually saved.
The one setting that has to be right before any of this works
Server Scripts as a whole feature are gated by server_script_enabled. It must be true in
common_site_config.json (bench-wide) — not site_config.json (per-site):
bench set-config -g server_script_enabled true
The -g flag is what makes the difference. Without it, bench set-config server_script_enabled true writes to the per-site file, has no effect, and every Server Script on the site fails with
ServerScriptNotEnabled — with no Error Log entry at all, since the check happens before the
script body ever runs. There's no Desk UI toggle for this either. If a brand-new Server Script
does nothing and leaves no trace anywhere, check this first.
Testing before you trust the UI
bench --site <site> console opens a live Python REPL against the real site — use it to prove a
script works before wiring up the button, especially for anything that writes data.
Testing a DocType Event script — actually create and submit a real (test) document and check the side effect:
import frappe
doc = frappe.get_doc({"doctype": "...", ...})
doc.insert(ignore_permissions=True)
doc.submit()
frappe.db.commit()
# now check whatever the script was supposed to do
Testing an API-type Server Script — go through the real dispatch path, not just
execute_method() directly, since the two behave slightly differently around frappe.response:
import frappe
frappe.local.form_dict = frappe._dict(cmd="your_api_method", key="value")
frappe.response = frappe._dict()
from frappe.handler import execute_cmd
result = execute_cmd("your_api_method")
print(result)
frappe.db.commit()
Each bench console invocation is its own process with its own DB transaction — nothing persists
unless you call frappe.db.commit() before the session ends.
Case study: the Item → Serial No dropdown
A worked example tying all of the above together — this is the actual sequence used to add a "View Serial Numbers" dropdown to the Item form, so staff opening an Item (e.g. "Cordless Drill - DeWalt 20V") can jump straight to a specific unit's Serial No record instead of going through Item's Connections tab.
1. Confirm the data shape first. Serial No records carry an item_code field pointing back
to their Item — that's the filter the dropdown needs:
SELECT name, item_code FROM `tabSerial No`;
2. Desk UI → Client Script → New:
- Document Type:
Item - View:
Form - Enabled: checked
- Script:
frappe.ui.form.on("Item", {
refresh: function(frm) {
if (frm.doc.has_serial_no && !frm.is_new()) {
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Serial No",
filters: { item_code: frm.doc.name },
fields: ["name"],
limit_page_length: 20,
order_by: "creation desc"
},
callback: function(r) {
const serials = r.message || [];
serials.forEach(function(s) {
frm.add_custom_button(s.name, function() {
frappe.set_route("Form", "Serial No", s.name);
}, __("View Serial Numbers"));
});
frm.add_custom_button(__("View All"), function() {
frappe.route_options = { item_code: frm.doc.name };
frappe.set_route("List", "Serial No");
}, __("View Serial Numbers"));
}
});
}
}
});
⚠ Gotcha, confirmed the hard way: frappe.set_route() does not accept a filter object as
a trailing argument — frappe.set_route("List", "Serial No", { item_code: ... }) silently drops
that third argument and opens the list completely unfiltered. Frappe's actual convention is a
separate global, set immediately before the route change: frappe.route_options = { item_code: frm.doc.name } then frappe.set_route("List", "Serial No"). This shipped broken initially — the
per-item dropdown entries worked (they route straight to a specific Form, no filter involved), but
"View All" opened the entire unfiltered Serial No list, so an item with two units appeared to show
serials belonging to unrelated items too. There's no error thrown anywhere; it just silently
doesn't filter, so test the actual list that opens, not just that the button exists.
3. No new Server Script needed here — frappe.client.get_list is a core, already-whitelisted
Frappe method (the same one every list view in Desk calls), so this button only needed the
Client Script half. That's the tell for when you don't need to build a matching Server Script:
if the operation is a plain read that respects the current user's existing permissions, a core
whitelisted method usually already exists.
4. Guard against scale. Capped at the 20 most recent serials (order_by: "creation desc")
plus a "View All" entry routing to the full filtered list view — an item with hundreds of units
in the field shouldn't turn into a 200-item dropdown.
5. Verify in the browser, not just in theory: open an Item with has_serial_no checked and at
least one real Serial No pointing at it, confirm the "View Serial Numbers" dropdown appears with
the right entries, and confirm each one navigates to the correct Serial No record.
Manual fallback: reproducing the provisioning script by hand
provisioning/provision_client.py automates
everything below onto a fresh site (see INSTALLATION_PLAYBOOK.md Stage 5). This section is what
to reach for if that script ever fails partway through, produces something wrong, or you need to
verify, fix, or manually reproduce one specific piece of it — the exact Desk UI steps and full
content for every single thing it creates. Nothing here is new information; it's the same source
the script's own functions were built from, kept here as the readable, browsable version.
Stock Settings flags
Desk UI → Stock → Settings → Stock Settings. Two of these default to off regardless of what the Setup Wizard asked — don't assume they're on just because a previous install had them on:
| Setting (UI label) | Field name | Default | Why it matters |
|---|---|---|---|
| Activate Serial / Batch No for Item | enable_serial_and_batch_no_for_item |
Off | Required before any serialized Tool can be received — without it, submitting throws an error, and with use_serial_batch_fields set it can silently post zero stock instead. |
| Raise Material Request when stock reaches re-order level | auto_indent |
Off | This is the low-stock alert feature. |
| Show barcode field in stock transactions | show_barcode_field |
On | Puts the scan-with-camera control on Serial No fields. |
Skip this one, don't enable it: "Notify by email on creation of automatic Material Request"
(reorder_email_notify) is ERPNext's own built-in low-stock email toggle. It isn't used here —
the dedicated Notification below (with a tested condition and recipient role) replaces it;
enabling both would double up alerts.
System Settings toggles
Desk UI → Settings → System Settings:
- Enable Scheduled Jobs (
enable_scheduler) — exactly whatbench scheduler enablesets under the hood. - Disable Standard Email Footer (
disable_standard_email_footer) — removes the "Sent via ERPNext" branding line Frappe appends to every outgoing email by default. Every custom Notification below keeps its own footer line regardless; this only strips the platform branding underneath it.
Customize Form fields
Stock Entry: Signature (Signature, mandatory), Photo (Attach Image, mandatory), Issue
Reason (Select: Consumed\nLost\nDamaged\nStolen), Tool Kit (Link → Tool Kit). Signature and
Photo are checked Mandatory deliberately — without that, both fields exist but a Stock Entry
can submit with neither filled in, quietly breaking the "signature captured every time a tool
moves" and "photo-evidenced write-offs" promises.
Serial No: Last Serviced Date (Date), Maintenance Interval (Days) (Int), Next Due Date (Date, read-only).
Tool Kit DocType
New DocType Tool Kit (Desk UI → New DocType) — autoname field:kit_name, one field kit_name
(Data, mandatory), one child table field items (Table → Tool Kit Item). The child DocType
Tool Kit Item has two fields: item (Link → Item, mandatory, shown in list view) and qty
(Int, shown in list view).
⚠ Order matters: create Tool Kit (and Tool Kit Item) before the Stock Entry tool_kit
Custom Field above — that field Links to Tool Kit, and Frappe validates the target DocType
exists at save time. Creating the Custom Field first fails with WrongOptionsDoctypeLinkError: Options must be a valid DocType.
Client Scripts
Tool Kit auto-populate — Desk UI → Client Script → New: Document Type Stock Entry, View
Form:
frappe.ui.form.on('Stock Entry', {
tool_kit: function(frm) {
if (!frm.doc.tool_kit) return;
frappe.call({
method: 'frappe.client.get',
args: { doctype: 'Tool Kit', name: frm.doc.tool_kit },
callback: function(response) {
const kit = response.message;
frm.clear_table('items');
(kit.items || []).forEach(function(kit_item) {
const row = frm.add_child('items');
row.item_code = kit_item.item;
row.qty = kit_item.qty || 1;
});
frm.refresh_field('items');
}
});
}
});
Maintenance date recalculation — Document Type Serial No, View Form:
frappe.ui.form.on('Serial No', {
last_serviced_date: function(frm) {
recalculate_next_due_date(frm);
},
maintenance_interval_days: function(frm) {
recalculate_next_due_date(frm);
}
});
function recalculate_next_due_date(frm) {
if (frm.doc.last_serviced_date && frm.doc.maintenance_interval_days) {
const next_due = frappe.datetime.add_days(
frm.doc.last_serviced_date,
frm.doc.maintenance_interval_days
);
frm.set_value('next_due_date', next_due);
}
}
"Regenerate QR Code" button — Document Type Serial No, View Form:
frappe.ui.form.on("Serial No", {
refresh: function(frm) {
if (frm.doc.name && !frm.is_new()) {
frm.add_custom_button("Regenerate QR Code", function() {
frappe.call({
method: "regenerate_serial_no_qr_code",
args: { serial_no: frm.doc.name },
freeze: true,
freeze_message: "Generating QR code...",
callback: function(r) {
if (r.message) {
frappe.show_alert({ message: "QR code regenerated", indicator: "green" });
frm.reload_doc();
}
}
});
});
}
}
});
"View Serial Numbers" dropdown on the Item form — see the Case Study below; it's the fully worked example for this exact script.
Server Scripts
⚠ Both QR scripts below depend on the backend-billing Docker container, which neither this
guide's steps nor provision_client.py bring up or touch — it's infrastructure, started by
docker compose up -d (Installation Playbook Stage 1), exactly like MariaDB or Redis. It's
genuinely tenant-agnostic — no per-client config needed — so once it's running anywhere on the
same compose project, every site's scripts can already reach it at
http://backend-billing:8000/.... If these scripts exist correctly but QR codes still aren't
generating, check docker compose ps for that container before suspecting the scripts themselves.
QR code auto-attach on tool receipt — Script Type DocType Event, Reference Document Type
Stock Entry, Event After Submit (see the "Automatic triggers" gotcha above for why it can't be
on Serial No itself):
for row in doc.items:
if not row.serial_no:
continue
for serial in [s.strip() for s in row.serial_no.split("\n") if s.strip()]:
if frappe.db.exists("File", {"attached_to_doctype": "Serial No", "attached_to_name": serial}):
continue
response = frappe.make_post_request(
"http://backend-billing:8000/qrcode/generate-base64",
json={"data": serial, "label_lines": [row.item_code, serial]}
)
if response and response.get("data_base64"):
frappe.get_doc({
"doctype": "File",
"file_name": response.get("filename") or (serial + ".png"),
"attached_to_doctype": "Serial No",
"attached_to_name": serial,
"content": response["data_base64"],
"decode": True,
"is_private": 1
}).insert(ignore_permissions=True)
The frappe.db.exists("File", ...) guard means a tool that already has a QR attached won't get a
duplicate one generated on a later transfer or return of the same serial. label_lines prints the
item name and serial number as text beneath the QR code itself, so a printed sheet of codes stays
identifiable without scanning each one.
"Regenerate QR Code" API — Script Type API, API Method regenerate_serial_no_qr_code (this
exact string is what the Client Script above calls):
serial_no = frappe.form_dict.get("serial_no")
if not serial_no or not frappe.db.exists("Serial No", serial_no):
frappe.throw("A valid Serial No is required")
item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
label_lines = [item_code, serial_no] if item_code else [serial_no]
for existing in frappe.get_all("File", filters={"attached_to_doctype": "Serial No", "attached_to_name": serial_no}, pluck="name"):
frappe.delete_doc("File", existing, ignore_permissions=True)
response = frappe.make_post_request(
"http://backend-billing:8000/qrcode/generate-base64",
json={"data": serial_no, "label_lines": label_lines}
)
if response and response.get("data_base64"):
new_file = frappe.get_doc({
"doctype": "File",
"file_name": response.get("filename") or (serial_no + ".png"),
"attached_to_doctype": "Serial No",
"attached_to_name": serial_no,
"content": response["data_base64"],
"decode": True,
"is_private": 1
})
new_file.insert(ignore_permissions=True)
frappe.flags.file_url = new_file.file_url
frappe.flags.file_name = new_file.file_name
else:
frappe.throw("Could not generate a QR code for this serial number")
Workflow: Material Request Approval
States: Draft (doc status Draft) → Pending Approval (Submitted) → Approved/Rejected (Submitted). Transitions: Draft →(Submit, allowed Stock User)→ Pending Approval; Pending Approval →(Approve, allowed Stock Manager)→ Approved; Pending Approval →(Reject, allowed Stock Manager)→ Rejected.
⚠ Gotcha, confirmed the hard way: Workflow State records for "Draft", "Pending Approval",
"Approved", "Rejected" and Workflow Action Master records for "Submit", "Approve", "Reject"
all need to exist first if the site doesn't already have generic ones — the Desk UI creates them
on the fly when you build a Workflow interactively, but a script has to pre-create them
explicitly. The "Submit" action master is the easy one to miss, since it reads like a built-in
document action rather than a workflow-specific one — skip it and creating the Workflow itself
fails with Could not find Row #1: Action: Submit, which doesn't obviously point at a missing
master record.
Notifications
Both use a rich HTML message body instead of plain text — a Notification's message field is
Jinja evaluated against the triggering doc, and Frappe wraps whatever HTML you put there in its
own responsive email frame automatically. Reuse the same CSS classes ERPNext's own built-in
notifications already use — email-header, table table-bordered, btn btn-primary,
more-info, text-muted text-small — so custom templates render consistently with the rest of
the product instead of looking bolted on.
⚠ Gotcha, confirmed the hard way: a Notification's Channel field (Email / System Notification / Slack / SMS) locks after the record is first saved — Frappe blocks changing it later with "Value cannot be changed for Channel." Choose the right channel before saving; fixing a wrong choice means deleting and recreating the record, not editing it.
Serial No Maintenance Due — Document Type Serial No, Event Days Before, Channel Email,
Date field next_due_date, Days in Advance 7, Condition doc.maintenance_interval_days,
Recipient role Stock Manager, Subject Maintenance due soon: {{ doc.name }}:
<table class="email-header" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td><h1 class="email-header-title">Maintenance Due</h1></td></tr>
</table>
<p>The following tool is due for scheduled maintenance:</p>
<table class="table table-bordered" style="width: 100%;">
<tr>
<td class="text-bold" style="background: #f8f8f8; width: 160px">Serial No</td>
<td>{{ doc.name }}</td>
</tr>
<tr>
<td class="text-bold" style="background: #f8f8f8;">Item</td>
<td>{{ doc.item_name or doc.item_code }}</td>
</tr>
<tr>
<td class="text-bold" style="background: #f8f8f8;">Warehouse</td>
<td>{{ doc.warehouse or "—" }}</td>
</tr>
<tr>
<td class="text-bold" style="background: #f8f8f8;">Last Serviced</td>
<td>{{ frappe.utils.format_date(doc.last_serviced_date) if doc.last_serviced_date else "Never recorded" }}</td>
</tr>
<tr>
<td class="text-bold" style="background: #f8f8f8;">Maintenance Interval</td>
<td>{{ doc.maintenance_interval_days }} days</td>
</tr>
<tr>
<td class="text-bold" style="background: #f8f8f8;">Next Due Date</td>
<td>{{ frappe.utils.format_date(doc.next_due_date) }}</td>
</tr>
</table>
<div class="more-info">
<a class="btn btn-primary" href="{{ frappe.utils.get_url_to_form("Serial No", doc.name) }}">
View Serial No
</a>
</div>
<p class="text-muted text-small" style="margin-top: 20px;">
This is an automated maintenance reminder from {{ frappe.utils.get_host_name() }}.
</p>
Low Stock Reorder Alert — Document Type Material Request, Event New, Channel Email,
Condition doc.material_request_type == "Purchase" (without this it would email on every
Material Request, not just the auto-generated re-order ones), Recipient role Stock Manager,
Subject Low stock: {{ doc.name }} needs fulfilling:
<table class="email-header" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td><h1 class="email-header-title">Low Stock Alert</h1></td></tr>
</table>
<p>A consumable dropped below its reorder level, and <b>{{ doc.name }}</b> was raised automatically to restock it.</p>
<table class="table table-bordered" width="100%">
<tr align="center">
<th>Item</th>
<th>Qty Requested</th>
<th>Warehouse</th>
</tr>
{% for item in doc.items %}
<tr align="center">
<td>{{ item.item_code }}</td>
<td>{{ frappe.utils.flt(item.qty, 2) }} {{ item.uom or "" }}</td>
<td>{{ item.warehouse or "—" }}</td>
</tr>
{% endfor %}
</table>
<div class="more-info">
<a class="btn btn-primary" href="{{ frappe.utils.get_url_to_form("Material Request", doc.name) }}">
Review & Arrange Restocking
</a>
</div>
<p class="text-muted text-small" style="margin-top: 20px;">
This is an automated low-stock alert from {{ frappe.utils.get_host_name() }}.
</p>
Verify either one by calling frappe.get_doc("Notification", name).send(doc) directly against a
real (or temporary test) record — the same code path the scheduler itself uses — and inspect the
resulting Email Queue entry's rendered HTML/plain-text before trusting it.
Damage & Cost Report
Query Report, Ref DocType Stock Entry, Roles Stock Manager + System Manager:
SELECT
se.issue_reason AS "Issue Reason:Data:120",
sed.item_code AS "Item:Link/Item:150",
sed.s_warehouse AS "Warehouse:Link/Warehouse:150",
SUM(sed.qty) AS "Qty:Float:100",
SUM(sed.amount) AS "Cost:Currency:120"
FROM `tabStock Entry` se
INNER JOIN `tabStock Entry Detail` sed ON sed.parent = se.name
WHERE se.docstatus = 1 AND se.purpose IN ('Material Issue', 'Material Transfer')
AND se.issue_reason IS NOT NULL AND se.issue_reason != ''
GROUP BY se.issue_reason, sed.item_code, sed.s_warehouse
ORDER BY se.issue_reason, sed.item_code
A "project" here is a Warehouse, not a separate Project record — Warehouses are already organized
one per property/site, and this report already groups by s_warehouse. Filtering the report grid
down to a single warehouse (Frappe's report view supports filtering any column natively) gives
exactly a per-site cost view without building anything further.
Role permissions: Stock Manager elevation
Neither Stock User nor Stock Manager can create or edit an Item or Warehouse by default — only System Manager can, which contradicts a Stock Manager "running the store." Fixed via Role Permission Manager: Desk UI → Role Permission Manager → select Item, Role Stock Manager → check Create and Write, leave Delete unchecked → Save; repeat for Warehouse, which additionally has no permission row for Stock Manager at all by default — not even Read — so add the row first.
Deliberately not granting Delete on either: correcting a typo'd Item or adding a new Warehouse for a new site is a real, expected task for that role; deleting a master that stock history may reference is not something it should be able to do unilaterally.
Audit trail hardening
Enable change tracking on Material Request — by default it does not track field-level edits, unlike Stock Entry/Item/Warehouse/Serial No, which already do. Desk UI → Customize Form → select Material Request → check Track Changes → Update.
Lock deletion-audit entries to Administrator only — Frappe's Deleted Document doctype stores a snapshot of any record's data at the moment it's deleted; by default System Manager can delete these entries, meaning a System Manager (not just Administrator) can erase evidence that something was ever deleted. Desk UI → Role Permission Manager → select Deleted Document, Role System Manager → uncheck Delete → Save. Administrator is unaffected — that account always bypasses role permissions by design, which is the intended "root" escape hatch, not a gap.
How immutable is any of this, honestly? Version and Deleted Document logs can't be edited or deleted by any ordinary user or System Manager through Desk UI or the API — a real, enforced guarantee at the application layer. It is not cryptographically tamper-proof at the database level: Administrator, and anyone with direct server/database access, can always bypass it. That's standard for a self-hosted single-tenant system, not a gap specific to this build.
Billing lockout: Role, Server Scripts, Web Page, Workspace shortcut
A locked-out User is never disabled — enabled stays 1, they can still log in. What locks them
out is a Role swap (their Roles replaced with a single Trial Expired Role that has no Desk
access) plus clearing their Default Workspace. Both pieces matter: ⚠ confirmed the hard
way, a User's own Default Workspace field silently overrides the Role's redirect if left in
place — Frappe resolves it after the Role-based redirect and sends the User to their old
workspace anyway, which then 403s since Desk access is gone. backend/billing/frappe_client.py's
lock_user()/restore_user() always move both together in one API call for exactly this reason.
The Trial Expired Role — Desk UI → Role List → New:
- Role Name:
Trial Expired - Uncheck Desk Access
- Home Page:
billing(no leading slash — Frappe strips it internally either way, but this matches what's actually stored)
The Custom Field System Settings.billing_tenant_slug — Desk UI → Customize Form → select
System Settings → add field: Label Billing Tenant Slug, Type Data, insert after
language. ⚠ Confirmed the hard way: this can't live in site_config.json instead —
frappe.conf is not reachable at all from inside a Server Script's RestrictedPython sandbox
(neither render_safe_globals() nor exec_safe_globals() expose it), unlike
frappe.db.get_single_value, which is. Every client's two Server Scripts below share the exact
same text; only this one Desk field differs per site — set it in Installation Playbook Stage 9,
step 6, to the same slug used in backend/tenants.json.
"Daily Trial Expiry Check" — Script Type Scheduler Event, Event Frequency Daily:
slug = frappe.db.get_single_value("System Settings", "billing_tenant_slug")
if slug:
frappe.make_post_request(f"http://backend-billing:8000/internal/check-trial/{slug}")
Independent of Stripe entirely — this fires once a day regardless of whether a subscription
exists, and locks the client out through the exact same disable_users() a real
invoice.payment_failed webhook would use, once the tenant's own trial_start_date/trial_days
(optional fields in tenants.json) has elapsed.
"Get Billing Status" — Script Type API, API Method get_billing_status, Allow Guest
left unchecked (a locked-out User is a "Website User," not a Guest — Server Script's own guest
check only blocks actual Guests, so this still works for them):
slug = frappe.db.get_single_value("System Settings", "billing_tenant_slug")
if slug:
response = frappe.make_get_request(f"http://backend-billing:8000/internal/billing-status/{slug}")
else:
response = {}
frappe.flags.subscription_status = response.get("subscription_status")
frappe.flags.current_period_end = response.get("current_period_end")
frappe.flags.trial_end = response.get("trial_end")
frappe.flags.invoices = response.get("invoices") or []
frappe.flags.payment_link_url = response.get("payment_link_url")
Output channel is frappe.flags, not frappe.response["message"] — confirmed by reading
execute_api_server_script()'s own source: an API-type Server Script's return value to the
caller is exactly the frappe.flags set during its run, which is what the billing page's
frappe.call() callback reads as r.message.
The /billing Web Page — Desk UI → Web Page → New:
-
Route:
billing, Published: checked, Content Type: HTML -
Main Section (HTML):
<div id="billing-page-wrap"> <div id="billing-status-app"> <p class="text-muted">Loading billing status…</p> </div> </div> -
CSS:
#billing-page-wrap { max-width: 720px; margin: 0 auto; } #billing-status-app table { margin-top: 1rem; } #billing-status-app .billing-cta { margin: 1rem 0; } -
JavaScript — calls
get_billing_statusabove and renders status, days-to-next-bill, recent invoices with receipt links, and a "Manage Billing" button frompayment_link_url; seeprovisioning/provision_client.py's_billing_status_pagefor the exact current text rather than duplicating it here twice.It also retargets the site navbar's top-left brand link to
/desk/stockviadocument.querySelector(".navbar-brand").setAttribute("href", "/desk/stock"). ⚠ Confirmed the hard way, after two wrong guesses: there is no field anywhere — notWebsite Settings.home_page, not the per-userget_home_page()resolution used for post-login redirects (see the lockout section above) — that controls this link for a Web Page document specifically. Reading Frappe's own source settles it: the Jinjahome_pagetemplate variablenavbar.htmlrenders ({{ home_page or "/" }}) is only ever set byfrappe/www/portal.py, for the unrelated/portalpage type — never byweb_page.py's ownget_context, so it's simply undefined here and always falls back to"/". Direct DOM manipulation in this page's own JS is the correct fix, not a workaround — the alternative would be patching Frappe core (frappe_docker/stays exactly as cloned, perCLAUDE.md) or a whole custom app for one link.⚠ Gotcha, confirmed the hard way — verify with a fresh Incognito window, not just a hard-refresh: this page is served with
Cache-Control: private, max-age=300, stale-while-revalidate=10800(Frappe's website page cache default) — a normal browser reload, and sometimes even a hard-refresh, can still serve up to 5 minutes of stale HTML without re-fetching. Two rounds of "the fix isn't showing up" on this exact link turned out to be a correct, already-deployed fix being masked by this — confirmed by fetching the raw page server-side (bypassing any browser entirely) and finding the new code already present and correct both times. When iterating on this page faster than 5 minutes per change, test in a fresh Incognito/Private window to rule this out before suspecting the code.
This is a public Web Page, not a Desk page, specifically because a locked-out User has no Desk access at all — it's the one page they can still reach. It's also open to any normal, logged-in staff member any time (see the Workspace shortcut below) — billing status isn't gated behind lockout.
"Billing" shortcut on the Stock Workspace — so /billing is actually discoverable from Desk,
not just reachable if you already know the URL. A Workspace shortcut is three things, all
required (confirmed by inspecting existing shortcut-bearing Workspaces on this bench):
- Desk UI → open the Stock Workspace → Edit → Add Shortcut: Type
URL, LabelBilling, URL/billing, Iconpayments(ERPNext's own icon set — Desk UI → Edit → the shortcut's own edit dialog has an icon picker). - The Workspace's layout (its
contentfield, a JSON block array) needs a matching{"type": "shortcut", "data": {"shortcut_name": "Billing"}}block — normally added automatically by dragging the new shortcut into the layout in the same Edit view; the row from step 1 alone doesn't render a visible card without it. - A
"header"block reading "Your Shortcuts", placed immediately before the shortcut block in the layout — drag a Heading element in above it, same Edit view.
⚠ Confirmed the hard way (caught by a user testing the live page, not in review): skipping
step 1's icon or step 3's header doesn't break anything functionally, but the shortcut visibly
doesn't match this Workspace's Card headings ("Custom Reports", "Other Reports", etc.) — and it
can't be made to, by design: a Card can only link to a DocType/Desk Page/Report, never a raw URL,
so a Shortcut is the only Workspace block capable of pointing at /billing at all, and Shortcuts
and Cards are two different native Frappe widgets with two different built-in typography
treatments. Grouping the shortcut under its own "Your Shortcuts" header — the exact pattern this
bench's own "ERPNext Settings" Workspace already uses — is what makes it read as an intentional
section instead of a stray, mismatched item dropped into the Cards grid.
Quick reference: everything native this project has built this way
| Feature | Kind |
|---|---|
| Signature / Photo / Issue Reason / Tool Kit fields on Stock Entry | Customize Form |
| Tool Kit auto-populates items when selected | Client Script (Stock Entry) |
| Maintenance / calibration date fields on Serial No | Customize Form |
| Maintenance due & low-stock alerts | Notification (native doctype, no script) |
| Damage & Cost Report | Query Report (SQL, no script) |
| QR code auto-attach on tool receipt | Server Script, DocType Event, Stock Entry → After Submit |
| "Regenerate QR Code" button | Client Script (Serial No) + Server Script, API |
| "View Serial Numbers" dropdown | Client Script (Item) only |
Trial Expired lockout Role (no Desk access, redirects to /billing) |
Role, native |
System Settings.billing_tenant_slug |
Customize Form |
| Daily trial-expiry lockout check | Server Script, Scheduler Event |
Billing status lookup for the /billing page |
Server Script, API |
/billing page (status, next bill, receipts, reactivation link) |
Web Page, native |
| "Billing" shortcut on the Stock Workspace | Workspace shortcut, native |
Every row above is created automatically by
provisioning/provision_client.py — see the
"Manual fallback" section above for the exact content of each, and
INSTALLATION_PLAYBOOK.md for where this fits in a full install.
The three rows below are a different mechanism — a Docker image patch, not a Frappe customization
provision_client.py could create (see "Patching the image itself" above for why) — built by
erpnext-image/build.sh, wired in via Stage 1 of INSTALLATION_PLAYBOOK.md, optional per
deployment:
| Feature | Kind |
|---|---|
| "ERPNext" text removed from the sidebar header and Apps-switcher tile | erpnext-image/Dockerfile, patches erpnext/hooks.py |
| ERPNext's own logo replaced on the Apps-switcher tile and website fallbacks | erpnext-image/Dockerfile, patches erpnext/hooks.py |
| ERPNext's own icon replaced on the Desk sidebar header (top-left, e.g. "Stock") | erpnext-image/Dockerfile, patches the bundled stock.svg |