pame-core-cli
Version:
PAME.AI Core Operating System CLI - Open Source AI Platform for Agentic Commerce
351 lines • 15.2 kB
JavaScript
import { Command } from 'commander';
import chalk from 'chalk';
import inquirer from 'inquirer';
import { ConfigManager } from '../config/config-manager.js';
const configManager = new ConfigManager();
class WhatsApp360DialogManager {
config;
constructor() {
this.config = this.loadConfig();
}
loadConfig() {
const config = configManager.getConfig();
return config.whatsapp || {
apiKey: process.env.DIALOG360_API_KEY_56949306840 || '',
phoneNumber: '56949306840',
webhookSecret: process.env.DIALOG360_WEBHOOK_SECRET || '',
partnerId: 'ljKnKpPA',
baseUrl: 'https://waba-v2.360dialog.io/v1',
enabled: false,
lastUpdated: new Date().toISOString()
};
}
saveConfig() {
const config = configManager.getConfig();
config.whatsapp = this.config;
configManager.saveConfig(config);
}
async enableWhatsApp(platform) {
console.log(chalk.blue(`🔄 Enabling WhatsApp for ${platform}...`));
// Validate platform
const validPlatforms = ['app', 'core', 'www', 'learn', 'store'];
if (!validPlatforms.includes(platform)) {
throw new Error(`Invalid platform: ${platform}. Valid platforms: ${validPlatforms.join(', ')}`);
}
// Check if API key is configured
if (!this.config.apiKey) {
console.log(chalk.yellow('⚠️ API key not configured. Please run configure command first.'));
return;
}
// Test connection
try {
await this.testConnection();
console.log(chalk.green('✅ Connection test successful'));
}
catch (error) {
console.log(chalk.red('❌ Connection test failed:'), error);
return;
}
// Enable for platform
this.config.enabled = true;
this.config.lastUpdated = new Date().toISOString();
this.saveConfig();
console.log(chalk.green(`✅ WhatsApp enabled for ${platform}.pame.ai`));
console.log(chalk.blue(`📱 Phone number: ${this.config.phoneNumber}`));
console.log(chalk.blue(`🔗 Webhook URL: https://${platform}.pame.ai/api/webhooks/360dialog/number/${this.config.phoneNumber}`));
}
async disableWhatsApp(platform) {
console.log(chalk.blue(`🔄 Disabling WhatsApp for ${platform}...`));
this.config.enabled = false;
this.config.lastUpdated = new Date().toISOString();
this.saveConfig();
console.log(chalk.yellow(`⚠️ WhatsApp disabled for ${platform}.pame.ai`));
}
async configureWhatsApp() {
console.log(chalk.blue('🔧 Configuring WhatsApp settings...'));
const questions = [
{
type: 'input',
name: 'apiKey',
message: '360dialog API Key:',
default: this.config.apiKey,
validate: (input) => input.length > 0 || 'API key is required'
},
{
type: 'input',
name: 'phoneNumber',
message: 'WhatsApp Phone Number:',
default: this.config.phoneNumber,
validate: (input) => {
const formatted = input.replace(/\D/g, '');
return formatted.length >= 10 || 'Please enter a valid phone number';
}
},
{
type: 'input',
name: 'webhookSecret',
message: 'Webhook Secret:',
default: this.config.webhookSecret,
validate: (input) => input.length > 0 || 'Webhook secret is required'
},
{
type: 'input',
name: 'baseUrl',
message: '360dialog Base URL:',
default: this.config.baseUrl
}
];
const answers = await inquirer.prompt(questions);
this.config = {
...this.config,
...answers,
lastUpdated: new Date().toISOString()
};
this.saveConfig();
console.log(chalk.green('✅ WhatsApp configuration saved'));
// Test connection
try {
await this.testConnection();
console.log(chalk.green('✅ Connection test successful'));
}
catch (error) {
console.log(chalk.red('❌ Connection test failed:'), error);
}
}
async showStatus() {
console.log(chalk.blue('📊 WhatsApp Status'));
console.log('='.repeat(50));
console.log(chalk.white('Configuration:'));
console.log(` Status: ${this.config.enabled ? chalk.green('Enabled') : chalk.red('Disabled')}`);
console.log(` Phone Number: ${chalk.cyan(this.config.phoneNumber)}`);
console.log(` Partner ID: ${chalk.cyan(this.config.partnerId)}`);
console.log(` API Key: ${this.config.apiKey ? chalk.green('Configured') : chalk.red('Not configured')}`);
console.log(` Webhook Secret: ${this.config.webhookSecret ? chalk.green('Configured') : chalk.red('Not configured')}`);
console.log(` Last Updated: ${chalk.gray(this.config.lastUpdated)}`);
console.log('\n' + chalk.white('Endpoints:'));
console.log(` Partner Webhook: ${chalk.cyan('https://app.pame.ai/api/webhooks/360dialog/partner')}`);
console.log(` Number Webhook: ${chalk.cyan(`https://app.pame.ai/api/webhooks/360dialog/number/${this.config.phoneNumber}`)}`);
console.log(` Onboarding Callback: ${chalk.cyan('https://app.pame.ai/api/360dialog/onboarding/callback')}`);
// Test connection if enabled
if (this.config.enabled && this.config.apiKey) {
try {
console.log('\n' + chalk.white('Connection Test:'));
await this.testConnection();
console.log(` Status: ${chalk.green('Connected')}`);
}
catch (error) {
console.log(` Status: ${chalk.red('Failed')}`);
console.log(` Error: ${chalk.red(error instanceof Error ? error.message : 'Unknown error')}`);
}
}
}
async showAnalytics(days = 30) {
console.log(chalk.blue(`📈 WhatsApp Analytics (Last ${days} days)`));
console.log('='.repeat(50));
try {
const analytics = await this.getAnalytics(days);
console.log(chalk.white('Message Statistics:'));
console.log(` Total Messages: ${chalk.cyan(analytics.totalMessages.toLocaleString())}`);
console.log(` Delivered: ${chalk.green(analytics.messagesDelivered.toLocaleString())}`);
console.log(` Read: ${chalk.blue(analytics.messagesRead.toLocaleString())}`);
console.log(` Failed: ${chalk.red(analytics.messagesFailed.toLocaleString())}`);
console.log('\n' + chalk.white('Engagement:'));
console.log(` Active Conversations: ${chalk.cyan(analytics.activeConversations.toLocaleString())}`);
console.log(` Webhook Events: ${chalk.cyan(analytics.webhookEvents.toLocaleString())}`);
console.log('\n' + chalk.white('Templates:'));
console.log(` Approved: ${chalk.green(analytics.templateApprovals.toLocaleString())}`);
console.log(` Rejected: ${chalk.red(analytics.templateRejections.toLocaleString())}`);
console.log('\n' + chalk.white('Activity:'));
console.log(` Last Activity: ${chalk.gray(analytics.lastActivity)}`);
// Calculate delivery rate
const deliveryRate = analytics.totalMessages > 0
? ((analytics.messagesDelivered / analytics.totalMessages) * 100).toFixed(1)
: '0';
console.log(` Delivery Rate: ${chalk.cyan(deliveryRate + '%')}`);
}
catch (error) {
console.log(chalk.red('❌ Failed to fetch analytics:'), error);
}
}
async testConnection() {
if (!this.config.apiKey) {
throw new Error('API key not configured');
}
const response = await fetch(`${this.config.baseUrl}/account`, {
headers: {
'D360-API-KEY': this.config.apiKey
}
});
if (!response.ok) {
throw new Error(`API test failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
console.log(chalk.green('✅ Account verified:'), data.display_name || 'Unknown');
}
async sendTestMessage(to, message) {
console.log(chalk.blue(`📱 Sending test message to ${to}...`));
if (!this.config.apiKey) {
throw new Error('API key not configured');
}
const response = await fetch('https://app.pame.ai/api/whatsapp/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
to,
message,
type: 'text'
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Send failed: ${error.error || 'Unknown error'}`);
}
const result = await response.json();
console.log(chalk.green('✅ Message sent successfully'));
console.log(` Message ID: ${chalk.cyan(result.messageId)}`);
console.log(` Status: ${chalk.cyan(result.status)}`);
}
async configureWebhook(url) {
console.log(chalk.blue('🔗 Configuring webhook...'));
if (!this.config.apiKey) {
throw new Error('API key not configured');
}
const webhookUrl = url || `https://app.pame.ai/api/webhooks/360dialog/number/${this.config.phoneNumber}`;
const response = await fetch(`${this.config.baseUrl}/configs/webhook`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'D360-API-KEY': this.config.apiKey
},
body: JSON.stringify({
url: webhookUrl,
events: [
'message.received',
'message.sent',
'message.delivered',
'message.read',
'message.failed'
]
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Webhook configuration failed: ${response.status} - ${error}`);
}
console.log(chalk.green('✅ Webhook configured successfully'));
console.log(` URL: ${chalk.cyan(webhookUrl)}`);
}
async getAnalytics(days) {
// In a real implementation, this would fetch from your analytics database
// For now, return mock data
return {
totalMessages: Math.floor(Math.random() * 10000),
messagesDelivered: Math.floor(Math.random() * 9500),
messagesRead: Math.floor(Math.random() * 8000),
messagesFailed: Math.floor(Math.random() * 500),
activeConversations: Math.floor(Math.random() * 1000),
templateApprovals: Math.floor(Math.random() * 50),
templateRejections: Math.floor(Math.random() * 10),
webhookEvents: Math.floor(Math.random() * 15000),
lastActivity: new Date().toISOString()
};
}
}
export function createWhatsAppCommand() {
const whatsappManager = new WhatsApp360DialogManager();
const command = new Command('whatsapp');
command
.description('Manage WhatsApp integration via 360dialog')
.addCommand(new Command('enable')
.description('Enable WhatsApp for a platform')
.argument('<platform>', 'Platform to enable (app, core, www, learn, store)')
.action(async (platform) => {
try {
await whatsappManager.enableWhatsApp(platform);
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}))
.addCommand(new Command('disable')
.description('Disable WhatsApp for a platform')
.argument('<platform>', 'Platform to disable')
.action(async (platform) => {
try {
await whatsappManager.disableWhatsApp(platform);
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}))
.addCommand(new Command('configure')
.description('Configure WhatsApp settings')
.action(async () => {
try {
await whatsappManager.configureWhatsApp();
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}))
.addCommand(new Command('status')
.description('Show WhatsApp status and configuration')
.action(async () => {
try {
await whatsappManager.showStatus();
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}))
.addCommand(new Command('analytics')
.description('Show WhatsApp analytics')
.option('-d, --days <days>', 'Number of days to analyze', '30')
.action(async (options) => {
try {
await whatsappManager.showAnalytics(parseInt(options.days));
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}))
.addCommand(new Command('test')
.description('Test WhatsApp connection and send a test message')
.option('-t, --to <number>', 'Phone number to send test message to')
.option('-m, --message <text>', 'Test message to send', 'Hello from PAME.AI! This is a test message.')
.action(async (options) => {
try {
if (options.to) {
await whatsappManager.sendTestMessage(options.to, options.message);
}
else {
await whatsappManager.testConnection();
}
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}))
.addCommand(new Command('webhook')
.description('Configure webhook URL')
.option('-u, --url <url>', 'Custom webhook URL')
.action(async (options) => {
try {
await whatsappManager.configureWebhook(options.url);
}
catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : 'Unknown error');
process.exit(1);
}
}));
return command;
}
//# sourceMappingURL=whatsapp-360dialog.js.map