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

Haikhavan Advanced Billing & Usage Metering

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

Quick Installation

  1. Purchase the module and download haikhavan_advanced_billing-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_advanced_billing/.
  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 Advanced Billing & Usage Metering, and assign administrator role access.

Module Slug: haikhavan_advanced_billing
Version: 1.0.0
Namespace: Haikhavan\AdvancedBilling\
Target Runtime: WHMCS 9.1.2 · PHP 8.3 · MySQL 8.4


1. Architecture & File Inventory

modules/addons/haikhavan_advanced_billing/
├── whmcs.json                         # WHMCS Marketplace & schema 1.0 manifest
├── haikhavan_advanced_billing.php            # Addon entry point (_config, _activate, _deactivate, _upgrade, _output, _clientarea)
├── hooks.php                          # 8 WHMCS hooks (Navbar, Sidebar, Product Widget, Admin Tab, Admin Widget, Cron, InvoicePaid)
├── api.php                            # Public authenticated REST / Webhook / Prometheus metric ingestion & query API
├── lib/
│   ├── Database.php                   # 9-table Capsule schema installer, AES-256-CBC+HMAC crypto, settings, audit logger
│   ├── CollectorRegistry.php          # Metadata & live HTTP adapters for all 8 collector platforms
│   ├── PricingEngine.php              # Flat/Overage/Tiered/Volume pricing math, P95 aggregation, EOM forecast, Z-score anomalies
│   ├── BillingEngine.php              # Collection runner, localAPI CreateInvoice, Credit Wallet engine, Auto-Upgrade, CSV/HTML statements
│   ├── SandboxSimulator.php           # Deterministic local telemetry generator & idempotent demo seeder
│   ├── AdminController.php            # Admin SPA dispatcher, CSRF-guarded AJAX API, overview & service drilldown views
│   └── ClientController.php           # Client portal dispatcher, ownership checks, CSRF-guarded AJAX API, statement exports
├── templates/
│   ├── admin/dashboard.php            # 7-tab Admin Analytics, Product Rules, Wallets, Anomalies, API Keys, Archive & Audit UI
│   ├── admin/service_detail.php       # Per-service Admin deep graph & itemized breakdown view
│   └── client/dashboard.tpl           # Smarty 4/5 Client Area Usage & Metered Billing Portal
└── assets/
    ├── css/haikhavan_advanced_billing.css    # Scoped zero-CDN enterprise stylesheet (.hkab-*)
    └── js/haikhavan_advanced_billing.js      # Zero-CDN High-DPI Canvas charting engine (Area/Line + Forecast + Anomaly Dots + Donut) & AJAX helper

2. Database Schema (mod_hk_ab_*)

All tables are created via WHMCS\Database\Capsule::schema() during haikhavan_advanced_billing_activate() and use parameterized queries exclusively.

2.1 mod_hk_ab_products

Stores per-product metered billing configuration.

Column Type Null Default Notes
id INT UNSIGNED AI PK No — Primary key
product_id INT UNSIGNED UNIQUE No — Foreign reference to tblproducts.id
enabled TINYINT No 1 Active flag
billing_type VARCHAR(24) No 'metered' metered | hybrid | credit | hourly
collector_type VARCHAR(32) No 'cpanel' cpanel | plesk | directadmin | proxmox | solusvm | openstack | aws | custom_api
collection_interval VARCHAR(16) No 'hourly' hourly | daily | monthly
billing_cycle VARCHAR(20) No 'monthly' monthly | weekly | daily | threshold | ondemand
billing_day TINYINT UNSIGNED No 1 Monthly invoicing day (1–28)
threshold_amount DECIMAL(12,4) No 0.0000 Threshold trigger amount for auto-invoicing
fixed_base_fee DECIMAL(12,4) No 0.0000 Recurring fixed base fee for hybrid billing
autoinvoice_enabled TINYINT No 1 Enables cron auto-invoicing
auto_upgrade_enabled TINYINT No 0 Enables Product Auto-Upgrade evaluator
auto_upgrade_rules_json TEXT Yes NULL JSON array of {resource_key, threshold, target_product_id}
credit_billing_enabled TINYINT No 0 Deducts accrued charges from client credit wallet
credit_min_balance DECIMAL(12,4) No 15.0000 Low-balance alert/top-up threshold
credit_auto_topup_enabled TINYINT No 0 Auto-creates wallet deposit invoice when low
credit_auto_topup_amount DECIMAL(12,4) No 50.0000 Auto-top-up invoice amount
credit_auto_suspend_enabled TINYINT No 0 Calls localAPI('ModuleSuspend') when depleted
collector_config_encrypted TEXT Yes NULL AES-256-CBC + HMAC encrypted JSON credentials
currency_id INT UNSIGNED No 1 Default currency ID
last_collected_at TIMESTAMP Yes NULL Last successful collector sweep

2.2 mod_hk_ab_resources

Per-product metered resource pricing & aggregation rules (UNIQUE(product_rule_id, resource_key)).

  • Columns: id, product_rule_id (indexed), resource_key (indexed), display_name, unit, pricing_model (flat|overage|tiered|volume), unit_price DECIMAL(14,6), free_allowance DECIMAL(14,4), tiers_json TEXT, aggregation_method (sum|avg|max|last|p95), enabled, sort_order, timestamps.

2.3 mod_hk_ab_usage_records

Time-series usage samples indexed by (service_id, resource_key, recorded_at) (idx_hkab_usage_svc_res_time).

  • Columns: id BIGINT, service_id, client_id, product_id, resource_key, quantity DECIMAL(16,4), unit, unit_cost DECIMAL(14,6), calculated_cost DECIMAL(14,6), collector_source, period_start, period_end, recorded_at, billed TINYINT, invoice_id INT NULL, meta_json TEXT.

2.4 mod_hk_ab_billing_items

Billed & archived cycle snapshots (Item Archive).

  • Columns: id, service_id, client_id, product_id, cycle_start DATE, cycle_end DATE, fixed_amount, metered_amount, total_amount, currency_code, breakdown_json LONGTEXT, status (open|invoiced|credit_deducted|archived|void), invoice_id, invoiced_at, timestamps.

2.5 mod_hk_ab_credit_wallets & mod_hk_ab_credit_ledger

Prepaid client credit wallets (UNIQUE(client_id)) and immutable double-entry style ledger (wallet_id, client_id, service_id, type: topup|deduction|refund|adjustment, amount, balance_after, description, invoice_id, created_at).

2.6 mod_hk_ab_alerts

Unified store for client/admin usage thresholds, statistical anomaly spikes, low-credit warnings, and auto-upgrade triggers (alert_type, threshold_value, observed_value, baseline_value, z_score, severity, status, message, triggered_at).

2.7 mod_hk_ab_api_keys & mod_hk_ab_audit_log

SHA-256 hashed scoped API keys (key_prefix, key_hash UNIQUE, scopes, allowed_ips, requests_count, last_used_at, enabled) and immutable operational audit trail (admin_id, client_id, service_id, action, status, summary, details_json, ip_address, created_at).


3. Billing Engine Math, Forecasting & Anomaly Detection

3.1 Aggregation Methods (PricingEngine::aggregate)

  • sum: $\sum_{i=1}^n x_i$ (e.g., vCPU-hours, bandwidth GB, API requests)
  • avg: $\frac{1}{n}\sum_{i=1}^n x_i$ (e.g., average S3/object storage)
  • max: $\max_i x_i$ (e.g., peak disk GB, active mailboxes, dedicated IPv4s)
  • last: $x_n$ (latest reported gauge)
  • p95: 95th percentile (ceil(0.95 * n) - 1 index of ascending sorted samples — standard colocation/transit bandwidth burstable billing)

3.2 Pricing Models (PricingEngine::calculateResourceCost)

Let $q = \max(0, \text{aggregated quantity})$, $f = \text{free_allowance}$, and $b = \max(0, q - f)$:

  1. Flat: $\text{cost} = q \cdot r$
  2. Free Allowance + Overage: $\text{cost} = b \cdot r$
  3. Graduated Tiered: For sorted tiers $[L_k, U_k)$ at rate $r_k$, each bracket charges $\min(\text{remaining}, U_k - L_k) \cdot r_k$, summing across brackets.
  4. Volume Tiered: Finds the single tier $[L_k, U_k]$ containing $b$ and computes $\text{cost} = b \cdot r_k$.
  5. Hybrid Total: $\text{total} = \text{fixed_base_fee} + \sum \text{resource_cost}_j$.

3.3 Real-Time End-of-Month (EOM) Cost Forecasting

For cumulative (sum) resources, the engine computes a recency-weighted burn rate combining the cycle-to-date daily rate (60%) and the trailing 24-hour burn rate (40%): $$\text{DailyRate}{\text{blended}} = 0.60 \cdot \frac{Q{\text{cycle}}}{\text{ObservedDays}} + 0.40 \cdot Q_{24\text{h}}$$ $$Q_{\text{EOM}} = Q_{\text{cycle}} + \text{DailyRate}_{\text{blended}} \cdot \text{RemainingDays}$$ Confidence intervals are evaluated at $0.85\times$ (low bound) and $1.18\times$ (high bound) of the projected remaining burn, passed through the exact tier pricing function so bracket transitions are reflected accurately in the EOM forecast.

3.4 Statistical Anomaly Spike Detection (PricingEngine::evaluateAnomalySpike)

For each incoming metric sample $x$ (when at least 5 historical samples exist over the prior 7 days excluding the most recent 30 minutes): $$z = \frac{x - \mu}{\sigma}, \qquad \Delta% = \frac{x - \mu}{\mu} \times 100$$

  • Critical Alert: $z \ge z_{\text{crit}}$ (default 3.2) OR $\Delta% \ge 175%$
  • Warning Alert: $z \ge z_{\text{warn}}$ (default 2.2) OR $\Delta% \ge 85%$
  • Deduplicated over a 6-hour rolling window per (service_id, resource_key).

4. Security Model

  1. Authenticated Encryption at Rest: Collector API tokens/passwords are encrypted using AES-256-CBC with a random 16-byte IV and HMAC-SHA256 Encrypt-then-MAC (v1:<base64(iv || mac || ciphertext)>), deriving independent encryption and MAC subkeys via HKDF-style HMAC from WHMCS $cc_encryption_hash. Verification uses constant-time hash_equals().
  2. API Key Security: Raw API keys (hkab_live_<40 hex>) are displayed once at creation and stored strictly as SHA-256 digests (key_hash), validated with hash_equals(), scoped by ingest / read, with optional IPv4/IPv6 allowlisting.
  3. CSRF Protection: All Admin (hkab_admin_csrf) and Client (hkab_client_csrf) write AJAX actions enforce hash_equals() verification via csrf_token POST field or X-HK-AB-CSRF header, returning HTTP 403 on failure.
  4. Strict Tenant Ownership: Every Client Area endpoint (charts, threshold alert CRUD, CSV/HTML statement exports) verifies tblhosting.userid === $_SESSION['uid'].
  5. Output Escaping & SQL Safety: Every query uses WHMCS\Database\Capsule bound parameters; PHP templates escape via htmlspecialchars(..., ENT_QUOTES, 'UTF-8') and Smarty templates escape via |escape.

5. WHMCS Hooks Inventory (hooks.php)

Hook Point Priority Behavior
ClientAreaPrimaryNavbar 1 Adds Usage & Metered Billing link under the Client Area Billing dropdown.
ClientAreaPrimarySidebar 1 Adds Live Usage & Cost Forecast sidebar link on metered Product Details pages.
ClientAreaFooterOutput 1 Injects live metered usage & projected EOM cost card (#hkab-product-usage-widget) on clientareaproductdetails.
AdminClientServicesTabFields 1 Displays live metered status, collector badge, accrued cost, EOM forecast & deep-links on Admin Client Services tab.
AdminHomeWidgets 1 Registers the Haikhavan Advanced Billing & Usage Metering Admin Home Dashboard widget.
AfterCronJob 1 Executes periodic collector sweeps, anomaly evaluation, credit wallet deductions, and threshold auto-invoicing.
DailyCronJob 1 Issues scheduled daily, weekly (Monday), and monthly (billing_day) WHMCS invoices via localAPI('CreateInvoice').
InvoicePaid 1 Detects paid [HKAB-WALLET-TOPUP:<clientId>] invoices, credits wallet, and auto-unsuspends depleted services.

6. REST / Webhook API & Controller Operations

Public Metric API (modules/addons/haikhavan_advanced_billing/api.php)

  • GET ?action=health — Requires valid Bearer / X-API-Key; returns module version, key scopes, server time.
  • GET ?action=usage&service_id=<ID> — Requires read scope; returns current cycle summary, EOM forecast, confidence range, anomalies, and itemized resources.
  • POST ?action=ingest — Requires ingest scope; accepts single JSON object or batch {"metrics":[...]} / Prometheus {"samples":[...]} and runs real-time anomaly detection.

Admin AJAX Operations (addonmodules.php?module=haikhavan_advanced_billing&ajax=1)

Write ops require CSRF: toggle_sandbox, seed_demo, run_collection, inject_spike, save_product_rule, delete_product_rule, save_resource_rule, delete_resource_rule, generate_invoice, wallet_adjust, wallet_update_settings, alert_update_status, create_threshold_alert, create_api_key, toggle_api_key, delete_api_key, test_ingest_metric. Read ops: get_service_series.

Client AJAX Operations (index.php?m=haikhavan_advanced_billing&ajax=1)

Write ops require CSRF: save_alert_rule, delete_alert_rule, request_topup, update_wallet_prefs. Read ops: get_series.


7. Troubleshooting

  • API returns 401 Missing API key under Apache/CGI: Ensure Apache passes Authorization headers (SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1) or send the X-API-Key header instead.
  • No metrics collected in production: Verify sandbox_mode is disabled, product rule enabled=1, target service domainstatus='Active', and collector API credentials/endpoint are configured. Check the Audit Log tab for collector_error entries.
  • Scheduled invoices not generating: Verify WHMCS system cron executes DailyCronJob and enable_auto_invoicing is enabled in module settings.