Real-time Chat System
Relevant source files
The following files were used as context for generating this wiki page:
The Real-time Chat System is a core module within the ELMEC application designed to facilitate instantaneous communication between customers, agents, and administrators. Built with a focus on a "WhatsApp-like" user experience, the system supports various message formats including text, images, audio, and file attachments, integrated directly with the project's request management workflow.
The system leverages Supabase Realtime for low-latency message delivery (typically < 1s) and uses a Context-based architecture in React Native to manage global chat state, presence tracking, and optimistic UI updates. This ensures that users receive immediate feedback even before a message is confirmed by the backend database.
System Architecture
The chat system is built on a provider-consumer pattern using React Context API and integrates with Supabase's PostgreSQL database and Realtime engine.
Core Components and Logic
The architecture is centralized in the ChatProvider, which handles the lifecycle of realtime channels and global state.
- ChatContext: Manages the state for chat rooms, messages, typing indicators, and online user status. It provides methods for sending messages, creating rooms, and marking messages as read.
- Supabase Realtime: Uses PostgreSQL Change Data Capture (CDC) to broadcast
INSERTandUPDATEevents from themessagestable to connected clients. - Presence Tracking: Implements the
supabase.channel().on('presence')feature to track which users are currently online and who is actively typing in a specific room.
Sources: contexts/ChatContext.tsx:50-80, REPORTE_CHAT_MODULE.md:95-125
Data Flow Diagram
The following diagram illustrates the flow of a message from the sender through the Supabase Realtime engine to the recipient.
This flow ensures the sender sees the message immediately while the recipient receives it via a persistent WebSocket connection.
Sources: contexts/ChatContext.tsx:191-240, FIXES-APLICADOS.md:120-145
Database Schema and Models
The chat system relies on two primary tables: chat_rooms and messages. The system currently utilizes a "soft delete" mechanism and stores rich metadata in JSONB fields.
Message Table Structure
The messages table contains the content and metadata for every exchange. Note that several advanced columns require specific SQL migrations to be fully functional.
| Column | Type | Description |
|---|---|---|
id | UUID (PK) | Unique identifier for the message. |
chat_room_id | UUID (FK) | Reference to the parent chat room. |
sender_id | UUID (FK) | ID of the user who sent the message. |
message | TEXT | The actual text content or description. |
type | TEXT | Enum: 'text', 'image', 'audio', 'file', 'system'. |
file_url | TEXT | URL to the attachment in Supabase Storage. |
reply_to | UUID (FK) | Reference to another message ID for threaded replies. |
read_by | JSONB | Tracks which users have seen the message (default {}). |
is_deleted | BOOLEAN | Flag for soft deletion of messages. |
Sources: REPORTE_CHAT_MODULE.md:278-300, INSTRUCCIONES_CHAT_SQL.md:88-105
Chat Room Structure
Rooms can be standalone or linked to specific service requests.
| Field | Type | Description |
|---|---|---|
tipo | TEXT | Types: 'support', 'sales', 'general'. |
participants | UUID[] | Array of user IDs in the conversation. |
last_message | JSONB | Snapshot of the latest message for list previews. |
request_id | UUID (FK) | Optional link to the requests table. |
Sources: scripts/test-chat-module.js:95-120, REPORTE-EJECUCION-PRUEBAS.md:162-170
Realtime Features
Presence and Typing Indicators
The system uses Supabase Presence to track ephemeral state that does not need to be persisted in the database, such as "is typing" status.
The sendTypingIndicator function is throttled to prevent excessive network traffic while maintaining a responsive UI.
Sources: contexts/ChatContext.tsx:534-555, REPORTE_CHAT_MODULE.md:120-130
Multi-Channel Subscriptions
The system maintains separate channels for different scopes:
- Global Room Channel: Listens for new rooms where the current user is added as a participant.
- Specific Room Channels: Listens for new messages and updates (edits/deletions) within a specific conversation.
- Online Status Channel: A global presence channel to track online/offline status for the entire directory.
Sources: contexts/ChatContext.tsx:105-130, FIXES-APLICADOS.md:125-135
Functional Implementation
Message Handling Logic
Sending a message involves several steps, including session validation and optimistic state management.
const sendMessage = async (roomId, message, messageType = 'text', ...) => {
// 1. Session and Auth Check
if (!user || !session) throw new Error('Usuario no autenticado');
// 2. Optimistic UI Update
const tempId = `temp_${Date.now()}`;
setMessages(prev => ({ ...prev, [roomId]: [...prev[roomId], optimisticMsg] }));
// 3. Database Insertion
const { data, error } = await supabaseClient.from('messages').insert({ ... });
// 4. State Synchronization
if (data) {
setMessages(prev => updateOptimisticWithReal(prev, tempId, data));
}
};
Sources: contexts/ChatContext.tsx:370-450, TEST_REPORT.md:150-180
File Attachments and Storage
Attachments are handled by first uploading the binary data to the request-files or chat-files bucket in Supabase Storage. Once the upload is successful, the resulting public URL is saved in the file_url column of the messages table.
| Feature | Support Status | Requirement |
|---|---|---|
| Images | Partially Functional | Requires file_name column in DB. |
| Audio/Voice | Partially Functional | Requires audio_duration column in DB. |
| Documents | Partially Functional | Requires file_size column in DB. |
Sources: REPORTE_CHAT_MODULE.md:45-70, TEST_REPORT.md:105-130
Implementation Status and Validation
The chat module has been validated through extensive automated testing, though some features are currently blocked by database schema limitations.
Validation Metrics
- Code Quality: 95% complete with professional architecture.
- Functionality: 60% operative (Blocked features: Reply, Edit, Read Receipts, Metadata).
- Realtime Performance: Latency < 1s.
Sources: REPORTE_CHAT_MODULE.md:10-35, REPORTE-EJECUCION-PRUEBAS.md:20-40
SQL Migration Requirements
To enable 100% of the chat features, the following columns must be added to the messages table:
reply_to(UUID): Enables WhatsApp-style replies.file_name(TEXT) &file_size(INT): Enables proper attachment metadata.audio_duration(INT): Required for voice note progress bars.edited_at(TIMESTAMP): Tracks message modifications.read_by(JSONB): Enables the "double blue check" read receipts.
Sources: INSTRUCCIONES_CHAT_SQL.md:20-50, REPORTE_CHAT_MODULE.md:175-195
Conclusion
The Real-time Chat System provides a robust foundation for user engagement within the ELMEC platform. By combining optimistic UI updates with Supabase's Realtime infrastructure, it delivers a high-performance messaging experience. While the core engine is fully implemented, finalizing the database schema through the provided SQL migrations is essential to unlock advanced features like threaded replies and comprehensive file metadata.
Sources: REPORTE_CHAT_MODULE.md:320-340, VALIDACION-COMPLETA.md:210-230