UNPKG

skailan-conversations

Version:

Servicio de conversaciones y mensajería para Skailan

63 lines 3.24 kB
import { Conversation } from "../../domain/entities/Conversation"; import axios from "axios"; // Import axios for HTTP calls to contacts service import { v4 as uuidv4 } from "uuid"; export class StartConversation { conversationRepository; channelRepository; constructor(conversationRepository, channelRepository) { this.conversationRepository = conversationRepository; this.channelRepository = channelRepository; } async execute(request) { const { organizationId, channelId, contactExternalId, contactName, contactEmail, contactPhone, } = request; const channel = await this.channelRepository.findById(channelId); if (!channel) { throw new Error("Channel not found."); } // Interact with the new Contacts Service const CONTACTS_SERVICE_URL = process.env.CONTACTS_SERVICE_URL || "http://localhost:3009"; let contactId; try { // Try to find contact by externalId first const findContactResponse = await axios.get(`${CONTACTS_SERVICE_URL}/contacts?externalId=${contactExternalId}`, { headers: { "x-tenant-id": organizationId }, }); if (findContactResponse.data && Array.isArray(findContactResponse.data) && findContactResponse.data.length > 0) { contactId = findContactResponse.data[0].id; } else { // If not found, create a new contact const createContactResponse = await axios.post(`${CONTACTS_SERVICE_URL}/contacts`, { externalId: contactExternalId, name: contactName, email: contactEmail, phone: contactPhone, }, { headers: { "x-tenant-id": organizationId }, }); contactId = createContactResponse.data.id; } } catch (error) { console.error("Error interacting with Contacts Service:", error.response?.data || error.message); throw new Error(`Failed to get or create contact: ${error.response?.data?.error || error.message}`); } // Check if an active conversation already exists for this channel and contact const existingConversations = await this.conversationRepository.findAll(organizationId, channelId, contactId); const activeConversation = existingConversations.find((conv) => conv.status === "open" || conv.status === "pending"); if (activeConversation) { return activeConversation; // Return existing active conversation } const newConversation = new Conversation(uuidv4(), organizationId, channelId, contactId, "open", // Default status null, // No assigned user initially new Date(), // lastMessageAt new Date(), new Date() // updatedAt ); // Temporarily store contactId in metadata or a dedicated field if needed for conversation context // For now, we'll just ensure the contact exists in the contacts service return this.conversationRepository.save(newConversation); } } //# sourceMappingURL=StartConversation.js.map