Technical Documentation v1.0.0 WHMCS 9.1.x · PHP 8.2–8.4

Haikhavan Report Generator & Executive BI

Complete architecture reference, installation guide, database schema, hooks, and troubleshooting.

Quick Installation

  1. Purchase the module and download haikhavan_report_generator-ioncube-8.2-1.0.0-install.zip from your VPSrv Client Area Downloads.
  2. Upload and extract the ZIP into your WHMCS root directory so files land in modules/addons/haikhavan_report_generator/.
  3. Verify PHP 8.2–8.4 with ionCube PHP Loader 14+ / 15.5+ is enabled on your server.
  4. Go to System Settings → Addon Modules in WHMCS Admin, click Activate next to Haikhavan Report Generator & Executive BI, and assign administrator role access.

Version: 1.0.0
WHMCS Compatibility: WHMCS 8.x & WHMCS 9.1.x (PHP 8.1 – 8.3, MySQL 8.x)
Module Type: WHMCS Addon Module (Admin Executive BI Suite + Client Spend Statements + 3 Native Hooks)


Haikhavan Report Generator & Executive BI (haikhavan_report_generator) — Technical Documentation

1. Architecture & File Inventory

haikhavan_report_generator uses a clean PSR-4 namespace (Haikhavan\ReportGenerator\) loaded via spl_autoload_register in haikhavan_report_generator.php and hooks.php. All database access goes through WHMCS\Database\Capsule with parameterized queries, and all visual charts render natively on HiDPI HTML5 <canvas> with zero external JS/CSS CDNs.

modules/addons/haikhavan_report_generator/
├── whmcs.json                      # WHMCS schema 1.0 addon manifest
├── haikhavan_report_generator.php         # Addon lifecycle (_config, _activate, _deactivate, _upgrade, _output, _clientarea)
├── hooks.php                       # AdminHomeWidgets, ClientAreaPrimaryNavbar, DailyCronJob
├── lib/
│   ├── Database.php                # 5-table schema installer, settings loader, AES-256-CBC+HMAC crypto, audit logger
│   ├── ExecutiveReports.php        # 14 built-in Executive BI reports + MoM/YoY KPI aggregation engine
│   ├── ReportBuilder.php           # Whitelisted visual SQL-free query builder across 8 WHMCS entities
│   ├── SqlGuard.php                # Strictly SELECT-only SQL validator, sensitive-table blocker & hard LIMIT cap
│   ├── ExportService.php           # Formula-safe CSV serializer & print-ready PDF/HTML report sheet generator
│   ├── ScheduleService.php         # Daily/Weekly/Monthly delivery engine + HMAC-SHA256 JSON webhook dispatcher
│   ├── AdminController.php         # Admin BI SPA controller, export routes & CSRF-protected JSON AJAX API
│   └── ClientController.php        # Logged-in Client Area Spend & Executive Statements + CSRF CSV export
├── templates/
│   ├── admin/app.php               # 5-tab Admin BI Studio template
│   └── client/statement.tpl        # Smarty Client Area Spend & Statements portal
└── assets/
    ├── css/haikhavan_report_generator.css # Scoped .bi-wrap enterprise stylesheet
    └── js/haikhavan_report_generator.js   # Zero-CDN Line/Bar/Donut Canvas engine + interactive Builder/SQL/Schedule client

2. Database Schema (5 Custom Tables)

Table Purpose Columns & Indexes
mod_hk_rg_reports Saved visual & SQL custom reports id PK, slug VARCHAR(100) UNIQUE, name VARCHAR(160), category VARCHAR(48) IDX, description VARCHAR(255), mode (builder/sql), entity VARCHAR(48), config_json LONGTEXT, custom_sql LONGTEXT, is_favorite TINYINT, created_by INT UNSIGNED, created_at, updated_at
mod_hk_rg_schedules Automated report delivery schedules id PK, report_key VARCHAR(120) IDX, report_name VARCHAR(160), frequency (daily/weekly/monthly) IDX, date_preset VARCHAR(24), format (csv/html/json), recipients TEXT, webhook_url VARCHAR(255), webhook_secret_enc TEXT (AES-256-CBC+HMAC), is_active TINYINT IDX, last_run_at, next_run_at IDX, created_by, created_at, updated_at
mod_hk_rg_executions Delivery & execution audit log id PK, schedule_id INT IDX, report_key VARCHAR(120) IDX, report_name VARCHAR(160), trigger_type (manual/cron/webhook), format VARCHAR(16), row_count INT, duration_ms INT, delivery_status (success/simulated/failed) IDX, delivery_summary TEXT, executed_by INT, created_at
mod_hk_rg_audit_log SQL Explorer & security audit trail id PK, admin_id INT IDX, action VARCHAR(64) IDX, summary VARCHAR(255), query_hash VARCHAR(64), ip_address VARCHAR(64), status (ok/blocked), created_at
mod_hk_rg_kpi_snapshots Monthly historical KPI snapshots id PK, ym VARCHAR(7) UNIQUE, mrr DECIMAL(16,2), arr DECIMAL(16,2), revenue DECIMAL(16,2), unpaid_ar DECIMAL(16,2), new_clients INT, churned_services INT, tickets_opened INT, created_at

3. Security Model

3.1 Safe Read-Only SQL Explorer (SqlGuard)

Every query submitted to op=run_sql or saved in sql mode passes through SqlGuard::validateAndNormalize():

  1. Comment Rejection: Blocks --, #, /*, */ to prevent obfuscated payloads.
  2. Single-Statement Enforcement: Strips a single optional trailing ; and rejects any embedded ;.
  3. SELECT-Only Prefix Check: Query must begin with SELECT .
  4. Forbidden Keyword Denylist: Outside quoted string literals, rejects INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, REPLACE, RENAME, GRANT, REVOKE, CALL, EXEC, EXECUTE, PREPARE, LOCK, SET, SHOW, LOAD, OUTFILE, DUMPFILE, BENCHMARK, SLEEP, INTO, etc.
  5. Sensitive Table & Column Guard: Blocks tbladmins, tblconfiguration, tblpaymentgateways, tblservers, tblregistrars, tblusers, mod_hk_cf_accounts, password, passwordhash, credential_encrypted, webhook_secret_enc, information_schema, mysql., performance_schema, sys..
  6. Hard Row Cap: Automatically appends or clamps LIMIT to min(sql_max_rows, 500).
  7. Audit Logging: Both allowed executions (sql_execute) and blocked attempts (sql_blocked) are recorded with SHA-256 query hash, admin ID, and IP address in mod_hk_rg_audit_log.

3.2 Encryption at Rest (Database::encryptSecret / decryptSecret)

Webhook signing secrets (webhook_secret_enc) are encrypted using AES-256-CBC + HMAC-SHA256 (Encrypt-then-MAC) with distinct domain-separated keys derived via HMAC-SHA256 from WHMCS's $cc_encryption_hash, verified in constant time with hash_equals().

3.3 CSRF, XSS, Ownership & CSV Formula Injection

  • CSRF Protection: All mutating Admin AJAX POSTs (run_builder, save_report, delete_report, import_report_json, run_sql, save_schedule, run_schedule, delete_schedule, toggle_demo_mode) validate $_SESSION['hk_rg_admin_csrf'] via hash_equals() (HTTP 403 on mismatch). Client CSV statement download validates $_SESSION['hk_rg_client_csrf'].
  • Client Ownership: ClientController requires an authenticated $_SESSION['uid'] and scopes every tblinvoices, tblhosting, and tbldomains query strictly to where('userid', $userId).
  • CSV Formula Neutralization: ExportService::sanitizeCsvCell() prefixes any cell starting with =, +, -, @, \t, or \r with a single quote (') to prevent spreadsheet formula execution.
  • SSRF Guard: Outbound JSON webhooks block cloud metadata endpoints (169.254.169.254, metadata.google.internal) and sign payloads with X-Haikhavan-Signature: sha256=<hmac>.

4. Visual Report Builder Whitelist (ReportBuilder::ENTITIES)

Supported entities with pre-configured safe LEFT JOIN relations and whitelisted columns:

  1. clients (tblclients)
  2. invoices (tblinvoices LEFT JOIN tblclients)
  3. transactions (tblaccounts LEFT JOIN tblclients)
  4. orders (tblorders LEFT JOIN tblclients)
  5. services (tblhosting LEFT JOIN tblproducts, tblclients)
  6. domains (tbldomains LEFT JOIN tblclients)
  7. tickets (tbltickets)
  8. affiliates (tblaffiliates LEFT JOIN tblclients)

Date Presets: today, 7d, 30d, mtd, qtd, ytd, all, custom (start_date..end_date).


5. WHMCS Hooks Inventory (hooks.php)

Hook Priority Behavior
AdminHomeWidgets 1 Renders the Haikhavan Report Generator & Executive BI dashboard widget (MRR, ARR, MTD Collected, Net Retention, Unpaid AR, Active Services + quick links).
ClientAreaPrimaryNavbar 1 Inserts Spend & Statements under the Client Area Billing menu when logged in and enabled.
DailyCronJob 1 Invokes ScheduleService::processDueSchedules() to run due Daily, Weekly, and Monthly report deliveries automatically.

6. Admin & Client AJAX / Export API Reference

Endpoint / Op Method CSRF Description
addonmodules.php?module=haikhavan_report_generator&ajax=1&op=run_executive GET No Execute any of the 14 built-in or saved reports (report_key, date_preset).
...&ajax=1&op=export_report_def&id=<id> GET No Export a saved report's JSON definition for backup/migration.
...&ajax=1 (op=run_builder) POST Yes Execute Visual Report Builder config_json and return SQL preview + rows + chart series.
...&ajax=1 (op=save_report) POST Yes Save a Visual Builder or validated SQL report into mod_hk_rg_reports.
...&ajax=1 (op=import_report_json) POST Yes Import a JSON report definition (validates SQL if mode=sql).
...&ajax=1 (op=run_sql) POST Yes Execute a SqlGuard-validated SELECT query against WHMCS MySQL.
...&ajax=1 (op=save_schedule / run_schedule / delete_schedule) POST Yes Manage and immediately trigger Daily/Weekly/Monthly deliveries & webhook pushes.
...&ajax=1 (op=toggle_demo_mode) POST Yes Toggle Executive Demo Telemetry mode (enable=1 or '').
...&export=csv|html|json&report_key=<key>&preset=<preset> GET Admin Session Download Formula-Safe CSV, Printable Executive PDF/HTML sheet, or structured JSON.
index.php?m=haikhavan_report_generator&export=csv&csrf_token=<tok> GET Yes Logged-in client downloads their personal Formula-Safe CSV invoice statement.

7. Troubleshooting

  • Visual Builder returns 0 rows on a fresh WHMCS install: Switch entity to Services (tblhosting) or Domains (tbldomains) with Date Preset All Time, or enable Executive Demo Telemetry Mode to explore populated 12-month Executive BI charts.
  • SQL Explorer rejects a query with HTTP 400: Review the exact SqlGuard message (e.g., remove trailing SQL comments, replace restricted table references, or verify the statement begins with SELECT).
  • WHMCS Admin POST encoding: AdminController automatically runs html_entity_decode(..., ENT_QUOTES | ENT_HTML5, 'UTF-8') on config_json, definition_json, and sql inputs so WHMCS's global request sanitizer never breaks JSON quotes or SQL string literals.