erpnext-impl-hooks
27
总安装量
9
周安装量
#13635
全站排名
安装命令
npx skills add https://github.com/openaec-foundation/erpnext_anthropic_claude_development_skill_package --skill erpnext-impl-hooks
Agent 安装分布
claude-code
7
opencode
5
github-copilot
5
codex
5
amp
5
Skill 文档
ERPNext Hooks – Implementation
This skill helps you determine HOW to implement hooks.py configurations. For exact syntax, see erpnext-syntax-hooks.
Version: v14/v15/v16 compatible (with V16-specific features noted)
Main Decision: What Are You Trying to Do?
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â WHAT DO YOU WANT TO ACHIEVE? â
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¤
â â
â ⺠React to document events on OTHER apps' DocTypes? â
â âââ doc_events in hooks.py â
â â
â ⺠Run code periodically (hourly, daily, custom schedule)? â
â âââ scheduler_events â
â â
â ⺠Modify behavior of existing DocType controller? â
â âââ V16+: extend_doctype_class (RECOMMENDED - multiple apps work) â
â âââ V14/V15: override_doctype_class (last app wins) â
â â
â ⺠Modify existing API endpoint behavior? â
â âââ override_whitelisted_methods â
â â
â ⺠Add custom permission logic? â
â âââ List filtering: permission_query_conditions â
â âââ Document-level: has_permission â
â â
â ⺠Send data to client on page load? â
â âââ extend_bootinfo â
â â
â ⺠Export/import configuration between sites? â
â âââ fixtures â
â â
â ⺠Add JS/CSS to desk or portal? â
â âââ Desk: app_include_js/css â
â âââ Portal: web_include_js/css â
â âââ Specific form: doctype_js â
â â
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
Decision Tree: doc_events vs Controller Methods
WHERE IS THE DOCTYPE?
â
ââ⺠DocType is in YOUR custom app?
â ââ⺠Use controller methods (doctype/xxx/xxx.py)
â - Direct control over lifecycle
â - Cleaner code organization
â
ââ⺠DocType is in ANOTHER app (ERPNext, Frappe)?
â ââ⺠Use doc_events in hooks.py
â - Only way to hook external DocTypes
â - Can register multiple handlers
â
ââ⺠Need to hook ALL DocTypes (logging, audit)?
ââ⺠Use doc_events with wildcard "*"
Rule: Controller methods for YOUR DocTypes, doc_events for OTHER apps’ DocTypes.
Decision Tree: Which doc_event?
WHAT DO YOU NEED TO DO?
â
ââ⺠Validate data or calculate fields?
â ââ⺠Before any save â validate
â ââ⺠Only on new documents â before_insert
â
ââ⺠React after document is saved?
â ââ⺠Only first save â after_insert
â ââ⺠Every save â on_update
â ââ⺠ANY change (including db_set) â on_change
â
ââ⺠Handle submittable documents?
â ââ⺠Before submit â before_submit
â ââ⺠After submit â on_submit (ledger entries here)
â ââ⺠Before cancel â before_cancel
â ââ⺠After cancel â on_cancel (reverse entries here)
â
ââ⺠Handle document deletion?
â ââ⺠Before delete (can prevent) â on_trash
â ââ⺠After delete (cleanup) â after_delete
â
ââ⺠Handle document rename?
ââ⺠Before rename â before_rename
ââ⺠After rename â after_rename
Decision Tree: Scheduler Event Type
HOW LONG DOES YOUR TASK RUN?
â
ââ⺠< 5 minutes
â â
â â HOW OFTEN?
â ââ⺠Every ~60 seconds â all
â ââ⺠Every hour â hourly
â ââ⺠Every day â daily
â ââ⺠Every week â weekly
â ââ⺠Every month â monthly
â ââ⺠Specific time â cron
â
ââ⺠> 5 minutes (up to 25 minutes)
â
â HOW OFTEN?
ââ⺠Every hour â hourly_long
ââ⺠Every day â daily_long
ââ⺠Every week â weekly_long
ââ⺠Every month â monthly_long
â ï¸ Tasks > 25 minutes: Split into chunks or use background jobs
Decision Tree: Override vs Extend (V16)
FRAPPE VERSION?
â
ââ⺠V16+
â â
â â WHAT DO YOU NEED?
â ââ⺠Add methods/properties to DocType?
â â ââ⺠extend_doctype_class (RECOMMENDED)
â â - Multiple apps can extend same DocType
â â - Safer, less breakage on updates
â â
â ââ⺠Completely replace controller logic?
â ââ⺠override_doctype_class (use sparingly)
â
ââ⺠V14/V15
ââ⺠override_doctype_class (only option)
â ï¸ Last installed app wins!
â ï¸ Always call super() in methods!
Implementation Workflow: doc_events
Step 1: Add to hooks.py
# myapp/hooks.py
doc_events = {
"Sales Invoice": {
"validate": "myapp.events.sales_invoice.validate",
"on_submit": "myapp.events.sales_invoice.on_submit"
}
}
Step 2: Create handler module
# myapp/events/sales_invoice.py
import frappe
def validate(doc, method=None):
"""
Args:
doc: The document object
method: Event name ("validate")
Changes to doc ARE saved (before save event)
"""
if doc.grand_total < 0:
frappe.throw("Total cannot be negative")
# Calculate custom field
doc.custom_margin = doc.grand_total - doc.total_cost
def on_submit(doc, method=None):
"""
After submit - document already saved
Use frappe.db.set_value for additional changes
"""
create_external_record(doc)
Step 3: Deploy
bench --site sitename migrate
Implementation Workflow: scheduler_events
Step 1: Add to hooks.py
# myapp/hooks.py
scheduler_events = {
"daily": ["myapp.tasks.daily_cleanup"],
"daily_long": ["myapp.tasks.heavy_processing"],
"cron": {
"0 9 * * 1-5": ["myapp.tasks.weekday_report"]
}
}
Step 2: Create task module
# myapp/tasks.py
import frappe
def daily_cleanup():
"""NO arguments - scheduler calls with no args"""
old_logs = frappe.get_all(
"Error Log",
filters={"creation": ["<", frappe.utils.add_days(None, -30)]},
pluck="name"
)
for name in old_logs:
frappe.delete_doc("Error Log", name)
def heavy_processing():
"""Long task - use _long variant in hooks"""
for batch in get_batches():
process_batch(batch)
frappe.db.commit() # Commit per batch for long tasks
Step 3: Deploy and verify
bench --site sitename migrate
bench --site sitename scheduler enable
bench --site sitename scheduler status
Implementation Workflow: extend_doctype_class (V16+)
Step 1: Add to hooks.py
# myapp/hooks.py
extend_doctype_class = {
"Sales Invoice": ["myapp.extensions.SalesInvoiceMixin"]
}
Step 2: Create mixin class
# myapp/extensions.py
import frappe
from frappe.model.document import Document
class SalesInvoiceMixin(Document):
"""Mixin that extends Sales Invoice"""
@property
def profit_margin(self):
"""Add computed property"""
if self.grand_total:
return ((self.grand_total - self.total_cost) / self.grand_total) * 100
return 0
def validate(self):
"""Extend validation - ALWAYS call super()"""
super().validate()
self.validate_margin()
def validate_margin(self):
"""Custom validation logic"""
if self.profit_margin < 10:
frappe.msgprint("Warning: Low margin invoice")
Step 3: Deploy
bench --site sitename migrate
Implementation Workflow: Permission Hooks
Step 1: Add to hooks.py
# myapp/hooks.py
permission_query_conditions = {
"Sales Invoice": "myapp.permissions.si_query"
}
has_permission = {
"Sales Invoice": "myapp.permissions.si_permission"
}
Step 2: Create permission handlers
# myapp/permissions.py
import frappe
def si_query(user):
"""
Returns SQL WHERE clause for list filtering.
ONLY works with get_list, NOT get_all!
"""
if not user:
user = frappe.session.user
if "Sales Manager" in frappe.get_roles(user):
return "" # No filter - see all
# Regular users see only their own
return f"`tabSales Invoice`.owner = {frappe.db.escape(user)}"
def si_permission(doc, user=None, permission_type=None):
"""
Document-level permission check.
Return: True (allow), False (deny), None (use default)
NOTE: Can only DENY, not grant additional permissions!
"""
if permission_type == "write" and doc.status == "Closed":
return False # Deny write on closed invoices
return None # Use default permission system
Quick Reference: Handler Signatures
| Hook | Signature |
|---|---|
| doc_events | def handler(doc, method=None): |
| rename events | def handler(doc, method, old, new, merge): |
| scheduler_events | def handler(): (no args) |
| extend_bootinfo | def handler(bootinfo): |
| permission_query | def handler(user): â returns SQL string |
| has_permission | def handler(doc, user=None, permission_type=None): â True/False/None |
| override methods | Must match original signature exactly |
Critical Rules
1. Never commit in doc_events
# â WRONG - breaks transaction
def on_update(doc, method=None):
frappe.db.commit()
# â
CORRECT - Frappe commits automatically
def on_update(doc, method=None):
update_related(doc)
2. Use db_set_value after on_update
# â WRONG - change is lost
def on_update(doc, method=None):
doc.status = "Processed"
# â
CORRECT
def on_update(doc, method=None):
frappe.db.set_value(doc.doctype, doc.name, "status", "Processed")
3. Always call super() in overrides
# â WRONG - breaks core functionality
class CustomInvoice(SalesInvoice):
def validate(self):
self.my_validation()
# â
CORRECT
class CustomInvoice(SalesInvoice):
def validate(self):
super().validate() # FIRST!
self.my_validation()
4. Always migrate after hooks changes
# Required after ANY hooks.py change
bench --site sitename migrate
5. permission_query only works with get_list
# â NOT filtered by permission_query_conditions
frappe.db.get_all("Sales Invoice", filters={})
# â
Filtered by permission_query_conditions
frappe.db.get_list("Sales Invoice", filters={})
Version Differences
| Feature | V14 | V15 | V16 |
|---|---|---|---|
| doc_events | â | â | â |
| scheduler_events | â | â | â |
| override_doctype_class | â | â | â |
| extend_doctype_class | â | â | â |
| permission hooks | â | â | â |
| Scheduler tick | 4 min | 4 min | 60 sec |
Reference Files
| File | Contents |
|---|---|
| decision-tree.md | Complete hook selection flowcharts |
| workflows.md | Step-by-step implementation patterns |
| examples.md | Working code examples |
| anti-patterns.md | Common mistakes and solutions |