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

Haikhavan CRM & Sales Pipeline

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

Quick Installation

  1. Purchase the module and download haikhavan_crm-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_crm/.
  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 CRM & Sales Pipeline, 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 UI + Client Area Portal + Public Web-to-Lead Endpoint + 9 Native Hooks)


Haikhavan CRM & Sales Pipeline (haikhavan_crm) — Technical Documentation

1. Architecture Overview

haikhavan_crm follows a modular PSR-4 namespace layout (Haikhavan\Crm\) loaded via spl_autoload_register in both haikhavan_crm.php and hooks.php. All persistence uses WHMCS's built-in WHMCS\Database\Capsule (Illuminate Query Builder / Schema Builder) with prepared statements and zero raw SQL concatenation. All frontend charts are rendered natively on HTML5 <canvas> with zero third-party CDN dependencies.

modules/addons/haikhavan_crm/
├── whmcs.json                 # WHMCS Addon metadata manifest
├── haikhavan_crm.php             # Addon lifecycle (_config, _activate, _deactivate, _upgrade, _output, _clientarea)
├── hooks.php                  # 9 WHMCS hooks (sync, tickets, invoices, widgets, cron, navbar)
├── lib/
│   ├── Database.php           # Schema installer (9 tables), settings loader, token generator, activity logger
│   ├── ScoringEngine.php      # Automated Lead Scoring (0-100) + Client Health & Churn-Risk Engine (0-100)
│   ├── PipelineService.php    # Kanban board queries, drag-and-drop stage transitions, weighted revenue forecasting
│   ├── WhmcsBridge.php        # 1-click Convert Lead->Client, Create Quote, Create Invoice, Bulk Client Sync
│   ├── CampaignService.php    # Merge-variable renderer, audience segmentation, email campaign dispatcher
│   ├── CsvService.php         # Safe CSV importer & formula-injection-hardened CSV exporter
│   ├── AdminController.php    # Admin UI renderer, CSV export route, CSRF-protected JSON AJAX API
│   └── ClientController.php   # Public Web-to-Lead webhook, Public Inquiry form, Client Area Account Hub
├── templates/
│   ├── admin/app.php          # Multi-tab Admin SPA template + modals + 360° Contact Drawer
│   └── client/portal.tpl      # Smarty template for Client Area Account Hub & Public Sales Inquiry
└── assets/
    ├── css/haikhavan_crm.css     # Scoped SaaS UI system (.crm-wrap)
    └── js/haikhavan_crm.js       # Vanilla ES6 Kanban DnD, Canvas Charts, Calendar, Drawer & AJAX client

2. Database Schema (9 Tables)

All tables are created idempotently via Database::install() on activation and upgrade:

Table Purpose Key Columns & Indexes
mod_hk_crm_stages Customizable sales pipeline stages id, name, slug (UNIQUE), color, default_probability, sort_order (IDX), is_won, is_lost
mod_hk_crm_contacts Unified Leads, Potentials, Customers & Archived contacts id, whmcs_userid (IDX), type (IDX), email (IDX), source (IDX), owner_admin_id, tags_json, labels_json, custom_fields_json, lead_score (IDX), lead_grade (IDX), score_breakdown_json, health_score (IDX), churn_risk_level (IDX), churn_factors_json, last_contacted_at, converted_at
mod_hk_crm_deals Pipeline opportunities linked to contacts & stages id, contact_id (IDX), stage_id (IDX), title, value DECIMAL(16,2), currency, probability, expected_close_date (IDX), owner_admin_id, status (open/won/lost), whmcs_quote_id, whmcs_order_id, whmcs_invoice_id, closed_at
mod_hk_crm_followups Calls, emails, meetings, demos, deadlines & retention tasks id, contact_id (IDX), deal_id (IDX), owner_admin_id, type, title, due_at (IDX), status (pending/completed/cancelled), priority, completed_at
mod_hk_crm_activities Per-contact communication timeline & internal notes id, contact_id (IDX), deal_id (IDX), admin_id, type, subject, body, meta_json, created_at
mod_hk_crm_email_templates Reusable HTML email templates with merge tags id, name, category, subject, body_html, merge_vars_hint, created_by
mod_hk_crm_campaigns Segmented email outreach campaigns id, name, template_id, segment_type, segment_filter_json, subject, body_html, status, total_recipients, sent_count, failed_count, sent_at
mod_hk_crm_campaign_logs Per-recipient campaign delivery & audit log id, campaign_id (IDX), contact_id (IDX), email, subject_rendered, status, error_message, sent_at
mod_hk_crm_webhooks Inbound Web-to-Lead submission & security audit log id, source_name, token_prefix, payload_json, contact_id, deal_id, ip_address, status (accepted/duplicate/rejected), message, created_at

3. Pipeline Engine & Weighted Revenue Forecasting

Drag-and-Drop Stage Transitions (PipelineService::moveDealStage)

When an admin drags a deal card into another stage column:

  1. Frontend posts op=move_deal with deal_id, stage_id, and csrf_token to addonmodules.php?module=haikhavan_crm&ajax=1.
  2. Backend updates stage_id, sets probability = stage.default_probability, updates status (won if stage.is_won, lost if stage.is_lost, else open), and sets closed_at when entering a terminal stage.
  3. Contacts currently typed as lead automatically promote to potential upon advancing past stage 1 (unless lost).
  4. A stage_change timeline event is recorded in mod_hk_crm_activities, ScoringEngine::recalculateContact() runs, and fresh KPIs + forecast arrays return in the JSON response for zero-reload UI updates.

Weighted Revenue Forecast Formula

For every open deal $d$: $$\text{Weighted Value}_d = \text{value}_d \times \frac{\text{probability}_d}{100}$$ Deals are bucketed into a rolling 6-month forecast horizon by expected_close_date alongside raw_value and realized won_value (bucketed by closed_at). The native HTML5 Canvas chart renders grouped bars + a weighted forecast trend line at HiDPI (window.devicePixelRatio).


4. Automated Lead Scoring & Client Churn-Risk Engines

Automated Lead Scoring Engine (ScoringEngine::computeLeadScore, 0–100 pts)

  • Lead Source Quality (max 25 pts): Referral (25), Partner (22), WHMCS Sync (20), Web-to-Lead (18), Organic (14), Ticket (12), Manual (10), Import (8), Cold (5).
  • Deal Value & Pipeline Momentum (max 30 pts): Up to 18 pts tiered by cumulative open/won deal value ($20k+ = 18, $10k+ = 15, $5k+ = 12, $1k+ = 8) + up to 12 pts scaled by maximum deal win probability (or 12 pts for won deals).
  • Engagement & Touchpoints (max 25 pts): min(25, activities * 4 + completed_followups * 6 + pending_followups * 3 + campaign_hits * 3).
  • Recent Responsiveness (max 15 pts): Within 24h (15), ≤3d (12), ≤7d (9), ≤14d (6), older (3).
  • Profile Completeness (max 5 pts): Company (+2), Phone (+2), Email (+1).
  • Grades: Hot (75–100), Warm (50–74), Nurture (25–49), Cold (0–24).

Client Health & Churn-Risk Score (ScoringEngine::computeClientHealth, 0–100 pts)

Evaluated live against core WHMCS tables for every contact with whmcs_userid > 0:

  • Unpaid / Overdue Invoices (tblinvoices): Overdue unpaid invoices deduct min(40, count * 18); non-overdue unpaid invoices deduct min(15, count * 7).
  • Service Cancellation Requests (tblcancelrequests JOIN tblhosting ON relid = id): Deducts min(45, count * 28).
  • Support Ticket Volume (tbltickets): 2+ open tickets deduct min(20, count * 6); 4+ tickets in the past 30 days deduct min(15, (count - 2) * 4).
  • Suspended Services (tblhosting): Deducts min(25, count * 15).
  • Churn Risk Levels: Low (83–100), Medium (61–82), High (36–60), Critical (0–35).

5. WHMCS Hooks Reference (hooks.php)

Hook Behavior
ClientAdd Auto-creates or links CRM customer contact and logs conversion activity + computes scores.
ClientEdit Synchronizes firstname, lastname, company, email, and phone to the linked CRM contact.
AfterShoppingCartCheckout Records new WHMCS orders on the contact timeline and recalculates scores.
TicketOpen Logs ticket activity for existing clients (updating churn risk) or captures unknown guest senders as lead contacts.
InvoicePaid / InvoiceUnpaid / CancellationRequest Immediately recalculates Client Health & Churn-Risk Score when billing or cancellation state changes.
AdminAreaClientSummaryPage Renders an inline CRM Profile card on the WHMCS Client Summary page with Lead Score, Health/Churn Risk, open deals, and deep link to the 360° Drawer.
AdminHomeWidgets Registers the Haikhavan CRM & Sales Pipeline dashboard widget displaying Open Pipeline, Weighted Forecast, Closed Won, Hot Leads, Overdue Tasks, and Churn-Risk Alerts.
ClientAreaPrimaryNavbar Adds Account & Proposals (logged in) or Sales Inquiry (guest) pointing to index.php?m=haikhavan_crm.
DailyCronJob Batch-recalculates Lead Scores and Client Health / Churn-Risk Scores across all contacts daily.

6. Web-to-Lead Public Capture Endpoint / Webhook

Endpoint: POST /index.php?m=haikhavan_crm&action=web_to_lead
Content Types: application/json or application/x-www-form-urlencoded / multipart/form-data

Authentication

Requests must supply EITHER:

  • A valid API token in X-Haikhavan-CRM-Token: <token>, Authorization: Bearer <token>, or api_token body/query parameter (verified via constant-time hash_equals()), OR
  • A valid WHMCS Client session CSRF token (csrf_token) from the built-in public inquiry form (index.php?m=haikhavan_crm&action=inquiry).

Invalid tokens are rejected with HTTP 401 Unauthorized and logged to mod_hk_crm_webhooks (status = 'rejected').

Example JSON Request

curl -X POST "https://your-whmcs.example/index.php?m=haikhavan_crm&action=web_to_lead" \
  -H "Content-Type: application/json" \
  -H "X-Haikhavan-CRM-Token: crm_w2l_your_secret_token" \
  -d '{
    "firstname": "Clara",
    "lastname": "Lindqvist",
    "company": "Skandia Cloud AB",
    "email": "[email protected]",
    "phone": "+46 8 111 22 33",
    "deal_title": "Dedicated NVMe Multi-Region Cluster",
    "deal_value": 12500,
    "source_name": "Marketing Pricing Page"
  }'

Example HTTP 201 Created Response

{
  "success": true,
  "message": "Thank you! Your inquiry has been received and assigned to our sales team.",
  "contact_id": 8,
  "deal_id": 8,
  "lead_score": 62,
  "lead_grade": "Warm"
}

7. Security Architecture

  • CSRF Protection: Every mutating Admin AJAX POST (op=...) and Client Area AJAX POST verifies a 48-char random session token via hash_equals(), rejecting unauthorized requests with HTTP 403.
  • SQL Injection Prevention: 100% Eloquent/Capsule parameterized queries; zero string-interpolated SQL.
  • XSS Prevention: All dynamic template values are HTML-escaped (htmlspecialchars(..., ENT_QUOTES, 'UTF-8') in PHP, |escape in Smarty, and DOM textContent escaping in JS).
  • CSV Formula Injection Protection: CsvService::sanitizeCell() neutralizes cells beginning with =, +, -, @, \t, or \r before exporting contacts or deals.
  • Anti-Spam Honeypot: Web-to-Lead submissions containing a non-empty hidden website_hp field are silently discarded without polluting the CRM database.
  • Direct Access Guard: Every entry PHP file checks if (!defined('WHMCS')) die(...).

8. Troubleshooting

  • Module not visible in Addons menu: Ensure haikhavan_crm is activated under System Settings → Addon Modules and your Admin Role Group has access enabled (tbladdonmodules.access).
  • Webhook returns HTTP 401: Confirm Enable Public Web-to-Lead Webhook Endpoint is enabled and the X-Haikhavan-CRM-Token header matches the active token in Web-to-Lead & Webhooks.
  • Campaign emails show status Simulated: In local/staging environments without SMTP configured, CampaignService safely falls back to simulated logging so campaign runs never crash. Configure WHMCS SMTP mail settings or choose whmcs_mail mode for production dispatch.