Overview
Trazea uses a PostgreSQL database hosted on Supabase with 17 main tables organized into functional domains. The database implements Row Level Security (RLS) for multi-tenancy and role-based access control, along with triggers for automatic audit logging.Database Domains
Table Schemas
User Management Domain
usuarios (Users)
Stores user accounts with approval workflow.
| Column | Type | Description |
|---|---|---|
id_usuario | uuid | Primary key (references auth.users) |
nombre_completo | text | Full name |
email | text | Email address |
id_rol | uuid | Foreign key to roles |
aprobado | boolean | Approval status (default: false) |
aprobado_por | uuid | Admin who approved (nullable) |
fecha_aprobacion | timestamptz | Approval timestamp (nullable) |
motivo_rechazo | text | Rejection reason (nullable) |
created_at | timestamptz | Account creation timestamp |
id_rol→roles.id_rolaprobado_por→usuarios.id_usuario- One-to-many with
usuarios_localizacion
- Users can read their own profile
- Admins can read all users
- Only admins can approve/reject users
roles (Roles)
Defines user roles with granular permissions.
| Column | Type | Description |
|---|---|---|
id_rol | uuid | Primary key |
nombre_rol | text | Role name (admin, tecnico, superuser) |
permisos | jsonb | Permissions object |
created_at | timestamptz | Creation timestamp |
- admin: Full permissions
- superuser: Most permissions except user management
- tecnico: View and create, limited edit/delete
usuarios_localizacion (User-Location Assignment)
Junction table for multi-location access.
| Column | Type | Description |
|---|---|---|
id_usuario | uuid | Foreign key to usuarios |
id_localizacion | uuid | Foreign key to localizacion |
created_at | timestamptz | Assignment timestamp |
(id_usuario, id_localizacion)
RLS: Users can only see data for their assigned locations.
admin_notifications (Admin Subscriptions)
Tracks admin notification preferences.
| Column | Type | Description |
|---|---|---|
id_admin | uuid | Foreign key to usuarios |
tipo_notificacion | text | Notification type |
activo | boolean | Subscription status |
Location Domain
localizacion (Locations)
Physical locations (workshops, warehouses).
| Column | Type | Description |
|---|---|---|
id_localizacion | uuid | Primary key |
nombre | text | Location name |
direccion | text | Physical address |
telefono | text | Contact phone |
activo | boolean | Active status |
created_at | timestamptz | Creation timestamp |
Inventory Domain
repuestos (Spare Parts)
Centralized spare parts catalog.
| Column | Type | Description |
|---|---|---|
id_repuesto | uuid | Primary key |
referencia | text | Unique part reference/SKU |
nombre | text | Part name |
tipo | text | Part type/category |
marca | text | Brand/manufacturer |
descripcion | text | Detailed description |
descontinuado | boolean | Discontinued flag |
fecha_estimada | date | Restock ETA (nullable) |
url_imagen | text | Product image URL (nullable) |
created_at | timestamptz | Creation timestamp |
referencia(unique)nombre(text search)tipo
inventario (Inventory)
Stock levels per location.
| Column | Type | Description |
|---|---|---|
id_inventario | uuid | Primary key |
id_localizacion | uuid | Foreign key to localizacion |
id_repuesto | uuid | Foreign key to repuestos |
stock_actual | integer | Current quantity |
cantidad_minima | integer | Minimum stock threshold |
posicion | text | Physical location in warehouse |
veces_contado | integer | Count audit frequency |
nuevo_hasta | timestamptz | ”New” badge expiry (nullable) |
created_at | timestamptz | Creation timestamp |
updated_at | timestamptz | Last update timestamp |
(id_localizacion, id_repuesto)
Computed Fields (via view vista_repuestos_inventario):
estado_stock: “Critico”, “Bajo”, “Normal”, “Alto”alerta_minimo:stock_actual <= cantidad_minimaes_nuevo:NOW() < nuevo_hasta
log_inventory_changes: Logs all stock modificationscheck_low_stock: Creates notification when stock is low
logs_inventario (Inventory Audit Logs)
Complete audit trail for inventory changes.
| Column | Type | Description |
|---|---|---|
id_log | uuid | Primary key |
id_inventario | uuid | Foreign key to inventario |
id_usuario | uuid | User who made change |
tipo_operacion | text | Operation type |
cantidad_anterior | integer | Old quantity |
cantidad_nueva | integer | New quantity |
diferencia | integer | Change amount |
motivo | text | Reason for change |
detalles | jsonb | Additional context |
fecha | timestamptz | Change timestamp |
AJUSTE_MANUAL- Manual adjustmentSOLICITUD_ENTRADA- Request receivedSOLICITUD_SALIDA- Request dispatchedMOVIMIENTO_TECNICO- Technician movementCONTEO_FISICO- Physical count adjustmentGARANTIA- Warranty claim
Request Domain
carrito_solicitudes (Request Cart)
Temporary cart for building requests.
| Column | Type | Description |
|---|---|---|
id_item_carrito | uuid | Primary key |
id_usuario | uuid | Foreign key to usuarios |
id_localizacion | uuid | Destination location |
id_repuesto | uuid | Foreign key to repuestos |
cantidad | integer | Requested quantity |
created_at | timestamptz | Added to cart timestamp |
solicitudes (Requests)
Inter-location transfer requests.
| Column | Type | Description |
|---|---|---|
id_solicitud | uuid | Primary key |
id_localizacion_origen | uuid | Source location |
id_localizacion_destino | uuid | Destination location |
id_usuario_solicitante | uuid | User who created request |
estado | text | Current state |
fecha_creacion | timestamptz | Creation timestamp |
fecha_alistamiento | timestamptz | Picking completed (nullable) |
fecha_despacho | timestamptz | Dispatched (nullable) |
fecha_recepcion | timestamptz | Received (nullable) |
guia_transporte | text | Shipping tracking number (nullable) |
observaciones_generales | text | General notes (nullable) |
PENDIENTE- Created, awaiting preparationALISTAMIENTO- Being pickedDESPACHADO- ShippedRECIBIDO- DeliveredCANCELADO- Cancelled
detalles_solicitud (Request Line Items)
Individual items in a request.
| Column | Type | Description |
|---|---|---|
id_detalle | uuid | Primary key |
id_solicitud | uuid | Foreign key to solicitudes |
id_repuesto | uuid | Foreign key to repuestos |
cantidad_solicitada | integer | Original request quantity |
cantidad_despachada | integer | Actually shipped (nullable) |
cantidad_recibida | integer | Actually received (nullable) |
observaciones | text | Item-specific notes (nullable) |
trazabilidad_solicitudes (Request Traceability)
State transition history for requests.
| Column | Type | Description |
|---|---|---|
id_trazabilidad | uuid | Primary key |
id_solicitud | uuid | Foreign key to solicitudes |
estado_anterior | text | Previous state |
estado_nuevo | text | New state |
id_usuario | uuid | User who made change |
fecha_cambio | timestamptz | Change timestamp |
comentario | text | Transition comment (nullable) |
solicitudes.estado change.
Operations Domain
movimientos_tecnicos (Technician Movements)
Daily parts movements for technicians.
| Column | Type | Description |
|---|---|---|
id_movimientos_tecnicos | uuid | Primary key |
id_localizacion | uuid | Foreign key to localizacion |
id_repuesto | uuid | Foreign key to repuestos |
id_usuario_responsable | uuid | User logging movement |
id_tecnico_asignado | uuid | Technician assigned part |
concepto | text | Movement concept |
tipo | text | Movement type (ingreso/salida/venta) |
cantidad | integer | Quantity moved |
numero_orden | integer | Work order number (nullable) |
descargada | boolean | Inventory deducted flag |
fecha | timestamptz | Movement timestamp |
created_at | timestamptz | Record creation timestamp |
updated_at | timestamptz | Last update timestamp |
salida- Parts taken by technicianingreso- Parts returnedventa- Parts soldgarantia- Warranty replacementprestamo- Temporary loancotizacion- Quote/estimatedevolucion- Return
ingreso- Increase stocksalida- Decrease stockventa- Decrease stock (sold)
garantias (Warranties)
Warranty claims for defective parts.
| Column | Type | Description |
|---|---|---|
id_garantia | uuid | Primary key |
id_repuesto | uuid | Foreign key to repuestos |
id_localizacion | uuid | Workshop location |
id_usuario_reporta | uuid | User who reported |
id_tecnico_asociado | uuid | Technician involved (nullable) |
cantidad | integer | Number of defective units |
motivo_falla | text | Failure description |
kilometraje | integer | Vehicle mileage (nullable) |
numero_orden | text | Work order reference (nullable) |
solicitante | text | Customer name (nullable) |
estado | text | Warranty status |
url_evidencia_foto | text | Photo evidence URL (nullable) |
comentarios_resolucion | text | Resolution notes (nullable) |
fecha_reporte | timestamptz | Report timestamp |
fecha_resolucion | timestamptz | Resolution timestamp (nullable) |
SIN_ENVIAR- DraftPENDIENTE- Submitted, awaiting reviewAPROBADA- Approved by supplierRECHAZADA- Denied by supplier
registro_conteo (Count Sessions)
Physical inventory count sessions.
| Column | Type | Description |
|---|---|---|
id_conteo | uuid | Primary key |
id_localizacion | uuid | Foreign key to localizacion |
id_usuario | uuid | User performing count |
fecha_conteo | timestamptz | Count date |
total_items | integer | Items counted |
total_diferencias | integer | Discrepancies found |
items_con_pq | integer | Items with “pequeños quedan” |
observaciones | text | General notes (nullable) |
created_at | timestamptz | Session creation timestamp |
detalles_conteo insert.
detalles_conteo (Count Line Items)
Individual item counts within a session.
| Column | Type | Description |
|---|---|---|
id_detalle_conteo | uuid | Primary key |
id_conteo | uuid | Foreign key to registro_conteo |
id_repuesto | uuid | Foreign key to repuestos |
cantidad_sistema | integer | System quantity |
cantidad_csa | integer | Counted quantity at location |
cantidad_pq | integer | ”Pequeños quedan” (loose parts) |
diferencia | integer | Calculated: (sistema + pq) - csa |
observaciones | text | Item notes (nullable) |
inventario.stock_actual if difference found.
Scooter Domain
scooter_types (Scooter Models)
Scooter model catalog.
| Column | Type | Description |
|---|---|---|
id_tipo | uuid | Primary key |
nombre | text | Model name |
potencia | text | Power specifications |
descripcion | text | Model description (nullable) |
order_follow (Order Tracking)
Scooter order status tracking.
| Column | Type | Description |
|---|---|---|
id_orden | uuid | Primary key |
numero_orden | text | Order number |
id_tipo_scooter | uuid | Foreign key to scooter_types |
nivel | integer | Progress level (1-3) |
estado | text | Order status |
telefono_contacto | text | Customer phone (nullable) |
email_contacto | text | Customer email (nullable) |
link_orden | text | External order link (nullable) |
fecha_orden | timestamptz | Order date |
fecha_entrega_estimada | date | ETA (nullable) |
- Ordered
- In transit
- Delivered
Database Views
vista_repuestos_inventario
Combined view of spare parts with inventory details.
Row Level Security (RLS)
Policies Overview
All tables have RLS enabled with policies based on:- User authentication state
- User role
- Location assignment
Example Policies
Inventory Access
Request Access
Database Diagram
Indexing Strategy
High-Traffic Queries
Triggers
Automatic Logging
Migration Strategy
Supabase uses versioned migrations:Backup & Recovery
Supabase provides:- Daily automated backups (retained 7 days)
- Point-in-time recovery (Pro plan)
- Manual backups via dashboard
- Export to SQL for local backups
Performance Considerations
Query Optimization
- Use views for complex joins
- Index foreign keys for fast lookups
- Limit result sets with pagination
- Use computed columns instead of runtime calculations
- Cache frequently accessed data with TanStack Query
Connection Pooling
Supabase uses PgBouncer for connection pooling:- Transaction mode for web connections
- Session mode for migrations
Related Resources
Architecture Overview
System architecture overview
Security
Authentication and RLS policies
API Reference
Database API usage
Data Migration
Import and export data