ES ERP Server Scripts - Workflow Automation
17 custom Server Scripts powering end-to-end automation across AI integration, fleet operations, order-to-cash processing, workforce scheduling, and real-time GPS tracking — all running natively inside ES ERP Framework.
Overview
ES ERP extends ES ERP Framework/ES ERP with 17 custom Server Scripts that automate business processes without requiring custom app deployments. These scripts span three execution types — API endpoints for real-time data access, Scheduler Events for timed automation (hourly and cron-based), and DocType Events that trigger on document lifecycle actions.
Together they deliver a fully automated pipeline from AI-powered chat, through fleet GPS tracking and trip sheet generation, to order-to-cash invoicing, purchase ordering, payment processing, and workforce capacity planning — all configurable through the ES ERP admin interface with zero code deployments.
📋 Script Types
🌐 API Scripts 8 scripts
Expose custom REST endpoints at /api/method/<name>. Called on-demand by dashboards, external systems, and frontend interfaces. Return JSON responses.
⏰ Scheduler Events 7 scripts
Run automatically on cron schedules or at hourly intervals. Handle background automation — trip sheet creation, invoice generation, payment processing, and calendar sync.
📄 DocType Events 1 script
Triggered by document lifecycle actions (Before Save, After Insert, etc.). The Fleet Report Generator fires on Before Save to compile vehicle, trip, fuel, and maintenance data into executive summaries.
📊 Complete Script Reference
🤖 Claude AI Integration
Three API scripts power the embedded Claude AI chat interface, providing message handling, conversation management, and configuration status — all communicating with the Anthropic API via secure server-side calls.
Claude AI Chat API
claude_ai_chatCore chat endpoint. Receives user messages, loads conversation history, builds the full message array with system prompt, calls the Anthropic /v1/messages API, and stores both user and assistant messages with token usage tracking. Supports multiple personas, conversation length limits, and automatic title generation. Creates new conversations on first message or continues existing ones.
Claude AI Conversations API
claude_ai_conversationsConversation CRUD operations. Supports four actions: list (user's active conversations sorted by modified date), load (full conversation with all messages and token stats), delete (soft-delete by setting status to Deleted), and rename (update conversation title). Enforces per-user access control with System Manager override.
Claude AI Status API
claude_ai_statusConfiguration and readiness check. Returns integration status (enabled, API key valid), default model, max tokens, chat UI settings (height, theme colour), rate limits, and all available personas (default, ERP analyst, developer, general) with {today} template variable replacement.
🚛 Fleet Operations & GPS Tracking
Seven scripts manage real-time GPS tracking via ES Tracking, automated trip sheet creation, daily fleet summaries, report generation, and Teltonika FOTA firmware management — with beacon sensor sync for temperature, humidity, and motion monitoring.
ES Tracking Auto Trip Sheet Creator
The largest script in the system. Runs every 5 minutes to poll ES Tracking GPS positions, automatically create Trip Sheets when vehicle motion or ignition-on is detected, and complete them when stationary. Creates Delivery Jobs for stops ≥ 5 minutes. Calculates fuel consumption at 10L/100km, tracks odometer readings, and syncs BLE beacon sensor data (temperature, humidity, battery, motion, magnet, pitch, roll) from Teltonika devices. Handles geofence enter/exit events.
Daily Trip Sheet Generator
Runs daily at 6 PM Perth time. Queries the ES Tracking /api/reports/trips endpoint for each GPS-enabled vehicle, creates one consolidated Trip Sheet per vehicle for the day, records start/end odometer, GPS coordinates, distance travelled, fuel consumed, and generates a ES Tracking Replay link for the actual route taken. Skips vehicles with existing daily sheets to prevent duplicates.
Fleet Report Generator
Triggers when a Fleet Report document's status is set to 'Generating'. Aggregates vehicles, drivers, trip sheets, fuel logs, and maintenance records for the selected date range. Calculates summary statistics (total distance, fuel consumed, costs, average consumption, cost per km) and generates an HTML executive summary table with key findings. Supports filtering by vehicle and driver.
ES Tracking Fetch All Data
ES Tracking_fetch_allReturns all devices and current positions from the ES Tracking GPS server in a single API call. Reads ES Tracking Settings for server URL and credentials, constructs Basic Auth headers using manual Base64 encoding (required for ES ERP Framework sandbox), and returns the combined device/position payload for dashboard consumption.
ES Tracking Get Position API
ES Tracking_get_positionFetches the current position for a specific device by IMEI or ES Tracking device ID. Returns device metadata (name, status, last update) and full position data including coordinates, speed (converted to km/h), course, altitude, address, and all ES Tracking attributes. Uses urllib with SSL context for direct HTTP communication.
Teltonika FOTA Scripts Disabled
teltonika_fota_sync / teltonika_fota_testTwo scripts for Teltonika FOTA (Firmware Over The Air) device management. The sync script fetches all devices from the Teltonika FOTA API, maps activity status, task queue, firmware versions, and creates/updates Teltonika Monitoring DocType records. The test script validates API connectivity. Currently disabled pending FOTA platform integration.
💰 Order-to-Cash Automation
Four hourly scheduler scripts automate the complete order-to-cash and procure-to-pay cycle — from Sales Order through to Sales Invoice, Payment Request, Purchase Order, and Supplier Payment — with duplicate prevention and email notifications at every step.
Hourly Sales Order to Invoice
Finds submitted Sales Orders with status 'To Deliver and Bill' or 'To Bill' and per_billed < 100%. Creates a Sales Invoice for each, copying all line items (item code, qty, rate, warehouse, SO reference), taxes, and pricing details. Submits the invoice automatically, then emails the customer with the PDF invoice attached. Logs creation and email summary.
Hourly Purchase Order Creation
Analyses submitted Sales Orders needing delivery, checks warehouse stock (actual qty minus reserved plus ordered), identifies shortages, and resolves default suppliers from Item Supplier table or Item Default records. Groups shortage items by supplier and creates consolidated Purchase Orders. Submits POs and emails suppliers with PDF attachments listing items, quantities, and delivery requirements.
Hourly Payment Request Creation
Scans for submitted Sales Invoices with outstanding balances. Checks for existing Payment Requests to prevent duplicates — each invoice receives exactly one Payment Request. Creates inbound Payment Requests linked to the default Payment Gateway Account, populates customer email, invoice details (posting date, due date, amounts), and submits with payment link for customer self-service.
Hourly Supplier Payment Creation
Processes outstanding Purchase Invoices by creating draft Payment Entries (not auto-submitted — requires accounts team approval). Checks Payment Entry References child table to prevent duplicates. Resolves default bank account and payable account from Company settings. Sends a single consolidated email to listing all created payments with supplier, invoice, amount, and due date details.
💡 Automated Pipeline Flow
Sell Side: Sales Order → Sales Invoice (auto-submitted + customer email) → Payment Request (customer payment link)
Buy Side: Sales Order shortage analysis → Purchase Order (auto-submitted + supplier email) → Supplier Payment Entry (draft for approval + accounts team email)
Safeguards: Every script checks for existing documents before creation, preventing duplicates across multiple hourly runs.
📊 Workforce & Scheduling
Two scripts power team capacity planning and automated task-to-calendar scheduling — the data API serves the Employee Utilisation Dashboard while the sync script converts project tasks into timed calendar events.
ES Utilisation Data
es_utilisation_dataSingle-call data API for the Employee Utilisation Dashboard. Fetches all non-cancelled Events (up to 500), resolves Event Participants via child table, and loads the 2026 Holiday List — all returned as one JSON payload: { events, participants, holidays }. Runs server-side with elevated permissions to bypass client-side restrictions on the Event Participants child table.
Task to Calendar Sync
The second-largest script. Reads configuration from the ES Task Assignment Single DocType: shift type, holiday list, priority sort order, team-to-calendar mappings, and 17 configurable settings. Scans tasks matching configured statuses (Open, Overdue), resolves all assignees via ToDo table, groups and sorts by priority (Urgent → High → Medium → Low, Overdue first), calculates shift-aware time slots with overflow prevention, and creates colour-coded ES ERP Framework Events with rich HTML descriptions. Supports multi-assignee sync (same time slot across calendars) and Google Calendar integration.
🏗️ Technical Architecture
Sandbox-Safe Coding
All scripts use callback-based ES ERP Framework.call(), regular functions (no arrow functions), Object.assign() for cloning, and manual Base64 encoding — ensuring compatibility with ES ERP Framework's restricted Server Script execution context.
Duplicate Prevention
Every scheduled script checks for existing records before creation — Payment Entries check the References child table, Payment Requests check reference_name, Trip Sheets check vehicle+date, and Task Sync tracks task+calendar pair combinations.
Email Notifications
Order-to-cash scripts send contextual emails at each step: PDF invoice attachments to customers, PO details to suppliers, and consolidated payment summaries to the accounts team — with one-email-per-document guarantees.
Error Handling & Logging
All scripts wrap operations in try/except blocks, log errors via ES ERP Framework.log_error(), and produce run summaries (records processed, created, skipped, errors). API scripts return structured JSON error responses.
External API Integration
Scripts integrate with Anthropic Claude API (chat), ES Tracking GPS API (positions, trips, reports), and Teltonika FOTA API (device management) — using ES ERP Framework.make_get_request(), ES ERP Framework.make_post_request(), and urllib.
Configuration-Driven
Complex scripts read all settings from dedicated Single DocTypes (ES Task Assignment, Claude AI Integration, ES Tracking Settings) — allowing administrators to modify behaviour (shift times, priorities, team mappings, API keys) without touching code.
Technical Specifications
Platform
- ✓ ES ERP Framework
- ✓ ES ERP v15
- ✓ Python Server Scripts
- ✓ Sandbox Execution
Script Types
- ✓ 8 API Endpoints
- ✓ 4 Hourly Schedulers
- ✓ 3 Cron Schedulers
- ✓ 1 DocType Event
External APIs
- ✓ Anthropic Claude API
- ✓ ES Tracking GPS API
- ✓ Teltonika FOTA API
- ✓ Google Calendar Sync
Automation
- ✓ SO → SI → PR Pipeline
- ✓ SO → PO → PE Pipeline
- ✓ GPS → Trip Sheet → Delivery
- ✓ Task → Calendar Events
Automate Your Entire Business Process
From AI-powered chat to GPS fleet tracking and fully automated order-to-cash processing — ES ERP Server Scripts eliminate manual work and run 24/7 inside your ES ERP instance.
Automation for ES ERP
© 2026 Enterprise Systems Australia |
