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

Haikhavan Billing & EU Tax Compliance

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

Quick Installation

  1. Purchase the module and download haikhavan_billing_tax_compliance-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_billing_tax_compliance/.
  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 Billing & EU Tax Compliance, and assign administrator role access.

Version: 1.0.0 | Module Slug: haikhavan_billing_tax_compliance | WHMCS Compatibility: 9.1.x (8.10+ compatible) | PHP: 8.2 / 8.3 / 8.4

Haikhavan Billing & EU Tax Compliance is an enterprise-grade WHMCS addon module for EU VAT/VIES/OSS compliance, immutable proforma-to-tax sequential invoicing, monthly consolidated billing, automated credit notes, multi-currency ECB FX snapshots, client tax exemption workflows, Peppol/UBL 2.1 e-invoicing, and quarterly EU OSS tax return exports.


Haikhavan Billing & EU Tax Compliance — Technical Documentation

Module Slug: haikhavan_billing_tax_compliance | Namespace: Haikhavan\BillingTax\ | Version: 1.0.0 | Target: WHMCS 9.1.2 (PHP 8.3+, MySQL 8.4)


1. Architecture & File Inventory

modules/addons/haikhavan_billing_tax_compliance/
├── haikhavan_billing_tax_compliance.php   # WHMCS addon lifecycle callbacks & PSR-4 autoloader
├── hooks.php                        # 9 WHMCS hooks (Invoice, ViewInvoice, AdminControls, Navbar, Widget, Cron)
├── whmcs.json                       # WHMCS Marketplace manifest (schema 1.0)
├── lib/
│   ├── Database.php                 # Schema installer (8 tables), 32-country VAT seeder, AES-256-CBC+HMAC crypto, audit logger
│   ├── ViesValidator.php            # EU VIES REST API client, regex syntax validator, TTL cache, reverse-charge/OSS decision engine
│   ├── InvoiceEngine.php            # Proforma->Locked sequential numbering, SHA-256 hash chain, $0 suppression, consolidation, credit notes
│   ├── FxService.php                # ECB Daily XML FX feed parser, EUR conversion & invoice-date FX snapshots
│   ├── OssExportService.php         # Quarterly EU OSS CSV/XML return aggregator + Peppol BIS 3.0 / UBL 2.1 XML invoice generator
│   ├── AnalyticsService.php         # MRR/ARR, Quarterly VAT Liability, €10k OSS threshold meter, 6-month series & sandbox demo seeder
│   ├── AdminController.php          # 7-tab Admin UI dispatcher, CSRF-guarded AJAX API & CSV/XML/UBL download handlers
│   └── ClientController.php         # Client Area portal dispatcher, ownership-guarded UBL download & multipart exemption uploader
├── templates/
│   ├── admin/dashboard.php          # Scoped 7-tab Admin dashboard with zero-CDN Canvas charts & Credit Note modal
│   └── client/portal.tpl            # Smarty Client Area EU VAT, Exemptions, Preferences & E-Invoice portal
└── assets/
    ├── css/haikhavan_billing_tax.css      # Scoped design system (.hk-tax-*)
    └── js/haikhavan_billing_tax.js        # Vanilla JS AJAX handlers + HDPI HTML5 Canvas charting engine

2. Database Schema (mod_hk_tax_*)

All tables are created via WHMCS\Database\Capsule::schema() during activation and upgrade.

2.1 mod_hk_tax_vat_rules

Stores the 32-jurisdiction EU/EEA/Global VAT & OSS rate matrix.

Column Type Constraints / Default Purpose
id INT UNSIGNED PK, AI Primary key
country_code VARCHAR(2) UNIQUE ISO 3166-1 alpha-2 country code
country_name VARCHAR(100) NOT NULL Jurisdiction display name
is_eu TINYINT INDEX, default 0 1 for all 27 EU Member States
standard_rate DECIMAL(5,2) default 0.00 Standard VAT percentage
reduced_rate DECIMAL(5,2) default 0.00 Reduced VAT percentage
oss_enabled TINYINT default 0 Apply destination rate for cross-border EU B2C
reverse_charge_eligible TINYINT default 0 Eligible for cross-border B2B 0% reverse charge
tax_label VARCHAR(32) default 'VAT' Localized tax label (e.g., MwSt / VAT, TVA / VAT)
created_at, updated_at TIMESTAMP nullable Timestamps

2.2 mod_hk_tax_vat_verifications

Audit cache of live EU VIES & sandbox VAT ID checks.

Column Type Constraints / Default Purpose
id INT UNSIGNED PK, AI Primary key
userid INT UNSIGNED INDEX, default 0 Associated WHMCS client ID (0 for ad-hoc admin lookups)
vat_number VARCHAR(40) INDEX Normalized VAT ID with country prefix
country_code VARCHAR(2) INDEX ISO country code
is_valid TINYINT INDEX, default 0 VIES validation outcome
company_name VARCHAR(255) nullable Entity name returned by VIES
company_address TEXT nullable Entity address returned by VIES
consultation_number VARCHAR(64) nullable Official VIES proof-of-consultation request identifier
reverse_charge_applied TINYINT default 0 Whether cross-border B2B reverse charge applies
source VARCHAR(24) default 'vies_live' vies_live | sandbox | manual
raw_response_json TEXT nullable Raw JSON audit payload
verified_at, expires_at TIMESTAMP expires_at indexed Verification & cache expiry timestamps

2.3 mod_hk_tax_invoice_ledger

Immutable fiscal ledger with sequential locked numbering, FX snapshots, legal entity snapshots, and chained SHA-256 hashes.

Column Type Constraints / Default Purpose
id INT UNSIGNED PK, AI Primary key
invoice_id INT UNSIGNED UNIQUE WHMCS tblinvoices.id
userid INT UNSIGNED INDEX WHMCS tblclients.id
doc_type VARCHAR(24) INDEX proforma | tax_invoice | consolidated
proforma_number VARCHAR(48) INDEX, nullable Sequential PRO-YYYY-NNNNN
final_invoice_number VARCHAR(48) UNIQUE, nullable Gap-free sequential INV-YYYY-NNNNN
sequence_series VARCHAR(24) INDEX, nullable e.g., INV-2026
sequence_number INT UNSIGNED default 0 Monotonic integer within sequence_series
status VARCHAR(24) INDEX proforma | locked | credited | suppressed
currency_code, base_currency_code VARCHAR(8) default 'EUR' Invoice currency & reporting currency (EUR)
fx_rate_snapshot DECIMAL(14,6) default 1.000000 Frozen ECB FX rate (1 EUR = X currency_code)
subtotal, tax_amount, tax_rate, total DECIMAL(12,2) / (5,2) default 0.00 Document monetary totals
base_subtotal_eur, base_tax_eur, base_total_eur DECIMAL(12,2) default 0.00 EUR-normalized values for EU OSS reporting
vat_country VARCHAR(2) INDEX Member State of Consumption (MSCON)
client_vat_id VARCHAR(40) nullable Frozen buyer VAT ID at issue
reverse_charge, is_oss_supply, is_sandbox TINYINT INDEX, default 0 Fiscal classification flags
company_snapshot_json, client_snapshot_json LONGTEXT nullable Immutable JSON snapshots of seller & buyer legal info
prev_hash, record_hash VARCHAR(64) record_hash indexed Chained SHA-256 fiscal digest
issued_at, locked_at TIMESTAMP INDEX, nullable Issue and cryptographic lock timestamps

2.4 mod_hk_tax_credit_notes

Sequential credit notes (CN-YYYY-NNNNN) linked to locked invoices (original_invoice_id, userid, reason, currency_code, fx_rate_snapshot, subtotal, tax_amount, tax_rate, total, base_tax_eur, vat_country, status, apply_to_credit, snapshot_json, record_hash, issued_by_admin, issued_at).

2.5 mod_hk_tax_exemptions

Client-uploaded tax exemption certificates (userid, certificate_type, certificate_number, issuing_country, file_name, file_path_encrypted, file_mime, file_size, file_sha256, status, valid_until, admin_notes, reviewed_by, reviewed_at).

2.6 mod_hk_tax_fx_rates

Cached ECB daily FX rates (UNIQUE(base_currency, quote_currency), rate, source, fetched_at).

2.7 mod_hk_tax_client_prefs

Per-client billing preferences (userid UNIQUE, consolidated_invoicing, preferred_einvoice_format, billing_po_reference, peppol_participant_id).

2.8 mod_hk_tax_audit_log

Immutable operational & compliance audit log (userid, adminid, invoice_id, action, status, summary, details_json, ip_address, created_at).


3. Security Model

  1. Authenticated Encryption at Rest: Database::encryptSecret() / decryptSecret() encrypts optional external FX/E-Invoice API keys and stored exemption file paths using AES-256-CBC with a random 16-byte IV and HMAC-SHA256 (Encrypt-then-MAC) verified in constant time via hash_equals(). Encryption and MAC subkeys are derived via HKDF-style hash_hmac('sha256', ...) from WHMCS's $cc_encryption_hash.
  2. Tamper-Evident SHA-256 Invoice Hash Chain: Every locked tax invoice hashes prev_hash|final_invoice_number|invoice_id|userid|currency_code|fx_rate|subtotal|tax_amount|total|vat_country|client_vat_id|reverse_charge|locked_at. Genesis records link to 64 zero hex characters. InvoiceEngine::verifyHashChain() recomputes and validates every link.
  3. CSRF Protection: Separate session-bound 48-char hex tokens ($_SESSION['hk_tax_admin_csrf'] and $_SESSION['hk_tax_client_csrf']) verified via hash_equals() on every POST/AJAX endpoint (returns HTTP 403 on mismatch).
  4. Client Ownership Isolation: All Client Area queries (download_ubl, verify_vat, save_billing_prefs, upload_exemption) strictly scope to (int) $_SESSION['uid']. Accessing another user's UBL XML returns HTTP 403.
  5. Upload Hardening: Exemption certificate uploads enforce max size (5 MB), strict extension allowlist (pdf, png, jpg, jpeg), server-side finfo_file() MIME inspection, randomized disk filenames, SHA-256 digesting, encrypted stored paths, and Apache .htaccess (Require all denied) inside storage/exemptions/.
  6. Output Escaping & SQL Safety: 100% parameterized WHMCS\Database\Capsule queries; htmlspecialchars(..., ENT_QUOTES, 'UTF-8') across all PHP admin views; |escape across all Smarty .tpl views.

4. External API Integrations

Integration Endpoint Method Timeout Fallback Behavior
EU Commission VIES REST API https://ec.europa.eu/taxation_customs/vies/rest-api/check-vat-number POST JSON 10s (connect 5s) Graceful error message if VIES is down; caches valid results for vies_cache_hours.
European Central Bank (ECB) Daily FX Feed https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml GET XML 8s (connect 4s) Retains cached mod_hk_tax_fx_rates baseline without interrupting checkout or cron.

5. WHMCS Hooks Inventory (hooks.php)

# Hook Point Purpose
1 InvoiceCreation Assigns PRO-YYYY-NNNNN, applies EU VAT/VIES reverse-charge or OSS rate, freezes FX rate snapshot, suppresses $0.00 invoices.
2 InvoicePaid Promotes Proforma -> locked sequential INV-YYYY-NNNNN with company/client JSON snapshots & SHA-256 hash chain.
3 InvoiceRefunded Automatically generates sequential Credit Note (CN-YYYY-NNNNN) linked to the refunded invoice.
4 ClientAreaPageViewInvoice Injects hk_tax_ledger, hk_tax_reverse_charge_note, hk_tax_fx_note, hk_tax_credit_notes, hk_tax_ubl_download_url Smarty variables.
5 ClientAreaFooterOutput Displays EU Tax Compliance & 1-click Download UBL 2.1 XML banner on viewinvoice.php.
6 AdminInvoicesControlsOutput Displays inline fiscal seal, proforma/locked badge, VIES/OSS tags, FX snapshot, and UBL XML button inside Admin Invoice View.
7 ClientAreaPrimaryNavbar Adds EU VAT & Tax Compliance under Client Area Billing dropdown.
8 AdminHomeWidgets Renders live MRR, Quarterly EU VAT Payable, Reverse Charge, Locked Invoices, Pending Exemptions & SHA-256 Chain status widget.
9 DailyCronJob Refreshes ECB daily FX rates, marks expired tax exemption certificates, and runs monthly consolidated invoicing on consolidation_day.

6. AJAX & Download API Reference

Admin Endpoints (addonmodules.php?module=haikhavan_billing_tax_compliance&ajax=1 — POST + csrf_token)

  • op=verify_vies (vat_number, force_refresh) — Real-time or cached VIES verification.
  • op=update_vat_rule (id, standard_rate, reduced_rate, tax_label, oss_enabled, reverse_charge_eligible) — Update country VAT matrix row.
  • op=lock_invoice (invoice_id) — Manually promote & cryptographically lock a proforma invoice.
  • op=issue_credit_note (invoice_id, amount, reason, apply_to_credit) — Issue sequential Credit Note.
  • op=run_consolidation — Group unpaid invoices for opted-in monthly consolidated clients.
  • op=verify_hash_chain — Recompute & validate SHA-256 chain across all locked tax invoices.
  • op=review_exemption (exemption_id, decision, admin_notes) — Approve or reject uploaded exemption certificate.
  • op=refresh_fx — Pull latest ECB daily FX rates.
  • op=sync_recent_invoices — Backfill recent WHMCS invoices into ledger.
  • op=seed_sandbox / op=clear_sandbox — Seed or surgically wipe demo records (is_sandbox=1).
  • op=save_settings — Save legal entity, numbering, compliance flags, and encrypted API key.

Admin GET Downloads

  • addonmodules.php?module=haikhavan_billing_tax_compliance&action=export_oss_csv&year=YYYY&quarter=Q
  • addonmodules.php?module=haikhavan_billing_tax_compliance&action=export_oss_xml&year=YYYY&quarter=Q
  • addonmodules.php?module=haikhavan_billing_tax_compliance&action=download_ubl&invoice_id=ID

Client Endpoints (index.php?m=haikhavan_billing_tax_compliance&ajax=1 — POST + csrf_token)

  • op=verify_vat (vat_number) — Verify client's EU VAT ID via VIES & sync to tblclients.tax_id.
  • op=save_billing_prefs (consolidated_invoicing, preferred_einvoice_format, billing_po_reference, peppol_participant_id) — Save client preferences.
  • op=upload_exemption (multipart: certificate_type, certificate_number, issuing_country, valid_until, certificate_file) — Upload tax exemption certificate.
  • GET Download: index.php?m=haikhavan_billing_tax_compliance&action=download_ubl&invoice_id=ID (strictly ownership-checked).

7. Troubleshooting

  • EU VIES Timeout: The EU Commission VIES SOAP/REST gateway experiences occasional member-state downtime (especially DE/ES/IT). Increase vies_cache_hours (default 168) or test offline using Sandbox Mode.
  • Broken Hash Chain Warning: If a database administrator manually alters subtotal, tax_amount, total, or final_invoice_number directly in mod_hk_tax_invoice_ledger, verifyHashChain() intentionally flags the exact tampered invoice ID. Never edit locked tax invoices—issue a Credit Note instead.
  • Zero-Value Invoices Appearing: Ensure suppress_zero_invoices is enabled in Settings; suppression applies to newly created $0.00 unpaid invoices via InvoiceCreation.