UNPKG

skailan-conversations

Version:

Servicio de conversaciones y mensajería para Skailan

266 lines 10.4 kB
import { Channel } from "../entities/Channel"; import { v4 as uuidv4 } from "uuid"; export class ChannelConfigurationService { channelRepository; constructor(channelRepository) { this.channelRepository = channelRepository; } /** * Crea una nueva configuración de canal */ async createChannelConfig(request) { try { console.log(`🔧 Creando configuración de canal: ${request.type} para organización ${request.organizationId}`); // Validar configuración según el tipo this.validateChannelConfig(request.type, request.config); const channel = new Channel(uuidv4(), request.organizationId, request.type, request.config, request.status || "active", new Date(), new Date()); const savedChannel = await this.channelRepository.save(channel); console.log(`✅ Configuración de canal creada: ${savedChannel.id}`); return savedChannel; } catch (error) { console.error("❌ Error creando configuración de canal:", error); throw error; } } /** * Actualiza la configuración de un canal existente */ async updateChannelConfig(request) { try { console.log(`🔧 Actualizando configuración de canal: ${request.id}`); const existingChannel = await this.channelRepository.findById(request.id); if (!existingChannel) { throw new Error("Canal no encontrado"); } // Validar configuración si se proporciona if (request.config) { this.validateChannelConfig(existingChannel.type, request.config); } // Actualizar configuración if (request.config) { existingChannel.config = { ...existingChannel.config, ...request.config, }; } if (request.status) { existingChannel.status = request.status; } existingChannel.updatedAt = new Date(); const updatedChannel = await this.channelRepository.save(existingChannel); console.log(`✅ Configuración de canal actualizada: ${updatedChannel.id}`); return updatedChannel; } catch (error) { console.error("❌ Error actualizando configuración de canal:", error); throw error; } } /** * Obtiene la configuración de un canal específico */ async getChannelConfig(channelId, organizationId) { try { console.log(`🔍 Obteniendo configuración de canal: ${channelId}`); const channel = await this.channelRepository.findById(channelId); if (!channel) { console.log(`❌ Canal no encontrado: ${channelId}`); return null; } console.log(`✅ Configuración de canal obtenida: ${channel.id}`); return channel; } catch (error) { console.error("❌ Error obteniendo configuración de canal:", error); throw error; } } /** * Obtiene todas las configuraciones de canales de una organización */ async getAllChannelConfigs(organizationId) { try { console.log(`🔍 Obteniendo todas las configuraciones de canales para organización: ${organizationId}`); const channels = await this.channelRepository.findAll(organizationId); console.log(`✅ Configuraciones obtenidas: ${channels.length} canales`); return channels; } catch (error) { console.error("❌ Error obteniendo configuraciones de canales:", error); throw error; } } /** * Obtiene la configuración de Telegram para una organización */ async getTelegramConfig(organizationId) { try { console.log(`🔍 Obteniendo configuración de Telegram para organización: ${organizationId}`); const channels = await this.channelRepository.findAll(organizationId); const telegramChannel = channels.find((channel) => channel.type === "telegram"); if (!telegramChannel) { console.log(`❌ Configuración de Telegram no encontrada para organización: ${organizationId}`); return null; } console.log(`✅ Configuración de Telegram obtenida: ${telegramChannel.id}`); return telegramChannel; } catch (error) { console.error("❌ Error obteniendo configuración de Telegram:", error); throw error; } } /** * Configura específicamente un canal de Telegram */ async configureTelegramChannel(organizationId, botToken, options) { try { console.log(`🔧 Configurando canal de Telegram para organización: ${organizationId}`); // Verificar si ya existe una configuración de Telegram const existingConfig = await this.getTelegramConfig(organizationId); if (existingConfig) { // Actualizar configuración existente return this.updateChannelConfig({ id: existingConfig.id, organizationId, config: { telegram: { botToken, webhookUrl: options?.webhookUrl, botUsername: options?.botUsername, autoResponse: options?.autoResponse, welcomeMessage: options?.welcomeMessage, }, }, }); } else { // Crear nueva configuración return this.createChannelConfig({ organizationId, type: "telegram", config: { telegram: { botToken, webhookUrl: options?.webhookUrl, botUsername: options?.botUsername, autoResponse: options?.autoResponse, welcomeMessage: options?.welcomeMessage, }, }, }); } } catch (error) { console.error("❌ Error configurando canal de Telegram:", error); throw error; } } /** * Valida la configuración de un canal según su tipo */ validateChannelConfig(type, config) { console.log(`🔍 Validando configuración de canal tipo: ${type}`); switch (type) { case "telegram": this.validateTelegramConfig(config.telegram); break; case "whatsapp": this.validateWhatsAppConfig(config.whatsapp); break; case "email": this.validateEmailConfig(config.email); break; default: throw new Error(`Tipo de canal no soportado: ${type}`); } console.log(`✅ Configuración de canal válida: ${type}`); } /** * Valida la configuración específica de Telegram */ validateTelegramConfig(telegramConfig) { if (!telegramConfig) { throw new Error("Configuración de Telegram requerida"); } if (!telegramConfig.botToken) { throw new Error("Bot token de Telegram requerido"); } if (telegramConfig.botToken.length < 10) { throw new Error("Bot token de Telegram inválido"); } // Validar formato del bot token (debe contener ':') if (!telegramConfig.botToken.includes(":")) { throw new Error("Formato de bot token de Telegram inválido"); } } /** * Valida la configuración específica de WhatsApp */ validateWhatsAppConfig(whatsappConfig) { if (!whatsappConfig) { throw new Error("Configuración de WhatsApp requerida"); } if (!whatsappConfig.phoneNumberId) { throw new Error("Phone Number ID de WhatsApp requerido"); } if (!whatsappConfig.accessToken) { throw new Error("Access Token de WhatsApp requerido"); } } /** * Valida la configuración específica de Email */ validateEmailConfig(emailConfig) { if (!emailConfig) { throw new Error("Configuración de Email requerida"); } if (!emailConfig.smtpHost) { throw new Error("SMTP Host requerido"); } if (!emailConfig.smtpPort || emailConfig.smtpPort < 1 || emailConfig.smtpPort > 65535) { throw new Error("Puerto SMTP inválido"); } if (!emailConfig.username) { throw new Error("Username de email requerido"); } if (!emailConfig.password) { throw new Error("Password de email requerido"); } } /** * Elimina la configuración de un canal */ async deleteChannelConfig(channelId, organizationId) { try { console.log(`🗑️ Eliminando configuración de canal: ${channelId}`); const channel = await this.channelRepository.findById(channelId); if (!channel) { throw new Error("Canal no encontrado"); } await this.channelRepository.delete(channelId, organizationId); console.log(`✅ Configuración de canal eliminada: ${channelId}`); } catch (error) { console.error("❌ Error eliminando configuración de canal:", error); throw error; } } /** * Verifica si un canal está activo */ async isChannelActive(channelId, organizationId) { try { const channel = await this.channelRepository.findById(channelId); return channel?.status === "active"; } catch (error) { console.error("❌ Error verificando estado del canal:", error); return false; } } } //# sourceMappingURL=ChannelConfigurationService.js.map