skailan-contacts
Version:
Servicio de gestión de contactos para Skailan
138 lines • 6.06 kB
JavaScript
import { CreateContactFromConversation } from '../../app/use-cases/CreateContactFromConversation';
export class ConversationIntegrationServiceImpl {
contactRepository;
platformRepository;
conversationsServiceUrl;
constructor(contactRepository, platformRepository, conversationsServiceUrl = process.env.CONVERSATIONS_SERVICE_URL || 'http://localhost:3007') {
this.contactRepository = contactRepository;
this.platformRepository = platformRepository;
this.conversationsServiceUrl = conversationsServiceUrl;
}
async handleNewConversation(conversationData) {
try {
const createContactFromConversationUseCase = new CreateContactFromConversation(this.contactRepository, this.platformRepository);
const contact = await createContactFromConversationUseCase.execute(conversationData);
// Disparar creación de Lead en CRM si el contacto tiene email o teléfono
if (contact.email || contact.phone) {
await this.triggerLeadCreation(contact);
}
return contact;
}
catch (error) {
console.error('Error handling new conversation:', error);
throw new Error(`Failed to handle new conversation: ${error}`);
}
}
async findContactByPlatformId(platformId, platform, organizationId) {
try {
const platforms = await this.platformRepository.findByPlatform(platform, organizationId);
const targetPlatform = platforms.find(p => p.platformUserId === platformId);
if (!targetPlatform) {
return null;
}
return await this.contactRepository.findById(targetPlatform.contactId, organizationId);
}
catch (error) {
console.error('Error finding contact by platform ID:', error);
return null;
}
}
async getContactPlatforms(contactId, organizationId) {
try {
const platforms = await this.platformRepository.findActiveByContactId(contactId, organizationId);
return platforms.map(platform => ({
id: platform.id,
platform: platform.platform,
platformUserId: platform.platformUserId,
platformUsername: platform.platformUsername,
isActive: platform.isActive,
isPrimary: platform.isPrimary,
config: platform.config
}));
}
catch (error) {
console.error('Error getting contact platforms:', error);
return [];
}
}
async sendMessageToContact(contactId, platform, message, organizationId) {
try {
// Buscar el contacto
const contact = await this.contactRepository.findById(contactId, organizationId);
if (!contact) {
throw new Error('Contact not found.');
}
// Buscar la plataforma específica
const targetPlatform = contact.getPlatformByType(platform);
if (!targetPlatform) {
throw new Error(`Platform ${platform} not found for this contact.`);
}
if (!targetPlatform.isActive) {
throw new Error(`Platform ${platform} is not active for this contact.`);
}
// Enviar mensaje a través del servicio de conversaciones
const response = await fetch(`${this.conversationsServiceUrl}/conversations/send-message`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-tenant-id': organizationId
},
body: JSON.stringify({
contactId: contactId,
platform: platform,
platformUserId: targetPlatform.platformUserId,
message: message,
senderType: 'user'
})
});
if (!response.ok) {
throw new Error(`Failed to send message: ${response.statusText}`);
}
return await response.json();
}
catch (error) {
console.error('Error sending message to contact:', error);
throw new Error(`Failed to send message to contact: ${error}`);
}
}
async triggerLeadCreation(contact) {
try {
const crmServiceUrl = process.env.CRM_SERVICE_URL || 'http://localhost:3008';
const leadData = {
name: contact.name || 'Unknown',
email: contact.email,
phone: contact.phone,
source: 'conversation',
notes: `Contact created from conversation. Platforms: ${contact.communicationPlatforms.map(p => p.platform).join(', ')}`,
metadata: {
contactId: contact.id,
externalId: contact.externalId,
platforms: contact.communicationPlatforms.map(p => ({
platform: p.platform,
platformUserId: p.platformUserId,
platformUsername: p.platformUsername
}))
}
};
const response = await fetch(`${crmServiceUrl}/leads`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-tenant-id': contact.organizationId
},
body: JSON.stringify(leadData)
});
if (!response.ok) {
console.error('Failed to trigger lead creation:', response.statusText);
}
else {
console.log(`Lead created for contact ${contact.id}`);
}
}
catch (error) {
console.error('Error triggering lead creation:', error);
// No fallamos si no se puede crear el lead
}
}
}
//# sourceMappingURL=ConversationIntegrationService.js.map