3 * Fetch all customer data from WHMCS API
4 * Saves to JSON and CSV formats for import
7require('dotenv').config();
8const fs = require('fs');
9const path = require('path');
10const WHMCSMysqlService = require('../services/whmcsMysqlService');
12const EXPORT_DIR = path.join(__dirname, '../exports');
14// Ensure export directory exists
15if (!fs.existsSync(EXPORT_DIR)) {
16 fs.mkdirSync(EXPORT_DIR, { recursive: true });
20 * Convert array to CSV
24function arrayToCSV(data, headers) {
25 if (!data || data.length === 0) return '';
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}"`;
37 return [csvHeaders, ...csvRows].join('\n');
41 * Main export function
43async function fetchWHMCSData() {
45 console.log('========================================');
46 console.log('WHMCS Data Export (MySQL Direct Access)');
47 console.log('========================================\n');
49 const whmcs = new WHMCSMysqlService();
52 console.log('Testing WHMCS MySQL connection...');
53 const connected = await whmcs.testConnection();
55 throw new Error('Failed to connect to WHMCS database');
60 console.log('Fetching data from WHMCS...\n');
61 const exportData = await whmcs.exportAllData();
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}`);
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'
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}`);
82 if (exportData.domains.length > 0) {
83 const domainHeaders = [
84 'id', 'userid', 'domainname', 'registrar', 'registrationdate',
85 'expirydate', 'status', 'nextduedate', 'recurringamount'
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}`);
94 if (exportData.products.length > 0) {
95 const productHeaders = [
96 'id', 'clientid', 'orderid', 'pid', 'name', 'domain',
97 'regdate', 'nextduedate', 'billingcycle', 'amount', 'status'
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}`);
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');
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}`);
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})`);
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');
138 console.error('\n❌ Export failed:', error.message);
139 console.error(error.stack);
142 // Close MySQL connection
144 const WHMCSMysqlService = require('../services/whmcsMysqlService');
145 const whmcs = new WHMCSMysqlService();
148 // Ignore close errors
153// Run if called directly
154if (require.main === module) {
158module.exports = { fetchWHMCSData };