Database Overview
The PAE Inventory System uses PostgreSQL via Supabase as its database platform. The schema is designed to manage school meal program operations including inventory control, meal planning, attendance tracking, and user management with role-based access control.Schema Version
- Last Updated: February 23, 2026
- Database: PostgreSQL (Supabase)
- Schema File:
supabase_schema.sql
Architecture Principles
1. Role-Based Access Control (RBAC)
The system implements a hierarchical role structure:- Desarrollador (id=4): Full system administrator (assigned only from database)
- Director (id=1): School administrator with approval permissions
- Madre Procesadora (id=2): Kitchen manager with operational access
- Supervisor (id=3): Read-only supervision access
2. Maker-Checker Pattern
Guía de Entrada (delivery guides) follow a two-step approval workflow:- Madre Procesadora creates and submits guides
- Director or Desarrollador approves/rejects guides
- Only approved guides update inventory stock
3. FIFO Inventory Management
The system implements First-In-First-Out (FIFO) inventory tracking:- Batch/lot tracking with expiration dates stored as JSONB
- Automatic consumption from oldest batches first
- Expiration alerts and reporting
4. Audit Trail
Comprehensive audit logging captures:- User actions (INSERT, UPDATE, DELETE)
- Approval/rejection events
- Stock movements
- User authentication and activity
Core Data Flow
Table Categories
User Management
rol- User roles and permissionsusers- User accounts (extends Supabase auth.users)audit_log- System audit trail
Inventory Management
category- Product categoriesproduct- Product catalog with stock levelsguia_entrada- Delivery guides (with approval workflow)input- Delivery guide line items with batch trackingoutput- Stock withdrawals
Daily Operations
registro_diario- Daily meal records (current)receta_porcion- Product yield/portion configurationasistencia_diaria- Student attendance (legacy)menu_diario- Daily menu (legacy)menu_detalle- Menu line items (legacy)
The
asistencia_diaria, menu_diario, and menu_detalle tables are legacy tables replaced by the unified registro_diario table. They are maintained for backward compatibility.Security Architecture
Row Level Security (RLS)
All tables have RLS enabled with policies based on user roles:- SELECT: Generally open to all authenticated users
- INSERT: Restricted to Director and Madre Procesadora
- UPDATE: Role-specific (varies by table)
- DELETE: Highly restricted (Director only on most tables)
Trigger-Based Protection
Critical business rules are enforced via PostgreSQL triggers:- User hierarchy protection: Prevents unauthorized role modifications
- Stock validation: Ensures sufficient inventory before withdrawals
- Automatic timestamps: Updates
updated_atfields - Audit logging: Automatic capture of all critical operations
Key Features
1. Transactional Integrity
All critical operations use PostgreSQL functions withSECURITY DEFINER:
aprobar_guia()- Atomic approval and stock updaterechazar_guia()- Rejection with audit trailprocesar_operacion_diaria()- FIFO-based meal operation processing
2. JSONB for Flexibility
Batch tracking uses JSONB for flexible data structures:3. Materialized Views
Pre-computed views for common queries:productos_stock_bajo- Low stock alertsinventario_actual- Current inventory statusguias_pendientes- Pending approvalshistorial_aprobaciones- Approval history
Performance Optimizations
Indexes
idx_guia_entrada_estado- Fast filtering by approval statusidx_input_lotes_detalle- GIN index for JSONB batch queries- Primary key indexes on all tables
- Foreign key indexes automatically created
Locking Strategy
SELECT FOR UPDATEused in FIFO processing to prevent race conditions- Row-level locking for concurrent operations
- Transaction isolation for critical workflows
Database Constraints
Data Integrity
CHECKconstraints for valid data ranges (stock >= 0, amount > 0)UNIQUEconstraints for business keys (numero_guia_sunagro, username)NOT NULLconstraints for required fields- Foreign key cascades for referential integrity
Business Rules
- Unique guía numbers per delivery
- One attendance record per date/shift combination
- Stock cannot go negative (enforced by triggers)
- Approval state transitions (Pending → Approved/Rejected only)
Migration & Deployment
For schema changes:- Test in development environment
- Create migration scripts
- Apply via Supabase CLI or Dashboard
- Update reference documentation
Related Documentation
- Database Tables Reference - Detailed table schemas
- PostgreSQL Functions - RPC functions and triggers
- Security & RLS Policies - Access control policies