Backend Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The backend for the ElmecV2 Mobile App is built entirely on Supabase, a Backend-as-a-Service (BaaS) platform. This serverless architecture provides a robust and scalable foundation for the application's core functionalities, including data persistence, user authentication, real-time communication, and file storage. By leveraging Supabase, the project centralizes backend logic and infrastructure, allowing the frontend application to interact directly with a suite of managed services via a unified API.
The architecture is designed around Supabase's integrated services: a PostgreSQL database for data storage, GoTrue for authentication and user management, Realtime for live data synchronization (primarily for the chat module), and Storage for handling file uploads. Security is enforced at the database level using PostgreSQL's Row Level Security (RLS), ensuring that users can only access data they are permitted to see.
Core Components
The backend is composed of several key Supabase services that work in concert. The mobile application communicates with these services using the Supabase client library.
This diagram shows the high-level architecture where the React Native app interacts with various Supabase services through the Supabase client.
Sources: README.md, VALIDACION-COMPLETA.md
Supabase Project Configuration
The connection to the Supabase backend is configured through environment variables. A setup script and detailed instructions guide the configuration process.
| Variable | Description | Example Value |
|---|---|---|
EXPO_PUBLIC_SUPABASE_URL | The unique URL for the Supabase project. | https://pdpqkgrqlubyzkcivifk.supabase.co |
EXPO_PUBLIC_SUPABASE_ANON_KEY | The public, anonymous key for accessing the Supabase API. | eyJhbGciOi... |
SUPABASE_SERVICE_ROLE_KEY | A secret key for administrative tasks, used in setup scripts. | (secret) |
Sources: supabase/setup-instructions.md:14-18, scripts/setup-supabase-complete.js:11-18, DEPLOY-NETLIFY.md
Database Schema
The application's data is stored in a PostgreSQL database managed by Supabase. The schema is defined through a series of SQL migration files and includes tables for managing users, requests, chats, and more.
The diagram below illustrates the primary entities and their relationships.
Key Tables
| Table | Description | Verified in |
|---|---|---|
users | Stores user profile information, linked to auth.users. | scripts/setup-supabase-complete.js:200-208 |
requests | Core table for managing user-submitted support or sales requests. | REPORTE_PRUEBAS_REQUESTS_CRUD.md |
chat_rooms | Defines a conversation space, typically between two or more users. | REPORTE_CHAT_MODULE.md |
messages | Contains individual chat messages, linked to a chat_room. | REPORTE_CHAT_MODULE.md |
notifications | Stores in-app notifications for users. | REPORTE-EJECUCION-PRUEBAS.md |
calculator_sessions | Stores data related to the in-app calculator feature. | scripts/setup-supabase-complete.js:200-208 |
requests Table Schema
This table is central to the application. Note that several columns (archivos, feedback, rating) were identified as missing in initial tests and required a database migration to be added.
| Column | Type | Description |
|---|---|---|
id | uuid | Primary Key. |
usuario_id | uuid | Foreign key to users table (the creator). |
agente_id | uuid | Foreign key to users table (the assigned agent). |
titulo | text | The title of the request. |
mensaje | text | The detailed message body of the request. |
estatus | text | The current status (e.g., 'nuevo', 'asignado', 'resuelto'). |
prioridad | text | The priority level (e.g., 'baja', 'media', 'alta'). |
archivos | text[] | An array of URLs pointing to files in Supabase Storage. |
feedback | text | User-provided feedback after resolution. |
rating | integer | A 1-5 star rating from the user. |
Sources: REPORTE_PRUEBAS_REQUESTS_CRUD.md, REPORTE_FINAL_VALIDACION.md
Authentication
User authentication is handled by Supabase's GoTrue service. It manages user sign-up, login, and session management using JWTs. The application provides a set of demo users for testing purposes, which are created via an automated script.
This diagram shows the login flow, from user input to redirection upon successful authentication.
Sources: FIXES-APLICADOS.md:10-23, scripts/setup-supabase-complete.js:50-80
Demo Users
The setup-supabase-complete.js script creates the following users for development and testing:
| Role | Password | |
|---|---|---|
| Admin | i.pineda@elmec.com.mx | Elmec2024!Admin |
| Agent | j.gonzalez@elmec.com.mx | Elmec2024!Agent |
| Customer | cliente@gmail.com | Elmec2024!Client |
| Customer | rgarciavital@gmail.com | Elmec2024!Client |
Sources: scripts/setup-supabase-complete.js:52-80, STATUS-DEPLOY.md
Real-time Functionality
The chat module leverages Supabase Realtime to provide instant messaging. The frontend subscribes to postgres_changes events on the messages and chat_rooms tables. When a new message is inserted or updated in the database, Supabase pushes the change to all subscribed clients.
// Source: FIXES-APLICADOS.md (describing contexts/ChatContext.tsx)
const setupRealtimeSubscription = (roomId: string) => {
const channel = supabase
.channel(`chat_room_${roomId}`)
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'messages',
filter: `chat_room_id=eq.${roomId}`,
}, async payload => {
// Handle new messages in real-time
})
.subscribe();
};
This implementation allows for features like optimistic UI updates, typing indicators (via Presence), and unread message counters.
Sources: FIXES-APLICADOS.md:120-137, REPORTE_CHAT_MODULE.md
File Storage
File attachments for requests are handled by Supabase Storage. The system is configured to use a private bucket named request-files.
The upload process is as follows:
- The user selects a file in the mobile app.
- The app uploads the file directly to the
request-filesbucket in Supabase Storage. - Upon successful upload, Supabase returns a public or signed URL for the file.
- This URL is then stored in the
archivosarray column of the corresponding row in therequeststable.
This flowchart shows the process of uploading a file and associating it with a request.
Sources: TEST_REPORT.md, RESUMEN_FINAL.md
Security: Row Level Security (RLS)
A critical aspect of the backend architecture is the use of Row Level Security (RLS) to control data access. RLS policies are SQL rules defined on database tables that filter which rows a user can view, insert, update, or delete based on their session information (e.g., auth.uid()).
RLS Policies for requests Table
| Policy Name | Description |
|---|---|
authenticated_users_can_create_requests | Allows any authenticated user to create a new request. |
users_can_view_own_requests | Allows users to view only the requests they have created. |
agents_can_view_assigned_requests | Allows agents to view requests assigned to them. |
admins_can_view_all_requests | Allows users with an 'admin' role to view all requests. |
Sources: FIXES-APLICADOS.md:213-218, VALIDACION-COMPLETA.md
RLS Policies for storage.objects (request-files bucket)
| Action | Policy Name | Description |
|---|---|---|
INSERT | Users can upload files | Allows authenticated users to upload files to the request-files bucket. |
SELECT | Users can read files | Allows authenticated users to read/download files from the bucket. |
DELETE | Users can delete their files | Allows users to delete only the files they own (owner = auth.uid()). |
Sources: TEST_REPORT.md, RESUMEN_FINAL.md
Summary
The backend of ElmecV2 is a modern, serverless architecture built on Supabase. It effectively outsources complex backend infrastructure, providing a scalable and secure platform for the application's needs. Key features include a PostgreSQL database with RLS for fine-grained security, real-time capabilities for live features like chat, integrated authentication, and object storage for file management. This BaaS approach allows developers to focus on frontend features while relying on a robust, managed backend.