sightbox/provisioning/provision_client.py

1139 lines
44 KiB
Python

"""
provision_client.py — replays every site-generic native customization from
INSTALLATION_PLAYBOOK.md onto a fresh site, in one idempotent pass.
Run against a target site via bench console, non-interactively:
docker compose exec -T backend bench --site <new-site> console < provision_client.py
(or use provision_client.sh, which wraps exactly that). Every step checks
whether its target already exists before creating it, so running this
twice — or against a site that already has some of this — is always safe.
What this script does NOT do, deliberately: the real Setup Wizard (Stage 3
— scripting around it caused three confirmed bugs, see the Installation
Playbook), the Resend Email Account (needs a real per-client API key), and
any client-specific business data — Item Groups, Warehouses, Items,
Company (Stage 6). Those stay manual/guided per client, exactly as
documented. Everything here is the generic, site-independent half: Stock
Settings flags, System Settings toggles, Customize Form fields, the Tool
Kit DocType, every Client/Server Script, the Workflow, both Notifications
(with their full HTML templates), the Damage & Cost Report, the Stock
Manager permission elevation (Item/Warehouse write access, Stock Ledger
Entry read access, and Stock Manager's addition to the standard Serial No
Ledger report's role list — the last one needs a brief in-process
frappe.conf.developer_mode toggle, since Frappe refuses to edit a standard
report's roles otherwise; it's restored immediately after and never
touches site_config.json), the entry-time serial-availability Client
Script (catches a serial that's already elsewhere/inactive the moment it's
added to a row, instead of only at submit), the two audit-hardening
settings, the "Trial Expired" lockout Role, the Custom Field System Settings.
billing_tenant_slug, the daily trial-expiry-check and billing-status-lookup
Server Scripts (both read their tenant slug from that Custom Field at
runtime — see _trial_check_scheduler / _billing_status_api — so this same
script text is correct for every client without templating), the public
/billing Web Page, a "Billing" shortcut on the Stock Workspace so it's
actually discoverable, not just reachable by URL, and this product's own
logo/footer branding site-wide (replacing ERPNext's own defaults) via
bettersight_logo.png, which ships alongside this script — see
provision_client.sh.
The QR-related Server/Client Scripts assume a reachable backend-billing
service at http://backend-billing:8000 (Stage 9) — they can be created
ahead of that being wired up; they just won't successfully attach a QR
image until it is.
"""
import frappe
def run():
print("=== provision_client.py starting ===")
_stock_settings()
_system_settings()
_tool_kit_doctype()
_custom_fields()
_client_scripts()
_server_scripts()
_workflow()
_notifications()
_damage_cost_report()
_role_permissions()
_serial_no_ledger_permission()
_audit_hardening()
_lockout_role()
_trial_check_scheduler()
_billing_status_api()
_billing_status_page()
_billing_workspace_shortcut()
_branding()
frappe.db.commit()
print("=== provision_client.py done ===")
# --- Stage 4: Stock Settings flags ------------------------------------------
def _stock_settings():
print("-- Stock Settings flags")
ss = frappe.get_single("Stock Settings")
changed = False
for field, value in (
("enable_serial_and_batch_no_for_item", 1),
("auto_indent", 1),
("show_barcode_field", 1),
):
if ss.get(field) != value:
ss.set(field, value)
changed = True
if changed:
ss.save(ignore_permissions=True)
print(" updated")
else:
print(" already correct")
# --- Stage 5 (partial) / Stage 10: System Settings toggles ------------------
def _system_settings():
print("-- System Settings toggles")
sys_settings = frappe.get_single("System Settings")
changed = False
for field, value in (
("enable_scheduler", 1),
("disable_standard_email_footer", 1),
):
if sys_settings.get(field) != value:
sys_settings.set(field, value)
changed = True
if changed:
sys_settings.save(ignore_permissions=True)
print(" updated")
else:
print(" already correct")
# --- Stage 7: Customize Form fields ------------------------------------------
def _ensure_custom_field(dt, fieldname, **kwargs):
name = f"{dt}-{fieldname}"
if frappe.db.exists("Custom Field", name):
existing = frappe.get_doc("Custom Field", name)
changed = False
for key, value in kwargs.items():
if existing.get(key) != value:
existing.set(key, value)
changed = True
if changed:
existing.save(ignore_permissions=True)
print(f" updated {name}")
else:
print(f" {name} already correct")
return
doc = frappe.get_doc({"doctype": "Custom Field", "dt": dt, "fieldname": fieldname, **kwargs})
doc.insert(ignore_permissions=True)
print(f" created {name}")
def _custom_fields():
print("-- Customize Form: Stock Entry")
_ensure_custom_field(
"Stock Entry", "signature", label="Signature", fieldtype="Signature",
insert_after="remarks", reqd=1,
)
_ensure_custom_field(
"Stock Entry", "photo", label="Photo", fieldtype="Attach Image",
insert_after="signature", reqd=1,
)
_ensure_custom_field(
"Stock Entry", "issue_reason", label="Issue Reason", fieldtype="Select",
options="Consumed\nLost\nDamaged\nStolen", insert_after="photo",
)
_ensure_custom_field(
"Stock Entry", "tool_kit", label="Tool Kit", fieldtype="Link",
options="Tool Kit", insert_after="issue_reason",
)
print("-- Customize Form: Serial No")
_ensure_custom_field(
"Serial No", "last_serviced_date", label="Last Serviced Date", fieldtype="Date",
insert_after="warranty_expiry_date",
)
_ensure_custom_field(
"Serial No", "maintenance_interval_days", label="Maintenance Interval (Days)",
fieldtype="Int", insert_after="last_serviced_date",
)
_ensure_custom_field(
"Serial No", "next_due_date", label="Next Due Date", fieldtype="Date",
insert_after="maintenance_interval_days", read_only=1,
)
print("-- Customize Form: System Settings")
_ensure_custom_field(
"System Settings", "billing_tenant_slug", label="Billing Tenant Slug", fieldtype="Data",
insert_after="language",
description=(
"This client's key in backend/tenants.json — set once during Installation "
"Playbook Stage 9. Read by the Daily Trial Expiry Check and Get Billing Status "
"Server Scripts via frappe.db.get_single_value (frappe.conf/site_config.json is "
"NOT reachable from inside a Server Script sandbox — confirmed the hard way)."
),
)
# --- Stage 7: Tool Kit DocType -----------------------------------------------
def _tool_kit_doctype():
print("-- Tool Kit DocType")
if not frappe.db.exists("DocType", "Tool Kit Item"):
frappe.get_doc({
"doctype": "DocType",
"name": "Tool Kit Item",
"module": "Custom",
"custom": 1,
"istable": 1,
"fields": [
{"fieldname": "item", "label": "Item", "fieldtype": "Link", "options": "Item", "reqd": 1, "in_list_view": 1},
{"fieldname": "qty", "label": "Qty", "fieldtype": "Int", "in_list_view": 1},
],
}).insert(ignore_permissions=True)
print(" created Tool Kit Item")
else:
print(" Tool Kit Item already exists")
if not frappe.db.exists("DocType", "Tool Kit"):
frappe.get_doc({
"doctype": "DocType",
"name": "Tool Kit",
"module": "Custom",
"custom": 1,
"autoname": "field:kit_name",
"fields": [
{"fieldname": "kit_name", "label": "Kit Name", "fieldtype": "Data", "reqd": 1},
{"fieldname": "items", "label": "Items", "fieldtype": "Table", "options": "Tool Kit Item"},
],
"permissions": [{"role": "System Manager", "read": 1, "write": 1, "create": 1, "delete": 1}],
}).insert(ignore_permissions=True)
print(" created Tool Kit")
else:
print(" Tool Kit already exists")
# --- Stage 7 / 9: Client Scripts ---------------------------------------------
def _ensure_client_script(name, dt, view, script):
if frappe.db.exists("Client Script", name):
doc = frappe.get_doc("Client Script", name)
if doc.script != script or not doc.enabled:
doc.script = script
doc.enabled = 1
doc.save(ignore_permissions=True)
print(f" updated {name}")
else:
print(f" {name} already correct")
return
frappe.get_doc({
"doctype": "Client Script", "name": name, "dt": dt, "view": view,
"enabled": 1, "script": script,
}).insert(ignore_permissions=True)
print(f" created {name}")
def _client_scripts():
print("-- Client Scripts")
_ensure_client_script(
"tool-kit-autopopulate", "Stock Entry", "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');
}
});
}
});""",
)
_ensure_client_script(
"maintenance-recalc", "Serial No", "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);
}
}""",
)
_ensure_client_script(
"Serial No QR Regenerate Button", "Serial No", "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();
}
}
});
});
}
}
});""",
)
_ensure_client_script(
"serial-availability-check", "Stock Entry", "Form",
"""function check_serials(frm, cdt, cdn, serials) {
const row = locals[cdt][cdn];
if (!row.s_warehouse || !serials.length) return;
frappe.call({
method: 'frappe.client.get_list',
args: {
doctype: 'Serial No',
filters: { name: ['in', serials] },
fields: ['name', 'warehouse', 'status']
},
callback: function (r) {
const bad = (r.message || []).filter(function (s) {
return s.status !== 'Active' || s.warehouse !== row.s_warehouse;
});
if (bad.length) {
const details = bad.map(function (s) {
return s.name + ' (status: ' + s.status + ', currently in: ' + (s.warehouse || 'no warehouse') + ')';
}).join('<br>');
frappe.msgprint({
title: __('Serial No Not Available'),
message: __('The following serial(s) cannot be issued from {0}:<br>{1}', [row.s_warehouse, details]),
indicator: 'red'
});
}
}
});
}
frappe.ui.form.on('Stock Entry Detail', {
serial_no: function (frm, cdt, cdn) {
const row = locals[cdt][cdn];
if (!row.serial_no) return;
const serials = row.serial_no.split('\\n').map(function (s) { return s.trim(); }).filter(Boolean);
check_serials(frm, cdt, cdn, serials);
},
serial_and_batch_bundle: function (frm, cdt, cdn) {
const row = locals[cdt][cdn];
if (!row.serial_and_batch_bundle) return;
frappe.call({
method: 'frappe.client.get',
args: {
doctype: 'Serial and Batch Bundle',
name: row.serial_and_batch_bundle
},
callback: function (r) {
const entries = (r.message && r.message.entries) || [];
const serials = entries.map(function (x) { return x.serial_no; }).filter(Boolean);
check_serials(frm, cdt, cdn, serials);
}
});
}
});""",
)
_ensure_client_script(
"Item Serial No Dropdown", "Item", "Form",
"""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"));
}
});
}
}
});""",
)
# --- Stage 9: Server Scripts (QR) --------------------------------------------
def _ensure_server_script(name, **kwargs):
if frappe.db.exists("Server Script", name):
doc = frappe.get_doc("Server Script", name)
changed = False
for key, value in kwargs.items():
if doc.get(key) != value:
doc.set(key, value)
changed = True
if changed:
doc.save(ignore_permissions=True)
print(f" updated {name}")
else:
print(f" {name} already correct")
return
frappe.get_doc({"doctype": "Server Script", "name": name, **kwargs}).insert(ignore_permissions=True)
print(f" created {name}")
def _server_scripts():
print("-- Server Scripts (requires server_script_enabled — see Installation Playbook Stage 9, step 1)")
_ensure_server_script(
"Attach QR Code on Stock Entry Submit",
script_type="DocType Event",
reference_doctype="Stock Entry",
doctype_event="After Submit",
disabled=0,
script="""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)
""",
)
_ensure_server_script(
"Regenerate Serial No QR Code",
script_type="API",
api_method="regenerate_serial_no_qr_code",
allow_guest=0,
disabled=0,
script="""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")
""",
)
# --- Stage 7: Approval Workflow ----------------------------------------------
def _workflow():
print("-- Workflow: Material Request Approval")
for state in ("Draft", "Pending Approval", "Approved", "Rejected"):
if not frappe.db.exists("Workflow State", state):
frappe.get_doc({"doctype": "Workflow State", "workflow_state_name": state}).insert(ignore_permissions=True)
print(f" created Workflow State {state}")
for action in ("Submit", "Approve", "Reject"):
if not frappe.db.exists("Workflow Action Master", action):
frappe.get_doc({"doctype": "Workflow Action Master", "workflow_action_name": action}).insert(ignore_permissions=True)
print(f" created Workflow Action Master {action}")
if frappe.db.exists("Workflow", "Material Request Approval"):
print(" Workflow already exists")
return
frappe.get_doc({
"doctype": "Workflow",
"workflow_name": "Material Request Approval",
"document_type": "Material Request",
"workflow_state_field": "workflow_state",
"is_active": 1,
"states": [
{"state": "Draft", "doc_status": "0", "allow_edit": "Stock User"},
{"state": "Pending Approval", "doc_status": "1", "allow_edit": "Stock Manager"},
{"state": "Approved", "doc_status": "1", "allow_edit": "Stock Manager"},
{"state": "Rejected", "doc_status": "1", "allow_edit": "Stock Manager"},
],
"transitions": [
{"state": "Draft", "action": "Submit", "next_state": "Pending Approval", "allowed": "Stock User"},
{"state": "Pending Approval", "action": "Approve", "next_state": "Approved", "allowed": "Stock Manager"},
{"state": "Pending Approval", "action": "Reject", "next_state": "Rejected", "allowed": "Stock Manager"},
],
}).insert(ignore_permissions=True)
print(" created Workflow")
# --- Stage 7 / QR labeling: Notifications, with full professional templates -
def _ensure_notification(name, **kwargs):
if frappe.db.exists("Notification", name):
doc = frappe.get_doc("Notification", name)
changed = False
for key, value in kwargs.items():
if key == "recipients":
continue
if doc.get(key) != value:
doc.set(key, value)
changed = True
if changed:
doc.save(ignore_permissions=True)
print(f" updated {name}")
else:
print(f" {name} already correct")
return
frappe.get_doc({"doctype": "Notification", "name": name, **kwargs}).insert(ignore_permissions=True)
print(f" created {name}")
def _notifications():
print("-- Notifications")
_ensure_notification(
"Serial No Maintenance Due",
document_type="Serial No",
event="Days Before",
channel="Email",
date_changed="next_due_date",
days_in_advance=7,
condition="doc.maintenance_interval_days",
subject="Maintenance due soon: {{ doc.name }}",
enabled=1,
recipients=[{"receiver_by_role": "Stock Manager"}],
message="""<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>
""",
)
_ensure_notification(
"Low Stock Reorder Alert",
document_type="Material Request",
event="New",
channel="Email",
condition='doc.material_request_type == "Purchase"',
subject="Low stock: {{ doc.name }} needs fulfilling",
enabled=1,
recipients=[{"receiver_by_role": "Stock Manager"}],
message="""<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 &amp; 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>
""",
)
# --- Stage 7: Damage & Cost Report -------------------------------------------
def _damage_cost_report():
print("-- Damage & Cost Report")
if frappe.db.exists("Report", "Damage & Cost Report"):
print(" already exists")
return
frappe.get_doc({
"doctype": "Report",
"report_name": "Damage & Cost Report",
"ref_doctype": "Stock Entry",
"report_type": "Query Report",
"is_standard": "No",
"roles": [{"role": "Stock Manager"}, {"role": "System Manager"}],
"query": """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""",
}).insert(ignore_permissions=True)
print(" created")
# --- Stage 8: Stock Manager permission elevation -----------------------------
def _role_permissions():
print("-- Role permissions: Stock Manager on Item / Warehouse")
from frappe.permissions import add_permission, update_permission_property
for dt in ("Item", "Warehouse"):
add_permission(dt, "Stock Manager", 0)
for prop, value in (("read", 1), ("create", 1), ("write", 1), ("delete", 0)):
update_permission_property(dt, "Stock Manager", 0, prop, value)
print(" Item + Warehouse: create/write granted, delete withheld")
# Stock Manager (our Store Manager persona's actual role) is missing read
# on Stock Ledger Entry out of the box — vanilla ERPNext only grants it to
# Stock User and Accounts Manager. Without this, the Store Manager persona
# cannot pull a tool's chain-of-custody via the Serial No Ledger report
# (see _serial_no_ledger_permission below), even once that report itself
# is opened up to them.
if not frappe.db.exists(
"Custom DocPerm", {"parent": "Stock Ledger Entry", "role": "Stock Manager"}
):
add_permission("Stock Ledger Entry", "Stock Manager", 0)
for prop, value in (("read", 1), ("report", 1), ("export", 1), ("print", 1)):
update_permission_property("Stock Ledger Entry", "Stock Manager", 0, prop, value)
print(" Stock Ledger Entry: read/report/export/print granted to Stock Manager")
else:
print(" Stock Ledger Entry permission already correct")
def _serial_no_ledger_permission():
print("-- Serial No Ledger report: open to Stock Manager")
report = frappe.get_doc("Report", "Serial No Ledger")
if "Stock Manager" in [d.role for d in report.roles]:
print(" already correct")
return
# Serial No Ledger ships with ERPNext as a standard report, and Frappe
# refuses to save any change to a standard report's `roles` list outside
# developer mode. Toggle it on just long enough to append the role, then
# restore whatever the site had before — never leave it flipped.
was_on = bool(frappe.conf.get("developer_mode"))
frappe.conf.developer_mode = 1
try:
report.append("roles", {"role": "Stock Manager"})
report.save(ignore_permissions=True)
finally:
frappe.conf.developer_mode = 1 if was_on else 0
print(" added Stock Manager")
# --- Stage 10: audit trail hardening -----------------------------------------
def _audit_hardening():
print("-- Audit trail hardening")
from frappe.custom.doctype.property_setter.property_setter import make_property_setter
from frappe.permissions import add_permission, update_permission_property
if not frappe.get_meta("Material Request").track_changes:
# remove any stale non-doctype property setter first so make_property_setter can insert cleanly
make_property_setter(
doctype="Material Request", fieldname=None, property="track_changes",
value="1", property_type="Check", for_doctype=True,
)
print(" enabled track_changes on Material Request")
else:
print(" track_changes on Material Request already enabled")
add_permission("Deleted Document", "System Manager", 0)
update_permission_property("Deleted Document", "System Manager", 0, "delete", 0)
print(" Deleted Document deletion locked to Administrator only")
# --- Trial-expiry lockout: the Role every locked-out User gets swapped onto -
def _lockout_role():
print("-- Lockout Role: Trial Expired")
if frappe.db.exists("Role", "Trial Expired"):
role = frappe.get_doc("Role", "Trial Expired")
changed = False
for field, value in (("desk_access", 0), ("home_page", "billing")):
if role.get(field) != value:
role.set(field, value)
changed = True
if changed:
role.save(ignore_permissions=True)
print(" updated")
else:
print(" already correct")
return
frappe.get_doc({
"doctype": "Role", "role_name": "Trial Expired",
"desk_access": 0, "home_page": "billing",
}).insert(ignore_permissions=True)
print(" created")
# --- Trial-expiry lockout: the daily check, generic across every client -----
def _trial_check_scheduler():
"""
Creates the one Server Script every client shares verbatim — it reads
*this* site's own tenant slug from System Settings.billing_tenant_slug
(set once in Stage 9 via Desk UI, a plain Custom Field — see
_custom_fields) rather than the slug being baked into the script text,
so the exact same script content is correct for every client and this
step never needs client-specific templating.
Confirmed the hard way: frappe.conf/site_config.json is NOT reachable
from inside a Server Script's RestrictedPython sandbox (neither
render_safe_globals() nor exec_safe_globals() expose `conf` at all) —
frappe.db.get_single_value IS exposed, so System Settings is the right
place for this, not site_config.json.
"""
print("-- Server Script: Daily Trial Expiry Check")
_ensure_server_script(
"Daily Trial Expiry Check",
script_type="Scheduler Event",
event_frequency="Daily",
disabled=0,
script="""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}")
""",
)
# --- Billing status page: the whitelisted proxy + the page that calls it ---
def _billing_status_api():
"""
Creates the one whitelisted API Server Script the billing Web Page's
JS calls. Same System Settings.billing_tenant_slug pattern as the
trial-expiry scheduler — one generic script, no client-specific
templating. allow_guest is deliberately 0: a locked-out User is a
"Website User" (no Desk access), not a Guest, so this still works for
them — Server Script's own guest check only blocks actual Guests.
Output channel is frappe.flags, not frappe.response["message"] —
confirmed in this project's DEVELOPER_GUIDE.md: Server Script's own
execute_api_server_script() returns exactly the frappe.flags set
during the script's run as the API response body, which is what the
billing page's frappe.call() callback reads as r.message.
"""
print("-- Server Script: Get Billing Status")
_ensure_server_script(
"Get Billing Status",
script_type="API",
api_method="get_billing_status",
allow_guest=0,
disabled=0,
script="""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")
""",
)
def _ensure_web_page(route, **kwargs):
"""
Idempotent Web Page upsert, keyed by `route` rather than `name` — Web
Page has no fixed autoname scheme tied to route, so existence and
lookup both go through route instead of assuming a name.
"""
existing_name = frappe.db.get_value("Web Page", {"route": route})
if existing_name:
doc = frappe.get_doc("Web Page", existing_name)
changed = False
for key, value in kwargs.items():
if doc.get(key) != value:
doc.set(key, value)
changed = True
if changed:
doc.save(ignore_permissions=True)
print(f" updated {route}")
else:
print(f" {route} already correct")
return
frappe.get_doc({"doctype": "Web Page", "route": route, **kwargs}).insert(ignore_permissions=True)
print(f" created {route}")
def _billing_status_page():
"""
The page frappe_client.py's LOCKOUT_ROLE.home_page points a locked-out
User straight to, and that a normal Desk user can also visit any time
(billing status isn't gated behind lockout — see CLIENT_DEMO_GUIDE.md's
positioning notes). Public/logged-in Web Page, not a Desk page,
specifically because a locked-out User has no Desk access at all —
this is the one page they can still reach.
"""
print("-- Web Page: /billing")
_ensure_web_page(
"billing",
title="Billing",
published=1,
content_type="HTML",
# Confirmed the hard way: show_title=1 renders Frappe's own unstyled
# <h1>{{title}}</h1> above main_section_html (web_page.py's
# get_context, gated on this exact field) — flush left, clashing
# with this page's own centered #billing-page-wrap layout.
show_title=0,
show_sidebar=0,
main_section_html="""<div id="billing-page-wrap">
<div id="billing-status-app">
<p class="text-muted">Loading billing status&hellip;</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="""frappe.ready(function() {
// Frappe never populates the `home_page` template context for a Web Page document
// (confirmed by reading Frappe's own source: only frappe/www/portal.py sets it, not
// web_page.py) - the site's navbar-brand link falls back to "/" unconditionally on this
// page, with no field anywhere that controls it. Setting it directly in JS is the only
// in-scope fix that doesn't mean modifying frappe_docker/ (never done in this project)
// or standing up a custom app for one link.
var brand = document.querySelector(".navbar-brand");
if (brand) {
brand.setAttribute("href", "/desk/stock");
}
var el = document.getElementById("billing-status-app");
frappe.call({
method: "get_billing_status",
callback: function(r) {
var data = r.message || {};
var html = "";
if (data.subscription_status === "active" || data.subscription_status === "trialing") {
html += '<div class="alert alert-success">Billing is active' +
(data.subscription_status === "trialing" ? " (free trial)" : "") + ".</div>";
} else if (data.subscription_status === "past_due" || data.subscription_status === "unpaid") {
html += '<div class="alert alert-danger">Payment is past due. Use the button below to restore full access.</div>';
} else if (!data.subscription_status) {
html += '<div class="alert alert-warning">No active subscription found.</div>';
}
if (data.current_period_end) {
var days = Math.max(0, Math.ceil((new Date(data.current_period_end) - new Date()) / 86400000));
html += "<p><strong>Next bill:</strong> " + frappe.datetime.str_to_user(data.current_period_end.split("T")[0]) +
" (" + days + " day" + (days === 1 ? "" : "s") + " from now)</p>";
}
if (data.payment_link_url) {
html += '<div class="billing-cta"><a class="btn btn-primary" href="' + data.payment_link_url +
'" target="_blank" rel="noopener">Manage Billing</a></div>';
}
if (data.invoices && data.invoices.length) {
html += "<h4>Recent Invoices</h4>";
html += '<table class="table table-bordered"><thead><tr><th>Date</th><th>Amount</th><th>Status</th><th>Receipt</th></tr></thead><tbody>';
data.invoices.forEach(function(inv) {
html += "<tr><td>" + frappe.datetime.str_to_user(inv.created.split("T")[0]) + "</td><td>" +
(inv.amount_paid / 100).toFixed(2) + " " + inv.currency.toUpperCase() + "</td><td>" +
frappe.utils.escape_html(inv.status) + "</td><td>" +
(inv.hosted_invoice_url ? '<a href="' + inv.hosted_invoice_url + '" target="_blank" rel="noopener">View / Download</a>' : "&mdash;") +
"</td></tr>";
});
html += "</tbody></table>";
} else {
html += '<p class="text-muted">No invoices yet.</p>';
}
el.innerHTML = html;
}
});
});""",
)
def _billing_workspace_shortcut():
"""
Adds a "Billing" shortcut to the Stock Workspace, under its own "Your
Shortcuts" header, so /billing is actually discoverable from Desk by a
normal (non-locked-out) user, not just reachable if they already know
the URL.
Three things, confirmed live and the hard way (the first version of
this function shipped without the header or icon, and the result
visibly did not match this Workspace's Card headings — "Custom
Reports", "Other Reports", etc.):
1. a row in the Workspace's own `shortcuts` child table, type URL,
with an icon set — a bare shortcut with no icon renders visibly
incomplete next to the Stock Workspace's icon-bearing Cards
2. a "header" content block reading "Your Shortcuts", placed
immediately before the shortcut's own block — Cards and Shortcuts
are two different native Frappe widgets with two different
built-in typography treatments, and that's not fixable by
changing this shortcut's data: a Card can only link to a
DocType/Page/Report, never a raw URL, so a Shortcut is the only
Workspace block capable of pointing at /billing at all. Grouping
it under its own header — exactly the pattern this bench's own
"ERPNext Settings" Workspace already uses for its shortcuts — is
what makes it read as an intentional section instead of a stray,
mismatched item dropped into the Cards grid.
3. a matching {"type": "shortcut", "data": {"shortcut_name": <label>}}
content block — the shortcuts-table row alone renders nothing
All three checked independently, including self-healing an
already-live shortcut that predates the icon/header, so re-running
this after either version has already run always converges on the
same correct end state rather than silently staying half-done.
"""
print("-- Workspace shortcut: Billing (Stock)")
import json as _json
doc = frappe.get_doc("Workspace", "Stock")
changed = False
# Step 1: the shortcuts-table row, self-healing a missing icon on an already-live row
shortcut_row = next((s for s in doc.shortcuts if s.label == "Billing"), None)
if shortcut_row is None:
doc.append("shortcuts", {"type": "URL", "url": "/billing", "label": "Billing", "icon": "payments"})
changed = True
elif shortcut_row.icon != "payments":
shortcut_row.icon = "payments"
changed = True
# Step 2/3: the header + shortcut content blocks, header always placed immediately
# before the shortcut block so it actually reads as this section's label
content = _json.loads(doc.content or "[]")
shortcut_idx = next(
(i for i, block in enumerate(content)
if block.get("type") == "shortcut" and block.get("data", {}).get("shortcut_name") == "Billing"),
None,
)
has_header = any(
block.get("type") == "header" and "Your Shortcuts" in block.get("data", {}).get("text", "")
for block in content
)
header_block = {
"id": frappe.generate_hash(length=10),
"type": "header",
"data": {"text": '<span class="h4"><b>Your Shortcuts</b></span>', "col": 12},
}
if shortcut_idx is None:
if not has_header:
content.append(header_block)
content.append(
{"id": frappe.generate_hash(length=10), "type": "shortcut", "data": {"shortcut_name": "Billing", "col": 3}}
)
changed = True
elif not has_header:
content.insert(shortcut_idx, header_block)
changed = True
if changed:
doc.content = _json.dumps(content)
doc.save(ignore_permissions=True)
print(" updated")
else:
print(" already correct")
# --- Stage 9: Product branding (logo, footer) --------------------------------
def _branding():
"""
Replaces every ERPNext/Frappe default logo that Website Settings actually
controls with this product's own green box mark — app_logo (login page,
Desk sidebar/navbar), favicon (every browser tab, confirmed via
www/desk.html's <link rel="icon">), and splash_image (Desk's own loading
screen, confirmed via templates/includes/splash_screen.html) — and clears
the default "Powered by ERPNext" website footer. Confirmed the hard way:
Website Settings.footer_powered can't just be cleared to "" —
footer_info.html's `{%- if footer_powered -%}` treats an empty string as
falsy and falls back to the hardcoded ERPNext credit again, so it's set
to a single space instead (truthy, renders blank).
NOT covered, and not fixable without a custom app: the "Apps" switcher
tile for ERPNext in Desk. Confirmed by reading boot.py's
load_desktop_data() — that specific icon comes from erpnext/hooks.py's
own hardcoded app_logo_url, per installed app, with no Website Settings
override point at all. Living with ERPNext's own tile there is the
accepted tradeoff of not maintaining a custom app for Phase 0.
bettersight_logo.png ships alongside this script (see provision_client.sh,
which copies it into the container next to provision_client.py) — it's the
same mark embedded in bettersightbox-index.html's header, extracted once so
it isn't duplicated as a giant base64 blob inside this file.
"""
print("-- Branding: logo + footer")
logo_path = "/tmp/bettersight_logo.png"
file_url = frappe.db.get_value(
"File", {"file_name": "bettersight-logo.png", "attached_to_doctype": "Website Settings"}, "file_url"
)
if not file_url:
with open(logo_path, "rb") as f:
content = f.read()
file_doc = frappe.get_doc(
{
"doctype": "File",
"file_name": "bettersight-logo.png",
"attached_to_doctype": "Website Settings",
"attached_to_name": "Website Settings",
"is_private": 0,
"content": content,
}
)
file_doc.save(ignore_permissions=True)
file_url = file_doc.file_url
print(" uploaded bettersight-logo.png")
else:
print(" bettersight-logo.png already uploaded")
ws = frappe.get_doc("Website Settings")
changed = False
for field in ("app_logo", "favicon", "splash_image"):
if ws.get(field) != file_url:
ws.set(field, file_url)
changed = True
if not ws.footer_powered:
ws.footer_powered = " "
changed = True
if changed:
ws.save(ignore_permissions=True)
print(" updated Website Settings (app_logo / favicon / splash_image / footer_powered)")
else:
print(" Website Settings already correct")
run()