# rzulantay/ventasj-j architecture

> Architecture diagram of the GitHub repository rzulantay/ventasj-j, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/rzulantay/ventasj-j
- Repository: https://github.com/rzulantay/ventasj-j

## Overview

1. **Forma general del sistema**  
   Este repositorio contiene principalmente una **SPA en React** para gestión de ventas, ubicada en `frontend/`, con backend “as a service” en **Supabase**. No hay un backend propio separado; la lógica de negocio vive en el frontend y las reglas de acceso/datos están en la base Supabase.

2. **Punto de entrada y despliegue**  
   La app arranca en `frontend/src/main.tsx` y `App.tsx`, se construye con **Vite** y se despliega en **Vercel** como SPA. El archivo `vercel.json` en `frontend/` y en la raíz ajusta el routing para que las rutas de React Router funcionen en refresh/direct links.

3. **Capas del frontend**  
   El frontend está dividido en:
   - `pages/`: pantallas por dominio funcional
   - `components/`: UI reutilizable, separada en `common`, `layout` y `clientes`
   - `contexts/`: estado global de sesión, carrito y sidebar
   - `services/`: acceso a Supabase y reglas de negocio por módulo
   - `utils/`, `types/`, `constants/`: validaciones, tipos generados y catálogo estático  
   Esto hace que el flujo principal sea: **pantalla → servicio → Supabase**.

4. **Autenticación y control de acceso**  
   `AuthContext` y `auth.service.ts` gestionan la sesión con **Supabase Auth**. `ProtectedRoute` bloquea rutas no autenticadas y la UI oculta acciones según rol. El README deja claro que la seguridad es de tres capas: **UI + servicios TypeScript + RLS en PostgreSQL**.

5. **Módulo de cliente final**  
   Las páginas `cliente/CatalogoPage`, `CarritoPage` y `MisPedidosPage` implementan el flujo de compra del cliente. El carrito usa `CarritoContext`; el catálogo usa categorías, carruseles y búsqueda; y los pedidos del cliente se leen desde Supabase con filtros por su propio usuario.

6. **Módulo operativo de ventas**  
   `pedidos/PedidosPage` concentra la operación de vendedores y supervisores: listado paginado, búsqueda, cambio de estado, observaciones internas y generación de reporte. También existe `CarritosAbandonadosPage` y `PedidosArchivadosPage` para operación y soporte administrativo.

7. **Gestión maestra de datos**  
   Los módulos `productos`, `clientes` y `usuarios` representan el núcleo administrativo:
   - `productos.service.ts` y `ProductosPage` para catálogo, imágenes y desactivación
   - `clientes.service.ts` y `ClientesPage` para clientes asignados y creación de clientes
   - `usuarios.service.ts` y `UsuariosPage` para staff y roles  
   Estos módulos están fuertemente condicionados por el rol del usuario.

8. **Flujo de pedidos y reglas de negocio**  
   El pedido no depende del carrito local para el precio final: al crear un pedido, `pedidos.service.ts` vuelve a consultar precios vigentes en BD y luego los **congela** en `pedido_items`. El sistema también soporta modificación de ítems por supervisores, cancelación, observaciones internas e historial de cambios.

9. **Realtime y estado operativo**  
   La app usa **Supabase Realtime** para reflejar cambios de estado de pedidos en vivo, con indicador de conexión. Esto afecta especialmente las vistas de pedidos y el seguimiento de clientes, donde el estado puede cambiar sin recargar.

10. **Imágenes y almacenamiento**  
   `storage.service.ts`, `ImageUpload` y `MultiImageUpload` cubren la subida de imagen principal y múltiples imágenes por producto. La arquitectura de medios depende de **Supabase Storage** y **Image Transform**, con optimización de thumbnails en catálogo y carrito.

11. **Reportes, estadísticas y auditoría**  
   - `reportes.service.ts` genera una lista de picking imprimible usando el navegador, sin librerías PDF externas.  
   - `estadisticas.service.ts` alimenta `estadisticas/EstadisticasPage` con KPIs, rankings y gráficos.  
   - `auditoria.service.ts` y `auditoria/AuditoriaPage` registran operaciones críticas y permiten filtrarlas por entidad, acción y usuario.  
   Estos tres módulos son de consumo administrativo y dependen de datos agregados desde Supabase.

12. **Base de datos, RLS y esquema**  
   La carpeta `frontend/supabase/` contiene el esquema SQL, fixes y migraciones para:
   - `usuarios`
   - `productos`
   - `pedidos`
   - `pedido_items`
   - `auditoria`  
   La seguridad real vive en **Row Level Security** y funciones SQL auxiliares como `get_my_role()`. Los archivos `fix_*` y `rls_*` muestran que la arquitectura ha requerido endurecer permisos y corregir políticas varias veces.

13. **Tipos, configuración y consistencia**  
   `types/database.ts` refleja tipos generados desde Supabase, lo que reduce desalineación entre frontend y esquema. `supabase.config.ts` define clientes separados para sesión normal y flujo de signup, evitando sobrescribir la sesión activa de un supervisor/admin.

14. **Utilidades y scripts de soporte**  
   `scripts/crear-productos.*` y `datos-productos.json` sirven para carga inicial o masiva de productos. `utils/diagnostico-rls.ts` sugiere herramientas internas para depurar permisos. Esto indica que el proyecto tiene un componente de operación/migración importante, no solo UI.

15. **Lectura arquitectónica resumida**  
   Si lo dibujas, el diagrama principal es:  
   **Usuario web → SPA React/Vite → servicios por dominio → Supabase Auth / Postgres / Storage / Realtime**,  
   con **RLS** como barrera final de seguridad y con módulos separados para catálogo, carrito, pedidos, administración, estadísticas, auditoría y reportes.

Main entry points: [`frontend/src/App.tsx`](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/App.tsx) (App shell), [`frontend/src/components/layout/MainLayout.tsx`](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/components/layout/MainLayout.tsx) (Main layout), [`frontend/src/services/pedidos.service.ts`](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/pedidos.service.ts) (Orders service), [`frontend/src/pages/cliente/CatalogoPage.tsx`](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/cliente/CatalogoPage.tsx) (Catalog)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_root["Repository"]
  node_vercel_root["Vercel config<br/>deploy config<br/>[vercel.json]"]
end

subgraph group_frontend["Frontend app"]
  node_vite_main["App entry<br/>react entry<br/>[main.tsx]"]
  node_app_shell["App shell<br/>route shell<br/>[App.tsx]"]
  node_auth_ctx(("Auth state<br/>session context<br/>[AuthContext.tsx]"))
  node_carrito_ctx(("Cart state<br/>shopping context<br/>[CarritoContext.tsx]"))
  node_sidebar_ctx(("Sidebar state<br/>ui context<br/>[SidebarContext.tsx]"))
  node_protected_route{{"Access gate<br/>route guard<br/>[ProtectedRoute.tsx]"}}
  node_main_layout["Main layout<br/>[MainLayout.tsx]"]
  node_catalog_page["Catalog<br/>customer page<br/>[CatalogoPage.tsx]"]
  node_cart_page["Cart<br/>customer page<br/>[CarritoPage.tsx]"]
  node_orders_page["Orders<br/>sales page<br/>[PedidosPage.tsx]"]
  node_products_page["Products<br/>admin page<br/>[ProductosPage.tsx]"]
  node_clients_page["Clients<br/>admin page<br/>[ClientesPage.tsx]"]
  node_users_page["Users<br/>admin page<br/>[UsuariosPage.tsx]"]
  node_stats_page["Stats<br/>admin page"]
  node_audit_page["Audit<br/>admin page<br/>[AuditoriaPage.tsx]"]
  node_auth_service["Auth service<br/>supabase auth<br/>[auth.service.ts]"]
  node_orders_service["Orders service<br/>business service<br/>[pedidos.service.ts]"]
  node_products_service["Products service<br/>business service"]
  node_clients_service["Clients service<br/>business service"]
  node_users_service["Users service<br/>business service"]
  node_stats_service["Stats service<br/>analytics service"]
  node_audit_service["Audit service<br/>logging service"]
  node_storage_service["Storage service<br/>media service<br/>[storage.service.ts]"]
  node_supabase_config["Supabase config<br/>client config<br/>[supabase.config.ts]"]
  node_database_types["DB types<br/>generated types<br/>[database.ts]"]
end

subgraph group_supabase["Supabase"]
  node_schema_sql[("Schema<br/>[schema.sql]")]
  node_rls_sql["RLS policies<br/>sql security"]
  node_migration_sql["Migrations<br/>sql migration<br/>[README.md]"]
end

node_vercel_root -->|"serves SPA"| node_vite_main
node_vite_main -->|"boots"| node_app_shell
node_app_shell -->|"uses"| node_auth_ctx
node_app_shell -->|"uses"| node_carrito_ctx
node_app_shell -->|"uses"| node_sidebar_ctx
node_app_shell -->|"protects"| node_protected_route
node_app_shell -->|"renders"| node_main_layout
node_auth_ctx -->|"delegates"| node_auth_service
node_auth_service -->|"creates clients"| node_supabase_config
node_protected_route -->|"checks session"| node_auth_ctx
node_main_layout -->|"hosts"| node_catalog_page
node_main_layout -->|"hosts"| node_cart_page
node_main_layout -->|"hosts"| node_orders_page
node_catalog_page -->|"reads"| node_products_service
node_catalog_page -->|"adds items"| node_carrito_ctx
node_cart_page -->|"creates order"| node_orders_service
node_orders_page -->|"manages"| node_orders_service
node_products_service -->|"uploads media"| node_storage_service
node_products_service -->|"typed by"| node_database_types
node_clients_page -->|"uses"| node_clients_service
node_users_page -->|"uses"| node_users_service
node_stats_page -->|"uses"| node_stats_service
node_audit_page -->|"uses"| node_audit_service
node_orders_service -->|"reads/writes"| node_schema_sql
node_orders_service -->|"constrained by"| node_rls_sql
node_clients_service -->|"constrained by"| node_rls_sql
node_users_service -->|"constrained by"| node_rls_sql
node_audit_service -->|"writes log"| node_schema_sql
node_storage_service -->|"uses"| node_supabase_config
node_migration_sql -->|"evolves"| node_schema_sql

click node_vercel_root "https://github.com/rzulantay/ventasj-j/blob/Producción/vercel.json"
click node_vite_main "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/main.tsx"
click node_app_shell "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/App.tsx"
click node_auth_ctx "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/contexts/AuthContext.tsx"
click node_carrito_ctx "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/contexts/CarritoContext.tsx"
click node_sidebar_ctx "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/contexts/SidebarContext.tsx"
click node_protected_route "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/components/common/ProtectedRoute.tsx"
click node_main_layout "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/components/layout/MainLayout.tsx"
click node_catalog_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/cliente/CatalogoPage.tsx"
click node_cart_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/cliente/CarritoPage.tsx"
click node_orders_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/pedidos/PedidosPage.tsx"
click node_products_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/productos/ProductosPage.tsx"
click node_clients_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/clientes/ClientesPage.tsx"
click node_users_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/usuarios/UsuariosPage.tsx"
click node_stats_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/estadisticas/EstadisticasPage.tsx"
click node_audit_page "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/auditoria/AuditoriaPage.tsx"
click node_auth_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/auth.service.ts"
click node_orders_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/pedidos.service.ts"
click node_products_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/productos.service.ts"
click node_clients_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/clientes.service.ts"
click node_users_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/usuarios.service.ts"
click node_stats_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/estadisticas.service.ts"
click node_audit_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/auditoria.service.ts"
click node_storage_service "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/storage.service.ts"
click node_supabase_config "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/supabase.config.ts"
click node_database_types "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/types/database.ts"
click node_schema_sql "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/supabase/schema.sql"
click node_rls_sql "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/supabase/rls_aplicar_definitivo.sql"
click node_migration_sql "https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/supabase/migrations/README.md"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_vercel_root toneBlue
class node_vite_main,node_app_shell,node_auth_ctx,node_carrito_ctx,node_sidebar_ctx,node_protected_route,node_main_layout,node_catalog_page,node_cart_page,node_orders_page,node_products_page,node_clients_page,node_users_page,node_stats_page,node_audit_page,node_auth_service,node_orders_service,node_products_service,node_clients_service,node_users_service,node_stats_service,node_audit_service,node_storage_service,node_supabase_config,node_database_types toneAmber
class node_schema_sql,node_rls_sql,node_migration_sql toneMint
```

## Components

### Repository

Deployment and repository-level files

- [Vercel config](https://github.com/rzulantay/ventasj-j/blob/Producción/vercel.json): deploy config · Root routing for SPA deployment · `vercel.json`

### Frontend app

React SPA and its runtime layers

- [App entry](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/main.tsx): react entry · Bootstraps the SPA runtime · `frontend/src/main.tsx`
- [App shell](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/App.tsx): route shell · Top-level routing and composition · `frontend/src/App.tsx`
- [Auth state](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/contexts/AuthContext.tsx): session context · Supabase session and role-aware auth state · `frontend/src/contexts/AuthContext.tsx`
- [Cart state](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/contexts/CarritoContext.tsx): shopping context · Client-side cart and checkout state · `frontend/src/contexts/CarritoContext.tsx`
- [Sidebar state](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/contexts/SidebarContext.tsx): ui context · Layout/navigation state · `frontend/src/contexts/SidebarContext.tsx`
- [Access gate](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/components/common/ProtectedRoute.tsx): route guard · Blocks unauthenticated routes · `frontend/src/components/common/ProtectedRoute.tsx`
- [Main layout](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/components/layout/MainLayout.tsx): layout · Shared page chrome and navigation · `frontend/src/components/layout/MainLayout.tsx`
- [Catalog](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/cliente/CatalogoPage.tsx): customer page · Product browsing and category discovery · `frontend/src/pages/cliente/CatalogoPage.tsx`
- [Cart](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/cliente/CarritoPage.tsx): customer page · Cart review and purchase flow · `frontend/src/pages/cliente/CarritoPage.tsx`
- [Orders](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/pedidos/PedidosPage.tsx): sales page · Operational order management · `frontend/src/pages/pedidos/PedidosPage.tsx`
- [Products](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/productos/ProductosPage.tsx): admin page · Catalog, images, and activation control · `frontend/src/pages/productos/ProductosPage.tsx`
- [Clients](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/clientes/ClientesPage.tsx): admin page · Client assignment and creation · `frontend/src/pages/clientes/ClientesPage.tsx`
- [Users](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/usuarios/UsuariosPage.tsx): admin page · Staff and role management · `frontend/src/pages/usuarios/UsuariosPage.tsx`
- [Stats](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/estadisticas/EstadisticasPage.tsx): admin page · KPIs, rankings, and charts · `frontend/src/pages/estadisticas/EstadisticasPage.tsx`
- [Audit](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/pages/auditoria/AuditoriaPage.tsx): admin page · Operational audit log and filters · `frontend/src/pages/auditoria/AuditoriaPage.tsx`
- [Auth service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/auth.service.ts): supabase auth · Login, reset, and session operations · `frontend/src/services/auth.service.ts`
- [Orders service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/pedidos.service.ts): business service · Order creation, status changes, and frozen line items · `frontend/src/services/pedidos.service.ts`
- [Products service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/productos.service.ts): business service · Product catalog and media operations · `frontend/src/services/productos.service.ts`
- [Clients service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/clientes.service.ts): business service · Client assignment and administration · `frontend/src/services/clientes.service.ts`
- [Users service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/usuarios.service.ts): business service · Staff and permissions management · `frontend/src/services/usuarios.service.ts`
- [Stats service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/estadisticas.service.ts): analytics service · Aggregations for dashboards and reports · `frontend/src/services/estadisticas.service.ts`
- [Audit service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/auditoria.service.ts): logging service · Critical action tracking and queries · `frontend/src/services/auditoria.service.ts`
- [Storage service](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/services/storage.service.ts): media service · Supabase Storage access and image handling · `frontend/src/services/storage.service.ts`
- [Supabase config](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/supabase.config.ts): client config · Separate clients for session and signup flows · `frontend/src/supabase.config.ts`
- [DB types](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/src/types/database.ts): generated types · Typed contract for Supabase schema · `frontend/src/types/database.ts`

### Supabase

Database schema, RLS, and migrations

- [Schema](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/supabase/schema.sql): sql schema · Core tables and database structure · `frontend/supabase/schema.sql`
- [RLS policies](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/supabase/rls_aplicar_definitivo.sql): sql security · Row-level security rules and fixes · `frontend/supabase/rls_aplicar_definitivo.sql`
- [Migrations](https://github.com/rzulantay/ventasj-j/blob/Producción/frontend/supabase/migrations/README.md): sql migration · Schema and policy changes over time · `frontend/supabase/migrations/README.md`

## Connections

- Vercel config → App entry: serves SPA · Routing is configured so direct links resolve to the React app
- App entry → App shell: boots · Main entry mounts the application shell
- App shell → Auth state: uses · Application shell consumes auth state
- App shell → Cart state: uses · Customer checkout state is provided globally
- App shell → Sidebar state: uses · Layout/navigation state is shared across pages
- App shell → Access gate: protects · Authenticated access is enforced at route boundaries
- App shell → Main layout: renders · Shared chrome wraps the page routes
- Auth state → Auth service: delegates · Session and login logic is centralized in the service layer
- Auth service → Supabase config: creates clients · Auth operations use configured Supabase clients
- Access gate → Auth state: checks session · Route gating depends on current user and role
- Main layout → Catalog: hosts · Customer browsing page is rendered inside the common layout
- Main layout → Cart: hosts · Cart page is rendered inside the common layout
- Main layout → Orders: hosts · Operational order management page is rendered inside the common layout
- Catalog → Products service: reads · Catalog data comes from the products domain service
- Catalog → Cart state: adds items · Selected items flow into the shared cart state
- Cart → Orders service: creates order · Checkout is finalized through the order service
- Orders → Orders service: manages · Status updates and operational actions go through the order service
- Products service → Storage service: uploads media · Product images are stored and transformed via storage
- Products service → DB types: typed by · Service queries follow the generated database contract
- Clients → Clients service: uses · Client administration is handled by the client service
- Users → Users service: uses · Staff and roles are managed through the user service
- Stats → Stats service: uses · Dashboard metrics are assembled by the stats service
- Audit → Audit service: uses · Audit listings and filters are powered by the audit service
- Orders service → Schema: reads/writes · Orders depend on the core Supabase schema
- Orders service → RLS policies: constrained by · Order operations are enforced by row-level security
- Clients service → RLS policies: constrained by · Client operations respect row-level security
- Users service → RLS policies: constrained by · User and role management is secured by RLS
- Audit service → Schema: writes log · Audit entries are stored in the database schema
- Storage service → Supabase config: uses · Storage operations use the configured Supabase client
- Migrations → Schema: evolves · Migrations and fixes adapt the schema and policies
