Todos los proyectos

Super La Estrella: ventas, pagos e inventario

El backend de una cadena de supermercados: una base de datos en SQL Server 2022 donde viven las reglas de negocio, un API REST en Node.js como única puerta de entrada y un panel en React con un demo en vivo. Proyecto en pareja para Bases de Datos 1.

Mi parte
Base de datos (DDL, carga, triggers) y el flujo de ventas y pagos
Equipo
2 personas · Bases de Datos 1, USAC
Datos
19 tablas, 22 llaves foráneas, 9 084 filas cargadas
Stack
SQL Server 2022, T-SQL, Node.js, Express, React, Vite, Docker

El problema

Una venta toca varias tablas a la vez: hay que validar el stock del producto en la tienda donde se vende, descontarlo, registrar los pagos y marcar la venta como pagada cuando se completa el total. Si esa lógica vive repartida en el código de la aplicación, cualquier cliente que escriba directo a la base puede dejar el inventario inconsistente.

Las reglas viven en el motor

Todos los proyectos

Super La Estrella: sales, payments and inventory

The backend for a supermarket chain: a SQL Server 2022 database where the business rules live, a Node.js REST API as the only way in, and a React dashboard with a live demo. A two-person project for Databases 1.

My part
Database (DDL, data load, triggers) and the sales and payments flow
Team
2 people · Databases 1, USAC
Data
19 tables, 22 foreign keys, 9,084 rows loaded
Stack
SQL Server 2022, T-SQL, Node.js, Express, React, Vite, Docker

The problem

A sale touches several tables at once: it has to check the product's stock at the store where it's sold, subtract it, record the payments and mark the sale as paid once the total is covered. If that logic is spread through application code, any client writing straight to the database can leave the inventory inconsistent.

The rules live in the engine

POST /api/ventas/15/detalles
ClienteClientAPI (Express)SQL Server POST detalle · cantidad: 9 999POST line item · quantity: 9,999 INSERT parametrizadoParameterized INSERT Trigger Insert_Detalle stock < cantidad → THROW 50001stock < quantity → THROW 50001 error 50001 · se revierte todoerror 50001 · everything rolls back 400 · "Stock insuficiente"
La regla de stock vive en el motor: el API no la repite, solo traduce el error del trigger a una respuesta HTTP.
The stock rule lives in the database engine: the API doesn't repeat it, it only translates the trigger's error into an HTTP response.

Decisiones de diseño

  1. Triggers para lo que no se puede romper. Insert_Detalle valida y descuenta el stock de la tienda de la venta; si no alcanza, lanza el error 50001 y se revierte la transacción completa. Insert_Pago marca la venta como PAGADA cuando los pagos llegan al total.
  2. Pagos inmutables. Dos triggers INSTEAD OF bloquean borrar o modificar un pago, y Delete_Detalle devuelve el stock a la tienda si se quita un detalle.
  3. El API es la única puerta. Node.js no repite la lógica de los triggers ni hace JOINs para los reportes: traduce HTTP a SQL parametrizado. El login del API no puede cambiar la estructura y el de DBeaver es de solo lectura.
  4. Una base que se arma sola. Un contenedor db-init ejecuta los scripts por prefijo: el DDL solo si no hay tablas, la carga con BULK INSERT solo si están vacías, y triggers, vistas y usuarios siempre, porque son idempotentes.

Resultados

  • 19 tablascon 19 llaves primarias, 22 foráneas, 5 CHECK y 2 UNIQUE
  • 5 triggersy 3 vistas analíticas para los reportes
  • 9 084 filascargadas desde 19 archivos CSV al levantar el contenedor

Pruébalo

En el demo en vivo el API y los triggers se simulan en el navegador con el mismo dataset: registra una venta en «Nueva venta» y pide más de lo que hay en stock para ver el error del trigger. Para correrlo con SQL Server real:

git clone https://github.com/akamariano/super-estrella-bd1
cd super-estrella-bd1
cp .env.example .env
docker compose up -d
cd backend && npm install && npm run dev

Design decisions

  1. Triggers for what can't break. Insert_Detalle checks and subtracts stock at the sale's store; if there isn't enough, it throws error 50001 and the whole transaction rolls back. Insert_Pago marks the sale as PAGADA once payments reach the total.
  2. Immutable payments. Two INSTEAD OF triggers block deleting or changing a payment, and Delete_Detalle returns stock to the store when a line item is removed.
  3. The API is the only door. Node.js doesn't repeat the trigger logic or do JOINs for reports: it translates HTTP into parameterized SQL. The API's login can't change the schema and DBeaver's is read-only.
  4. A database that sets itself up. A db-init container runs scripts by prefix: the DDL only if there are no tables, the BULK INSERT load only if they're empty, and triggers, views and users every time, since they're idempotent.

Results

  • 19 tableswith 19 primary keys, 22 foreign keys, 5 CHECK and 2 UNIQUE constraints
  • 5 triggersand 3 analytical views for reporting
  • 9,084 rowsloaded from 19 CSV files when the container starts

Try it

In the live demo the API and triggers are simulated in the browser with the same dataset: record a sale under “Nueva venta” and ask for more than what's in stock to see the trigger's error. To run it with a real SQL Server:

git clone https://github.com/akamariano/super-estrella-bd1
cd super-estrella-bd1
cp .env.example .env
docker compose up -d
cd backend && npm install && npm run dev