EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
fetch_whmcs_data.js
Go to the documentation of this file.
1#!/usr/bin/env node
2/**
3 * Fetch all customer data from WHMCS API
4 * Saves to JSON and CSV formats for import
5 */
6
7require('dotenv').config();
8const fs = require('fs');
9const path = require('path');
10const WHMCSMysqlService = require('../services/whmcsMysqlService');
11
12const EXPORT_DIR = path.join(__dirname, '../exports');
13
14// Ensure export directory exists
15if (!fs.existsSync(EXPORT_DIR)) {
16 fs.mkdirSync(EXPORT_DIR, { recursive: true });
17}
18
19/**
20 * Convert array to CSV
21 * @param data
22 * @param headers
23 */
24function arrayToCSV(data, headers) {
25 if (!data || data.length === 0) return '';
26
27 const csvHeaders = headers.join(',');
28 const csvRows = data.map(row => {
29 return headers.map(header => {
30 const value = row[header] || '';
31 // Escape commas and quotes
32 const escaped = String(value).replace(/"/g, '""');
33 return `"${escaped}"`;
34 }).join(',');
35 });
36
37 return [csvHeaders, ...csvRows].join('\n');
38}
39
40/**
41 * Main export function
42 */
43async function fetchWHMCSData() {
44 try {
45 console.log('========================================');
46 console.log('WHMCS Data Export (MySQL Direct Access)');
47 console.log('========================================\n');
48
49 const whmcs = new WHMCSMysqlService();
50
51 // Test connection
52 console.log('Testing WHMCS MySQL connection...');
53 const connected = await whmcs.testConnection();
54 if (!connected) {
55 throw new Error('Failed to connect to WHMCS database');
56 }
57 console.log('');
58
59 // Fetch all data
60 console.log('Fetching data from WHMCS...\n');
61 const exportData = await whmcs.exportAllData();
62
63 // Save full JSON export
64 const jsonPath = path.join(EXPORT_DIR, 'whmcs_export.json');
65 fs.writeFileSync(jsonPath, JSON.stringify(exportData, null, 2));
66 console.log(`\n✅ Full export saved: ${jsonPath}`);
67
68 // Save clients CSV
69 if (exportData.clients.length > 0) {
70 const clientHeaders = [
71 'id', 'firstname', 'lastname', 'companyname', 'email',
72 'address1', 'address2', 'city', 'state', 'postcode', 'country',
73 'phonenumber', 'status', 'datecreated', 'currency'
74 ];
75 const clientsCSV = arrayToCSV(exportData.clients, clientHeaders);
76 const clientsPath = path.join(EXPORT_DIR, 'whmcs_clients.csv');
77 fs.writeFileSync(clientsPath, clientsCSV);
78 console.log(`✅ Clients CSV saved: ${clientsPath}`);
79 }
80
81 // Save domains CSV
82 if (exportData.domains.length > 0) {
83 const domainHeaders = [
84 'id', 'userid', 'domainname', 'registrar', 'registrationdate',
85 'expirydate', 'status', 'nextduedate', 'recurringamount'
86 ];
87 const domainsCSV = arrayToCSV(exportData.domains, domainHeaders);
88 const domainsPath = path.join(EXPORT_DIR, 'whmcs_domains.csv');
89 fs.writeFileSync(domainsPath, domainsCSV);
90 console.log(`✅ Domains CSV saved: ${domainsPath}`);
91 }
92
93 // Save products CSV
94 if (exportData.products.length > 0) {
95 const productHeaders = [
96 'id', 'clientid', 'orderid', 'pid', 'name', 'domain',
97 'regdate', 'nextduedate', 'billingcycle', 'amount', 'status'
98 ];
99 const productsCSV = arrayToCSV(exportData.products, productHeaders);
100 const productsPath = path.join(EXPORT_DIR, 'whmcs_products.csv');
101 fs.writeFileSync(productsPath, productsCSV);
102 console.log(`✅ Products CSV saved: ${productsPath}`);
103 }
104
105 // Summary
106 console.log('\n========================================');
107 console.log('Export Summary');
108 console.log('========================================');
109 console.log(`Clients: ${exportData.clients.length}`);
110 console.log(`Domains: ${exportData.domains.length}`);
111 console.log(`Products: ${exportData.products.length}`);
112 console.log(`Custom Fields: ${exportData.customFields.length}`);
113 console.log(`\nExported at: ${exportData.exportedAt}`);
114 console.log('========================================\n');
115
116 // Show sample data
117 if (exportData.clients.length > 0) {
118 console.log('Sample Clients (first 3):');
119 exportData.clients.slice(0, 3).forEach(client => {
120 console.log(` ${client.id}: ${client.firstname} ${client.lastname} (${client.companyname || 'N/A'}) - ${client.email}`);
121 });
122 console.log('');
123 }
124
125 if (exportData.domains.length > 0) {
126 console.log('Sample Domains (first 3):');
127 exportData.domains.slice(0, 3).forEach(domain => {
128 console.log(` ${domain.id}: ${domain.domainname} - ${domain.status} (expires: ${domain.expirydate})`);
129 });
130 console.log('');
131 }
132
133 console.log('✅ Export complete! Files saved to:', EXPORT_DIR);
134 console.log('\nNext step: Run import script');
135 console.log(' node migration-scripts/import_whmcs_customers.js\n');
136
137 } catch (error) {
138 console.error('\n❌ Export failed:', error.message);
139 console.error(error.stack);
140 process.exit(1);
141 } finally {
142 // Close MySQL connection
143 try {
144 const WHMCSMysqlService = require('../services/whmcsMysqlService');
145 const whmcs = new WHMCSMysqlService();
146 await whmcs.close();
147 } catch (e) {
148 // Ignore close errors
149 }
150 }
151}
152
153// Run if called directly
154if (require.main === module) {
155 fetchWHMCSData();
156}
157
158module.exports = { fetchWHMCSData };