Files
conversation-layer/whatsapp-router/src/index.ts
google-labs-jules[bot] 2ea837c2ae Refactor: Modularize whatsapp-router interactions
This commit introduces a significant refactoring to the whatsapp-router service to improve modularity and extend its capabilities for interacting with OpenWA (nucleo-whatsapp).

Key changes include:

1.  **Message Processing Logic**:
    *   Created a new `messageProcessor.ts` module.
    *   Moved message mapping (`mapWhatsAppMessageToMsg`), message addition to conversations (`processIncomingMessageForConversation`), and audio transcription handling (`handleAudioMessageTranscription`) into this new module.
    *   Updated `store/conversation.ts` and `webhook.ts` to utilize `messageProcessor.ts`, streamlining their responsibilities.

2.  **OpenWA Client (`nucleoClient.ts`)**:
    *   Introduced `nucleoClient.ts`, a dedicated module for encapsulating API calls to OpenWA.
    *   Implemented functions for various OpenWA commands:
        *   Sending text, image, and file messages.
        *   Fetching chat and contact information.
        *   Creating groups.
        *   Managing the blocklist (get, block, unblock).
        *   Listing all chats and fetching messages for a specific chat.
    *   Includes error handling and basic typing for API responses.

3.  **New API Endpoints (`routes/nucleoActions.ts`)**:
    *   Created `nucleoActions.ts` to expose the functionalities of `nucleoClient.ts` via a new set of HTTP API endpoints.
    *   Endpoints cover all implemented client functions, with request validation and robust error handling.
    *   These routes are grouped under the `/nucleo` base path.

4.  **Route Registration**:
    *   Registered the new `/nucleo` routes in the main `index.ts` file.

5.  **Conversation Store and Routes Review**:
    *   Reviewed and confirmed that `store/conversation.ts` and `routes/conversations.ts` are correctly integrated with the new `messageProcessor.ts` and remain focused on their core responsibilities.

This refactoring enhances the structure of `whatsapp-router`, making it easier to maintain and extend. It also provides a comprehensive set of API endpoints for more granular control over OpenWA functionalities.
2025-06-07 02:49:50 +00:00

68 lines
2.0 KiB
TypeScript

import express from 'express';
import dotenv from 'dotenv';
import { registerConversationRoutes } from './routes/conversations';
import {
registerWebhookRoutes,
clearWebhooks,
registerWebhook,
waitForGateway,
WebhookConfig,
} from './webhook';
import nucleoActionsRouter from './routes/nucleoActions'; // New import
dotenv.config();
console.log(`Environment: ${process.env.NODE_ENV}`);
console.log(`Port: ${process.env.PORT}`);
console.log(`LLM Agent URL: ${process.env.LLM_AGENT_URL}`);
console.log(`Open WA URL: ${process.env.OPEN_WA_URL}`);
console.log(`Webhook URL: ${process.env.WEBHOOK_URL}`);
console.log(`Conversation Agent URL: ${process.env.CONVERSATION_AGENT_URL}`);
console.log(`Planilla Agent URL: ${process.env.PLANILLA_AGENT_URL}`);
console.log(`GEMINI API Key: ${process.env.GEMINI_API_KEY}`);
if (process.env.NODE_ENV === 'development') {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
if (
process.env.NODE_ENV !== 'development' &&
process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0'
) {
throw new Error('NODE_TLS_REJECT_UNAUTHORIZED está activado en producción. Abortando.');
}
const app = express();
app.use(express.json());
const port = Number(process.env.PORT) || 3001;
const agentUrl = process.env.LLM_AGENT_URL as string | undefined;
const openWaUrl = process.env.OPEN_WA_URL as string | undefined;
const config: WebhookConfig = {
API_URL: openWaUrl || '',
MAX_ATTEMPTS: parseInt(process.env.MAX_ATTEMPTS || '100', 10),
RETRY_MS: parseInt(process.env.RETRY_MS || '2000', 10),
};
registerConversationRoutes(app, openWaUrl);
registerWebhookRoutes(app, config, openWaUrl, agentUrl);
// Register new nucleoActions routes
app.use('/nucleo', nucleoActionsRouter); // New line
app.listen(port, async () => {
console.log(`WhatsApp router listening on ${port}`);
try {
await waitForGateway(config);
await clearWebhooks(config);
await registerWebhook(config, port);
} catch (err: any) {
console.error('Webhook setup failed:', err.message);
}
});