From 691b6f79a2a7518f7800bb20ee435f2a7ed7a093 Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 4 Oct 2026 14:54:45 -0600 Subject: [PATCH] feat: inicializacion de RecreoPay - Monedero QR y Pre-ordenes para Soda Escolar CR --- .gitignore | 6 + README.md | 81 +++ package-lock.json | 1245 +++++++++++++++++++++++++++++++++++++++++ package.json | 29 + public/carnet.html | 159 ++++++ public/css/styles.css | 781 ++++++++++++++++++++++++++ public/index.html | 238 ++++++++ public/js/app.js | 449 +++++++++++++++ public/js/pos.js | 428 ++++++++++++++ public/js/sounds.js | 124 ++++ public/manifest.json | 21 + public/pos.html | 169 ++++++ public/sw.js | 47 ++ server/db.js | 458 +++++++++++++++ server/server.js | 388 +++++++++++++ 15 files changed, 4623 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/carnet.html create mode 100644 public/css/styles.css create mode 100644 public/index.html create mode 100644 public/js/app.js create mode 100644 public/js/pos.js create mode 100644 public/js/sounds.js create mode 100644 public/manifest.json create mode 100644 public/pos.html create mode 100644 public/sw.js create mode 100644 server/db.js create mode 100644 server/server.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1aab67 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +*.log +.DS_Store +*.db +!schema.sql +.env diff --git a/README.md b/README.md new file mode 100644 index 0000000..4c1867c --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# 🥪 RecreoPay - Soda Escolar Costa Rica 🇨🇷 + +> Sistema de Monedero Digital, Identificación por Código QR y Pre-Órdenes para Sodas Escolares en Costa Rica, adaptado pedagógicamente para estudiantes de 7 a 15 años y sus padres. + +--- + +## 🎯 Propósito del Proyecto +RecreoPay resuelve el cuello de botella más crítico de los centros educativos costarricenses: **atender a cientos de estudiantes en los 15 a 20 minutos de recreo**. +Elimina el uso de dinero en efectivo en la escuela (evitando pérdidas, robos y compras indebidas), cumple con las directrices de **alimentación saludable del MEP**, y permite que los estudiantes de primaria sin teléfono móvil utilicen **carnés físicos plastificados con código QR**. + +--- + +## 🚀 Características Principales + +### 1. Experiencia de Usuario Adaptativa (UX/UI 7 a 15 Años) +* **🧒 Modo Kids (7 a 10 años / Primaria):** + * Metáfora visual de "Monedas" y "Colones ₡". + * Tarjetas táctiles gigantes con fotos de alta resolución e iconografía clara. + * Interacciones con sonidos amigables de refuerzo positivo (Web Audio API). + * Menor carga cognitiva y lectura simplificada. +* **⚡ Modo Teens (11 a 15 años / Secundaria):** + * Estética moderna estilo fintech (Modo Oscuro / Cyber-slate). + * Filtros ágiles de combos, platos del día y frescos naturales. + * Indicadores nutricionales (calorías, sellos MEP saludable, alérgenos). + +### 2. Doble Modalidad de Pago e Identificación +* **📱 QR Digital Dinámico (PWA):** En el teléfono móvil del estudiante con código QR de alto contraste. +* **🖨️ Carné Físico Impreso con QR:** Plantilla lista para imprimir en tamaño credencial estándar (85.6 × 54 mm) con foto del alumno, grado, sección, alérgenos y código QR. + +### 3. Dos Flujos de Compra para Descongestionar el Recreo +1. **🛒 Venta en Mostrador (Monedero QR):** La cajera marca los productos, escanea el QR del estudiante en 0.5 segundos; el sistema verifica saldo, valida que no exceda el límite diario fijado por el padre y debita el saldo atómicamente. +2. **📦 Fila Rápida de Pre-Órdenes (Click & Collect):** El estudiante o padre pide desde su casa o aula para el 1er recreo o almuerzo. En el recreo, hay una fila rápida exclusiva donde solo escanean el QR y retiran la bolsa en 3 segundos. + +### 4. Portal de Padres y Recargas SINPE Móvil +* Recargas directas con número de comprobante SINPE. +* Control del límite máximo de gasto diario (ej: máximo ₡2.500 por día). +* Filtro de alérgenos y opción de bloquear golosinas/chucherías. +* Auditoría completa de cada transacción y compra. + +### 5. Terminal POS de la Soda con Escáner QR en Tiempo Real +* Soporta la cámara de tablets Android/iPad o lectores de código de barras láser USB. +* Notificaciones en tiempo real vía **Server-Sent Events (SSE)** cuando ingresa una nueva pre-orden. +* Alerta médica en pantalla si el estudiante identificado tiene alguna alergia registrada. + +--- + +## 🛠️ Stack Tecnológico +* **Backend:** Node.js, Express, Better-SQLite3 (motor de base de datos con modo WAL y transacciones ACID). +* **Frontend:** PWA con HTML5 semántico, CSS Responsive adaptativo (Kids / Teens / POS), Vanilla JS modular y Web Audio API. +* **Códigos QR:** Generación de alta resolución vía biblioteca nativa `qrcode`. + +--- + +## 💻 Instalación y Ejecución Local + +1. **Clonar el repositorio:** + ```bash + git clone https://github.com/pampo32-hub/recreopay.git + cd recreopay + ``` + +2. **Instalar dependencias:** + ```bash + npm install + ``` + +3. **Iniciar la aplicación:** + ```bash + npm start + ``` + +4. **Abrir en el navegador:** + * **📱 PWA Estudiantes / Padres:** [http://localhost:3030](http://localhost:3030) + * **📟 Terminal de la Soda (Cajero y Escáner QR):** [http://localhost:3030/pos.html](http://localhost:3030/pos.html) + * **🖨️ Generador de Carnés Físicos:** [http://localhost:3030/carnet.html](http://localhost:3030/carnet.html) + +--- + +## 🌐 Repositorios Remotos +* **GitHub:** [https://github.com/pampo32-hub/recreopay](https://github.com/pampo32-hub/recreopay) +* **Gitea:** [https://git.reservascr.app/Pampo32/recreopay](https://git.reservascr.app/Pampo32/recreopay) diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..88e4d16 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1245 @@ +{ + "name": "recreopay", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "recreopay", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "better-sqlite3": "^13.0.3", + "cors": "^2.8.6", + "express": "^5.2.1", + "qrcode": "^1.5.4" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/better-sqlite3": { + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", + "license": "MIT", + "dependencies": { + "node-addon-api": "^8.0.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..1f973e7 --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "recreopay", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "node server/server.js", + "dev": "node --watch server/server.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pampo32-hub/recreopay.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "bugs": { + "url": "https://github.com/pampo32-hub/recreopay/issues" + }, + "homepage": "https://github.com/pampo32-hub/recreopay#readme", + "dependencies": { + "better-sqlite3": "^13.0.3", + "cors": "^2.8.6", + "express": "^5.2.1", + "qrcode": "^1.5.4" + } +} diff --git a/public/carnet.html b/public/carnet.html new file mode 100644 index 0000000..cc992e4 --- /dev/null +++ b/public/carnet.html @@ -0,0 +1,159 @@ + + + + + RecreoPay - Carnés Escolares Físicos con Código QR + + + + + + + + + +
+
+ +
+
+ + + + diff --git a/public/css/styles.css b/public/css/styles.css new file mode 100644 index 0000000..2820b2e --- /dev/null +++ b/public/css/styles.css @@ -0,0 +1,781 @@ +/* ========================================================================== + RECREOPAY - SISTEMA DE DISEÑO ADAPTATIVO (KIDS 7-10 & TEENS 11-15 & SODA POS) + ========================================================================== */ + +:root { + --primary: #0284c7; + --primary-hover: #0369a1; + --secondary: #10b981; + --accent: #f59e0b; + --danger: #ef4444; + --bg-main: #f8fafc; + --card-bg: #ffffff; + --text-main: #0f172a; + --text-muted: #64748b; + --border: #e2e8f0; + --radius: 16px; + --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.08), 0 2px 4px -2px rgb(0 0 0 / 0.06); +} + +/* Modo Teens (Estilo Fintech / Dark Mode) */ +body.mode-teens { + --primary: #38bdf8; + --primary-hover: #0284c7; + --secondary: #34d399; + --accent: #fbbf24; + --bg-main: #0b1120; + --card-bg: #1e293b; + --text-main: #f1f5f9; + --text-muted: #94a3b8; + --border: #334155; + --radius: 12px; + --shadow: 0 10px 15px -3px rgb(0 0 0 / 0.4); +} + +/* Modo Kids (Primaria: Lúdico, Grande, Amigable) */ +body.mode-kids { + --primary: #0284c7; + --secondary: #10b981; + --accent: #f59e0b; + --bg-main: #eff6ff; + --card-bg: #ffffff; + --text-main: #1e293b; + --border: #bfdbfe; + --radius: 22px; + --shadow: 0 8px 20px -4px rgb(2 132 199 / 0.15); + font-size: 16px; +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + -webkit-tap-highlight-color: transparent; +} + +body { + background-color: var(--bg-main); + color: var(--text-main); + min-height: 100vh; + display: flex; + flex-direction: column; + transition: background-color 0.3s ease, color 0.3s ease; +} + +/* Contenedor móvil centrado para PWA */ +.app-container { + max-width: 480px; + margin: 0 auto; + width: 100%; + padding-bottom: 90px; +} + +/* Top App Bar */ +.top-bar { + background: var(--card-bg); + padding: 14px 18px; + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid var(--border); + position: sticky; + top: 0; + z-index: 40; + box-shadow: var(--shadow); +} + +.brand-badge { + display: flex; + align-items: center; + gap: 8px; + font-size: 1.25rem; + font-weight: 800; + color: var(--text-main); + text-decoration: none; +} + +.brand-badge .logo-icon { + background: linear-gradient(135deg, #0284c7, #38bdf8); + color: white; + width: 36px; + height: 36px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 1.2rem; +} + +/* Selector de Perfil y Modo */ +.mode-toggle { + display: flex; + background: var(--bg-main); + border: 1px solid var(--border); + padding: 3px; + border-radius: 30px; + gap: 2px; +} + +.mode-btn { + border: none; + background: transparent; + padding: 5px 12px; + border-radius: 20px; + font-size: 0.78rem; + font-weight: 700; + color: var(--text-muted); + cursor: pointer; + display: flex; + align-items: center; + gap: 4px; + transition: all 0.2s ease; +} + +.mode-btn.active { + background: var(--primary); + color: #ffffff; + box-shadow: 0 2px 6px rgba(0,0,0,0.15); +} + +/* Tarjeta de Saldo y Carné Digital */ +.wallet-card { + margin: 16px; + background: linear-gradient(135deg, #0369a1, #0284c7); + color: white; + border-radius: var(--radius); + padding: 20px; + box-shadow: 0 12px 25px -4px rgba(2, 132, 199, 0.4); + position: relative; + overflow: hidden; +} + +body.mode-teens .wallet-card { + background: linear-gradient(135deg, #1e293b, #0f172a); + border: 1px solid #334155; + box-shadow: 0 10px 25px -4px rgba(0, 0, 0, 0.5); +} + +body.mode-kids .wallet-card { + background: linear-gradient(135deg, #0284c7, #38bdf8); + border: 3px solid #7dd3fc; +} + +.wallet-card::after { + content: ""; + position: absolute; + top: -40px; + right: -40px; + width: 140px; + height: 140px; + background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%); + border-radius: 50%; +} + +.student-info { + display: flex; + align-items: center; + gap: 14px; + margin-bottom: 16px; +} + +.student-avatar { + width: 58px; + height: 58px; + border-radius: 50%; + border: 3px solid rgba(255, 255, 255, 0.8); + background: white; + object-fit: cover; + box-shadow: 0 4px 10px rgba(0,0,0,0.15); +} + +.student-meta h2 { + font-size: 1.15rem; + font-weight: 800; + line-height: 1.2; +} + +.student-grade { + font-size: 0.85rem; + opacity: 0.9; + display: inline-block; + margin-top: 2px; +} + +.balance-row { + display: flex; + justify-content: space-between; + align-items: flex-end; + border-top: 1px solid rgba(255, 255, 255, 0.2); + padding-top: 14px; +} + +.balance-col .label { + font-size: 0.78rem; + text-transform: uppercase; + letter-spacing: 0.5px; + opacity: 0.85; +} + +.balance-col .amount { + font-size: 1.85rem; + font-weight: 900; + letter-spacing: -0.5px; + display: flex; + align-items: center; + gap: 4px; +} + +.kids-coin-icon { + font-size: 1.6rem; + animation: bounce 2s infinite ease-in-out; +} + +@keyframes bounce { + 0%, 100% { transform: translateY(0); } + 50% { transform: translateY(-4px); } +} + +.qr-toggle-btn { + background: rgba(255, 255, 255, 0.2); + border: 1px solid rgba(255, 255, 255, 0.4); + color: white; + padding: 8px 14px; + border-radius: 30px; + font-weight: 700; + font-size: 0.85rem; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; + backdrop-filter: blur(8px); + transition: all 0.2s; +} + +.qr-toggle-btn:hover { + background: rgba(255, 255, 255, 0.35); + transform: scale(1.02); +} + +/* Modal del Código QR Escolar */ +.modal-qr-backdrop { + position: fixed; + inset: 0; + background: rgba(15, 23, 42, 0.8); + backdrop-filter: blur(6px); + display: flex; + align-items: center; + justify-content: center; + z-index: 100; + padding: 20px; +} + +.modal-qr-card { + background: white; + border-radius: 24px; + padding: 26px 20px; + max-width: 340px; + width: 100%; + text-align: center; + box-shadow: 0 20px 40px rgba(0,0,0,0.3); + position: relative; + animation: zoomIn 0.25s cubic-bezier(0.16, 1, 0.3, 1); +} + +@keyframes zoomIn { + from { transform: scale(0.9); opacity: 0; } + to { transform: scale(1); opacity: 1; } +} + +.qr-code-img { + width: 220px; + height: 220px; + margin: 14px auto; + display: block; + border-radius: 12px; + border: 2px dashed #0284c7; + padding: 6px; +} + +/* Banner de Límite Diario / Alerta */ +.daily-limit-badge { + background: var(--card-bg); + border: 1px solid var(--border); + margin: 0 16px 16px 16px; + padding: 10px 14px; + border-radius: var(--radius); + display: flex; + justify-content: space-between; + align-items: center; + font-size: 0.84rem; +} + +.daily-limit-badge strong { + color: var(--secondary); +} + +/* Navegación por Categorías */ +.category-scroll { + display: flex; + overflow-x: auto; + gap: 8px; + padding: 4px 16px 12px 16px; + scrollbar-width: none; +} + +.category-scroll::-webkit-scrollbar { + display: none; +} + +.cat-pill { + flex-shrink: 0; + background: var(--card-bg); + border: 1px solid var(--border); + color: var(--text-main); + padding: 8px 16px; + border-radius: 30px; + font-size: 0.86rem; + font-weight: 700; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; + box-shadow: var(--shadow); + transition: all 0.2s; +} + +.cat-pill.active { + background: var(--primary); + color: white; + border-color: var(--primary); +} + +/* Grilla de Productos */ +.section-title { + padding: 0 16px; + margin-bottom: 10px; + font-size: 1.1rem; + font-weight: 800; + display: flex; + justify-content: space-between; + align-items: center; +} + +.products-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + padding: 0 16px; +} + +body.mode-kids .products-grid { + grid-template-columns: 1fr; +} + +.product-card { + background: var(--card-bg); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 14px; + box-shadow: var(--shadow); + display: flex; + flex-direction: column; + justify-content: space-between; + position: relative; + transition: transform 0.15s, box-shadow 0.15s; +} + +.product-card:active { + transform: scale(0.98); +} + +body.mode-kids .product-card { + flex-direction: row; + align-items: center; + gap: 16px; + padding: 16px; +} + +.product-icon-wrap { + font-size: 2.8rem; + text-align: center; + margin-bottom: 8px; +} + +body.mode-kids .product-icon-wrap { + font-size: 3.4rem; + margin-bottom: 0; + flex-shrink: 0; +} + +.product-name { + font-size: 0.95rem; + font-weight: 800; + line-height: 1.25; + margin-bottom: 4px; +} + +body.mode-kids .product-name { + font-size: 1.15rem; +} + +.product-desc { + font-size: 0.76rem; + color: var(--text-muted); + line-height: 1.3; + margin-bottom: 8px; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.badge-mep { + font-size: 0.68rem; + font-weight: 700; + background: #dcfce7; + color: #166534; + padding: 2px 6px; + border-radius: 4px; + display: inline-block; + margin-bottom: 6px; +} + +.product-footer { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 6px; +} + +body.mode-kids .product-footer { + flex-direction: column; + align-items: flex-end; + gap: 8px; +} + +.product-price { + font-size: 1.1rem; + font-weight: 900; + color: var(--primary); +} + +.add-btn { + background: var(--primary); + color: white; + border: none; + width: 36px; + height: 36px; + border-radius: 50%; + font-size: 1.2rem; + font-weight: 900; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + box-shadow: 0 4px 10px rgba(2, 132, 199, 0.3); + transition: transform 0.15s; +} + +body.mode-kids .add-btn { + width: 48px; + height: 48px; + font-size: 1.5rem; + border-radius: 14px; +} + +.add-btn:active { + transform: scale(0.9); +} + +/* Barra Flotante de Carrito / Pre-orden */ +.floating-cart-bar { + position: fixed; + bottom: 16px; + left: 16px; + right: 16px; + max-width: 448px; + margin: 0 auto; + background: #0f172a; + color: white; + border-radius: 20px; + padding: 12px 18px; + display: flex; + justify-content: space-between; + align-items: center; + box-shadow: 0 10px 25px rgba(0,0,0,0.4); + z-index: 50; + cursor: pointer; +} + +body.mode-kids .floating-cart-bar { + background: #0284c7; + border: 2px solid white; +} + +.cart-summary { + display: flex; + align-items: center; + gap: 12px; +} + +.cart-count-badge { + background: var(--accent); + color: #0f172a; + font-weight: 900; + padding: 4px 10px; + border-radius: 12px; + font-size: 0.9rem; +} + +.cart-total-text { + font-size: 1.1rem; + font-weight: 800; +} + +.cart-action-btn { + background: var(--secondary); + color: white; + border: none; + padding: 8px 16px; + border-radius: 12px; + font-weight: 800; + font-size: 0.9rem; + cursor: pointer; +} + +/* ========================================================================== + TERMINAL POS SODA (pos.html) + ========================================================================== */ +.pos-layout { + display: grid; + grid-template-columns: 1fr 420px; + height: 100vh; + overflow: hidden; + background: #0f172a; + color: #f8fafc; +} + +.pos-catalog-pane { + padding: 20px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 16px; +} + +.pos-tabs { + display: flex; + gap: 10px; + border-bottom: 2px solid #334155; + padding-bottom: 12px; +} + +.pos-tab-btn { + background: #1e293b; + border: 1px solid #334155; + color: #94a3b8; + padding: 10px 18px; + border-radius: 10px; + font-size: 0.95rem; + font-weight: 800; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; +} + +.pos-tab-btn.active { + background: #0284c7; + color: white; + border-color: #0284c7; +} + +.pos-products-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); + gap: 14px; +} + +.pos-prod-card { + background: #1e293b; + border: 1px solid #334155; + border-radius: 14px; + padding: 16px; + cursor: pointer; + display: flex; + flex-direction: column; + justify-content: space-between; + min-height: 140px; + transition: all 0.15s; +} + +.pos-prod-card:hover { + border-color: #38bdf8; + transform: translateY(-2px); +} + +.pos-checkout-pane { + background: #1e293b; + border-left: 2px solid #334155; + display: flex; + flex-direction: column; + justify-content: space-between; + padding: 20px; +} + +.scanner-feed-card { + background: #0f172a; + border: 2px dashed #0284c7; + border-radius: 16px; + padding: 16px; + text-align: center; + position: relative; + overflow: hidden; +} + +.camera-preview { + width: 100%; + height: 180px; + background: #000000; + border-radius: 10px; + object-fit: cover; + display: block; +} + +.laser-scan-line { + position: absolute; + top: 20px; + left: 16px; + right: 16px; + height: 2px; + background: #ef4444; + box-shadow: 0 0 10px #ef4444; + animation: scanMove 2s infinite ease-in-out; +} + +@keyframes scanMove { + 0% { top: 20px; opacity: 0.8; } + 50% { top: 180px; opacity: 1; } + 100% { top: 20px; opacity: 0.8; } +} + +.pos-cart-list { + flex-grow: 1; + overflow-y: auto; + margin: 16px 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.pos-cart-item { + display: flex; + justify-content: space-between; + align-items: center; + background: #0f172a; + padding: 10px 14px; + border-radius: 10px; + border: 1px solid #334155; +} + +/* ========================================================================== + CARNÉ ESCOLAR FÍSICO IMPRIMIBLE (carnet.html) + ========================================================================== */ +.carnets-sheet { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 15mm; + padding: 10mm; +} + +.carnet-card { + width: 85.6mm; + height: 54mm; + border: 1.5px solid #cbd5e1; + border-radius: 3.5mm; + padding: 3mm 4mm; + display: flex; + flex-direction: column; + justify-content: space-between; + background: white; + color: #0f172a; + position: relative; + box-sizing: border-box; + page-break-inside: avoid; +} + +.carnet-header { + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 2px solid #0284c7; + padding-bottom: 1.5mm; +} + +.carnet-school-name { + font-size: 7.5pt; + font-weight: 800; + color: #0284c7; + text-transform: uppercase; +} + +.carnet-body { + display: flex; + gap: 3mm; + align-items: center; + margin: 2mm 0; +} + +.carnet-photo { + width: 22mm; + height: 22mm; + border-radius: 2mm; + border: 1px solid #cbd5e1; + object-fit: cover; +} + +.carnet-details { + flex: 1; +} + +.carnet-name { + font-size: 9pt; + font-weight: 900; + line-height: 1.15; + margin-bottom: 1mm; +} + +.carnet-meta-item { + font-size: 6.8pt; + color: #475569; +} + +.carnet-qr { + width: 20mm; + height: 20mm; + border: 1px solid #e2e8f0; +} + +.carnet-footer { + font-size: 5.5pt; + color: #64748b; + border-top: 1px solid #e2e8f0; + padding-top: 1mm; + display: flex; + justify-content: space-between; +} + +@media print { + body { + background: white !important; + padding: 0 !important; + } + .no-print { + display: none !important; + } + .carnet-card { + border: 1px solid #94a3b8; + box-shadow: none; + } +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..bca0a86 --- /dev/null +++ b/public/index.html @@ -0,0 +1,238 @@ + + + + + + RecreoPay - Tu Soda Escolar Digital + + + + + + + +
+ +
+ +
🥪
+
+ RecreoPay + SODA ESCOLAR CR 🇨🇷 +
+
+ + +
+ + + +
+
+ + +
+ Estudiante Activo: + +
+ + +
+
+ Avatar +
+

Cargando...

+ Grado y Sección +
+
+ +
+
+
💰 Mis Colones Disponibles
+
+ ₡0 + 🪙 +
+
+ + +
+
+ + +
+
+ Límite diario fijado: + ₡0 +
+
+ Disponible hoy: ₡0 +
+
+ + + + + +
+ +
+ + +
+ Menú del Recreo + +
+ + +
+ +
+ + + + + +
+

Acceso Rápido del Sistema:

+
+ 📟 Terminal Soda (Caja & QR) + 🖨️ Carnés Físicos para Imprimir +
+
+
+ + + + + + + + + + + + + + diff --git a/public/js/app.js b/public/js/app.js new file mode 100644 index 0000000..305463e --- /dev/null +++ b/public/js/app.js @@ -0,0 +1,449 @@ +// RECREOPAY - LÓGICA DE CLIENTE PWA (ESTUDIANTES Y PADRES) + +let students = []; +let currentStudent = null; +let categories = []; +let products = []; +let activeCategoryId = null; +let cart = []; +let currentAppMode = 'kids'; + +// Inicialización al cargar la página +document.addEventListener('DOMContentLoaded', async () => { + // Registrar Service Worker para PWA si está soportado + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js').catch(err => console.log('SW error:', err)); + } + + await loadInitialData(); +}); + +async function loadInitialData() { + try { + // 1. Cargar estudiantes + const resEst = await fetch('/api/estudiantes'); + students = await resEst.json(); + + populateStudentSelector(); + + // Seleccionar por defecto el primer estudiante (Mateo, 8 años -> Modo Kids) + if (students.length > 0) { + await selectStudent(students[0].id); + } + + // 2. Cargar productos y categorías + const resProd = await fetch('/api/productos'); + const dataProd = await resProd.json(); + categories = dataProd.categorias; + products = dataProd.productos; + + renderCategories(); + renderProducts(); + } catch (error) { + console.error('Error cargando datos iniciales:', error); + } +} + +function populateStudentSelector() { + const sel = document.getElementById('studentSelector'); + sel.innerHTML = students.map(s => ` + + `).join(''); +} + +async function onStudentChange(studentId) { + await selectStudent(studentId); +} + +async function selectStudent(studentId) { + try { + const res = await fetch(`/api/estudiantes/${studentId}`); + currentStudent = await res.json(); + + // Adaptar modo automáticamente por edad (7-10 Kids, 11-15 Teens) + if (currentStudent.edad <= 10) { + setAppMode('kids', false); + } else { + setAppMode('teens', false); + } + + updateStudentUI(); + } catch (e) { + console.error('Error seleccionando estudiante:', e); + } +} + +function updateStudentUI() { + if (!currentStudent) return; + + // Actualizar avatar, nombre y grado + document.getElementById('walletAvatar').src = currentStudent.foto_url || 'https://api.dicebear.com/7.x/bottts/svg?seed=est'; + document.getElementById('walletName').textContent = currentStudent.nombre_completo; + document.getElementById('walletGrade').textContent = `${currentStudent.grado} • Sección ${currentStudent.seccion} • Cód: ${currentStudent.codigo_estudiante}`; + + // Saldo en colones + document.getElementById('walletBalance').textContent = `₡${currentStudent.saldo_colones.toLocaleString('es-CR')}`; + + // Límite diario + document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; + document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${currentStudent.disponible_hoy.toLocaleString('es-CR')}`; + + // Alergias + const allergyBox = document.getElementById('allergyWarning'); + if (currentStudent.alergias && currentStudent.alergias !== 'Ninguna' && currentStudent.alergias !== 'Ninguna conocida') { + allergyBox.style.display = 'flex'; + document.getElementById('allergyText').textContent = currentStudent.alergias; + } else { + allergyBox.style.display = 'none'; + } + + // QR Modal info + document.getElementById('qrDisplayImg').src = `/api/qr-image/${encodeURIComponent(currentStudent.qr_token)}`; + document.getElementById('qrTokenDisplay').textContent = currentStudent.qr_token; + + // Panel de Padres sliders y valores + document.getElementById('lblParentDailyLimit').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; + document.getElementById('rangeDailyLimit').value = currentStudent.limite_diario_colones; + renderParentHistory(); +} + +function setAppMode(mode, playSound = true) { + currentAppMode = mode; + document.body.classList.remove('mode-kids', 'mode-teens'); + + document.getElementById('btnModeKids').classList.remove('active'); + document.getElementById('btnModeTeens').classList.remove('active'); + + if (mode === 'kids') { + document.body.classList.add('mode-kids'); + document.getElementById('btnModeKids').classList.add('active'); + document.getElementById('balanceLabel').textContent = '💰 Mis Colones para el Recreo'; + document.getElementById('kidsCoinIcon').style.display = 'inline-block'; + document.getElementById('qrBtnText').textContent = 'Tocar para mi QR 📱'; + } else { + document.body.classList.add('mode-teens'); + document.getElementById('btnModeTeens').classList.add('active'); + document.getElementById('balanceLabel').textContent = 'SALDO DISPONIBLE'; + document.getElementById('kidsCoinIcon').style.display = 'none'; + document.getElementById('qrBtnText').textContent = 'QR de Pago'; + } + + if (playSound && window.sounds) { + window.sounds.playCoin(); + } +} + +// Renderizado de Categorías +function renderCategories() { + const bar = document.getElementById('categoriesBar'); + let html = ` + + `; + + for (const cat of categories) { + html += ` + + `; + } + bar.innerHTML = html; +} + +function selectCategory(catId) { + activeCategoryId = catId; + renderCategories(); + renderProducts(); +} + +// Renderizado de Productos del Menú +function renderProducts() { + const grid = document.getElementById('productsGrid'); + const filterMepOnly = document.getElementById('chkFilterMep').checked; + + let filtered = products; + + if (activeCategoryId !== null) { + filtered = filtered.filter(p => p.categoria_id === activeCategoryId); + } + + if (filterMepOnly) { + filtered = filtered.filter(p => p.cumple_mep === 1); + } + + if (filtered.length === 0) { + grid.innerHTML = ` +
+

🥪

+

No hay productos en esta categoría por ahora.

+
+ `; + return; + } + + grid.innerHTML = filtered.map(prod => ` +
+
${prod.icono || '🥪'}
+
+ ${prod.cumple_mep ? '🌿 MEP Saludable' : ''} +

${prod.nombre}

+

${prod.descripcion || ''}

+ ${prod.alergenos ? `
⚠️ Contiene: ${prod.alergenos}
` : ''} +
+ +
+ `).join(''); +} + +// ========================================== +// CARRITO Y PRE-ÓRDENES +// ========================================== + +function addToCart(productId) { + const prod = products.find(p => p.id === productId); + if (!prod) return; + + const existing = cart.find(item => item.product.id === productId); + if (existing) { + existing.cantidad++; + } else { + cart.push({ product: prod, cantidad: 1 }); + } + + if (window.sounds) { + window.sounds.playCoin(); + } + + updateCartBar(); +} + +function updateCartBar() { + const bar = document.getElementById('floatingCart'); + const countBadge = document.getElementById('cartCountBadge'); + const totalText = document.getElementById('cartTotalText'); + + const totalCount = cart.reduce((sum, item) => sum + item.cantidad, 0); + const totalColones = cart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0); + + if (totalCount > 0) { + bar.style.display = 'flex'; + countBadge.textContent = `${totalCount} ${totalCount === 1 ? 'ítem' : 'ítems'}`; + totalText.textContent = `₡${totalColones.toLocaleString('es-CR')}`; + } else { + bar.style.display = 'none'; + } +} + +function openCartModal() { + renderCartModalItems(); + document.getElementById('modalCart').style.display = 'flex'; +} + +function closeCartModal(e) { + if (e && e.target !== e.currentTarget) return; + document.getElementById('modalCart').style.display = 'none'; +} + +function renderCartModalItems() { + const list = document.getElementById('cartItemsList'); + const totalEl = document.getElementById('modalCartTotal'); + + if (cart.length === 0) { + list.innerHTML = '

El carrito está vacío

'; + totalEl.textContent = '₡0'; + return; + } + + let total = 0; + list.innerHTML = cart.map((item, idx) => { + const subtotal = item.product.precio_colones * item.cantidad; + total += subtotal; + return ` +
+
+ ${item.product.icono} ${item.product.nombre} +
₡${item.product.precio_colones.toLocaleString('es-CR')} c/u
+
+
+ + ${item.cantidad} + + ₡${subtotal.toLocaleString('es-CR')} +
+
+ `; + }).join(''); + + totalEl.textContent = `₡${total.toLocaleString('es-CR')}`; +} + +function changeCartQty(index, delta) { + cart[index].cantidad += delta; + if (cart[index].cantidad <= 0) { + cart.splice(index, 1); + } + renderCartModalItems(); + updateCartBar(); +} + +async function submitPreOrder() { + if (!currentStudent) return; + if (cart.length === 0) return alert('Agrega al menos un producto a tu pre-orden'); + + const momento = document.getElementById('momentoEntregaSelect').value; + const items = cart.map(item => ({ + producto_id: item.product.id, + cantidad: item.cantidad + })); + + const btn = document.getElementById('btnConfirmarOrden'); + btn.disabled = true; + btn.textContent = 'Procesando en la soda...'; + + try { + const res = await fetch('/api/ordenes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + estudiante_id: currentStudent.id, + tipo_orden: 'preorden', + momento_entrega: momento, + items + }) + }); + + const data = await res.json(); + if (!res.ok) { + if (window.sounds) window.sounds.playError(); + throw new Error(data.error || 'Error procesando pre-orden'); + } + + if (window.sounds) window.sounds.playSuccess(); + + alert(`🎉 ¡Pre-Orden confirmada con éxito!\nCódigo de entrega: ${data.codigo_orden}\nRebajada de tu monedero: ₡${data.total_colones.toLocaleString('es-CR')}\n\nPodrás retirarla en la fila rápida de la soda durante el recreo presentando tu QR.`); + + // Limpiar carrito y recargar datos del estudiante + cart = []; + updateCartBar(); + closeCartModal(); + await selectStudent(currentStudent.id); + } catch (err) { + alert(`❌ No se pudo procesar: ${err.message}`); + } finally { + btn.disabled = false; + btn.textContent = '✅ Confirmar y Pagar Pre-Orden'; + } +} + +// ========================================== +// MODAL QR ESCOLAR +// ========================================== + +function openQrModal() { + if (window.sounds) window.sounds.playScanChirp(); + document.getElementById('modalQr').style.display = 'flex'; +} + +function closeQrModal(e) { + if (e && e.target !== e.currentTarget) return; + document.getElementById('modalQr').style.display = 'none'; +} + +// ========================================== +// PANEL DE PADRES Y RECARGAS SINPE +// ========================================== + +function toggleParentPanel(show, e) { + if (e && e.target !== e.currentTarget) return; + document.getElementById('modalPadres').style.display = show ? 'flex' : 'none'; +} + +async function quickSinpeRecharge(monto) { + await doSinpeRecharge(monto); +} + +async function customSinpeRecharge() { + const val = parseInt(document.getElementById('inputCustomSinpe').value, 10); + if (!val || val <= 0) return alert('Ingresa un monto válido en colones'); + await doSinpeRecharge(val); + document.getElementById('inputCustomSinpe').value = ''; +} + +async function doSinpeRecharge(monto) { + if (!currentStudent) return; + const comprobante = `SINPE-${Math.floor(100000 + Math.random() * 900000)}`; + + try { + const res = await fetch(`/api/estudiantes/${currentStudent.id}/recarga`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + monto, + comprobante, + descripcion: `Recarga SINPE Móvil desde portal de padres` + }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + if (window.sounds) window.sounds.playSuccess(); + alert(`✅ ¡Recarga SINPE exitosa!\nSe acreditaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentStudent.nombre_completo}.\nComprobante: ${comprobante}`); + + await selectStudent(currentStudent.id); + } catch (err) { + alert(`Error en recarga: ${err.message}`); + } +} + +async function onDailyLimitSlider(val) { + document.getElementById('lblParentDailyLimit').textContent = `₡${parseInt(val, 10).toLocaleString('es-CR')}`; + if (!currentStudent) return; + + try { + await fetch(`/api/estudiantes/${currentStudent.id}/limite`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ limite_diario_colones: parseInt(val, 10) }) + }); + // Actualizar UI sutilmente + currentStudent.limite_diario_colones = parseInt(val, 10); + document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; + } catch (e) {} +} + +function renderParentHistory() { + const container = document.getElementById('parentHistoryList'); + if (!currentStudent || !currentStudent.transacciones || currentStudent.transacciones.length === 0) { + container.innerHTML = '

Sin movimientos recientes

'; + return; + } + + container.innerHTML = currentStudent.transacciones.map(t => { + const esPositivo = t.monto_colones > 0; + const color = esPositivo ? '#166534' : '#0f172a'; + const signo = esPositivo ? '+' : ''; + const fecha = new Date(t.fecha).toLocaleDateString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + + return ` +
+
+
${t.descripcion || t.tipo}
+
${fecha}
+
+
+ ${signo}₡${Math.abs(t.monto_colones).toLocaleString('es-CR')} +
+
+ `; + }).join(''); +} diff --git a/public/js/pos.js b/public/js/pos.js new file mode 100644 index 0000000..702adb0 --- /dev/null +++ b/public/js/pos.js @@ -0,0 +1,428 @@ +// RECREOPAY - LÓGICA DE LA TERMINAL DE LA SODA (POS & ESCÁNER) + +let posProducts = []; +let posCategories = []; +let posCart = []; +let scannedStudent = null; +let currentTab = 'mostrador'; +let sseSource = null; +let videoStream = null; +let isScanningActive = true; + +document.addEventListener('DOMContentLoaded', async () => { + await loadCatalog(); + await loadPreOrders(); + initCamera(); + initSSE(); +}); + +// Cargar catálogo de productos +async function loadCatalog() { + try { + const res = await fetch('/api/productos'); + const data = await res.json(); + posCategories = data.categorias; + posProducts = data.productos; + + renderPosCategories(); + renderPosProducts(null); + } catch (err) { + console.error('Error cargando catálogo:', err); + } +} + +function renderPosCategories() { + const bar = document.getElementById('posCategoriesBar'); + bar.innerHTML = ` + + ${posCategories.map(c => ` + + `).join('')} + `; +} + +function filterPosCat(catId, btn) { + document.querySelectorAll('#posCategoriesBar .pos-tab-btn').forEach(b => b.classList.remove('active')); + if (btn) btn.classList.add('active'); + renderPosProducts(catId); +} + +function renderPosProducts(catId) { + const grid = document.getElementById('posProductsGrid'); + let list = posProducts; + if (catId !== null) { + list = list.filter(p => p.categoria_id === catId); + } + + grid.innerHTML = list.map(prod => ` +
+
${prod.icono || '🥪'}
+
+
${prod.nombre}
+ ${prod.cumple_mep ? '🌿 MEP Saludable' : ''} +
+
+ ₡${prod.precio_colones.toLocaleString('es-CR')} +
+
+ `).join(''); +} + +// Carrito de mostrador +function addToPosCart(prodId) { + const prod = posProducts.find(p => p.id === prodId); + if (!prod) return; + + const existing = posCart.find(i => i.product.id === prodId); + if (existing) { + existing.cantidad++; + } else { + posCart.push({ product: prod, cantidad: 1 }); + } + + if (window.sounds) window.sounds.playCoin(); + updatePosCartUI(); +} + +function updatePosCartUI() { + const list = document.getElementById('posCartList'); + const totalEl = document.getElementById('posCartTotal'); + + if (posCart.length === 0) { + list.innerHTML = '

Toca productos del menú para cobrar

'; + totalEl.textContent = '₡0'; + return; + } + + let total = 0; + list.innerHTML = posCart.map((item, idx) => { + const subtotal = item.product.precio_colones * item.cantidad; + total += subtotal; + return ` +
+
+ ${item.product.icono} ${item.product.nombre} +
₡${item.product.precio_colones.toLocaleString('es-CR')} c/u
+
+
+ + ${item.cantidad} + + ₡${subtotal.toLocaleString('es-CR')} +
+
+ `; + }).join(''); + + totalEl.textContent = `₡${total.toLocaleString('es-CR')}`; +} + +function changePosQty(idx, delta) { + posCart[idx].cantidad += delta; + if (posCart[idx].cantidad <= 0) { + posCart.splice(idx, 1); + } + updatePosCartUI(); +} + +function clearPosCart() { + posCart = []; + updatePosCartUI(); +} + +// ========================================== +// ESCÁNER Y LECTURA DE QR +// ========================================== + +async function initCamera() { + const video = document.getElementById('scannerVideo'); + const status = document.getElementById('cameraStatus'); + + if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { + try { + videoStream = await navigator.mediaDevices.getUserMedia({ + video: { facingMode: 'environment', width: { ideal: 640 } } + }); + video.srcObject = videoStream; + status.textContent = '🟢 Cámara conectada'; + startQrDetection(video); + } catch (err) { + status.textContent = '⚪ Modo simulación QR activo'; + } + } else { + status.textContent = '⚪ Modo simulación QR activo'; + } +} + +// Detección nativa por BarcodeDetector si el navegador lo soporta (Chrome/Edge Android) +function startQrDetection(video) { + if ('BarcodeDetector' in window) { + const detector = new window.BarcodeDetector({ formats: ['qr_code'] }); + const interval = setInterval(async () => { + if (!isScanningActive) return; + try { + const barcodes = await detector.detect(video); + if (barcodes.length > 0) { + const rawValue = barcodes[0].rawValue; + onQrCodeDetected(rawValue); + } + } catch (e) {} + }, 400); + } +} + +function simulateScan(qrToken) { + onQrCodeDetected(qrToken); +} + +async function onQrCodeDetected(token) { + if (window.sounds) window.sounds.playScanChirp(); + + // Si estamos en la pestaña de fila rápida de pre-órdenes, despachamos de inmediato + if (currentTab === 'preordenes') { + await dispatchPreOrderExpress(token); + return; + } + + // Si estamos en mostrador, identificamos al estudiante + try { + const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}`); + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + scannedStudent = data; + renderScannedStudent(); + + // Si tiene pre-órdenes listas, alertar a la cajera + if (data.preordenes_pendientes && data.preordenes_pendientes.length > 0) { + if (confirm(`🔔 ¡Atención! ${data.nombre_completo} tiene ${data.preordenes_pendientes.length} pre-orden lista para retirar. ¿Deseas verla y entregarla ahora?`)) { + switchPosTab('preordenes'); + } + } + } catch (err) { + if (window.sounds) window.sounds.playError(); + alert(`QR no reconocido: ${err.message}`); + } +} + +function renderScannedStudent() { + if (!scannedStudent) { + document.getElementById('studentScannedCard').style.display = 'none'; + document.getElementById('scannedAllergyAlert').style.display = 'none'; + return; + } + + document.getElementById('scannedAvatar').src = scannedStudent.foto_url; + document.getElementById('scannedName').textContent = scannedStudent.nombre_completo; + document.getElementById('scannedGrade').textContent = `${scannedStudent.grado} • Sección ${scannedStudent.seccion} • Cód: ${scannedStudent.codigo_estudiante}`; + document.getElementById('scannedBalance').textContent = `₡${scannedStudent.saldo_colones.toLocaleString('es-CR')}`; + document.getElementById('scannedAvailable').textContent = `₡${scannedStudent.disponible_hoy.toLocaleString('es-CR')}`; + document.getElementById('studentScannedCard').style.display = 'flex'; + + // Alerta médica en mostrador + const alertBox = document.getElementById('scannedAllergyAlert'); + if (scannedStudent.alergias && scannedStudent.alergias !== 'Ninguna' && scannedStudent.alergias !== 'Ninguna conocida') { + alertBox.style.display = 'block'; + document.getElementById('scannedAllergyText').textContent = scannedStudent.alergias; + } else { + alertBox.style.display = 'none'; + } +} + +function clearScannedStudent() { + scannedStudent = null; + renderScannedStudent(); +} + +// Ejecutar cobro en mostrador +async function executePosDebit() { + if (!scannedStudent) { + if (window.sounds) window.sounds.playError(); + return alert('⚠️ Primero escanea el carné o celular del estudiante (puedes usar los botones de prueba rápida en la cámara).'); + } + + if (posCart.length === 0) { + if (window.sounds) window.sounds.playError(); + return alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.'); + } + + const items = posCart.map(item => ({ + producto_id: item.product.id, + cantidad: item.cantidad + })); + + const btn = document.getElementById('btnCobrarPos'); + btn.disabled = true; + btn.textContent = 'Procesando débito...'; + + try { + const res = await fetch('/api/ordenes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + estudiante_id: scannedStudent.id, + tipo_orden: 'mostrador', + momento_entrega: 'inmediato', + items + }) + }); + + const data = await res.json(); + if (!res.ok) { + if (window.sounds) window.sounds.playError(); + throw new Error(data.error); + } + + if (window.sounds) window.sounds.playSuccess(); + + alert(`✅ ¡COBRO EXITOSO!\nTicket: ${data.codigo_orden}\nEstudiante: ${scannedStudent.nombre_completo}\nMonto: ₡${data.total_colones.toLocaleString('es-CR')}\nNuevo Saldo: ₡${data.financiero.estudiante.saldo_nuevo.toLocaleString('es-CR')}`); + + // Limpiar caja y refrescar + clearPosCart(); + clearScannedStudent(); + } catch (err) { + alert(`❌ Fallo en la transacción: ${err.message}`); + } finally { + btn.disabled = false; + btn.innerHTML = '📱 COBRAR CON QR DE ALUMNO'; + } +} + +// ========================================== +// FILA RÁPIDA DE PRE-ÓRDENES +// ========================================== + +function switchPosTab(tab) { + currentTab = tab; + document.getElementById('tabBtnMostrador').classList.toggle('active', tab === 'mostrador'); + document.getElementById('tabBtnPreordenes').classList.toggle('active', tab === 'preordenes'); + + document.getElementById('viewPosMostrador').style.display = tab === 'mostrador' ? 'block' : 'none'; + document.getElementById('viewPosPreordenes').style.display = tab === 'preordenes' ? 'block' : 'none'; + + if (tab === 'preordenes') { + loadPreOrders(); + } +} + +async function loadPreOrders() { + try { + const res = await fetch('/api/ordenes?tipo=preorden'); + const orders = await res.json(); + + const pendingCount = orders.filter(o => o.estado !== 'entregado' && o.estado !== 'cancelado').length; + document.getElementById('badgePreordenesCount').textContent = pendingCount; + + const list = document.getElementById('preOrdersList'); + if (orders.length === 0) { + list.innerHTML = '

No hay pre-órdenes registradas para hoy.

'; + return; + } + + list.innerHTML = orders.map(ord => { + const hora = new Date(ord.creado_en).toLocaleTimeString('es-CR', { hour: '2-digit', minute: '2-digit' }); + const itemsList = ord.items.map(i => `${i.cantidad}x ${i.icono || '🥪'} ${i.nombre}`).join(', '); + + return ` +
+
+ +
+
+ ${ord.estudiante_nombre} + ${ord.grado} - ${ord.seccion} + ${ord.estado} +
+
📦 ${itemsList}
+
Ticket: ${ord.codigo_orden} • Pedido a las ${hora} • Total: ₡${ord.total_colones.toLocaleString('es-CR')}
+
+
+ +
+ ${ord.estado === 'pendiente' ? ` + + ` : ''} + ${ord.estado === 'en_preparacion' ? ` + + ` : ''} + ${ord.estado === 'listo' ? ` + + ` : ''} + ${ord.estado === 'entregado' ? ` + ✓ Entregado + ` : ''} +
+
+ `; + }).join(''); + } catch (err) { + console.error('Error cargando pre-órdenes:', err); + } +} + +async function updateOrderStatus(orderId, nuevoEstado) { + try { + const res = await fetch(`/api/ordenes/${orderId}/estado`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ estado: nuevoEstado }) + }); + if (!res.ok) throw new Error('Error actualizando orden'); + if (window.sounds) window.sounds.playCoin(); + loadPreOrders(); + } catch (e) { + alert(e.message); + } +} + +// Despacho Express en 3 segundos mediante escaneo de QR +async function dispatchPreOrderExpress(qrToken) { + try { + const res = await fetch('/api/ordenes/despachar-qr', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ qr_token: qrToken }) + }); + + const data = await res.json(); + if (!res.ok) { + if (window.sounds) window.sounds.playError(); + throw new Error(data.error); + } + + if (window.sounds) window.sounds.playSuccess(); + + alert(`🎉 ¡ENTREGA EXPRESS EXITOSA!\n${data.mensaje}\nAlumno: ${data.estudiante.nombre_completo}\nGrado: ${data.estudiante.grado}\nProductos a entregar:\n${data.orden.items.map(i => `• ${i.cantidad}x ${i.nombre}`).join('\n')}`); + + loadPreOrders(); + } catch (err) { + alert(err.message); + } +} + +// ========================================== +// SSE (SERVER-SENT EVENTS EN TIEMPO REAL) +// ========================================== + +function initSSE() { + sseSource = new EventSource('/api/events'); + + sseSource.addEventListener('nueva_orden', (e) => { + const orden = JSON.parse(e.data); + if (window.sounds) window.sounds.playSuccess(); + // Notificación sonora y visual + loadPreOrders(); + }); + + sseSource.addEventListener('orden_actualizada', () => { + loadPreOrders(); + }); +} diff --git a/public/js/sounds.js b/public/js/sounds.js new file mode 100644 index 0000000..76c10ea --- /dev/null +++ b/public/js/sounds.js @@ -0,0 +1,124 @@ +// Sintetizador Web Audio API para feedback sonoro en tiempo real sin dependencias externas +class SoundEffects { + constructor() { + this.ctx = null; + } + + init() { + if (!this.ctx) { + const AudioCtx = window.AudioContext || window.webkitAudioContext; + this.ctx = new AudioCtx(); + } + if (this.ctx.state === 'suspended') { + this.ctx.resume(); + } + } + + // Sonido de escaneo exitoso / cobro completado (Tono alegre ascendente) + playSuccess() { + try { + this.init(); + const now = this.ctx.currentTime; + const osc1 = this.ctx.createOscillator(); + const osc2 = this.ctx.createOscillator(); + const gain = this.ctx.createGain(); + + osc1.type = 'triangle'; + osc2.type = 'sine'; + + // Acorde alegre de confirmación: C5 -> E5 -> G5 + osc1.frequency.setValueAtTime(523.25, now); + osc1.frequency.exponentialRampToValueAtTime(659.25, now + 0.1); + osc1.frequency.exponentialRampToValueAtTime(783.99, now + 0.2); + + osc2.frequency.setValueAtTime(261.63, now); + osc2.frequency.setValueAtTime(329.63, now + 0.1); + osc2.frequency.setValueAtTime(392.00, now + 0.2); + + gain.gain.setValueAtTime(0.2, now); + gain.gain.exponentialRampToValueAtTime(0.01, now + 0.35); + + osc1.connect(gain); + osc2.connect(gain); + gain.connect(this.ctx.destination); + + osc1.start(now); + osc2.start(now); + osc1.stop(now + 0.35); + osc2.stop(now + 0.35); + } catch (e) { + console.warn('Audio no disponible:', e); + } + } + + // Sonido de moneda para Modo Kids + playCoin() { + try { + this.init(); + const now = this.ctx.currentTime; + const osc = this.ctx.createOscillator(); + const gain = this.ctx.createGain(); + + osc.type = 'sine'; + osc.frequency.setValueAtTime(987.77, now); // B5 + osc.frequency.setValueAtTime(1318.51, now + 0.08); // E6 + + gain.gain.setValueAtTime(0.25, now); + gain.gain.exponentialRampToValueAtTime(0.01, now + 0.3); + + osc.connect(gain); + gain.connect(this.ctx.destination); + + osc.start(now); + osc.stop(now + 0.3); + } catch (e) {} + } + + // Chirp de escáner láser de código de barras + playScanChirp() { + try { + this.init(); + const now = this.ctx.currentTime; + const osc = this.ctx.createOscillator(); + const gain = this.ctx.createGain(); + + osc.type = 'square'; + osc.frequency.setValueAtTime(2000, now); + osc.frequency.exponentialRampToValueAtTime(1200, now + 0.06); + + gain.gain.setValueAtTime(0.15, now); + gain.gain.exponentialRampToValueAtTime(0.01, now + 0.07); + + osc.connect(gain); + gain.connect(this.ctx.destination); + + osc.start(now); + osc.stop(now + 0.07); + } catch (e) {} + } + + // Sonido de error / límite superado (Tono grave de advertencia) + playError() { + try { + this.init(); + const now = this.ctx.currentTime; + const osc = this.ctx.createOscillator(); + const gain = this.ctx.createGain(); + + osc.type = 'sawtooth'; + osc.frequency.setValueAtTime(220, now); + osc.frequency.setValueAtTime(180, now + 0.15); + + gain.gain.setValueAtTime(0.2, now); + gain.gain.exponentialRampToValueAtTime(0.01, now + 0.35); + + osc.connect(gain); + gain.connect(this.ctx.destination); + + osc.start(now); + osc.stop(now + 0.35); + } catch (e) {} + } +} + +window.sounds = new SoundEffects(); diff --git a/public/manifest.json b/public/manifest.json new file mode 100644 index 0000000..4e2b986 --- /dev/null +++ b/public/manifest.json @@ -0,0 +1,21 @@ +{ + "name": "RecreoPay - Soda Escolar Costa Rica", + "short_name": "RecreoPay", + "start_url": "/index.html", + "display": "standalone", + "background_color": "#0f172a", + "theme_color": "#0284c7", + "description": "Monedero Digital y Pre-órdenes para Sodas Escolares en Costa Rica", + "icons": [ + { + "src": "/icons/icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/icons/icon-512.png", + "sizes": "512x512", + "type": "image/png" + } + ] +} diff --git a/public/pos.html b/public/pos.html new file mode 100644 index 0000000..4333c70 --- /dev/null +++ b/public/pos.html @@ -0,0 +1,169 @@ + + + + + + RecreoPay POS - Terminal de Mostrador y Despacho + + + + + +
+ +
+
+
+ 🥪 +
+

RecreoPay Terminal Soda

+ Soda Escolar • Ventana de Atención Rápida +
+
+ +
+ + + En Línea (SSE Activo) + + + Ver PWA Estudiante ↗ + +
+
+ + +
+ + +
+ + +
+
+ +
+ +
+ +
+
+ + + +
+ + +
+
+ +
+
+ 📷 Escáner QR de Alumnos + Cámara lista +
+ +
+ +
+
+ + +
+ Prueba rápida de escaneo de carné: + + + +
+
+ + + + + + + + +
+
+ Ítems en Mostrador + +
+
+

Toca productos del menú para cobrar

+
+
+
+ + +
+
+ TOTAL A DEBITAR: + ₡0 +
+ + +
+
+
+ + + + + diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..fd5f9a5 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,47 @@ +const CACHE_NAME = 'recreopay-static-v1'; +const ASSETS_TO_CACHE = [ + '/', + '/index.html', + '/pos.html', + '/carnet.html', + '/css/styles.css', + '/js/sounds.js', + '/manifest.json' +]; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => { + return cache.addAll(ASSETS_TO_CACHE).catch(err => console.log('Cache warn:', err)); + }) + ); + self.skipWaiting(); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then((keys) => { + return Promise.all( + keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key)) + ); + }) + ); + self.clients.claim(); +}); + +self.addEventListener('fetch', (event) => { + // Let API requests pass through to the network + if (event.request.url.includes('/api/')) { + return; + } + + event.respondWith( + caches.match(event.request).then((cachedResponse) => { + return cachedResponse || fetch(event.request).catch(() => { + if (event.request.mode === 'navigate') { + return caches.match('/index.html'); + } + }); + }) + ); +}); diff --git a/server/db.js b/server/db.js new file mode 100644 index 0000000..d65785e --- /dev/null +++ b/server/db.js @@ -0,0 +1,458 @@ +const Database = require('better-sqlite3'); +const path = require('path'); +const fs = require('fs'); + +const dbPath = path.join(__dirname, 'recreopay.db'); +const db = new Database(dbPath); + +// Enable WAL mode for high concurrent read/write performance +db.pragma('journal_mode = WAL'); +db.pragma('foreign_keys = ON'); + +function initDatabase() { + const schema = ` + -- 1. Usuarios del Sistema + CREATE TABLE IF NOT EXISTS usuarios ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + rol TEXT NOT NULL, -- 'admin', 'cajero', 'padre', 'estudiante' + nombre TEXT NOT NULL, + telefono TEXT, + email TEXT, + creado_en DATETIME DEFAULT CURRENT_TIMESTAMP + ); + + -- 2. Estudiantes + CREATE TABLE IF NOT EXISTS estudiantes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + usuario_id INTEGER REFERENCES usuarios(id), + codigo_estudiante TEXT UNIQUE NOT NULL, + nombre_completo TEXT NOT NULL, + edad INTEGER NOT NULL, + grado TEXT NOT NULL, -- Ej: "2° Grado", "8° Año" + seccion TEXT NOT NULL, -- Ej: "2-B", "8-1" + qr_token TEXT UNIQUE NOT NULL, -- Token único para el QR + pin_seguridad TEXT DEFAULT '1234', + foto_url TEXT, + saldo_colones INTEGER DEFAULT 0, + limite_diario_colones INTEGER DEFAULT 3000, + alergias TEXT, -- Ej: "Alérgico al maní, intolerante a lactosa" + bloquear_chucherias INTEGER DEFAULT 0, + padre_nombre TEXT, + padre_telefono TEXT, + activo INTEGER DEFAULT 1, + creado_en DATETIME DEFAULT CURRENT_TIMESTAMP + ); + + -- 3. Categorías de Alimentos + CREATE TABLE IF NOT EXISTS categorias ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + nombre TEXT NOT NULL, + icono TEXT NOT NULL, + orden INTEGER DEFAULT 0 + ); + + -- 4. Productos + CREATE TABLE IF NOT EXISTS productos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + categoria_id INTEGER REFERENCES categorias(id), + nombre TEXT NOT NULL, + descripcion TEXT, + precio_colones INTEGER NOT NULL, + imagen_url TEXT, + icono TEXT, + calorias INTEGER, + cumple_mep INTEGER DEFAULT 1, -- 1: Saludable MEP, 0: Ocasional + alergenos TEXT, -- 'gluten, lactosa, maní' + disponible INTEGER DEFAULT 1, + permite_preorden INTEGER DEFAULT 1, + destacado INTEGER DEFAULT 0 + ); + + -- 5. Órdenes (Mostrador y Pre-órdenes) + CREATE TABLE IF NOT EXISTS ordenes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + codigo_orden TEXT UNIQUE NOT NULL, -- Ej: "ORD-1001" + estudiante_id INTEGER NOT NULL REFERENCES estudiantes(id), + tipo_orden TEXT NOT NULL, -- 'mostrador' o 'preorden' + momento_entrega TEXT NOT NULL, -- 'inmediato', 'recreo_1', 'almuerzo', 'recreo_2' + estado TEXT DEFAULT 'pendiente', -- 'pendiente', 'en_preparacion', 'listo', 'entregado', 'cancelado' + total_colones INTEGER NOT NULL, + notas TEXT, + creado_en DATETIME DEFAULT CURRENT_TIMESTAMP, + entregado_en DATETIME + ); + + -- 6. Detalles de Orden + CREATE TABLE IF NOT EXISTS orden_detalles ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + orden_id INTEGER NOT NULL REFERENCES ordenes(id) ON DELETE CASCADE, + producto_id INTEGER NOT NULL REFERENCES productos(id), + cantidad INTEGER NOT NULL, + precio_unitario INTEGER NOT NULL, + subtotal INTEGER NOT NULL + ); + + -- 7. Historial y Auditoría de Saldos (SINPE y Compras) + CREATE TABLE IF NOT EXISTS transacciones_saldo ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + estudiante_id INTEGER NOT NULL REFERENCES estudiantes(id), + tipo TEXT NOT NULL, -- 'recarga_sinpe', 'compra_mostrador', 'preorden', 'reembolso' + monto_colones INTEGER NOT NULL, -- Positivo recarga, negativo compra + saldo_previo INTEGER NOT NULL, + saldo_posterior INTEGER NOT NULL, + comprobante_sinpe TEXT, + orden_id INTEGER REFERENCES ordenes(id), + descripcion TEXT, + fecha DATETIME DEFAULT CURRENT_TIMESTAMP + ); + `; + + db.exec(schema); + seedInitialData(); +} + +function seedInitialData() { + const existingProducts = db.prepare('SELECT COUNT(*) as count FROM productos').get(); + if (existingProducts.count > 0) return; + + console.log('🌱 Inicializando datos de prueba para RecreoPay...'); + + // 1. Categorías + const insertCat = db.prepare('INSERT INTO categorias (nombre, icono, orden) VALUES (?, ?, ?)'); + insertCat.run('Meriendas Saludables', '🥪', 1); + insertCat.run('Platos Fuertes y Pintos', '🍛', 2); + insertCat.run('Bebidas y Frescos', '🧃', 3); + insertCat.run('Frutas y Snacks', '🍎', 4); + + // 2. Productos Ticos para Soda Escolar + const insertProd = db.prepare(` + INSERT INTO productos + (categoria_id, nombre, descripcion, precio_colones, icono, calorias, cumple_mep, alergenos, destacado) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + + // Meriendas + insertProd.run(1, 'Empanada Arreglada de Carne', 'Empanada casera horneada con repollo fresco y carne mechada.', 1200, '🥟', 280, 1, 'gluten', 1); + insertProd.run(1, 'Empanada de Queso Tierno', 'Masa suave de maíz con queso blanco semiduro artesanal.', 1000, '🥟', 250, 1, 'lactosa', 0); + insertProd.run(1, 'Sandwich Escolar de Jamón y Queso', 'Pan integral, jamón de pavo, queso blanco, lechuga y tomate.', 1100, '🥪', 230, 1, 'gluten, lactosa', 1); + insertProd.run(1, 'Taco Tico Crujiente', 'Tortilla de maíz con carne mechada, repollo y salsas caseras.', 1300, '🌮', 310, 1, '', 0); + + // Platos fuertes + insertProd.run(2, 'Gallo Pinto Escolar Completo', 'Pinto tradicional con huevo picado, queso fresco y natilla.', 1500, '🍳', 380, 1, 'lactosa', 1); + insertProd.run(2, 'Arroz con Pollo en Porción Escolar', 'Clásico arroz con pollo tico, frijoles molidos y ensalada rusa.', 1800, '🍗', 420, 1, '', 1); + insertProd.run(2, 'Casadito Infantil', 'Bistec en salsa suave, arroz blanco, frijoles tiernos y plátano maduro.', 2000, '🍛', 450, 1, '', 0); + + // Bebidas + insertProd.run(3, 'Fresco Natural de Cas (350ml)', 'Fruta 100% natural endulzada con moderación según norma MEP.', 700, '🍹', 90, 1, '', 1); + insertProd.run(3, 'Fresco Natural de Mora (350ml)', 'Mora fresca de altura rica en antioxidantes.', 700, '🥤', 95, 1, '', 0); + insertProd.run(3, 'Té Frío Casero con Limón', 'Té negro natural infusionado con limón fresco.', 650, '🧃', 70, 1, '', 0); + insertProd.run(3, 'Leche con Chocolate Semidescremada', 'Caja de 250ml fortalecida con calcio y vitamina D.', 800, '🥛', 140, 1, 'lactosa', 0); + + // Frutas y snacks + insertProd.run(4, 'Vaso de Fruta Picada Mixta', 'Sandía, piña y papaya dulce en cubos frescos.', 800, '🍉', 75, 1, '', 1); + insertProd.run(4, 'Yogurt Natural con Granola y Miel', 'Vaso de yogurt artesanal con avena crujiente.', 950, '🥣', 180, 1, 'lactosa, gluten', 1); + insertProd.run(4, 'Barra de Avena y Semillas', 'Horneada en la soda, libre de sellos de exceso de azúcar.', 550, '🌾', 120, 1, '', 0); + insertProd.run(4, 'Gelatina Tricolor con Leche', 'Postre ligero y divertido para el recreo.', 600, '🍮', 110, 1, 'lactosa', 0); + + // 3. Estudiantes de Prueba (Primaria y Secundaria) + const insertEst = db.prepare(` + INSERT INTO estudiantes + (codigo_estudiante, nombre_completo, edad, grado, seccion, qr_token, pin_seguridad, foto_url, saldo_colones, limite_diario_colones, alergias, padre_nombre, padre_telefono) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + + // Niños de Primaria (7 a 10 años) + insertEst.run( + 'EST-2026-001', + 'Mateo Alvarado Castro', + 8, + '2° Grado', + '2-A', + 'QR-MATEO-2026-A891', + '1234', + 'https://api.dicebear.com/7.x/bottts/svg?seed=Mateo&backgroundColor=b6e3f4', + 4500, + 2500, + 'Ninguna conocida', + 'Carlos Alvarado (Papá)', + '+506 8888-1122' + ); + + insertEst.run( + 'EST-2026-002', + 'Sofía Jiménez Morales', + 9, + '3° Grado', + '3-B', + 'QR-SOFIA-2026-B442', + '2468', + 'https://api.dicebear.com/7.x/bottts/svg?seed=Sofia&backgroundColor=ffd5dc', + 3200, + 2000, + 'Intolerancia leve a la lactosa', + 'Mariana Morales (Mamá)', + '+506 8777-3344' + ); + + insertEst.run( + 'EST-2026-003', + 'Lucía Fernández Solís', + 7, + '1° Grado', + '1-A', + 'QR-LUCIA-2026-C119', + '1111', + 'https://api.dicebear.com/7.x/bottts/svg?seed=Lucia&backgroundColor=d1d4f9', + 1800, + 1500, + 'Alérgica al maní y frutos secos', + 'Elena Solís (Mamá)', + '+506 8666-5566' + ); + + // Adolescentes de Secundaria (11 a 15 años) + insertEst.run( + 'EST-2026-004', + 'Ignacio Vargas Chaves', + 14, + '8° Año', + '8-3', + 'QR-NACHO-2026-D902', + '5555', + 'https://api.dicebear.com/7.x/bottts/svg?seed=Ignacio&backgroundColor=c0aede', + 6000, + 3500, + 'Ninguna', + 'Roberto Vargas (Papá)', + '+506 8333-7788' + ); + + insertEst.run( + 'EST-2026-005', + 'Valentina Rojas Quesada', + 13, + '7° Año', + '7-1', + 'QR-VALE-2026-E715', + '4321', + 'https://api.dicebear.com/7.x/bottts/svg?seed=Vale&backgroundColor=ffdfbf', + 5200, + 3000, + 'Vegetariana', + 'Patricia Quesada (Mamá)', + '+506 8999-0011' + ); + + console.log('✅ Base de datos inicializada con éxito.'); +} + +// ========================================== +// TRANSACCIONES ATÓMICAS FINANCIERAS (ACID) +// ========================================== + +/** + * Realiza el débito por compra (Mostrador o Preorden) + * Verifica saldo suficiente y límite diario establecido por el padre. + */ +function debitoCompraTransaction({ estudianteId, montoTotal, ordenId, descripcion, tipoOrden = 'compra_mostrador' }) { + const transaction = db.transaction(() => { + // 1. Obtener estudiante con bloqueo + const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estudianteId); + if (!est) throw new Error('Estudiante no encontrado'); + if (!est.activo) throw new Error('La cuenta del estudiante se encuentra inactiva'); + + // 2. Verificar saldo + if (est.saldo_colones < montoTotal) { + throw new Error(`Saldo insuficiente. Saldo actual: ₡${est.saldo_colones.toLocaleString('es-CR')}, Total: ₡${montoTotal.toLocaleString('es-CR')}`); + } + + // 3. Verificar límite diario + const startOfDay = new Date(); + startOfDay.setHours(0, 0, 0, 0); + const startOfDayISO = startOfDay.toISOString().replace('T', ' ').substring(0, 19); + + const gastoHoyRow = db.prepare(` + SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total_gastado_hoy + FROM transacciones_saldo + WHERE estudiante_id = ? AND monto_colones < 0 AND fecha >= ? + `).get(estudianteId, startOfDayISO); + + const totalGastadoHoy = gastoHoyRow.total_gastado_hoy; + if (totalGastadoHoy + montoTotal > est.limite_diario_colones) { + const disponibleHoy = Math.max(0, est.limite_diario_colones - totalGastadoHoy); + throw new Error(`Límite diario superado. Su límite por día es ₡${est.limite_diario_colones.toLocaleString('es-CR')}. Disponible hoy: ₡${disponibleHoy.toLocaleString('es-CR')}`); + } + + // 4. Actualizar saldo + const nuevoSaldo = est.saldo_colones - montoTotal; + db.prepare('UPDATE estudiantes SET saldo_colones = ? WHERE id = ?').run(nuevoSaldo, estudianteId); + + // 5. Registrar auditoría financiera + db.prepare(` + INSERT INTO transacciones_saldo + (estudiante_id, tipo, monto_colones, saldo_previo, saldo_posterior, orden_id, descripcion) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + estudianteId, + tipoOrden, + -montoTotal, + est.saldo_colones, + nuevoSaldo, + ordenId || null, + descripcion || 'Compra en soda escolar' + ); + + return { + exito: true, + estudiante: { + id: est.id, + nombre: est.nombre_completo, + grado: est.grado, + seccion: est.seccion, + foto_url: est.foto_url, + saldo_anterior: est.saldo_colones, + saldo_nuevo: nuevoSaldo, + limite_diario: est.limite_diario_colones, + gastado_hoy: totalGastadoHoy + montoTotal + } + }; + }); + + return transaction(); +} + +/** + * Realiza una recarga de saldo (Ej. Vía SINPE Móvil) + */ +function recargaSaldoTransaction({ estudianteId, monto, comprobanteSinpe, descripcion }) { + const transaction = db.transaction(() => { + const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estudianteId); + if (!est) throw new Error('Estudiante no encontrado'); + if (monto <= 0) throw new Error('El monto de recarga debe ser mayor a ₡0'); + + const nuevoSaldo = est.saldo_colones + monto; + db.prepare('UPDATE estudiantes SET saldo_colones = ? WHERE id = ?').run(nuevoSaldo, estudianteId); + + db.prepare(` + INSERT INTO transacciones_saldo + (estudiante_id, tipo, monto_colones, saldo_previo, saldo_posterior, comprobante_sinpe, descripcion) + VALUES (?, 'recarga_sinpe', ?, ?, ?, ?, ?) + `).run( + estudianteId, + monto, + est.saldo_colones, + nuevoSaldo, + comprobanteSinpe || 'SINPE-APP', + descripcion || `Recarga SINPE Móvil por ₡${monto.toLocaleString('es-CR')}` + ); + + return { + exito: true, + estudiante_id: est.id, + nombre: est.nombre_completo, + saldo_anterior: est.saldo_colones, + saldo_nuevo: nuevoSaldo + }; + }); + + return transaction(); +} + +/** + * Crea una orden completa (Mostrador o Preorden) con sus ítems + */ +function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, items }) { + const transaction = db.transaction(() => { + if (!items || items.length === 0) throw new Error('La orden no contiene productos'); + + // Calcular total y validar productos + let totalColones = 0; + const detallesParaInsertar = []; + + for (const item of items) { + const prod = db.prepare('SELECT * FROM productos WHERE id = ?').get(item.producto_id); + if (!prod) throw new Error(`Producto #${item.producto_id} no existe`); + if (!prod.disponible) throw new Error(`El producto "${prod.nombre}" no está disponible en este momento`); + + const cantidad = parseInt(item.cantidad, 10) || 1; + const subtotal = prod.precio_colones * cantidad; + totalColones += subtotal; + + detallesParaInsertar.push({ + producto_id: prod.id, + nombre: prod.nombre, + cantidad, + precio_unitario: prod.precio_colones, + subtotal + }); + } + + // Generar código de orden único + const countOrders = db.prepare('SELECT COUNT(*) as count FROM ordenes').get().count + 1001; + const codigoOrden = `ORD-${countOrders}`; + + // Estado inicial: si es mostrador nace entregado; si es preorden nace pendiente + const estadoInicial = tipoOrden === 'mostrador' ? 'entregado' : 'pendiente'; + const entregadoEn = tipoOrden === 'mostrador' ? new Date().toISOString() : null; + + // Insertar orden cabecera + const resultOrden = db.prepare(` + INSERT INTO ordenes + (codigo_orden, estudiante_id, tipo_orden, momento_entrega, estado, total_colones, notas, entregado_en) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `).run( + codigoOrden, + estudianteId, + tipoOrden, + momentoEntrega || 'inmediato', + estadoInicial, + totalColones, + notas || '', + entregadoEn + ); + + const ordenId = resultOrden.lastInsertRowid; + + // Insertar detalle de productos + const insertDetalle = db.prepare(` + INSERT INTO orden_detalles (orden_id, producto_id, cantidad, precio_unitario, subtotal) + VALUES (?, ?, ?, ?, ?) + `); + + for (const det of detallesParaInsertar) { + insertDetalle.run(ordenId, det.producto_id, det.cantidad, det.precio_unitario, det.subtotal); + } + + // Efectuar débito financiero + const resultadoDebito = debitoCompraTransaction({ + estudianteId, + montoTotal: totalColones, + ordenId, + descripcion: `Orden ${codigoOrden} (${tipoOrden})`, + tipoOrden: tipoOrden === 'mostrador' ? 'compra_mostrador' : 'preorden' + }); + + return { + orden_id: ordenId, + codigo_orden: codigoOrden, + tipo_orden: tipoOrden, + momento_entrega: momentoEntrega, + estado: estadoInicial, + total_colones: totalColones, + detalles: detallesParaInsertar, + financiero: resultadoDebito + }; + }); + + return transaction(); +} + +module.exports = { + db, + initDatabase, + debitoCompraTransaction, + recargaSaldoTransaction, + crearOrdenCompleta +}; diff --git a/server/server.js b/server/server.js new file mode 100644 index 0000000..a06562f --- /dev/null +++ b/server/server.js @@ -0,0 +1,388 @@ +const express = require('express'); +const cors = require('cors'); +const path = require('path'); +const QRCode = require('qrcode'); +const { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, crearOrdenCompleta } = require('./db'); + +const app = express(); +const PORT = process.env.PORT || 3030; + +// Initialize DB schema & seed data +initDatabase(); + +app.use(cors()); +app.use(express.json()); +app.use(express.static(path.join(__dirname, '../public'))); + +// Simple in-memory SSE clients for real-time notifications +const sseClients = new Set(); + +function broadcastEvent(eventType, data) { + const payload = `event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`; + for (const client of sseClients) { + try { + client.write(payload); + } catch (e) { + sseClients.delete(client); + } + } +} + +// SSE stream for real-time soda screen +app.get('/api/events', (req, res) => { + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.flushHeaders(); + + sseClients.add(res); + req.on('close', () => sseClients.delete(res)); +}); + +// ========================================== +// 1. ESTUDIANTES Y QR +// ========================================== + +// Listar todos los estudiantes +app.get('/api/estudiantes', (req, res) => { + try { + const list = db.prepare(` + SELECT e.*, + COALESCE(( + SELECT SUM(ABS(monto_colones)) + FROM transacciones_saldo + WHERE estudiante_id = e.id AND monto_colones < 0 + AND date(fecha) = date('now', 'localtime') + ), 0) as gastado_hoy + FROM estudiantes e + WHERE activo = 1 + ORDER BY grado, seccion, nombre_completo + `).all(); + res.json(list); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// Obtener estudiante por ID con historial +app.get('/api/estudiantes/:id', (req, res) => { + try { + const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(req.params.id); + if (!est) return res.status(404).json({ error: 'Estudiante no encontrado' }); + + // Gastado hoy + const gastoHoy = db.prepare(` + SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total + FROM transacciones_saldo + WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha) = date('now', 'localtime') + `).get(est.id).total; + + // Transacciones recientes + const transacciones = db.prepare(` + SELECT * FROM transacciones_saldo + WHERE estudiante_id = ? + ORDER BY fecha DESC LIMIT 20 + `).all(est.id); + + // Órdenes activas + const ordenesActivas = db.prepare(` + SELECT * FROM ordenes + WHERE estudiante_id = ? AND estado IN ('pendiente', 'en_preparacion', 'listo') + ORDER BY creado_en DESC + `).all(est.id); + + res.json({ + ...est, + gastado_hoy: gastoHoy, + disponible_hoy: Math.max(0, est.limite_diario_colones - gastoHoy), + transacciones, + ordenes_activas: ordenesActivas + }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// Buscar estudiante por código QR (Ultra rápido para terminal de caja) +app.get('/api/estudiantes/qr/:token', (req, res) => { + try { + const { token } = req.params; + const est = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(token, token); + if (!est) { + return res.status(404).json({ error: 'Código QR no reconocido en la base de datos de la escuela' }); + } + + const gastoHoy = db.prepare(` + SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total + FROM transacciones_saldo + WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha) = date('now', 'localtime') + `).get(est.id).total; + + // Verificar si tiene pre-órdenes listas para retirar en el recreo + const preordenesPendientes = db.prepare(` + SELECT o.*, + (SELECT json_group_array(json_object('nombre', p.nombre, 'cantidad', d.cantidad, 'precio', d.precio_unitario)) + FROM orden_detalles d JOIN productos p ON d.producto_id = p.id WHERE d.orden_id = o.id) as items_json + FROM ordenes o + WHERE o.estudiante_id = ? AND o.tipo_orden = 'preorden' AND o.estado IN ('pendiente', 'en_preparacion', 'listo') + ORDER BY o.creado_en ASC + `).all(est.id); + + const preordenesFormateadas = preordenesPendientes.map(o => ({ + ...o, + items: JSON.parse(o.items_json || '[]') + })); + + res.json({ + ...est, + gastado_hoy: gastoHoy, + disponible_hoy: Math.max(0, est.limite_diario_colones - gastoHoy), + preordenes_pendientes: preordenesFormateadas + }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// Generar imagen QR en PNG/SVG para el carné +app.get('/api/qr-image/:token', async (req, res) => { + try { + const qrDataUrl = await QRCode.toDataURL(req.params.token, { + width: 300, + margin: 2, + color: { + dark: '#0f172a', + light: '#ffffff' + } + }); + const base64Data = qrDataUrl.replace(/^data:image\/png;base64,/, ''); + const imgBuffer = Buffer.from(base64Data, 'base64'); + res.writeHead(200, { + 'Content-Type': 'image/png', + 'Content-Length': imgBuffer.length + }); + res.end(imgBuffer); + } catch (error) { + res.status(500).send('Error generando QR'); + } +}); + +// Recarga de saldo (SINPE Móvil) +app.post('/api/estudiantes/:id/recarga', (req, res) => { + try { + const { monto, comprobante, descripcion } = req.body; + const estudianteId = parseInt(req.params.id, 10); + + const resultado = recargaSaldoTransaction({ + estudianteId, + monto: parseInt(monto, 10), + comprobanteSinpe: comprobante || 'SINPE-MÓVIL', + descripcion: descripcion || `Recarga SINPE de ₡${parseInt(monto, 10).toLocaleString('es-CR')}` + }); + + broadcastEvent('recarga_exitosa', resultado); + res.json(resultado); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); + +// Actualizar configuración parental (Límite diario y restricciones) +app.put('/api/estudiantes/:id/limite', (req, res) => { + try { + const { limite_diario_colones, alergias, bloquear_chucherias } = req.body; + const estId = req.params.id; + + db.prepare(` + UPDATE estudiantes + SET limite_diario_colones = COALESCE(?, limite_diario_colones), + alergias = COALESCE(?, alergias), + bloquear_chucherias = COALESCE(?, bloquear_chucherias) + WHERE id = ? + `).run(limite_diario_colones, alergias, bloquear_chucherias, estId); + + const actualizado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estId); + res.json(actualizado); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); + +// ========================================== +// 2. PRODUCTOS Y MENÚ +// ========================================== + +app.get('/api/productos', (req, res) => { + try { + const categorias = db.prepare('SELECT * FROM categorias ORDER BY orden ASC').all(); + const productos = db.prepare(` + SELECT p.*, c.nombre as categoria_nombre, c.icono as categoria_icono + FROM productos p + JOIN categorias c ON p.categoria_id = c.id + WHERE p.disponible = 1 + ORDER BY p.categoria_id, p.nombre + `).all(); + + res.json({ categorias, productos }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// ========================================== +// 3. ÓRDENES (MOSTRADOR Y PRE-ÓRDENES) +// ========================================== + +// Crear orden (compra con QR o pre-orden) +app.post('/api/ordenes', (req, res) => { + try { + const { estudiante_id, qr_token, tipo_orden, momento_entrega, notas, items } = req.body; + + let targetEstudianteId = estudiante_id; + if (!targetEstudianteId && qr_token) { + const est = db.prepare('SELECT id FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(qr_token, qr_token); + if (!est) return res.status(404).json({ error: 'Estudiante no encontrado por código QR' }); + targetEstudianteId = est.id; + } + + if (!targetEstudianteId) { + return res.status(400).json({ error: 'Debe especificar el estudiante o escanear su código QR' }); + } + + const resultado = crearOrdenCompleta({ + estudianteId: targetEstudianteId, + tipoOrden: tipo_orden || 'mostrador', + momentoEntrega: momento_entrega || 'inmediato', + notas, + items + }); + + // Notificar en tiempo real a la pantalla de cocina/caja de la soda + broadcastEvent('nueva_orden', resultado); + + res.status(201).json(resultado); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); + +// Listar órdenes (con filtro por estado o tipo) +app.get('/api/ordenes', (req, res) => { + try { + const { estado, tipo } = req.query; + let query = ` + SELECT o.*, e.nombre_completo as estudiante_nombre, e.grado, e.seccion, e.foto_url, + (SELECT json_group_array(json_object('producto_id', p.id, 'nombre', p.nombre, 'icono', p.icono, 'cantidad', d.cantidad, 'precio_unitario', d.precio_unitario, 'subtotal', d.subtotal)) + FROM orden_detalles d JOIN productos p ON d.producto_id = p.id WHERE d.orden_id = o.id) as items_json + FROM ordenes o + JOIN estudiantes e ON o.estudiante_id = e.id + WHERE 1=1 + `; + const params = []; + + if (estado) { + query += ' AND o.estado = ?'; + params.push(estado); + } + if (tipo) { + query += ' AND o.tipo_orden = ?'; + params.push(tipo); + } + + query += ' ORDER BY o.creado_en DESC LIMIT 50'; + + const ordenes = db.prepare(query).all(...params); + const resultado = ordenes.map(o => ({ + ...o, + items: JSON.parse(o.items_json || '[]') + })); + + res.json(resultado); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// Actualizar estado de una orden (Cocina -> Listo -> Entregado) +app.put('/api/ordenes/:id/estado', (req, res) => { + try { + const { estado } = req.body; + const ordenId = req.params.id; + + const entregadoEn = estado === 'entregado' ? new Date().toISOString() : null; + + db.prepare(` + UPDATE ordenes + SET estado = ?, entregado_en = COALESCE(?, entregado_en) + WHERE id = ? + `).run(estado, entregadoEn, ordenId); + + const actualizada = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId); + broadcastEvent('orden_actualizada', actualizada); + + res.json(actualizada); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); + +// Despacho ultra-rápido en fila de pre-órdenes mediante escaneo de QR +app.post('/api/ordenes/despachar-qr', (req, res) => { + try { + const { qr_token } = req.body; + if (!qr_token) return res.status(400).json({ error: 'Se requiere el código QR del estudiante' }); + + const est = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(qr_token, qr_token); + if (!est) return res.status(404).json({ error: 'Estudiante no identificado' }); + + // Buscar la pre-orden más prioritaria lista o pendiente para entrega + const preorden = db.prepare(` + SELECT * FROM ordenes + WHERE estudiante_id = ? AND tipo_orden = 'preorden' AND estado IN ('listo', 'pendiente', 'en_preparacion') + ORDER BY creado_en ASC LIMIT 1 + `).get(est.id); + + if (!preorden) { + return res.status(404).json({ + error: `No hay pre-órdenes pendientes de retiro para ${est.nombre_completo} en este recreo.` + }); + } + + // Marcar como entregada + db.prepare("UPDATE ordenes SET estado = 'entregado', entregado_en = datetime('now', 'localtime') WHERE id = ?").run(preorden.id); + + // Obtener detalles para mostrar en pantalla de caja + const items = db.prepare(` + SELECT p.nombre, p.icono, d.cantidad, d.subtotal + FROM orden_detalles d + JOIN productos p ON d.producto_id = p.id + WHERE d.orden_id = ? + `).all(preorden.id); + + const responseData = { + exito: true, + mensaje: `¡Pre-orden ${preorden.codigo_orden} despachada con éxito!`, + estudiante: est, + orden: { + id: preorden.id, + codigo: preorden.codigo_orden, + momento_entrega: preorden.momento_entrega, + total: preorden.total_colones, + items + } + }; + + broadcastEvent('orden_despachada', responseData); + res.json(responseData); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// Iniciar servidor +app.listen(PORT, () => { + console.log(`🚀 Servidor RecreoPay iniciado en http://localhost:${PORT}`); + console.log(`📱 PWA Estudiantes/Padres: http://localhost:${PORT}/index.html`); + console.log(`📟 Terminal Soda/Escáner QR: http://localhost:${PORT}/pos.html`); + console.log(`🖨️ Generador de Carnés Físicos: http://localhost:${PORT}/carnet.html`); +});