diff --git a/.agents/skills/frontend-design/LICENSE.txt b/.agents/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/.agents/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..a533345 --- /dev/null +++ b/.agents/skills/frontend-design/SKILL.md @@ -0,0 +1,71 @@ +--- +name: frontend-design +description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. +license: Complete terms in LICENSE.txt +--- + +# Frontend Design + +Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified. + +## Ground your designs in the subject matter + +If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout. + +## Design principles + +For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option. + +Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct. + +Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content. + +Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif. + +Avoid these default typographic treatments; they are the commonest tells of a generated page: +- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color. +- Using all caps for labels. +- Adding unnecessary typographic labels above content. + +Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence. + +Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed. + +Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance. + +## Process: plan, review against the brief, build, critique + +For calibration, AI-generated design right now clusters around some traits: +1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell); +2. a near-black background with a single bright acid-green or vermilion accent; +3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns; +4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration; +5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text. + +All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn. + +Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles. +- Color: describe the core base palette as 4–6 named hex values. +- Type: the typefaces and their roles. +- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified? +- Principles: the high-level guidance for what makes this page unique. + +Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan. + +When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections. + +## Restraint and self-critique + +Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes. + +## More on writing in design + +Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience. + +Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever. + +Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around. + +Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act. + +Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job. diff --git a/.archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html b/.archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html new file mode 100644 index 0000000..ce31416 --- /dev/null +++ b/.archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html @@ -0,0 +1,14936 @@ + + + + + + + + Arquitectura de Gruperly · Diagrama + + + + + + + + + +
+ +
+
+
+

Arquitectura de Gruperly

+
+
+ + + + +
+ + Arquitectura de Gruperly + Un diagrama de arquitectura generado por Archify. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Profesor · navegador / PWA · Componente de arquitectura + + + + Profesor + navegador / PWA + + + + Web PWA · React 19 · Vite · Componente de arquitectura + + + + Web PWA + React 19 · Vite + + + + Alumno / tutor · /i/:token · /student · Componente de arquitectura + + + + Alumno / tutor + /i/:token · /student + + + + nginx · bundle + proxy /api · Dokploy + + + + nginx + bundle + proxy /api + + + + Guards de sesión · Better Auth · alumno · Dokploy › contenedor api + + + + Guards de sesión + Better Auth · alumno + + + + API Hono + jobs · Bun.serve :4000 · cron · Dokploy › contenedor api + + + + API Hono + jobs + Bun.serve :4000 · cron + + + + PostgreSQL · Prisma 7 · adapter-pg · Dokploy + + + + PostgreSQL + Prisma 7 · adapter-pg + + + + Mercado Pago · OAuth · Checkout Pro · Componente de arquitectura + + + + Mercado Pago + OAuth · Checkout Pro + + + + Stripe · Pro fuera de AR · Componente de arquitectura + + + + Stripe + Pro fuera de AR + + + + WhatsApp · OpenWA / Kapso · Componente de arquitectura + + + + WhatsApp + OpenWA / Kapso + + + + SMTP · mails · Componente de arquitectura + + + + SMTP + mails + + + + S3 (RustFS) · comprobantes · Componente de arquitectura + + + + S3 (RustFS) + comprobantes + + + + + + HTTPS + + + + link de WhatsApp + + + + /api/v1 + + + + proxy_pass + + + + + SQL + + + + cobros + + + + Pro + + + + mensajes + + + + mails + + + + URLs firmadas + + + + + + Dokploy + + + + + contenedor api + + + + + Leyenda + + + Frontend + + + + Backend + + + + Base de datos + + + + Nube + + + + Seguridad + + + + Externo + + + +

+ + + + + + + + + +
+ + + +
+ + + + diff --git a/.archify/architecture-gruperly-20261103-121500/candidate.json b/.archify/architecture-gruperly-20261103-121500/candidate.json new file mode 100644 index 0000000..d1dab3b --- /dev/null +++ b/.archify/architecture-gruperly-20261103-121500/candidate.json @@ -0,0 +1,448 @@ +{ + "schema_version": 1, + "diagram_type": "architecture", + "meta": { + "title": "Arquitectura de Gruperly", + "locale": "es", + "output": ".archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html", + "quality_profile": "showcase", + "repository": { + "url": "https://git.2pidev.com/jselesan/gruperly.git", + "link_mode": "local-only", + "revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3" + }, + "views": [ + { + "id": "request", + "label": "Pedido del profe", + "focus": [ + "teacher", + "web", + "nginx", + "guards", + "api", + "db" + ], + "note": "Mismo dominio: nginx sirve el bundle y hace proxy de /api al contenedor api." + }, + { + "id": "students", + "label": "App de alumnos", + "focus": [ + "student", + "web", + "guards", + "storage" + ], + "note": "Sin Better Auth: cookie y middleware propios; comprobantes en S3 privado." + }, + { + "id": "integrations", + "label": "Integraciones", + "focus": [ + "api", + "mp", + "stripe", + "whatsapp", + "smtp", + "storage" + ], + "note": "Cada proveedor detrás de un puerto; sin credenciales responde 503 y el resto sigue andando." + } + ] + }, + "components": [ + { + "id": "teacher", + "type": "external", + "label": "Profesor", + "sublabel": "navegador / PWA", + "icon": "person", + "pos": [ + 40, + 60 + ], + "size": [ + 120, + 60 + ], + "sources": [ + { + "path": "apps/web/src/routes/_authenticated.tsx", + "line": 1 + } + ] + }, + { + "id": "web", + "type": "frontend", + "label": "Web PWA", + "sublabel": "React 19 · Vite", + "pos": [ + 230, + 56 + ], + "size": [ + 140, + 68 + ], + "sources": [ + { + "path": "apps/web/vite.config.ts", + "line": 12, + "label": "VitePWA" + } + ] + }, + { + "id": "student", + "type": "external", + "label": "Alumno / tutor", + "sublabel": "/i/:token · /student", + "icon": "person", + "pos": [ + 230, + 240 + ], + "size": [ + 140, + 60 + ], + "sources": [ + { + "path": "apps/web/src/routes/i.$token.tsx", + "line": 1 + }, + { + "path": "apps/web/src/routes/_student.tsx", + "line": 1 + } + ] + }, + { + "id": "nginx", + "type": "cloud", + "label": "nginx", + "sublabel": "bundle + proxy /api", + "pos": [ + 450, + 60 + ], + "size": [ + 140, + 60 + ], + "sources": [ + { + "path": "apps/web/nginx.conf", + "line": 14, + "end_line": 26 + }, + { + "path": "docker-compose.yml", + "line": 1, + "end_line": 8 + } + ] + }, + { + "id": "guards", + "type": "security", + "label": "Guards de sesión", + "sublabel": "Better Auth · alumno", + "pos": [ + 680, + 56 + ], + "size": [ + 150, + 68 + ], + "sources": [ + { + "path": "apps/backend/src/http/session-auth.ts", + "line": 23, + "end_line": 48 + }, + { + "path": "apps/backend/src/modules/student-portal/middleware.ts", + "line": 50 + } + ] + }, + { + "id": "api", + "type": "backend", + "label": "API Hono + jobs", + "sublabel": "Bun.serve :4000 · cron", + "pos": [ + 880, + 56 + ], + "size": [ + 150, + 68 + ], + "sources": [ + { + "path": "apps/backend/src/server.ts", + "line": 14, + "end_line": 23 + }, + { + "path": "apps/backend/src/app.ts", + "line": 44, + "end_line": 73 + } + ] + }, + { + "id": "db", + "type": "database", + "label": "PostgreSQL", + "sublabel": "Prisma 7 · adapter-pg", + "pos": [ + 1090, + 60 + ], + "size": [ + 140, + 60 + ], + "sources": [ + { + "path": "apps/backend/src/lib/prisma.ts", + "line": 14, + "end_line": 18 + } + ] + }, + { + "id": "mp", + "type": "external", + "label": "Mercado Pago", + "sublabel": "OAuth · Checkout Pro", + "pos": [ + 610, + 320 + ], + "size": [ + 130, + 60 + ], + "sources": [ + { + "path": "apps/backend/src/modules/mp/lib/mp-oauth.ts", + "line": 3, + "end_line": 4 + }, + { + "path": "apps/backend/src/modules/mp/lib/mp-http.ts", + "line": 4 + } + ] + }, + { + "id": "stripe", + "type": "external", + "label": "Stripe", + "sublabel": "Pro fuera de AR", + "pos": [ + 760, + 320 + ], + "size": [ + 110, + 60 + ], + "sources": [ + { + "path": "apps/backend/src/modules/billing/providers/index.ts", + "line": 24, + "end_line": 31 + } + ] + }, + { + "id": "whatsapp", + "type": "external", + "label": "WhatsApp", + "sublabel": "OpenWA / Kapso", + "pos": [ + 890, + 320 + ], + "size": [ + 130, + 60 + ], + "sources": [ + { + "path": "apps/backend/src/modules/whatsapp/providers/index.ts", + "line": 26, + "end_line": 40 + } + ] + }, + { + "id": "smtp", + "type": "external", + "label": "SMTP", + "sublabel": "mails", + "pos": [ + 1040, + 320 + ], + "size": [ + 100, + 60 + ], + "sources": [ + { + "path": "apps/backend/src/lib/email.ts", + "line": 181, + "end_line": 187 + } + ] + }, + { + "id": "storage", + "type": "cloud", + "label": "S3 (RustFS)", + "sublabel": "comprobantes", + "pos": [ + 1160, + 320 + ], + "size": [ + 130, + 60 + ], + "sources": [ + { + "path": "apps/backend/src/lib/storage.ts", + "line": 38, + "end_line": 54 + } + ] + } + ], + "boundaries": [ + { + "kind": "region", + "label": "Dokploy", + "wraps": [ + "nginx", + "guards", + "api", + "db" + ] + }, + { + "kind": "security-group", + "label": "contenedor api", + "wraps": [ + "guards", + "api" + ] + } + ], + "connections": [ + { + "id": "teacher-web", + "from": "teacher", + "to": "web", + "label": "HTTPS", + "variant": "emphasis" + }, + { + "id": "student-web", + "from": "student", + "to": "web", + "label": "link de WhatsApp" + }, + { + "id": "web-nginx", + "from": "web", + "to": "nginx", + "label": "/api/v1", + "variant": "emphasis" + }, + { + "id": "nginx-guards", + "from": "nginx", + "to": "guards", + "label": "proxy_pass", + "variant": "emphasis" + }, + { + "id": "guards-api", + "from": "guards", + "to": "api", + "variant": "security" + }, + { + "id": "api-db", + "from": "api", + "to": "db", + "label": "SQL" + }, + { + "id": "api-mp", + "from": "api", + "to": "mp", + "label": "cobros" + }, + { + "id": "api-stripe", + "from": "api", + "to": "stripe", + "label": "Pro" + }, + { + "id": "api-whatsapp", + "from": "api", + "to": "whatsapp", + "label": "mensajes" + }, + { + "id": "api-smtp", + "from": "api", + "to": "smtp", + "label": "mails" + }, + { + "id": "api-storage", + "from": "api", + "to": "storage", + "label": "URLs firmadas" + } + ], + "cards": [ + { + "dot": "cyan", + "title": "Entrada", + "items": [ + "Un solo dominio público en el contenedor web: nginx sirve la PWA y hace proxy de /api a api:4000, así la cookie de sesión es first-party.", + "Los alumnos entran por un link de invitación de un solo uso; no tienen contraseña." + ] + }, + { + "dot": "rose", + "title": "Seguridad", + "items": [ + "sessionAuthMiddleware exige sesión de Better Auth salvo la whitelist pública (isPublicApiRequest).", + "/student-portal usa cookie y middleware propios (studentSession); una sesión de alumno no llega a rutas del profe.", + "Los webhooks de MP, Stripe y WhatsApp son públicos y se autentican por firma." + ] + }, + { + "dot": "emerald", + "title": "Jobs en el mismo proceso", + "items": [ + "server.ts arranca los crons de MP, pagos, WhatsApp, billing y app de alumnos junto a Bun.serve.", + "La conciliación de pagos es por polling a Mercado Pago, sin webhook." + ] + } + ] +} \ No newline at end of file diff --git a/.archify/erd-personas-membresias-20261103-120000/candidate.json b/.archify/erd-personas-membresias-20261103-120000/candidate.json new file mode 100644 index 0000000..d4c9565 --- /dev/null +++ b/.archify/erd-personas-membresias-20261103-120000/candidate.json @@ -0,0 +1,515 @@ +{ + "schema_version": 1, + "diagram_type": "erd", + "meta": { + "title": "Personas y membresías", + "locale": "es", + "output": ".archify/erd-personas-membresias-20261103-120000/personas-membresias.html", + "quality_profile": "standard", + "repository": { + "url": "https://git.2pidev.com/jselesan/gruperly.git", + "link_mode": "local-only", + "revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3" + }, + "views": [ + { + "id": "membership", + "label": "Persona y membresía", + "focus": [ + "people", + "attendees", + "groups" + ], + "note": "Una persona del profe, una fila de attendees por cada grupo en el que está." + }, + { + "id": "owner", + "label": "Todo cuelga del profe", + "focus": [ + "users", + "groups", + "people", + "student_accounts" + ], + "note": "Grupos, personas y cuentas de alumno tienen created_by_id al profe." + }, + { + "id": "student_app", + "label": "Una cuenta por persona", + "focus": [ + "student_accounts", + "student_account_people", + "people" + ], + "note": "La cuenta se vincula a la persona, así ve todos sus grupos." + } + ] + }, + "layout": { + "mode": "grid", + "gapX": 72, + "gapY": 40 + }, + "entities": [ + { + "id": "groups", + "label": "groups", + "tag": "grupos", + "row": 0, + "col": 0, + "width": 256, + "sources": [ + { + "path": "apps/backend/prisma/models/domain.prisma", + "line": 3, + "end_line": 32 + } + ], + "attributes": [ + { + "name": "id", + "type": "text", + "key": "pk" + }, + { + "name": "name", + "type": "text" + }, + { + "name": "description", + "type": "text?" + }, + { + "name": "days", + "type": "WeekDay[]" + }, + { + "name": "time", + "type": "text?" + }, + { + "name": "capacity", + "type": "int?" + }, + { + "name": "price", + "type": "numeric(10,2)?" + }, + { + "name": "billing_type", + "type": "BillingType?" + }, + { + "name": "due_day", + "type": "int?" + }, + { + "name": "auto_payment_reminders", + "type": "boolean" + }, + { + "name": "auto_reengagement", + "type": "boolean" + }, + { + "name": "invite_token", + "type": "text?", + "key": "uk" + }, + { + "name": "created_by_id", + "type": "text", + "key": "fk", + "references": "users.id" + }, + { + "name": "created_at", + "type": "timestamp" + }, + { + "name": "updated_at", + "type": "timestamp" + } + ] + }, + { + "id": "attendees", + "label": "attendees", + "sublabel": "membresía", + "tag": "membresías", + "row": 0, + "col": 1, + "width": 250, + "sources": [ + { + "path": "apps/backend/prisma/models/domain.prisma", + "line": 100, + "end_line": 125 + } + ], + "attributes": [ + { + "name": "id", + "type": "text", + "key": "pk" + }, + { + "name": "group_id", + "type": "text", + "key": [ + "fk", + "uk" + ], + "references": "groups.id" + }, + { + "name": "person_id", + "type": "text", + "key": [ + "fk", + "uk" + ], + "references": "people.id" + }, + { + "name": "notify_token", + "type": "text?", + "key": "uk" + }, + { + "name": "status", + "type": "AttendeeStatus" + }, + { + "name": "created_at", + "type": "timestamp" + }, + { + "name": "updated_at", + "type": "timestamp" + } + ] + }, + { + "id": "people", + "label": "people", + "sublabel": "persona del profe", + "tag": "personas", + "row": 0, + "col": 2, + "width": 250, + "sources": [ + { + "path": "apps/backend/prisma/models/domain.prisma", + "line": 75, + "end_line": 98 + }, + { + "path": "apps/backend/prisma/migrations/20261102180000_add_people/migration.sql", + "line": 155, + "label": "índice parcial" + } + ], + "attributes": [ + { + "name": "id", + "type": "text", + "key": "pk" + }, + { + "name": "created_by_id", + "type": "text", + "key": [ + "fk", + "uk" + ], + "references": "users.id" + }, + { + "name": "full_name", + "type": "text" + }, + { + "name": "email", + "type": "text?" + }, + { + "name": "phone", + "type": "text?", + "key": "uk" + }, + { + "name": "guardian_name", + "type": "text?" + }, + { + "name": "guardian_phone", + "type": "text?" + }, + { + "name": "notes", + "type": "text?" + }, + { + "name": "created_at", + "type": "timestamp" + }, + { + "name": "updated_at", + "type": "timestamp" + } + ] + }, + { + "id": "users", + "label": "users", + "sublabel": "profesor", + "tag": "profesor", + "row": 1, + "col": 2, + "width": 250, + "sources": [ + { + "path": "apps/backend/prisma/models/auth.prisma", + "line": 3, + "end_line": 34 + } + ], + "attributes": [ + { + "name": "id", + "type": "text", + "key": "pk" + }, + { + "name": "name", + "type": "text" + }, + { + "name": "email", + "type": "text", + "key": "uk" + }, + { + "name": "email_verified", + "type": "boolean" + }, + { + "name": "image", + "type": "text?" + }, + { + "name": "onboarding_completed", + "type": "boolean" + }, + { + "name": "country_code", + "type": "text?" + }, + { + "name": "plan_selected_at", + "type": "timestamp?" + }, + { + "name": "transfer_alias", + "type": "text?" + }, + { + "name": "transfer_holder", + "type": "text?" + }, + { + "name": "created_at", + "type": "timestamp" + }, + { + "name": "updated_at", + "type": "timestamp" + } + ] + }, + { + "id": "student_account_people", + "label": "student_account_people", + "tag": "app de alumnos", + "row": 0, + "col": 3, + "width": 300, + "sources": [ + { + "path": "apps/backend/prisma/models/student-access.prisma", + "line": 40, + "end_line": 54 + } + ], + "attributes": [ + { + "name": "account_id", + "type": "text", + "key": [ + "pk", + "fk" + ], + "references": "student_accounts.id" + }, + { + "name": "person_id", + "type": "text", + "key": [ + "pk", + "fk" + ], + "references": "people.id" + }, + { + "name": "created_at", + "type": "timestamp" + } + ] + }, + { + "id": "student_accounts", + "label": "student_accounts", + "tag": "app de alumnos", + "row": 1, + "col": 3, + "width": 300, + "sources": [ + { + "path": "apps/backend/prisma/models/student-access.prisma", + "line": 10, + "end_line": 38 + } + ], + "attributes": [ + { + "name": "id", + "type": "text", + "key": "pk" + }, + { + "name": "name", + "type": "text" + }, + { + "name": "recovery_email", + "type": "text?" + }, + { + "name": "recovery_email_verified_at", + "type": "timestamp?" + }, + { + "name": "pending_recovery_email", + "type": "text?" + }, + { + "name": "welcomed_at", + "type": "timestamp?" + }, + { + "name": "created_by_id", + "type": "text", + "key": "fk", + "references": "users.id" + }, + { + "name": "created_at", + "type": "timestamp" + }, + { + "name": "updated_at", + "type": "timestamp" + } + ] + } + ], + "relationships": [ + { + "id": "attendee_group", + "from": "attendees", + "to": "groups", + "label": "en el grupo", + "fromCardinality": "many", + "fromOptional": true, + "toCardinality": "one" + }, + { + "id": "attendee_person", + "from": "attendees", + "to": "people", + "label": "membresía de", + "fromCardinality": "many", + "toCardinality": "one" + }, + { + "id": "person_owner", + "from": "people", + "to": "users", + "label": "del profe", + "fromCardinality": "many", + "fromOptional": true, + "toCardinality": "one" + }, + { + "id": "group_owner", + "from": "groups", + "to": "users", + "label": "dueño", + "fromCardinality": "many", + "fromOptional": true, + "toCardinality": "one" + }, + { + "id": "link_person", + "from": "student_account_people", + "to": "people", + "fromCardinality": "many", + "fromOptional": true, + "toCardinality": "one" + }, + { + "id": "link_account", + "from": "student_account_people", + "to": "student_accounts", + "fromCardinality": "many", + "toCardinality": "one" + }, + { + "id": "account_owner", + "from": "student_accounts", + "to": "users", + "label": "creada por", + "fromCardinality": "many", + "fromOptional": true, + "toCardinality": "one" + } + ], + "cards": [ + { + "dot": "cyan", + "title": "Unicidad", + "items": [ + "attendees: @@unique(group_id, person_id), una persona está una sola vez en cada grupo.", + "people_owner_phone_key: (created_by_id, phone) WHERE phone IS NOT NULL, índice parcial escrito a mano (Prisma no lo modela; el choque llega como P2002)." + ] + }, + { + "dot": "amber", + "title": "Qué es de quién", + "items": [ + "people: contacto y notas; editarlos cambia en todos los grupos.", + "attendees: status y notify_token por grupo; asistencia, cuotas, alertas y mensajes cuelgan de esta fila (no dibujados).", + "El límite del plan cuenta personas con al menos una membresía ACTIVE." + ] + }, + { + "dot": "emerald", + "title": "Borrados", + "items": [ + "Todas las FK son ON DELETE CASCADE.", + "Quitar la última membresía borra también la persona, y con ella el vínculo a la cuenta de alumno." + ] + } + ] +} \ No newline at end of file diff --git a/.archify/erd-personas-membresias-20261103-120000/personas-membresias.html b/.archify/erd-personas-membresias-20261103-120000/personas-membresias.html new file mode 100644 index 0000000..2cda21e --- /dev/null +++ b/.archify/erd-personas-membresias-20261103-120000/personas-membresias.html @@ -0,0 +1,15274 @@ + + + + + + + + Personas y membresías · Diagrama + + + + + + + + + +
+ +
+
+
+

Personas y membresías

+
+
+ + + + +
+ + Personas y membresías + Un diagrama de entidad-relación generado por Archify. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + grupos + + + + + + membresías + + + + + + personas + + + + + + profesor + + + + + + app de alumnos + + + + + + + + + + + + + + + + + groups · Entidad · grupos + + + + + + groups + + + + + PK + id + text + + + + + + name + text + + + + + + description + text? + + + + + + days + WeekDay[] + + + + + + time + text? + + + + + + capacity + int? + + + + + + price + numeric(10,2)? + + + + + + billing_type + BillingType? + + + + + + due_day + int? + + + + + + auto_payment_reminders + boolean + + + + + + auto_reengagement + boolean + + + + + UK + invite_token + text? + + + + + FK + created_by_id + text + + + + + + created_at + timestamp + + + + + + updated_at + timestamp + + + + + attendees · membresía · Entidad · membresías + + + + + + attendees + + + + + PK + id + text + + + + + FKUK + group_id + text + + + + + FKUK + person_id + text + + + + + UK + notify_token + text? + + + + + + status + AttendeeStatus + + + + + + created_at + timestamp + + + + + + updated_at + timestamp + + + + + people · persona del profe · Entidad · personas + + + + + + people + + + + + PK + id + text + + + + + FKUK + created_by_id + text + + + + + + full_name + text + + + + + + email + text? + + + + + UK + phone + text? + + + + + + guardian_name + text? + + + + + + guardian_phone + text? + + + + + + notes + text? + + + + + + created_at + timestamp + + + + + + updated_at + timestamp + + + + + users · profesor · Entidad · profesor + + + + + + users + + + + + PK + id + text + + + + + + name + text + + + + + UK + email + text + + + + + + email_verified + boolean + + + + + + image + text? + + + + + + onboarding_completed + boolean + + + + + + country_code + text? + + + + + + plan_selected_at + timestamp? + + + + + + transfer_alias + text? + + + + + + transfer_holder + text? + + + + + + created_at + timestamp + + + + + + updated_at + timestamp + + + + + student_account_people · Entidad · app de alumnos + + + + + + student_account_people + + + + + PKFK + account_id + text + + + + + PKFK + person_id + text + + + + + + created_at + timestamp + + + + + student_accounts · Entidad · app de alumnos + + + + + + student_accounts + + + + + PK + id + text + + + + + + name + text + + + + + + recovery_email + text? + + + + + + recovery_email_verified_at + timestamp? + + + + + + pending_recovery_email + text? + + + + + + welcomed_at + timestamp? + + + + + FK + created_by_id + text + + + + + + created_at + timestamp + + + + + + updated_at + timestamp + + + + + + + en el grupo + + + + membresía de + + + + del profe + + + + dueño + + + + creada por + + + + + Leyenda + + PK + Clave primaria + + + FK + Clave foránea + + + UK + Clave única + + + + Uno + + + + Muchos + + + + Opcional + + + +

+ + + + + + + + + +
+ + + +
+ + + + diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..858898b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,29 @@ +# Dependencias y artefactos locales: el build los regenera adentro de la imagen. +node_modules +**/node_modules + +# Se generan en el builder (prisma generate, vite build). +apps/backend/generated +apps/backend/dist +apps/web/dist +.turbo +**/.turbo + +# Secretos: en Dokploy llegan por variables de entorno. +.env +**/.env +!.env.example +**/.env.example + +# Ruido del repo. +.git +.gitignore +.github +.DS_Store +*.log +README.md +stack.md +skills-lock.json +**/skills-lock.json +.agents +**/.agents diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..867841c --- /dev/null +++ b/.env.example @@ -0,0 +1,81 @@ +# Variable template for `docker compose`. +# +# Local: copy this file to `.env` at the root and fill in the values. +# Dokploy: no file needed; define the same variables in the Environment tab of +# the Compose service (Dokploy writes them to a `.env` next to the compose +# file, which is where the `${...}` come from). + +# Public origin of the app, no trailing slash. The same value feeds WEB_URL and +# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a +# domain, so the session cookie is first-party. +WEB_URL="http://localhost:8080" + +# Production PostgreSQL. +# The password must be percent-encoded: if it has #, @, :, /, ?, % or a space, +# escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the +# URL where the fragment starts and fails with P1013 "invalid port number in +# database URL". +DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public" + +# Generate it with: openssl rand -base64 32 +BETTER_AUTH_SECRET="" + +# ── Optional ───────────────────────────────────────────────────────────────── + +# Social login with Google. Without a client id/secret the provider is not +# registered. +# GOOGLE_CLIENT_ID="" +# GOOGLE_CLIENT_SECRET="" + +# Email sending (same variables as apps/backend/.env.example). +# EMAIL_PROVIDER="smtp" +# EMAIL_SERVER_HOST="" +# EMAIL_SERVER_PORT="587" +# EMAIL_SERVER_USER="" +# EMAIL_SERVER_PASSWORD="" +# EMAIL_FROM="Gruperly " + +# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales +# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando +# (el paso "Cobros" del onboarding es salteable). +# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded. +# TOKEN_ENCRYPTION_KEY="" +# Redirect URL registered in the Mercado Pago panel, character for character. +# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel. +# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback" +# MP_CLIENT_ID="" +# MP_CLIENT_SECRET="" + +# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md). +# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra +# entre países). No son las del OAuth del profesor. Un país sin las dos queda +# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY. +# MP_PLATFORM_ACCESS_TOKEN_AR="" +# MP_PLATFORM_WEBHOOK_SECRET_AR="" +# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro. +# BILLING_ENFORCEMENT="off" +# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando. +# BILLING_GRACE_DAYS="7" + +# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md). +# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503 +# whatsapp_not_configured y el paso del onboarding es salteable. +# WHATSAPP_PROVIDER="openwa" # openwa (MVP) | kapso +# WHATSAPP_SEND_INTERVAL_MS="5000" # pausa entre envios del mismo profesor +# +# OpenWA (se instala aparte, fuera de este compose). +# OPENWA_API_URL="https://openwa.example.com/api" +# OPENWA_API_KEY="" # key OPERATOR, sin allowedSessions +# OPENWA_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/openwa" +# OPENWA_WEBHOOK_SECRET="" # 16+ caracteres: openssl rand -hex 24 +# +# Kapso (API oficial de WhatsApp Cloud). +# KAPSO_API_KEY="" +# KAPSO_CALLBACK_URL="https://app.gruperly.com/api/v1/whatsapp/callback" +# KAPSO_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/kapso" +# KAPSO_WEBHOOK_SECRET="" # el mismo del project webhook de Kapso + +# Only if you want the API on another domain: it is baked into the Vite bundle +# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same +# origin (recommended). +# VITE_API_URL="" diff --git a/.gitignore b/.gitignore index 6129279..e4107d5 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,8 @@ out # Nuxt.js build / generate output .nuxt dist +# Service worker que vite-plugin-pwa escribe al serving en dev +dev-dist # Gatsby files .cache/ @@ -147,3 +149,14 @@ apps/backend/generated/ # env apps/backend/.env + +# macOS +.DS_Store + +# archify: solo se versionan el HTML final y el candidate.json; lo intermedio no +.archify/**/*.browser-check.json +.archify/**/*.delivery.json +.archify/**/*.finalize.json +.archify/**/*.finalize-summary.json +.archify/**/candidate.before-review.json +.archify/**/review-*/ diff --git a/.interface-design/group-detail-redesign.html b/.interface-design/group-detail-redesign.html new file mode 100644 index 0000000..96e49b5 --- /dev/null +++ b/.interface-design/group-detail-redesign.html @@ -0,0 +1,954 @@ + + + + + + Gruperly — Rediseño detalle de grupo (2 estados) + + + + + + + + + +
+
+

+ Gruperly · /groups/$groupId +

+

Rediseño del detalle de grupo

+

+ Dos pestañas (Miembros · + Pendientes), tarjeta de info con lectura + Horario → Cupo → Cobro, un solo foco primario por estado y objetivos táctiles de 44px. + Tema oscuro, tokens reales de apps/web/src/index.css. +

+
+ +
+ +
+

+ 1 · Con miembros + pre-inscripciones — pestaña “Miembros” +

+
+
+ +
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+ + +
+ + + +
+
+ + +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 3/4 +

+
+
+
+

1 lugar libre · 1 en espera

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ + +
+
+
+
+ + +
+
+ + +
+
+

+ Listado de todos los miembros incorporados al grupo. +

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
NombreTeléfonoDetalle
+
+
A
+ Ana López +
+
+ 55 1234 5678 + + +
+
+
C
+ Carlos Mendoza +
+
+ 55 2345 6789 + + +
+
+
L
+ Lucía Hernández +
+
+ 55 3456 7890 + + +
+
+
+
+
+

+ Un solo tono activo: el chip “Miembros”. “Agregar Miembros” es + ghost — disponible, no dominante. Cupo + escaneable como 3/4 + barra. +

+
+ + +
+

+ 1 · Con miembros + pre-inscripciones — pestaña “Pendientes” +

+
+
+
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+
+ + + +
+
+ +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 3/4 +

+
+
+
+

1 lugar libre · 1 en espera

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+

+ Pre-inscripciones que esperan tu aprobación y personas en lista de espera por + un cupo libre. +

+
+ +
+ +
+
+ +

+ Pre-inscripciones +

+ 2 +
+
+ + + + + + + + + + + + + + + + + + + + +
NombreTeléfono
+
+
J
+
+

Jorge Ramírez

+

+ jorge.r@correo.mx +

+
+
+
+ 55 4567 8901 + + +
+
+
S
+
+

Sofía Torres

+

+ sofia.t@correo.mx +

+
+
+
+ 55 5678 9012 + + +
+
+
+ + +
+
+ +

+ Lista de espera +

+ 1 +
+
+ + + + + + + + + + + + + + + +
NombreTeléfonoDetalle
+
+
D
+
+

Diego Peña

+

+ Prefiere horario de 19:00 +

+
+
+
+ 55 6789 0123 + + +
+
+
+
+
+
+
+

+ “Pendientes” agrupa Pre-inscripciones (pill ámbar = requiere decisión) y Lista de + espera como secciones apiladas — sin una tercera pestaña. +

+
+ + +
+

+ 2 · Estado vacío — pestaña “Miembros” (sin miembros ni pre-inscripciones) +

+
+
+
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+ +
+ +
+
+ + +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 0/4 +

+
+
+
+

4 lugares libres

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+

+ Listado de todos los miembros incorporados al grupo. +

+
+ +
+
+ +

+ Todavía no hay miembros en este grupo +

+

+ Puedes compartir el enlace de invitación único o agregar miembros de forma + manual o masiva. +

+
+ + +
+
+
+
+
+
+

+ Exactamente un primario: “Agregar Miembros” en el + empty state. El header no repite Compartir/Agregar —solo queda Estadísticas—, así que + no compiten dos CTA idénticos. +

+
+ + +
+

+ 2 · Estado vacío — pestaña “Pendientes” +

+
+
+
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+ +
+ +
+
+ +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 0/4 +

+
+
+
+

4 lugares libres

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+

+ Pre-inscripciones que esperan tu aprobación y personas en lista de espera por + un cupo libre. +

+
+ +
+
+ +

No hay pendientes

+

+ Las pre-inscripciones que lleguen por el enlace compartido y las personas en + lista de espera aparecerán aquí para que las revises. +

+
+ +
+
+
+
+
+
+

+ Cada pestaña vacía explica qué aparecerá ahí y ofrece + una acción primaria concreta. +

+
+
+ +
+

+ Jerarquía de la tarjeta: label 11px · dato 16px · + cupo 24px (único hero). Orden de lectura: Horario → Cupo → Cobro. + Objetivos táctiles: chips, botones y buscador a + 44px; filas de tabla ~56px. Badges “Activo” y + “Riesgo moderado” conservados. +

+
+
+ + + + diff --git a/.interface-design/group-detail-redesign.png b/.interface-design/group-detail-redesign.png new file mode 100644 index 0000000..8a515ba Binary files /dev/null and b/.interface-design/group-detail-redesign.png differ diff --git a/.interface-design/system.md b/.interface-design/system.md new file mode 100644 index 0000000..c84ae4a --- /dev/null +++ b/.interface-design/system.md @@ -0,0 +1,136 @@ +# Gruperly — sistema de interfaz (apps/web) + +Aplicado en el rediseño de `/groups/$groupId` (sept 2026). Fuente de verdad de tokens: +`apps/web/src/index.css` (`@theme`). Ojo: `stack.md` trae tokens viejos (accent `#1e90ff`); +el accent real es **`#2544ea`**. + +## Dirección y sensación + +Herramienta diaria de un profesor/organizador que abre la pantalla para responder tres +preguntas: ¿quién está? ¿quién falta? ¿qué cobro?. Sensación: **calma operativa** — densa +pero escaneable, nada grita salvo lo que requiere decisión. Tema oscuro slate + un solo +accent azul; copy en español, verbos en infinitivo. + +## Profundidad y espaciado + +- **Estrategia de depth**: cambios de superficie + bordes de baja opacidad. Sombras solo + `shadow-xs` en tarjetas/paneles. Nada de drop shadows marcados. +- **Unidad base 4px.** Densidad: padding de componente 8–16px, separación entre bloques + `space-y-5 sm:space-y-6` (20/24px). +- **Radius**: default `rounded-xl` (0.75rem). Concéntrico: contenedor `rounded-2xl` (16px) + + padding 8px → interior `rounded-lg` (8px). Chips y pills: `rounded-full`. + +## Jerarquía tipográfica (ratio ~1.25) + +| nivel | valor | uso | +| --- | --- | --- | +| label | 11px semibold uppercase `tracking-wide` `text-foreground/70` | títulos de celda/sección | +| body | 14px (`text-sm`) `text-foreground/80` | descripciones, filas | +| value | 16px semibold `text-primary` (`text-base`) | dato principal de una celda | +| hero | 24px semibold `tracking-tight` `tabular-nums` | **solo uno por bloque** (hoy: el cupo `1/4`) | +| micro | 10–12px | pills de conteo (`text-[10px] font-bold`), captions | + +- Cuatro niveles de color de texto: `text-primary` → `text-foreground` → `/70` → `/50`. +- **Todo dato numérico lleva `tabular-nums`** (contadores, teléfonos, precios, fechas). + +## Patrón focal + +**Un punto focal por bloque y por estado.** La tarjeta de info manda con el cupo; el header +de grupo no tiene ningún `primary` (Estadísticas y Compartir son `outline` y **Agregar es +`ghost`**: con miembros en el grupo deja de competir con el listado) y el `primary` vive en +el empty state de la vista que lo explica. Así nunca hay dos elementos azules compitiendo. + +**Objetivos táctiles ≥ 44px** en esta pantalla: chips (`min-h-11`), botones del header y del +empty state (`h-11`), buscador (`h-11`). Filas de tabla ~56px. + +Preview visual de los dos estados (con miembros + vacío): +`group-detail-redesign.html` / `.png` (mismo directorio). + +## Componentes (valores exactos) + +### Chip de sección — `detail/SectionChips.tsx` +- Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist). +- Chip: `min-h-11 rounded-full border px-3.5 text-xs font-semibold gap-1.5`, + activo `border-transparent bg-accent text-on-accent shadow-xs`, + inactivo `border-border bg-surface text-foreground/80 hover:border-accent/40 hover:bg-primary-soft hover:text-primary`, + focus `ring-2 ring-accent ring-offset-2 ring-offset-primary-soft`. +- Pill de conteo: `px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums`; + **oculto si el conteo es 0**; atención `bg-warning-soft text-warning`; + neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`. +- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta. + +### Encabezado de pantalla — `components/layout/LargeTitle.tsx` +- Patrón iOS: título grande que al scrollear se desliza debajo de una barra de + navegación que se opaca y recibe el título en versión chica. +- Caja de la barra: `h-14` (56px) `sticky top-0 z-40` + `bg-background/80 backdrop-blur-md` + y `border-b`, con opacidad ligada al progreso. `h-14` tiene que coincidir con + `BAR_HEIGHT` de `hooks/useLargeTitleCollapse.ts`. +- Título grande: `text-[2.125rem] leading-[1.1] tracking-tight`, `sm:text-[2.5rem]`, + con `text-balance` para nombres largos. +- Título de la barra: `text-base font-semibold`, `truncate`, `aria-hidden` (es + duplicado visual del `h1`). +- El progreso sale de la posición del título en cada frame (`rAF` agrupa los + eventos de scroll), no de una transición: por eso se siente pegado al dedo. El + estado vive dentro de `LargeTitle` para que `children` no se re-renderice en + cada frame. +- La barra se monta en una caja que el layout pone arriba de `
` + (`ImmersiveBarHost`): un `sticky` está limitado a la caja de su padre, y el + padre natural (el bloque del feature) es corto. +- Sólo en tres rutas: `isImmersiveRoute` (`lib/immersive-routes.ts`): ficha de + grupo, sus estadísticas y la asistencia. Ahí no se renderiza el header global + y el sidebar pasa a `top-0 h-dvh`. +- El link "volver" vive en la barra como `leading` y sigue `hidden lg:inline-flex`. +- En las pantallas de un grupo (ficha y estadísticas) el título grande es **el + nombre del grupo**, no el de la sección: la barra colapsada tiene que decir + sobre qué se está mirando. "Estadísticas" va como subtítulo (label 11px + uppercase + body), no como título. + +### Acciones de cabecera — `detail/GroupHeader.tsx` +- Título, badges y descripción los dibuja `LargeTitle`; las acciones quedan + debajo, en el flujo normal. +- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros: + `variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px). +- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** — + Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado. +- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`. +- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`, + en su propia fila bajo el título grande (`mt-3`) y se van al colapsar la barra. + +### Tarjeta de info — `detail/GroupInfoCard.tsx` +- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil, + `md:grid md:grid-cols-3 md:divide-x md:divide-y-0`. +- Celda: `flex items-start gap-3 py-3 first:pt-0 last:pb-0 md:py-0` + `md:pr-6` / `md:px-6` / `md:pl-6`. +- Barra de cupo: `h-1.5 max-w-[9rem] rounded-full bg-accent/15`, fill `bg-accent` + (o `bg-warning` si `total >= capacity`), `transition-[width] duration-300 ease-out`, + con `role="progressbar"` + `aria-valuetext`. + +### Sección de listados — `detail/MembersWaitlistSection.tsx` +- Externo `rounded-2xl bg-primary-soft p-2`; interno `space-y-2 p-2 sm:p-3`. +- Panel de contenido: `rounded-lg bg-surface p-1 shadow-xs sm:p-2`. +- Fila header: chips + buscador (`sm:w-72 lg:shrink-0`), apilados hasta `lg`. +- Sub-encabezado de sección apilada (`PendingView.tsx`): + `flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3`, + título label 11px, pill a la derecha con `ml-auto`; tabla envuelta en `pt-1`. + +### Empty state +`rounded-lg bg-primary-soft/50 px-4 py-10 text-center` · icono `size-10 text-foreground/40` · +título `text-sm font-semibold text-primary` · cuerpo `max-w-sm text-sm text-foreground/80` · +acciones: **una** `primary` + el resto `outline`, todas `h-11`. + +### Tablas — `detail/*Table.tsx` +`table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5` +con `border-b border-border/70 last:border-b-0 hover:bg-primary-soft/60` · +avatar `size-9 rounded-full bg-accent/10 text-xs font-semibold text-accent` · +columnas secundarias con `hidden sm:table-cell` (en móvil manda el teléfono). + +### Botón — `components/ui/button.tsx` +`rounded-xl font-medium h-10 px-4 text-sm` · `active:scale-[0.96] motion-reduce:active:scale-100` · +focus `ring-2 ring-accent` · variantes `primary` (`bg-accent`/`hover:bg-accent-strong`), +`outline`, `ghost`. + +## Convenciones que sostienen el sistema + +- Sin Radix/shadcn instalado: primitivos propios en `components/ui/` + `cn()` (clsx + tailwind-merge). +- Sin botón "volver" en mobile: `hidden lg:inline-flex`. +- Elementos fijos abajo: `env(safe-area-inset-bottom)` en el padding. +- Los controles nuevos deben pasar el squint test: si dos cosas brillan, sobra una. diff --git a/AGENTS.md b/AGENTS.md index 95ab8cb..9149b33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ bun run lint:fix # biome check --write bun --filter @gruperly/backend typecheck # verificación de un solo paquete bun --filter @gruperly/backend test # bun test (backend) bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio +bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web/public/ (sharp) ``` ## Estructura y fronteras @@ -30,30 +31,91 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/logger.ts` — pino + pino-pretty. - - Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `students`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). -- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`); el backend llama a `/api/v1/groups/from-organization` (`src/routes/organizations.tsx`). + - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla. + - `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**. +- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). ## Gotchas operativos +- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`. - **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`. - **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness. +- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**. +- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto: + 1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers//`. + 2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre. + 3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor. + 4. La idempotencia de los envíos es el `@@unique([kind, attendeeId, periodKey])` de `outbound_messages` (semana ISO): la fila se crea **antes** de llamar al proveedor y su id es el `Idempotency-Key`. + 5. Los teléfonos se guardan en formato nacional: el envío pasa por `toWhatsappE164` (shared) con el país del profesor. + 6. Sin SDK de Kapso (trae su propio zod): `fetch` plano. + 7. El sandbox de Kapso no soporta templates. + 8. OpenWA se instala **aparte** (no está en `docker-compose.yml`); la API le habla por `OPENWA_API_URL`. Su guard SSRF rechaza webhooks a hosts internos que no estén en `SSRF_ALLOWED_HOSTS`. + 9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`. + 10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos. + 11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`. +- **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual), no lo que pagan los alumnos. Ojo con esto: + 1. Proveedor intercambiable detrás del puerto `BillingProvider` (`providers/billing-provider.ts`, mismo patrón que WhatsApp): Mercado Pago (`/preapproval`) en **AR** y Stripe (Checkout en modo suscripción, `fetch` plano sin SDK) en el resto; el mapa es `BILLING_PROVIDER_BY_COUNTRY` (shared). Los use-cases, `SyncSubscription` y el job **nunca** importan un adaptador: piden `getBillingProvider(id)` (inyectable como `providers` en `deps`). El país elige proveedor solo para suscripciones **nuevas**: sync/cancel/webhook usan siempre `row.provider`. MP usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_`, nunca `getMpAccessToken`); Stripe, una sola cuenta (`STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET`) que cobra en la moneda local (CLP es zero-decimal). Sin credenciales: `503 billing_not_available`. Con Stripe la suscripción no existe hasta completar el checkout: la fila guarda `checkoutRef` (la session) y la sync completa `externalId`. + 2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard. + 3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`). + 4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback. + 5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`. + 6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde. - **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema. -- `.env`, `dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia). +- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación. +- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari). +- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/access`, `/student/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto: + 1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`. + 2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410. + 3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`. + 4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`. + 5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) es solo del lado profe y **todavía no tiene UI**. + 6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo. + 7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires). + 8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado. + 9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`). + 10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`. +- **Personas y membresías (`Person` / `Attendee`)**: una persona puede estar en varios grupos del mismo profe. Ojo con esto: + 1. `Person` (`people`, del profe vía `created_by_id`) tiene los datos de contacto y las notas; `Attendee` es la **membresía** (`group_id` + `person_id` + `status` + `notify_token`), con `@@unique([groupId, personId])`. Asistencia, cuotas, alertas y mensajes siguen siendo por attendee (por grupo). (`Member` ya existe: es la organización de Better Auth.) + 2. El teléfono es único por profe con un índice **parcial** a mano (`people_owner_phone_key`, `WHERE phone IS NOT NULL`): Prisma no lo modela y un choque llega como `P2002` (`isUniqueViolation` en `modules/people/lib/people.ts`). Los teléfonos se guardan normalizados (`normalizePhone`, también al editar); `phoneVariants` cubre filas viejas. + 3. Las altas resuelven a la persona por teléfono: el alta individual sin `personId` con un teléfono existente responde `409 person_exists` (la web lo detecta antes con `GET /people/lookup?groupId=&phone=` y manda `personId`); bulk, lista de espera y preinscripciones vinculan solas (`findOrCreatePerson`). Ya estar en el grupo es `attendee_already_registered`; una membresía `DROPPED` se reactiva. + 4. `POST /groups/:gid/attendees/:aid/add-to-group` ("Agregar a otro grupo") crea otra membresía de la misma persona; `move` sigue cambiando el `groupId` de la misma membresía. Ambas validan con `checkCanJoinGroup(db, group, personId)`. + 5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona. + 6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`). + 7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`. +- **Multi idioma (`apps/web/src/i18n/`)**: i18next + react-i18next. Idiomas: `es-AR` (rioplatense, voseo; AR y UY), `es-419` (tuteo), `pt-BR` y `en`; la lista vive en `SUPPORTED_LOCALES` (`packages/shared/src/schemas/locale.ts`) y `resolveLocale` mapea los idiomas del dispositivo (cualquier otro `es-*` → `es-419`, cualquier `pt-*` → `pt-BR`, lo no soportado → `en`). Ojo con esto: + 1. **`es-AR` es la fuente**: `i18next.d.ts` tipa las claves con sus JSON, así que una clave que no exista ahí rompe el typecheck. `test/i18n-keys.test.ts` exige las mismas claves (salvo sufijos de plural) y variables en los 4 idiomas. Un namespace nuevo = un JSON por idioma + `NAMESPACES` (`instance.ts`) + `i18next.d.ts`. + 2. La preferencia es `'system' | AppLocale` en `localStorage['locale']`; para el profe también en `users.locale` (Better Auth `additionalFields`, validado con `appLocaleSchema`; `null` = idioma del dispositivo). `LocaleProfileSync` aplica el del perfil al iniciar sesión; `LanguageCard` lo guarda con `authClient.updateUser`. La app de alumnos solo usa `localStorage`. + 3. `main.tsx` carga el idioma (más `en` de fallback) **antes** del primer render; los JSON se cargan lazy por `import.meta.glob` (solo existe en Vite: en `bun test` el preload `test/setup.ts` carga `es-AR` del disco, por eso los tests asertan el copy rioplatense). + 4. Un componente que pinta texto traducido llama `useTranslation`, aunque el texto salga de un helper (`weekDayLabel`, `paymentStatusLabel`, `copy.ts` con `i18n.t`): es lo que lo re-renderiza al cambiar de idioma. + 5. Fechas y nombres de días/meses van en el idioma de la UI (`useIntlLocale()` / `i18n.language`), **nunca** con `'es-AR'` fijo. Montos y teléfonos **no**: `formatPrice`/`formatPhoneDisplay` siguen al **país** (`lib/region.ts`). + 6. Validación: los esquemas (shared y web) llevan **claves** (`'group.nameMin'`) en vez de texto; se pintan con `` (traduce contra el namespace `validation`). `installZodErrorMap` cubre los mensajes por defecto de Zod. + 7. Errores de la API: `errorMessage(error, fallback)` traduce el `code` del Problem Details (namespace `errors`, `codes.*`; los de Better Auth en `auth.*`); los `params` del problema (`limit`, `feature`, `max`, `capacity`) eligen variante y plural. Con la UI en español cae al `detail` del backend; si no, al `fallback`. Un error nuevo del backend que la UI muestre tiene que llevar `code` y su traducción. + 8. Lo que arma el backend en español y la UI muestra se redacta en la web a partir de datos estructurados: las alertas de `computeStudentAlerts` traen `razon` + `valores` (la web usa `alertLabel`/`alertDetail` de `features/attention/attention.ts`; `etiqueta`/`detalle` quedan para el backend), y los `message` de la API (importación masiva, preinscripción) se ignoran y se arman con los contadores. Nombres de país: `countryName` (`Intl.DisplayNames`), no `COUNTRY_LABELS`. + 9. Pendiente: mails, WhatsApp y el manifest de la PWA (`vite.config.ts`) siguen solo en español (etapa 2: usar `users.locale`). +- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia). ## Convenciones repo-específicas -- **Frontend en español**: copy de UI, comentarios y textos en español. -- **Base de datos**: todas las tablas usan **snake_case** vía `@@map` en `prisma/models/*.prisma` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`). Al agregar un modelo nuevo, incluir siempre `@@map("nombre_tabla")`. +- **Commits en inglés**: los mensajes de commit (título y cuerpo) van siempre en inglés, con prefijo Conventional Commits (`feat(i18n): …`, `fix: …`, `chore: …`). Los commits anteriores en español quedan como están. +- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español. +- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`). +- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client. - **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio. - **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`). -- **Router NO es file-based** (aunque `stack.md` lo diga): las rutas se declaran manualmente en `apps/web/src/router.tsx` con `createRoute` + `addChildren` y se registran vía module augmentation. **Cada vista nueva debe añadirse ahí.** +- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con ``). +- **Vistas en `apps/web/src/features//`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use()` y las forms locales mantienen su propio estado. +- **Grupos y "Requiere atención"** comparten la query `['attention']` (`features/attention/queries.ts`): el "Resuelto" es optimista sobre ese caché y por eso los contadores de Grupos se mueven sin refetch. El "Nuevo grupo" de Grupos es un FAB (`NewGroupFab`, se pliega al scrollear con `useCollapseOnScroll`) y por eso los toasts en mobile van a `bottom-[calc(9rem+…)]`. Los colores de gravedad son tokens (`alert-urgent-*`, `alert-watch-*`, `free-fg`) definidos para claro y oscuro en `index.css`. - Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista. +- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `
`, `
` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `
`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar ``; nada más. En las tres pantallas el `

` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos. - **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos. +- **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición. - Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`. +- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `
` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa. +- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). **Excepción**: `/groups/attention` ("Requiere atención", sin entrada en el nav) muestra su botón Volver también en mobile. Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen. ## Fuentes de contexto - `stack.md` — arquitectura y spec técnica de referencia (UI tokens exactos, stack por app). -- `README.md` — setup de la base de datos y comandos generales. \ No newline at end of file +- `README.md` — setup de la base de datos y comandos generales. diff --git a/Dockerfile.backend b/Dockerfile.backend new file mode 100644 index 0000000..a5662a9 --- /dev/null +++ b/Dockerfile.backend @@ -0,0 +1,66 @@ +# syntax=docker/dockerfile:1 + +# ─── Base ──────────────────────────────────────────────────────────────────── +FROM oven/bun:1.4-alpine AS base +WORKDIR /app +ENV CI=1 + +# ─── Dependencies ──────────────────────────────────────────────────────────── +# Only the package.json files: bun needs no source code to resolve the lockfile. +FROM base AS deps +COPY package.json bun.lock bunfig.toml turbo.json ./ +COPY apps/backend/package.json ./apps/backend/ +COPY apps/web/package.json ./apps/web/ +COPY packages/config/package.json ./packages/config/ +COPY packages/shared/package.json ./packages/shared/ +# bun's global cache weighs ~370MB: it is dropped in the same layer. +RUN bun install --frozen-lockfile && rm -rf /root/.bun/install + +# ─── Prisma Client ─────────────────────────────────────────────────────────── +# The "prisma-client" generator emits TypeScript, so the generated client runs +# with Bun without compilation. The URL is a placeholder: `generate` only needs +# to read the schema, not connect to a database. +FROM deps AS generate +ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder +ENV DATABASE_URL=$DATABASE_URL +COPY apps/backend/prisma.config.ts ./apps/backend/ +COPY apps/backend/prisma ./apps/backend/prisma +WORKDIR /app/apps/backend +RUN bun run db:generate + +# ─── API image ─────────────────────────────────────────────────────────────── +FROM base AS api +ENV NODE_ENV=production \ + PORT=4000 + +COPY package.json bun.lock bunfig.toml ./ +COPY apps/backend/package.json ./apps/backend/ +COPY packages/config/package.json ./packages/config/ +COPY packages/shared/package.json ./packages/shared/ +# `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs +# `prisma migrate deploy` on every boot. With `--production` the rest of the +# tooling does not come in: biome, typescript, turbo. +RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install + +# The Prisma CLI loads prisma.config.ts, which points to the schema. +COPY apps/backend/prisma ./apps/backend/prisma +COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts +COPY --from=generate /app/apps/backend/generated ./apps/backend/generated +COPY apps/backend/tsconfig.json ./apps/backend/ +COPY apps/backend/src ./apps/backend/src +# @gruperly/shared is consumed as TS source; @gruperly/config provides the base +# tsconfig that the backend tsconfig extends. +COPY packages ./packages +COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh + +WORKDIR /app/apps/backend +EXPOSE 4000 +# No `${...}` here: the CMD runs under /bin/sh (ash), where that is a syntax error. +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" + +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +# Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json, +# same as `bun start` locally. +CMD ["bun", "src/server.ts"] diff --git a/Dockerfile.web b/Dockerfile.web new file mode 100644 index 0000000..d7509c9 --- /dev/null +++ b/Dockerfile.web @@ -0,0 +1,35 @@ +# syntax=docker/dockerfile:1 + +# ─── Base ──────────────────────────────────────────────────────────────────── +FROM oven/bun:1.4-alpine AS base +WORKDIR /app +ENV CI=1 + +# ─── Dependencies ──────────────────────────────────────────────────────────── +FROM base AS deps +COPY package.json bun.lock bunfig.toml turbo.json ./ +COPY apps/backend/package.json ./apps/backend/ +COPY apps/web/package.json ./apps/web/ +COPY packages/config/package.json ./packages/config/ +COPY packages/shared/package.json ./packages/shared/ +# bun's global cache weighs ~370MB: it is dropped in the same layer. +RUN bun install --frozen-lockfile && rm -rf /root/.bun/install + +# ─── Vite build ────────────────────────────────────────────────────────────── +FROM deps AS build +# Vite replaces import.meta.env.* at build time, not at runtime. +# Empty = same origin: nginx's /api proxy acts as the API. +ARG VITE_API_URL="" +ENV VITE_API_URL=$VITE_API_URL +COPY apps/web ./apps/web +COPY packages ./packages +RUN bun --filter @gruperly/web build + +# ─── Final image ───────────────────────────────────────────────────────────── +FROM nginx:1.27-alpine AS web +COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/apps/web/dist /usr/share/nginx/html +EXPOSE 80 +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD wget --quiet --tries=1 --spider http://127.0.0.1/ || exit 1 +CMD ["nginx", "-g", "daemon off;"] diff --git a/README.md b/README.md index 87cfb83..2bcc883 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Monorepo de Gruperly. Consulta [stack.md](./stack.md) para arquitectura y especi - Package manager: [Bun](https://bun.sh/) 1.4 - Monorepo: bun workspaces + Turborepo - Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth -- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 +- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 + PWA (vite-plugin-pwa / Workbox) - Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos ## Estructura @@ -31,9 +31,202 @@ bun run lint # biome check (backend y shared) bun --filter @gruperly/backend test # bun test (backend) bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos bun --filter @gruperly/backend db:studio # Abre Prisma Studio +bun --filter @gruperly/web icons # Regenera los iconos PWA de public/ desde el isotipo SVG ``` +## PWA + +La web es instalable y abre sin conexión el shell de la app (rutas, JS, CSS, tipografía e iconos). Los datos de la API **no** se cachean: son cobros y una respuesta vieja sería peor que un error, así que offline la app carga pero las consultas fallan. + +- **Manifest y service worker**: `apps/web/vite.config.ts` (`VitePWA`, `generateSW`, `registerType: 'autoUpdate'`). El registro se hace desde `apps/web/src/features/pwa/PwaProvider.tsx` (`injectRegister: null`) para poder avisar con un toast cuando la app ya quedó lista para offline. +- **`workbox-window` es dependencia directa de `apps/web` a propósito**: `virtual:pwa-register` la importa desde el grafo de la app, pero llega como dependencia transitiva de `vite-plugin-pwa`. Localmente bun la hoistea a la raíz y todo anda; en la imagen de Docker bun usa el layout aislado y la deja solo en `node_modules/.bun/`, así que Rollup falla con `failed to resolve import "workbox-window"` y el build de Dokploy se cae. Declararla en `apps/web/package.json` la hace resoluble desde `apps/web/node_modules/`. **No la borres por "no estar imports en el código".** +- **Iconos**: se generan con sharp desde `apps/web/src/assets/brand/isotipo-y-organica.svg` y se versionan en `apps/web/public/` (`pwa-192x192`, `pwa-512x512`, `pwa-maskable-512x512`, `apple-touch-icon-180`). El build **no** los regenera; corré `bun --filter @gruperly/web icons` cuando cambie el isotipo. +- **Tipografía**: Inter variable auto-hospedada vía `@fontsource-variable/inter`, declarada a mano en `apps/web/src/index.css`. No hay `` a `fonts.googleapis.com`: era una dependencia de red en runtime. +- **Aviso de instalación**: la lógica de *cuándo* se ofrece vive en `apps/web/src/features/pwa/PwaProvider.tsx` (captura `beforeinstallprompt`, gate de sesión, dwell y descarte) y el dibujo en `InstallPrompt.tsx` → `InstallBanner.tsx` (Chromium) o `IosInstallHint.tsx` (Safari en iOS, que no dispara el evento y hay que instruir con Compartir → Agregar a pantalla de inicio). + - Se ofrece solo con **sesión iniciada**, **fuera del onboarding** y después de **20 s seguidos en la misma ruta**; `beforeinstallprompt` llega a los segundos y sin ese margen el aviso cae en medio de la primera tarea de la visita. Navegar antes de que se cumpla el tiempo reinicia la cuenta; una vez cumplido no se oculta más al navegar. + - El descarte es definitivo: se guarda en `localStorage['pwa-install-dismissed']` y no vuelve a preguntar en ese navegador. + - El timer vive en el provider y no en el componente que dibuja el aviso a propósito: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un timer en el hijo se perdería en cada navegación. El provider, en cambio, sigue montado y se suscribe al router (`router.subscribe('onResolved')`) porque está fuera del `RouterProvider`. + - Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` sin usuario—, así que el gate se chequea en el provider y no se puede inferir de dónde se monte el prompt. +- **nginx**: `apps/web/nginx.conf` sirve `sw.js`, `workbox-*.js` y `manifest.webmanifest` con `Cache-Control: no-cache` y `=404` (no el fallback del SPA), para que una versión vieja no quede cacheada para siempre. + +### Requisitos para que funcione + +El service worker necesita un **contexto seguro**: HTTPS, o `http://localhost`. Probar por IP de LAN sobre `http://` no registra el SW en silencio, sin error visible. En producción el TLS lo termina Traefik adelante de nginx. + +### Verificar + +```bash +bun --filter @gruperly/web build +bun --filter @gruperly/web preview # http://localhost:4173 +``` + +En DevTools → Application: el manifest sin warnings, el service worker `activated`, y en Network → Offline un reload de `/` o `/groups` tiene que seguir pintando la app. `bun dev` también registra el SW (está en `devOptions`), así que se puede probar sin build, pero `dev-dist/` queda gitignoreado. + ## Setup de base de datos 1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`. -2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo). \ No newline at end of file +2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo). + +## Mercado Pago (OAuth) + +Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago en modo directo: el profesor autoriza desde el panel de MP y los pagos entran en su propia cuenta, sin comisión ni split de plataforma (`platform_id=mp`). El OAuth vive en `apps/backend/src/modules/mp/`; los links de pago y la reconciliación están en `modules/payments/` (ver [Cobros](#cobros-links-de-pago)). + +**Panel de Mercado Pago** (Developer panel → Tu aplicación): + +- **Redirect URL**: el panel la exige en **HTTPS** (rechaza `http://localhost`) y tiene que coincidir carácter por carácter con `MP_REDIRECT_URI`. En local, meté un túnel delante del backend y registrá esa URL HTTPS tanto en el panel como en la env var: `ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000` (el *dev domain* de ngrok es fijo por cuenta, gratis) o un túnel nombrado de Cloudflare (`cloudflared tunnel route dns …`). `WEB_URL` y `VITE_API_URL` siguen en localhost: el túnel solo lo usa el navegador para volver desde MP. Los *quick tunnels* de cloudflared generan una URL nueva en cada arranque, así que obligan a regenerar la URL en el panel y en la env var cada reinicio. +- **PKCE (S256)**: activado. El `code_verifier` se genera y se consume en el servidor, nunca pasa por el navegador. +- **Permisos**: `offline_access read write`. Sin `offline_access` Mercado Pago no devuelve *refresh token* y la renovación automática no tiene con qué trabajar. + +**Variables de entorno** (`apps/backend/.env` en local, pestaña Environment del compose en Dokploy): + +| Variable | ¿Obligatoria? | Descripción | +| --- | --- | --- | +| `MP_CLIENT_ID` | para vincular | Client ID de la app de MP | +| `MP_CLIENT_SECRET` | para vincular | Secret de la app de MP | +| `MP_REDIRECT_URI` | para vincular | Callback registrado en el panel | +| `TOKEN_ENCRYPTION_KEY` | para vincular | `openssl rand -base64 32`. Cifra los tokens en reposo con AES-256-GCM. Si no decodifica a 32 bytes, el backend lo rechaza al guardar la cuenta | + +Sin las cuatro, `GET /api/v1/mp/connect` responde `503 mp_not_configured` y la app sigue funcionando: el paso "Cobros" del onboarding es **salteable**. + +En local se usan las credenciales de **producción** de la app: no existe OAuth sandbox en MP (las credenciales de prueba del panel son solo Public Key y Access Token, sin Client ID/secret). No hay riesgo, porque el OAuth solo vincula una cuenta y no mueve dinero; se prueba con una cuenta propia y se desvincúa con `DELETE /mp/connect`. Los links de pago también se prueban con la cuenta propia (crear un link no cobra nada; el cobro real le pide credenciales de pago al alumno). + +### Cómo funciona + +```text +onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state + PKCE en la DB, 10 min) + → https://auth.mercadopago.com/authorization + → GET /mp/callback → ?code&state (se quema el state, se cambia el código) + → 302 a /onboarding?mp=success o /settings?mp=error&reason=… +``` + +- La API de MP es `GET /mp/status` (`none` | `active` | `requires_reauth`) y `DELETE /mp/connect` (desvincula; conserva la fila para que la cuenta de MP quede reservada al mismo profesor). +- Los tokens se guardan cifrados; `status` nunca devuelve tokens, scope ni el id completo de MP (solo los últimos 4 dígitos, para que el profesor confirme que vinculó la cuenta correcta). +- Un cron diario (`17 3 * * *` UTC) renueva las cuentas que vencen en menos de 30 días, en lotes de 20 con `FOR UPDATE SKIP LOCKED`. Solo `invalid_grant` marca la cuenta como `requires_reauth`; un 5xx o un fallo de red se reintenta al día siguiente, para no bloquear a un profesor por una tarde mala de MP. `apps/backend/src/modules/mp/access-token.ts` (`getMpAccessToken`) renueva bajo demanda si el token está por vencer. + +### Verificar a mano + +1. `bun dev`, crear una cuenta nueva y llegar al paso "Cobros". +2. **Vincular**: "Vincular cuenta" debe abrir el consent de MP; al aceptar se vuelve a `/onboarding` con el mensaje de cuenta vinculada, y Ajustes → Cobros muestra "Vinculada" con los últimos 4 dígitos. +3. **Saltear**: con una cuenta nueva, "Lo hago después" deja crear el grupo igual; el resumen final ofrece vincularlo después desde Ajustes. +4. **Denegar**: en la pantalla de consentimiento de MP, elegir no autorizar → vuelve con "No autorizaste la conexión en Mercado Pago" y el estado sigue en `none`. +5. **Desvincular**: Ajustes → Cobros → Desvincular (pide confirmación) deja el estado en `none` y la tarjeta de cuenta conectada desaparece. +6. **Reautenticación**: `UPDATE users SET ...` no hace falta; para forzarla, `UPDATE mp_accounts SET status = 'REQUIRES_REAUTH'` y recargar cualquier pantalla: aparece el aviso global (excepto en Ajustes, donde la tarjeta ofrece la acción). + +```bash +# Estado real, con la sesión del profesor: +curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: ' | jq +``` + +## Cobros (links de pago) + +Un cobro es un **link de pago de Checkout Pro por alumno y por período**. El profesor lo dispara desde la ficha del grupo (**Cobrar**, habilitado cuando el grupo tiene precio): se crea un `Payment` por cada asistente activo y, para cada uno, una preferencia de Checkout Pro con `external_reference` = id del pago. Crear un link no cobra nada; el cobro real lo paga el alumno desde el link. + +La moneda sale del país del profesor (`user.country`, elegido en el onboarding; default `AR` → `ARS`): `AR→ARS, BR→BRL, CL→CLP, CO→COP, MX→MXN, PE→PEN, UY→UYU`. + +**Endpoints** (todos requieren sesión; solo grupos propios o donde el profesor es miembro): + +| Endpoint | Qué hace | +| --- | --- | +| `POST /api/v1/groups/:groupId/payments/batch` | Crea el lote. Body: `{ dueDate, description?, attendeeIds? }`. Responde `201` con `{ total, linked, failed, items }`; cada item es `LINKED` (trae `checkoutUrl`) o `FAILED` (error del proveedor, la fila queda `PENDING` sin link) | +| `POST /api/v1/payments/:id/renew` | Regenera el link de un pago que lo perdió (item `FAILED`). Idempotente: si ya tiene link, lo devuelve tal cual | +| `GET /api/v1/payments?groupId&status&page&pageSize` | Lista paginada `{ data, pagination }` de los cobros visibles | + +**Estados**: `PENDING` (esperando pago) → `PAID` (aprobado en MP) | `OVERDUE` (venció + 24 h de gracia y sigue sin pagar; sigue siendo cobrable) | `CANCELLED` (reservado, hoy no se usa). + +**Reconciliación, sin webhook.** El MVP consolida por polling porque un webhook exige una URL pública y verificación de firma, y no aporta nada a esta escala: un cron cada 15 min consulta la API de MP por `external_reference`, y si el pago está `approved` marca el `Payment` como `PAID` (guarda `mpPaymentId` y `paidAt`). Solo toca pagos con link y de más de 5 min de antigüedad, en lotes de 50. Un cron diario (`4 4 * * *` UTC) convierte en `OVERDUE` los `PENDING` cuya fecha venció hace más de 24 h. Los anuncian en el log (`startPaymentJobs()` en `apps/backend/src/server.ts`). + +**En la web**: la vista **Cobros** (nav) filtra por grupo y estado y deja copiar el link o regenerarlo con "Generar link" (botón renovar). Del modal **Cobrar** en la ficha del grupo se eligen vencimiento y descripción (default: mes en mayúscula) y se muestra un link por alumno para copiar, con los que fallaron listos para reintentar. + +**Errores típicos**: `409 group_without_price` (el grupo no tiene precio definido), `409 no_attendees_to_bill` (sin alumnos activos), `409 mp_not_connected` (el dueño desvinculó MP), `503 mp_not_configured` (faltan las env vars del OAuth). + +### Verificar a mano (además del flujo de OAuth) + +1. Con un grupo con precio y alumnos, "Cobrar" → elegir vencimiento → los links se generan uno por alumno. +2. En **Cobros** el grupo aparece con `PENDING` por alumno; "Copiar" pega un link `https://www.mercadopago.com.ar/checkout/v1/…`. +3. Abrir el link, pagar (puede fallar si el teste es con la cuenta real: probar el "sandbox de pago" del panel si existe) y esperar la reconciliación (hasta 15 min) o correr el job a mano. +4. Un pago aprobado pasa a `PAID`; uno cuyo vencimiento pasó (con +24 h) pasa a `OVERDUE` y permite regenerar el link. + +## WhatsApp (recordatorios y reenganche) + +Una vez por semana (lunes 10:00, hora de Argentina) Gruperly le escribe por WhatsApp, **desde el número del profesor**, a los miembros de los grupos que tengan la automatización prendida: + +- **Recordatorio de pago**: cobros `PENDING`/`OVERDUE` con link que vencen en los próximos 7 días o ya vencieron. +- **Reenganche**: los mismos que muestra "Alumnos en riesgo", como mucho uno cada 14 días. + +Las dos se prenden por grupo (ficha del grupo → "Mensajes automáticos por WhatsApp") y vienen apagadas. El profesor vincula su número en el onboarding (paso "WhatsApp", salteable) o en Ajustes → WhatsApp. + +El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`): + +- **`openwa`** (MVP, default): gateway self-hosted. El profesor lo vincula escaneando un QR o, desde el teléfono, con un código para su número; los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número. +- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados. + +El código vive en `apps/backend/src/modules/whatsapp/`. + +| Variable | ¿Obligatoria? | Descripción | +| --- | --- | --- | +| `WHATSAPP_PROVIDER` | no | `openwa` (default) o `kapso` | +| `OPENWA_API_URL`, `OPENWA_API_KEY` | con OpenWA | URL de la API de OpenWA y una key OPERATOR | +| `OPENWA_WEBHOOK_URL`, `OPENWA_WEBHOOK_SECRET` | no | Confirmaciones de entrega y lectura. El secreto es obligatorio si hay URL | +| `KAPSO_API_KEY`, `KAPSO_CALLBACK_URL`, `KAPSO_WEBHOOK_URL`, `KAPSO_WEBHOOK_SECRET` | con Kapso | Ver la guía | +| `WHATSAPP_SEND_INTERVAL_MS` | no | Pausa entre envíos del mismo profesor. Default `5000` | + +Si faltan las variables del proveedor activo, `/whatsapp/*` responde `503 whatsapp_not_configured` y la app sigue funcionando. + +La guía completa está en **[docs/whatsapp.md](docs/whatsapp.md)**: arquitectura, deploy de OpenWA y primera API key, setup de Kapso y templates, riesgos, verificación a mano, troubleshooting y una guía para el profesor. + +## Deploy en producción (Docker / Dokploy) + +Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx). + +- `api` corre Bun sobre el TypeScript fuente (`bun src/server.ts`), igual que en local: el cliente de Prisma se genera como TS y el tsconfig resuelve los aliases `@/*`. +- Al arrancar, `apps/backend/docker-entrypoint.sh` aplica `prisma migrate deploy` y recién después levanta el servidor. Si la migración falla, el contenedor no levanta y el error queda en los logs del servicio. Reintenta hasta 30 veces (5s) porque la base puede seguir arrancando. +- `web` compila con Vite y lo sirve nginx, que además hace de proxy de `/api` hacia `api`. Así el navegador siempre pega al mismo origen: la cookie de sesión es first-party y el CORS del backend no se activa. +- Ambos servicios se enchufan a `dokploy-network`, la red donde Dokploy deja las bases de datos que administra. Dokploy solo agrega esa red al servicio al que le asociás el dominio, así que está declarada a mano en el compose: sin ella, `api` no alcanza a la base y Prisma falla con `P1001 Can't reach database server`. + +### Variables de entorno + +El compose las interpola desde el entorno. En Dokploy van en la pestaña **Environment** del servicio Compose (Dokploy las guarda en un `.env` al lado del `docker-compose.yml`); en local, copiá `.env.example` → `.env` en la raíz. + +| Variable | ¿Obligatoria? | Descripción | +| --- | --- | --- | +| `DATABASE_URL` | sí | `postgresql://user:pass@host:5432/gruperly?schema=public`. La password va percent-encoded: `#` → `%23`, `@` → `%40`, `:` → `%3A`, `/` → `%2F`, `?` → `%3F`, `%` → `%25`, espacio → `%20`. Sin eso, Prisma corta la URL en el fragmento y falla con `P1013 invalid port number` | +| `WEB_URL` | sí | Origen público de la app, sin barra final (`https://gruperly.com`). Alimenta `WEB_URL` y `BETTER_AUTH_URL` del contenedor, porque el proxy de nginx deja web y API en el mismo dominio | +| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` | +| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider | +| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) | +| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) | +| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo | +| `WHATSAPP_PROVIDER`, `OPENWA_*`, `KAPSO_*`, `WHATSAPP_SEND_INTERVAL_MS` | no | Mensajes automáticos por WhatsApp (ver [WhatsApp](#whatsapp-recordatorios-y-reenganche)). OpenWA no está en el compose: se instala aparte y la API le habla por `OPENWA_API_URL` | +| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio | +| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones | + +Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre de la variable en el mensaje. + +### Pasos en Dokploy + +1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz). +2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá. +3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway. +4. Deploy. + +En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`. + +Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma. + +### Correr las migraciones a mano + +```bash +docker compose exec api bun run db:deploy +``` + +### Comprobar el compose en local + +Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la declara como externa: + +```bash +docker network create dokploy-network # una sola vez +cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET +docker compose up --build -d +docker compose logs api # debe salir "migrate: listo" y "Server running on ..." +curl http://localhost:8080/api/v1/health +``` diff --git a/apps/backend/.agents/skills/prisma-cli/SKILL.md b/apps/backend/.agents/skills/prisma-cli/SKILL.md new file mode 100644 index 0000000..b2b770e --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/SKILL.md @@ -0,0 +1,265 @@ +--- +name: prisma-cli +description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, complete, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not the Prisma Platform CLI. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma complete", "prisma studio", "prisma mcp". +license: MIT +metadata: + author: prisma + version: "7.9.1" +--- + +# Prisma CLI Reference + +Reference for Prisma ORM CLI commands. This skill provides guidance on command usage, options, and best practices for current Prisma ORM releases. + +## Boundary: Platform and Compute + +Do not confuse the stable ORM command (`prisma`) with the public-beta Platform package (`@prisma/cli`, binary `prisma-cli`). Use `prisma-compute` for Compute apps and workspace auth, and `prisma-postgres` for Platform projects and databases. + +## When to Apply + +Reference this skill when: +- Setting up a new Prisma project (`prisma init`) +- Generating Prisma Client (`prisma generate`) +- Running database migrations (`prisma migrate`) +- Managing database state (`prisma db push/pull`) +- Using local development database (`prisma dev`) +- Debugging Prisma issues (`prisma debug`) +- Generating shell completions (`prisma complete`) + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Setup | HIGH | `init` | +| 2 | Generation | HIGH | `generate` | +| 3 | Development | HIGH | `dev` | +| 4 | Database | HIGH | `db-` | +| 5 | Migrations | CRITICAL | `migrate-` | +| 6 | Utility | MEDIUM | `complete`, `studio`, `validate`, `format`, `debug`, `mcp` | + +## Command Categories + +| Category | Commands | Purpose | +|----------|----------|---------| +| Setup | `init` | Initialize a Prisma project | +| Generation | `generate` | Generate Prisma Client | +| Validation | `validate`, `format` | Schema validation and formatting | +| Development | `dev` | Local Prisma Postgres for development | +| Database | `db pull`, `db push`, `db seed`, `db execute` | Direct database operations | +| Migrations | `migrate dev`, `migrate deploy`, `migrate reset`, `migrate status`, `migrate diff`, `migrate resolve` | Schema migrations | +| Utility | `complete`, `studio`, `mcp`, `version`, `debug` | Shell, development, and AI tooling | + +## Quick Reference + +### Project Setup + +```bash +# Initialize new project (creates prisma/ folder and prisma.config.ts) +prisma init + +# Initialize with specific database +prisma init --datasource-provider postgresql +prisma init --datasource-provider mysql +prisma init --datasource-provider sqlite + +# Initialize with Prisma Postgres (cloud) +prisma init --db + +# Initialize with an example model +prisma init --with-model + +``` + +### Client Generation + +```bash +# Generate Prisma Client +prisma generate + +# Watch mode for development +prisma generate --watch + +# Generate specific generator only +prisma generate --generator client +``` + +### Bun Runtime + +When using Bun, always add the `--bun` flag so Prisma runs with the Bun runtime (otherwise it falls back to Node.js because of the CLI shebang): + +```bash +bunx --bun prisma init +bunx --bun prisma generate +``` + +### Local Development Database + +```bash +# Start local Prisma Postgres +prisma dev + +# Start with specific name +prisma dev --name myproject + +# Start in background (detached) +prisma dev --detach + +# List all local instances +prisma dev ls + +# Stop instance +prisma dev stop myproject + +# Remove instance data +prisma dev rm myproject +``` + +### Database Operations + +```bash +# Pull schema from existing database +prisma db pull + +# Push schema to database (no migrations) +prisma db push + +# Seed database +prisma db seed + +# Execute raw SQL +prisma db execute --file ./script.sql +``` + +### Migrations (Development) + +```bash +# Create and apply migration +prisma migrate dev + +# Create migration with name +prisma migrate dev --name add_users_table + +# Create migration without applying +prisma migrate dev --create-only + +# Reset database and apply all migrations +prisma migrate reset +``` + +### Migrations (Production) + +```bash +# Apply pending migrations (CI/CD) +prisma migrate deploy + +# Check migration status +prisma migrate status + +# Compare schemas and generate diff +prisma migrate diff --from-config-datasource --to-schema schema.prisma --script +``` + +### Utility Commands + +```bash +# Open Prisma Studio (database GUI) +prisma studio + +# Start Prisma's MCP server for AI tools +prisma mcp + +# Show version info +prisma version +prisma -v + +# Debug information +prisma debug + +# Validate schema +prisma validate + +# Format schema +prisma format + +# Generate shell completion code +prisma complete zsh +``` + +## AI Safety Checkpoint + +Prisma blocks destructive commands when it detects an AI agent until the agent has obtained explicit user consent. This covers `migrate reset`, `db push --force-reset`, and `db push --accept-data-loss`. + +- Explain the exact data-loss impact and ask for consent immediately before running the command. +- Do not infer consent from earlier or unrelated messages. +- If automation needs the consent variable, set `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` to the user's exact consent message. Do not invent the text. +- The Prisma MCP server deliberately has no `migrate-reset` tool. + +Read `references/agent-safety.md` before any destructive Prisma command. + +## Current Prisma CLI Setup + +### New Configuration File + +Use `prisma.config.ts` for CLI configuration: + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + seed: 'tsx prisma/seed.ts', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +### Current Command Behavior + +- Run `prisma generate` explicitly after `migrate dev`, `db push`, or other schema syncs when you need fresh client output +- Run `prisma db seed` explicitly after `migrate dev` or `migrate reset` when you need seed data +- Use `prisma db execute --file ...` for raw SQL scripts + +### Environment Variables + +Load environment variables explicitly in `prisma.config.ts`, commonly with `dotenv`: + +```typescript +// prisma.config.ts +import 'dotenv/config' +``` + +## Rule Files + +See individual rule files for detailed command documentation: + +``` +references/init.md - Project initialization +references/generate.md - Client generation +references/dev.md - Local development database +references/db-pull.md - Database introspection +references/db-push.md - Schema push +references/db-seed.md - Database seeding +references/db-execute.md - Raw SQL execution +references/migrate-dev.md - Development migrations +references/migrate-deploy.md - Production migrations +references/migrate-reset.md - Database reset +references/migrate-status.md - Migration status +references/migrate-resolve.md - Migration resolution +references/migrate-diff.md - Schema diffing +references/studio.md - Database GUI +references/mcp.md - Prisma MCP server +references/complete.md - Shell completion generation +references/agent-safety.md - AI consent checkpoint for destructive commands +references/validate.md - Schema validation +references/format.md - Schema formatting +references/debug.md - Debug info +``` + +## How to Use + +Use the command categories above for navigation, then open the specific command reference file you need. diff --git a/apps/backend/.agents/skills/prisma-cli/references/agent-safety.md b/apps/backend/.agents/skills/prisma-cli/references/agent-safety.md new file mode 100644 index 0000000..651c6c3 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/agent-safety.md @@ -0,0 +1,27 @@ +# AI safety checkpoint for destructive commands + +Prisma detects common AI-agent environments and blocks these commands until the user gives explicit consent: + +- `prisma migrate reset` +- `prisma db push --force-reset` +- `prisma db push --accept-data-loss` + +## Required workflow + +1. Inspect the target database/config and explain exactly what can be deleted or reset. +2. Ask the user for explicit consent immediately before the action. +3. Run the command only after that consent. + +For an agent-run subprocess, Prisma accepts the exact consent text through: + +```bash +PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION='' prisma migrate reset --force +``` + +The value must match the user's message exactly and must not contain added quotes or newlines. Never fabricate consent, reuse an old unrelated approval, or bypass the checkpoint by hiding agent-detection environment variables. + +The MCP server has no `migrate-reset` tool. Use the shell command only after consent. + +## Reference + +- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0) diff --git a/apps/backend/.agents/skills/prisma-cli/references/complete.md b/apps/backend/.agents/skills/prisma-cli/references/complete.md new file mode 100644 index 0000000..7332440 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/complete.md @@ -0,0 +1,22 @@ +# prisma complete + +Prints a shell completion script. + +```bash +prisma complete zsh +prisma complete bash +prisma complete fish +prisma complete powershell +``` + +For a direct global CLI installation, load the output using the shell's normal startup mechanism. For example, in zsh: + +```bash +source <(prisma complete zsh) +``` + +Prisma also integrates with supported package-manager completion flows. `npx` and `bunx` do not themselves provide completion; invoke the installed binary or the package manager's supported execution form such as `npm exec` or `bun x`. + +## Reference + +- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0) diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-execute.md b/apps/backend/.agents/skills/prisma-cli/references/db-execute.md new file mode 100644 index 0000000..c966f23 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/db-execute.md @@ -0,0 +1,78 @@ +# prisma db execute + +Execute native commands (SQL) to your database. + +## Command + +```bash +prisma db execute [options] +``` + +## What It Does + +- Connects to your database using the configured datasource +- Executes a script provided via file (`--file`) or stdin (`--stdin`) +- Useful for running raw SQL, maintenance tasks, or applying diffs from `migrate diff` +- Not supported on MongoDB + +## Options + +| Option | Description | +|--------|-------------| +| `--file` | Path to a file containing the script to execute | +| `--stdin` | Use terminal standard input as the script | +| `--config` | Custom path to your Prisma config file | + +## Current Option Surface + +`prisma db execute` uses the datasource configured in `prisma.config.ts`. Use `--config` if you need a separate config file for another environment. + +## Examples + +### Execute from file + +```bash +prisma db execute --file ./script.sql +``` + +### Execute from stdin + +```bash +echo "TRUNCATE TABLE User;" | prisma db execute --stdin +``` + +### Execute `migrate diff` output + +Pipe the output of `migrate diff` directly to the database: + +```bash +prisma migrate diff \ + --from-empty \ + --to-schema prisma/schema.prisma \ + --script \ +| prisma db execute --stdin +``` + +## Configuration + +Uses `datasource` from `prisma.config.ts`: + +```typescript +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Use Cases + +- **Manual Migrations**: Applying raw SQL changes +- **Data Maintenance**: Truncating tables, cleaning up data +- **Schema Synchronization**: Applying `migrate diff` scripts +- **Debugging**: Running test queries (though typically not for fetching data) + +## Limitations + +- **No Data Return**: The command reports success/failure, not query results (rows). Use Prisma Client or `prisma studio` to view data. +- **SQL Only**: Primarily for SQL databases. diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-pull.md b/apps/backend/.agents/skills/prisma-cli/references/db-pull.md new file mode 100644 index 0000000..58a6e47 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/db-pull.md @@ -0,0 +1,185 @@ +# prisma db pull + +Introspects an existing database and updates your Prisma schema to reflect its structure. + +## Command + +```bash +prisma db pull [options] +``` + +## What It Does + +- Connects to your database +- Reads the database schema (tables, columns, relations, indexes) +- Updates `schema.prisma` with corresponding Prisma models +- For MongoDB, samples data to infer schema + +## Options + +| Option | Description | +|--------|-------------| +| `--force` | Ignore current Prisma schema file | +| `--print` | Print the introspected Prisma schema to stdout | +| `--schema` | Custom path to your Prisma schema | +| `--config` | Custom path to your Prisma config file | +| `--url` | Override the datasource URL from the Prisma config file | +| `--composite-type-depth` | Specify the depth for introspecting composite types (default: -1 for infinite, 0 = off) | +| `--schemas` | Specify the database schemas to introspect | +| `--local-d1` | Generate a Prisma schema from a local Cloudflare D1 database | + +## Examples + +### Basic introspection + +```bash +prisma db pull +``` + +### Preview without writing + +```bash +prisma db pull --print +``` + +Outputs schema to terminal for review. + +### Force overwrite + +```bash +prisma db pull --force +``` + +Replaces schema file, losing any manual customizations. + +## Prerequisites + +Configure database connection in `prisma.config.ts`: + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Workflow + +### Starting from existing database + +1. Initialize Prisma: + ```bash + prisma init + ``` + +2. Configure database URL + +3. Pull schema: + ```bash + prisma db pull + ``` + +4. Review and customize generated schema + +5. Generate client: + ```bash + prisma generate + ``` + +### Syncing changes from database + +When database changes are made outside Prisma: + +```bash +prisma db pull +prisma generate +``` + +## Generated Schema Example + +Database tables become Prisma models: + +```sql +-- Database tables +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + email VARCHAR(255) UNIQUE NOT NULL, + name VARCHAR(100) +); + +CREATE TABLE posts ( + id SERIAL PRIMARY KEY, + title VARCHAR(255) NOT NULL, + author_id INTEGER REFERENCES users(id) +); +``` + +Becomes: + +```prisma +model users { + id Int @id @default(autoincrement()) + email String @unique @db.VarChar(255) + name String? @db.VarChar(100) + posts posts[] +} + +model posts { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + author_id Int? + users users? @relation(fields: [author_id], references: [id]) +} +``` + +## Post-Introspection Cleanup + +After `db pull`, consider: + +1. **Rename models** to PascalCase: + ```prisma + model User { // Was: users + @@map("users") + } + ``` + +2. **Rename fields** to camelCase: + ```prisma + authorId Int? @map("author_id") + ``` + +3. **Add relation names** for clarity: + ```prisma + author User? @relation("PostAuthor", fields: [authorId], references: [id]) + ``` + +4. **Add documentation**: + ```prisma + /// User account information + model User { + /// Primary email for authentication + email String @unique + } + ``` + +## MongoDB Introspection + +For MongoDB, `db pull` samples documents to infer schema: + +```bash +prisma db pull +``` + +May require manual refinement since MongoDB is schemaless. + +## Warning + +`db pull` overwrites your schema file. Always: +- Commit current schema before pulling +- Use `--print` to preview first +- Backup customizations you want to keep diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-push.md b/apps/backend/.agents/skills/prisma-cli/references/db-push.md new file mode 100644 index 0000000..74da0cf --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/db-push.md @@ -0,0 +1,150 @@ +# prisma db push + +Pushes schema changes directly to database without creating migrations. Ideal for prototyping. + +## Command + +```bash +prisma db push [options] +``` + +## What It Does + +- Syncs your Prisma schema to the database +- Creates database if it doesn't exist +- Does NOT create migration files +- Does NOT track migration history + +## Options + +| Option | Description | +|--------|-------------| +| `--force-reset` | Force a reset of the database before push | +| `--accept-data-loss` | Ignore data loss warnings | +| `--schema` | Custom path to your Prisma schema | +| `--config` | Custom path to your Prisma config file | +| `--url` | Override the datasource URL from the Prisma config file | + +When Prisma detects an AI agent, `--force-reset` and `--accept-data-loss` require explicit user consent. Follow `agent-safety.md`; never infer or fabricate the consent text. + +### Follow-up Command + +- Run `prisma generate` explicitly when you need refreshed client output + +## Examples + +### Basic push + +```bash +prisma db push +``` + +### Accept data loss + +```bash +prisma db push --accept-data-loss +``` + +Required when changes would delete data (dropping columns, etc.) + +### Force reset + +```bash +prisma db push --force-reset +``` + +Completely resets database and applies schema. + +### Full workflow + +```bash +prisma db push +prisma generate +``` + +## When to Use + +- **Prototyping** - Rapid schema iteration +- **Local development** - Quick schema changes +- **MongoDB** - Primary workflow (migrations not supported) +- **Testing** - Setting up test databases + +## When NOT to Use + +- **Production** - Use `migrate deploy` +- **Team collaboration** - Use migrations for trackable changes +- **When you need rollback** - Migrations provide history + +## Comparison with migrate dev + +| Feature | db push | migrate dev | +|---------|---------|-------------| +| Creates migration files | No | Yes | +| Tracks history | No | Yes | +| Requires shadow database | No | Yes | +| Speed | Faster | Slower | +| Rollback capability | No | Yes | +| Best for | Prototyping | Development | + +## MongoDB Workflow + +MongoDB doesn't support migrations. Use `db push` exclusively: + +```bash +# Schema changes for MongoDB +prisma db push +prisma generate +``` + +## Common Patterns + +### Prototyping workflow + +```bash +# Make schema changes +# ... + +# Push to database +prisma db push + +# Generate client +prisma generate + +# Test your changes +# Repeat as needed +``` + +### Reset and start fresh + +```bash +prisma db push --force-reset +prisma db seed +``` + +### Handling conflicts + +If `db push` can't apply changes safely: + +``` +Error: The following changes cannot be applied: + - Removing field `email` would cause data loss + +Use --accept-data-loss to proceed +``` + +Decide whether data loss is acceptable, then: + +```bash +prisma db push --accept-data-loss +``` + +## Transition to Migrations + +When ready for production, switch to migrations: + +```bash +# Create baseline migration from current schema +prisma migrate dev --name init +``` + +Then use `migrate dev` for future changes. diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-seed.md b/apps/backend/.agents/skills/prisma-cli/references/db-seed.md new file mode 100644 index 0000000..7657cff --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/db-seed.md @@ -0,0 +1,188 @@ +# prisma db seed + +Runs your database seed script to populate data. + +## Command + +```bash +prisma db seed [options] +``` + +## What It Does + +- Executes your configured seed script +- Populates database with initial/test data +- Runs independently (not auto-run by migrations in v7) + +## Options + +| Option | Description | +|--------|-------------| +| `--config` | Custom path to your Prisma config file | +| `--` | Pass custom arguments to seed script | + +## Configuration + +Configure seed script in `prisma.config.ts`: + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + seed: 'tsx prisma/seed.ts', // Your seed command + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +### Common seed commands + +```typescript +// TypeScript with tsx +seed: 'tsx prisma/seed.ts' + +// TypeScript with ts-node +seed: 'ts-node prisma/seed.ts' + +// JavaScript +seed: 'node prisma/seed.js' +``` + +## Seed Script Example + +```typescript +// prisma/seed.ts +import { PrismaClient } from '../generated/client' + +const prisma = new PrismaClient() + +async function main() { + // Create users + const alice = await prisma.user.upsert({ + where: { email: 'alice@prisma.io' }, + update: {}, + create: { + email: 'alice@prisma.io', + name: 'Alice', + posts: { + create: { + title: 'Hello World', + published: true, + }, + }, + }, + }) + + const bob = await prisma.user.upsert({ + where: { email: 'bob@prisma.io' }, + update: {}, + create: { + email: 'bob@prisma.io', + name: 'Bob', + }, + }) + + console.log({ alice, bob }) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +## Examples + +### Run seed + +```bash +prisma db seed +``` + +### With custom arguments + +```bash +prisma db seed -- --environment development +``` + +Arguments after `--` are passed to your seed script. + +## Current Workflow + +Run seeding explicitly after migrations when you need seed data: + +```bash +prisma migrate dev --name init +prisma generate +prisma db seed # Must run explicitly +``` + +## Idempotent Seeding + +Use `upsert` to make seeds re-runnable: + +```typescript +// Good: Can run multiple times +await prisma.user.upsert({ + where: { email: 'alice@prisma.io' }, + update: {}, // Don't change existing + create: { email: 'alice@prisma.io', name: 'Alice' }, +}) + +// Bad: Fails on second run +await prisma.user.create({ + data: { email: 'alice@prisma.io', name: 'Alice' }, +}) +``` + +## Common Patterns + +### Development reset + +```bash +prisma migrate reset --force +prisma db seed +``` + +### Conditional seeding + +```typescript +// prisma/seed.ts +const count = await prisma.user.count() +if (count === 0) { + // Only seed if empty + await seedUsers() +} +``` + +### Environment-specific seeds + +```typescript +// prisma/seed.ts +const env = process.env.NODE_ENV || 'development' + +if (env === 'development') { + await seedDevData() +} else if (env === 'test') { + await seedTestData() +} +``` + +## Best Practices + +1. Use `upsert` for idempotent seeds +2. Keep seeds focused and minimal +3. Use realistic but fake data +4. Document required seed data +5. Version control your seed scripts diff --git a/apps/backend/.agents/skills/prisma-cli/references/debug.md b/apps/backend/.agents/skills/prisma-cli/references/debug.md new file mode 100644 index 0000000..1c2b0af --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/debug.md @@ -0,0 +1,46 @@ +# prisma debug + +Prints information helpful for debugging and bug reports. + +## Command + +```bash +prisma debug [options] +``` + +## What It Does + +Outputs details about your Prisma environment, including: +- Prisma CLI version +- Prisma Client version (if installed) +- Engine binaries (Query Engine, Migration Engine, etc.) +- Platform information (OS, Architecture) +- Node.js version +- Configured datasource provider + +## Options + +| Option | Description | +|--------|-------------| +| `--schema` | Path to schema file | +| `--config` | Custom path to your Prisma config file | + +## Example Output + +``` +prisma : 7.3.0 +@prisma/client : 7.3.0 +Operating System : darwin +Architecture : arm64 +Node.js : v20.10.0 +TypeScript : 5.3.3 +Query Compiler : enabled +PSL : ... +Schema Engine : ... +``` + +## When to Use + +- **Troubleshooting**: Checking version mismatches +- **Reporting Issues**: Including environment info in GitHub issues +- **Verifying Installation**: Ensuring correct binaries are downloaded diff --git a/apps/backend/.agents/skills/prisma-cli/references/dev.md b/apps/backend/.agents/skills/prisma-cli/references/dev.md new file mode 100644 index 0000000..870efb9 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/dev.md @@ -0,0 +1,157 @@ +# prisma dev + +Starts a local Prisma Postgres database for development. Provides a PostgreSQL-compatible database that runs entirely on your machine. + +## Command + +```bash +prisma dev [options] +``` + +## What It Does + +- Starts a local PostgreSQL-compatible database +- Runs in your terminal or as a background process +- Perfect for development and testing +- Easy migration to Prisma Postgres cloud in production + +## Options + +| Option | Description | Default | +|--------|-------------|---------| +| `--name` / `-n` | Name for the database instance | `default` | +| `--port` / `-p` | HTTP server port | `51213` | +| `--db-port` / `-P` | Database server port | `51214` | +| `--shadow-db-port` | Shadow database port (for migrations) | `51215` | +| `--detach` / `-d` | Run in background | `false` | +| `--debug` | Enable debug logging | `false` | + +## Examples + +### Start local database + +```bash +prisma dev +``` + +Interactive mode with keyboard shortcuts: +- `q` - Quit +- `h` - Show HTTP URL +- `t` - Show TCP URLs + +### Named instance + +```bash +prisma dev --name myproject +``` + +Useful for multiple projects. + +### Background mode + +```bash +prisma dev --detach +``` + +Frees your terminal for other commands. + +### Custom ports + +```bash +prisma dev --port 5000 --db-port 5432 +``` + +## Instance Management + +### List all instances + +```bash +prisma dev ls +``` + +Shows all local Prisma Postgres instances with status. + +### Start existing instance + +```bash +prisma dev start myproject +``` + +Starts a previously created instance in background. + +### Stop instance + +```bash +prisma dev stop myproject +``` + +### Stop with glob pattern + +```bash +prisma dev stop "myproject*" +``` + +Stops all instances matching pattern. + +### Remove instance + +```bash +prisma dev rm myproject +``` + +Removes instance data from filesystem. + +### Force remove (stops first) + +```bash +prisma dev rm myproject --force +``` + +## Configuration + +Configure your `prisma.config.ts` to use local Prisma Postgres: + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + // Local Prisma Postgres URL (from prisma dev output) + url: env('DATABASE_URL'), + }, +}) +``` + +## Workflow + +1. Start local database: + ```bash + prisma dev + ``` + +2. In another terminal, run migrations: + ```bash + prisma migrate dev + ``` + +3. Generate client: + ```bash + prisma generate + ``` + +4. Run your application + +## Production Migration + +When ready for production, switch to Prisma Postgres cloud: + +```bash +prisma init --db +``` + +Update your `DATABASE_URL` to the cloud connection string. diff --git a/apps/backend/.agents/skills/prisma-cli/references/format.md b/apps/backend/.agents/skills/prisma-cli/references/format.md new file mode 100644 index 0000000..896b1ec --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/format.md @@ -0,0 +1,48 @@ +# prisma format + +Formats your Prisma schema file. + +## Command + +```bash +prisma format [options] +``` + +## What It Does + +- Fixes formatting (indentation, spacing) +- Adds missing back-relations (e.g., adds the other side of a relation) +- Adds missing relation arguments (e.g., `fields`, `references`) +- Sorts fields and attributes (opinionated) + +## Options + +| Option | Description | +|--------|-------------| +| `--schema` | Path to schema file | +| `--config` | Custom path to your Prisma config file | + +## Examples + +### Format default schema + +```bash +prisma format +``` + +### Format specific schema + +```bash +prisma format --schema=./custom/schema.prisma +``` + +## Behavior + +`prisma format` modifies the file in place. It is equivalent to "Prettier for Prisma schemas" but also has semantic understanding to fix/add missing schema definitions. + +## Use in Editor + +Most Prisma editor extensions (VS Code, WebStorm) run `prisma format` automatically on save. This command is useful for: +- CI pipelines (check formatting) +- CLI-based workflows +- Fixing large schema refactors diff --git a/apps/backend/.agents/skills/prisma-cli/references/generate.md b/apps/backend/.agents/skills/prisma-cli/references/generate.md new file mode 100644 index 0000000..3d371cf --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/generate.md @@ -0,0 +1,173 @@ +# prisma generate + +Generates assets based on the generator blocks in your Prisma schema, most commonly Prisma Client. + +## Command + +```bash +prisma generate [options] +``` + +## Bun Runtime + +If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js: + +```bash +bunx --bun prisma generate +``` + +## What It Does + +1. Reads your `schema.prisma` file +2. Generates a customized Prisma Client based on your models +3. Outputs to the directory specified in the generator block + +## Options + +| Option | Description | +|--------|-------------| +| `--schema` | Custom path to your Prisma schema | +| `--config` | Custom path to your Prisma config file | +| `--sql` | Generate typed sql module | +| `--watch` | Watch the Prisma schema and rerun after a change | +| `--generator` | Generator to use (may be provided multiple times) | +| `--no-hints` | Hides the hint messages but still outputs errors and warnings | +| `--require-models` | Do not allow generating a client without models | + +## Examples + +### Basic generation + +```bash +prisma generate +``` + +### Watch mode (development) + +```bash +prisma generate --watch +``` + +Auto-regenerates when `schema.prisma` changes. + +### Specific generator + +```bash +prisma generate --generator client +``` + +### Multiple generators + +```bash +prisma generate --generator client --generator zod_schemas +``` + +### Typed SQL generation + +```bash +prisma generate --sql +``` + +## Schema Configuration + +```prisma +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +### Current Generator Behavior + +- `prisma-client` is the standard generator +- `output` is required when using `prisma-client` +- `prisma-client` supports both ESM and CommonJS via `moduleFormat` +- `compilerBuild` supports `fast` and `small` query compiler artifacts +- Use TypeScript `satisfies` for typed query fragments with `prisma-client` +- Import Prisma Client from your generated output path, for example: + +```typescript +import { PrismaClient } from '../generated/prisma/client' +``` + +### Compiler Build Tuning + +Use `compilerBuild` when you need to trade artifact size against the default build: + +```prisma +generator client { + provider = "prisma-client" + output = "../generated" + compilerBuild = "small" +} +``` + +- `fast` is the default build for most targets +- `small` is useful for size-constrained targets +- Prisma defaults `vercel-edge` targets to `small` + +## Common Patterns + +### After schema changes + +```bash +prisma migrate dev --name my_migration +prisma generate +``` + +Run `prisma generate` whenever you need refreshed client code after schema-changing commands. + +### CI/CD pipeline + +```bash +prisma generate +``` + +Run before building your application. + +### Multiple generators + +```prisma +generator client { + provider = "prisma-client" + output = "../generated" +} + +generator zod { + provider = "zod-prisma-types" + output = "../generated/zod" +} +``` + +```bash +prisma generate # Runs all generators +``` + +## Output Structure + +After running `prisma generate`, your output directory contains: + +``` +generated/ +├── browser.ts +├── client.ts +├── commonInputTypes.ts +├── models/ +├── enums.ts +├── models.ts +└── ... +``` + +Import the client: + +```typescript +import { PrismaClient, Prisma } from '../generated/prisma/client' +``` + +Import browser-safe types: + +```typescript +import { Prisma } from '../generated/prisma/browser' +import { Role } from '../generated/prisma/enums' +import type { UserModel } from '../generated/prisma/models/User' +``` diff --git a/apps/backend/.agents/skills/prisma-cli/references/init.md b/apps/backend/.agents/skills/prisma-cli/references/init.md new file mode 100644 index 0000000..c4390ed --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/init.md @@ -0,0 +1,139 @@ +# prisma init + +Bootstraps a fresh Prisma ORM project in the current directory. + +## Command + +```bash +prisma init [options] +``` + +## Bun Runtime + +If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js: + +```bash +bunx --bun prisma init +``` + +## What It Creates + +- `prisma/schema.prisma` - Your Prisma schema file +- `prisma.config.ts` - TypeScript configuration for Prisma CLI +- `.env` - Environment variables (DATABASE_URL) +- `.gitignore` - Ensures `.env` is ignored and appends the generated client path + +## Options + +| Option | Description | Default | +|--------|-------------|---------| +| `--datasource-provider` | Database provider: `postgresql`, `mysql`, `sqlite`, `sqlserver`, `mongodb`, `cockroachdb` | `postgresql` | +| `--db` | Provisions a fully managed Prisma Postgres database on the Prisma Data Platform | - | +| `--url` | Define a custom datasource url | - | +| `--generator-provider` | Define the generator provider to use | `prisma-client` | +| `--output` | Define Prisma Client generator output path to use | - | +| `--preview-feature` | Define a preview feature to use | - | +| `--with-model` | Add example model to created schema file | - | +| `--no-skills` | Skip the best-effort installation of Prisma agent skills | - | + +`prisma init` attempts to install `prisma/skills` for detected agents. This is best-effort and does not make project initialization fail. Use `--no-skills` in minimal or controlled environments. + +## Examples + +### Basic initialization + +```bash +prisma init +``` + +Creates a PostgreSQL project setup. + +### SQLite project + +```bash +prisma init --datasource-provider sqlite +``` + +### MySQL with custom URL + +```bash +prisma init --datasource-provider mysql --url "mysql://user:password@localhost:3306/mydb" +``` + +### Prisma Postgres (cloud) + +```bash +prisma init --db +``` + +Opens browser for authentication, creates cloud database instance. + +### Add an example model + +```bash +prisma init --with-model +``` + +Adds a starter model to the generated schema. + +### With preview features + +```bash +prisma init --preview-feature relationJoins --preview-feature fullTextSearch +``` + +## Generated Schema + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## Generated Config (Node.js default) + +```typescript +// prisma.config.ts +import "dotenv/config"; +import { defineConfig } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: process.env['DATABASE_URL'], + }, +}) +``` + +## Generated Config (Bun) + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Next Steps After Init + +1. Configure `DATABASE_URL` in `.env` (and let `prisma.config.ts` read it) +2. Define your models in `prisma/schema.prisma` +3. Run `prisma dev` for local development or connect to remote DB +4. Run `prisma migrate dev` to create migrations +5. Run `prisma generate` to generate Prisma Client +6. Run `prisma db seed` explicitly if you want seed data diff --git a/apps/backend/.agents/skills/prisma-cli/references/mcp.md b/apps/backend/.agents/skills/prisma-cli/references/mcp.md new file mode 100644 index 0000000..284130f --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/mcp.md @@ -0,0 +1,39 @@ +# prisma mcp + +Starts Prisma's MCP server for AI development tools. + +## Command + +```bash +prisma mcp +``` + +## What It Does + +- Starts a Model Context Protocol (MCP) server for your Prisma project +- Exposes Prisma schema and database context to compatible AI tools +- Helps AI assistants understand models, generate queries, and suggest migrations + +## Usage + +```bash +prisma mcp +``` + +## Typical Use Cases + +- Connect Prisma to ChatGPT, Claude, or other MCP-aware tools +- Give an AI assistant access to your Prisma schema structure +- Help an agent propose queries, schema updates, and migration steps with project context + +## Notes + +- Run this from the project that contains your Prisma schema and `prisma.config.ts` +- The command is separate from Prisma Studio and does not open a browser UI +- The MCP server exposes `migrate-status`, `migrate-dev`, and Prisma Studio tooling. It does not expose the destructive `migrate-reset` tool; do not claim it is available or try to bypass that safety boundary. +- For destructive shell commands, follow `agent-safety.md` and obtain explicit user consent. + +## References + +- [Prisma CLI `mcp` command](https://docs.prisma.io/docs/cli/mcp) +- [Prisma MCP Server](https://www.prisma.io/docs/ai/tools/chatgpt) diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-deploy.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-deploy.md new file mode 100644 index 0000000..2132075 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-deploy.md @@ -0,0 +1,127 @@ +# prisma migrate deploy + +Applies pending migrations in production/staging environments. + +## Command + +```bash +prisma migrate deploy +``` + +## What It Does + +- Applies all pending migrations from `prisma/migrations/` +- Updates `_prisma_migrations` table +- Does NOT generate new migrations +- Does NOT run seed scripts +- Safe for CI/CD and production + +## Options + +| Option | Description | +|--------|-------------| +| `--schema` | Custom path to your Prisma schema | +| `--config` | Custom path to your Prisma config file | + +## When to Use + +- Production deployments +- Staging environments +- CI/CD pipelines +- Any non-development environment + +## Examples + +### Basic deployment + +```bash +prisma migrate deploy +``` + +### In CI/CD pipeline + +```yaml +# GitHub Actions example +- name: Apply migrations + run: npx prisma migrate deploy + env: + DATABASE_URL: ${{ secrets.DATABASE_URL }} +``` + +### Docker deployment + +```dockerfile +# Run migrations before starting app +CMD npx prisma migrate deploy && node dist/index.js +``` + +## Comparison with migrate dev + +| Feature | migrate dev | migrate deploy | +|---------|-------------|----------------| +| Creates migrations | Yes | No | +| Applies migrations | Yes | Yes | +| Detects drift | Yes | No | +| Prompts for input | Yes | No | +| Uses shadow database | Yes | No | +| Safe for production | No | Yes | +| Resets on issues | Prompts | Fails | + +## Production Workflow + +1. **Development**: Create migrations locally + ```bash + prisma migrate dev --name add_feature + ``` + +2. **Commit**: Include migration files in version control + ```bash + git add prisma/migrations + git commit -m "Add feature migration" + ``` + +3. **Deploy**: Apply in production + ```bash + prisma migrate deploy + ``` + +## Error Handling + +### Failed migration + +If a migration fails, `migrate deploy` exits with error. The failed migration is marked as failed in `_prisma_migrations`. + +To fix: +1. Resolve the issue (fix SQL, database state, etc.) +2. Mark as resolved: `prisma migrate resolve --applied ` +3. Re-run: `prisma migrate deploy` + +### Check status first + +```bash +prisma migrate status +``` + +Shows pending and applied migrations before deploying. + +## Configuration + +Ensure `prisma.config.ts` has the production database URL: + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Best Practices + +1. Always run `migrate status` before `migrate deploy` in CI +2. Have a rollback plan (backup before migrations) +3. Test migrations in staging first +4. Never use `migrate dev` in production diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md new file mode 100644 index 0000000..48643b6 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md @@ -0,0 +1,145 @@ +# prisma migrate dev + +Creates and applies migrations during development. Requires a shadow database. + +## Command + +```bash +prisma migrate dev [options] +``` + +## What It Does + +1. Runs existing migrations in shadow database to detect drift +2. Applies any pending migrations +3. Generates new migration from schema changes +4. Applies new migration to development database +5. Updates `_prisma_migrations` table + +## Options + +| Option | Description | +|--------|-------------| +| `--name` / `-n` | Name the migration | +| `--create-only` | Create a new migration but do not apply it | +| `--schema` | Custom path to your Prisma schema | +| `--config` | Custom path to your Prisma config file | +| `--url` | Override the datasource URL from the Prisma config file | + +### Follow-up Commands + +- Run `prisma generate` explicitly when you need refreshed client output +- Run `prisma db seed` explicitly when you need seed data + +Run `prisma generate` as an explicit follow-up when you need refreshed generated artifacts. Do not rely on historical CLI help that described generators as part of `migrate dev`. + +## Examples + +### Create and apply migration + +```bash +prisma migrate dev +``` + +Prompts for migration name if schema changed. + +### Named migration + +```bash +prisma migrate dev --name add_users_table +``` + +### Create without applying + +```bash +prisma migrate dev --create-only +``` + +Useful for reviewing migration SQL before applying. + +### Full workflow + +```bash +prisma migrate dev --name my_migration +prisma generate +prisma db seed +``` + +## Migration Files + +Created in `prisma/migrations/`: + +``` +prisma/migrations/ +├── 20240115120000_add_users_table/ +│ └── migration.sql +├── 20240116090000_add_posts/ +│ └── migration.sql +└── migration_lock.toml +``` + +## Schema Drift Detection + +If `migrate dev` detects drift (manual database changes or edited migrations), it prompts to reset: + +``` +Drift detected: Your database schema is not in sync. + +Do you want to reset your database? All data will be lost. +``` + +## When to Use + +- Local development +- Adding new models/fields +- Changing relations +- Creating indexes + +## When NOT to Use + +- Production deployments (use `migrate deploy`) +- CI/CD pipelines (use `migrate deploy`) +- MongoDB (use `db push` instead) + +## Common Patterns + +### After schema changes + +```prisma +// schema.prisma - Add new field +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + createdAt DateTime @default(now()) // New field +} +``` + +```bash +prisma migrate dev --name add_created_at +``` + +### Handling data loss warnings + +When a migration would cause data loss: + +```bash +prisma migrate dev --name remove_field +# Warning: You are about to delete data... +# Accept with: --accept-data-loss +``` + +## Shadow Database + +`migrate dev` requires a shadow database for drift detection. Configure in `prisma.config.ts`: + +```typescript +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), + }, +}) +``` + +For local Prisma Postgres (`prisma dev`), shadow database is handled automatically. diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-diff.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-diff.md new file mode 100644 index 0000000..873107e --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-diff.md @@ -0,0 +1,89 @@ +# prisma migrate diff + +Compares database schemas and generates diffs (SQL or summary). + +## Command + +```bash +prisma migrate diff [options] +``` + +## What It Does + +- Compares two sources (`--from-...` and `--to-...`) +- Sources can be: + - Empty (`empty`) + - Schema file (`schema`) + - Migrations directory (`migrations`) + - Database URL (`url`) or Configured Datasource (`config-datasource`) +- Outputs the difference: + - Human-readable summary (default) + - SQL script (`--script`) + +## Options + +| Option | Description | +|--------|-------------| +| `--script` | Render SQL script to stdout | +| `--exit-code` | Exit 2 if changes detected, 0 if empty, 1 if error | +| `--config` | Custom path to your Prisma config file | + +### Sources (Must provide one `from` and one `to`) + +- `--from-empty`, `--to-empty` +- `--from-schema `, `--to-schema ` +- `--from-migrations `, `--to-migrations ` +- `--from-url `, `--to-url ` +- `--from-config-datasource`, `--to-config-datasource` (uses `prisma.config.ts`) + +## Examples + +### Generate SQL for a schema change + +Compare current production DB to your local schema: + +```bash +prisma migrate diff \ + --from-url "$PROD_DB_URL" \ + --to-schema ./prisma/schema.prisma \ + --script +``` + +### Review pending migrations + +Compare database state to migrations directory: + +```bash +prisma migrate diff \ + --from-config-datasource \ + --to-migrations ./prisma/migrations +``` + +### Create baseline migration + +Compare empty state to current schema: + +```bash +prisma migrate diff \ + --from-empty \ + --to-schema ./prisma/schema.prisma \ + --script > prisma/migrations/0_init/migration.sql +``` + +### Check for drift (CI) + +Check if database matches schema: + +```bash +prisma migrate diff \ + --from-config-datasource \ + --to-schema ./prisma/schema.prisma \ + --exit-code +``` + +## Use Cases + +- **Forward-generating migrations**: Creating SQL without `migrate dev`. +- **Drift detection**: Checking if DB is in sync. +- **Baselining**: Creating initial migration from existing DB. +- **Debugging**: Understanding what `migrate dev` would do. diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-reset.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-reset.md new file mode 100644 index 0000000..900e288 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-reset.md @@ -0,0 +1,80 @@ +# prisma migrate reset + +Resets your database and re-applies all migrations. + +## Command + +```bash +prisma migrate reset [options] +``` + +## What It Does + +1. **Drops** the database (if possible) or deletes all data/tables +2. **Re-creates** the database +3. **Applies** all migrations from `prisma/migrations/` +4. Stops there - run seed and generate explicitly if needed + +**Warning: All data will be lost.** + +When Prisma detects an AI agent, this command is blocked until the user gives explicit consent. Follow `agent-safety.md`; `--force` skips the ordinary prompt but does not constitute user consent for an agent. + +## Options + +| Option | Description | +|--------|-------------| +| `--force` / `-f` | Skip confirmation prompt | +| `--schema` | Path to schema file | +| `--config` | Custom path to your Prisma config file | + +## Examples + +### Basic reset + +```bash +prisma migrate reset +``` + +Prompts for confirmation in interactive terminals. + +### Force reset (CI/Automation) + +```bash +prisma migrate reset --force +``` + +### With custom schema + +```bash +prisma migrate reset --schema=./custom/schema.prisma +``` + +## When to Use + +- **Development**: When you want a fresh start +- **Testing**: Resetting test database before suites +- **Drift Recovery**: When the database is out of sync and you can't migrate + +## Follow-up Steps + +Run `prisma generate` and `prisma db seed` explicitly when you need refreshed client output or seed data after a reset. + +## Configuration + +Configure the seed script in `prisma.config.ts`, then run it explicitly after reset: + +```typescript +export default defineConfig({ + migrations: { + seed: 'tsx prisma/seed.ts', + }, +}) +``` + +Typical workflow: + +```bash +prisma migrate reset --force +prisma generate +prisma db seed +``` diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-resolve.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-resolve.md new file mode 100644 index 0000000..6b65f65 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-resolve.md @@ -0,0 +1,57 @@ +# prisma migrate resolve + +Resolves issues with database migrations, such as failed migrations or baselining. + +## Command + +```bash +prisma migrate resolve [options] +``` + +## What It Does + +Updates the `_prisma_migrations` table to manually change the state of a migration. This is a recovery tool. + +## Options + +You must provide exactly one of `--applied` or `--rolled-back`. + +| Option | Description | +|--------|-------------| +| `--applied ` | Mark a migration as **applied** (success) | +| `--rolled-back ` | Mark a migration as **rolled back** (ignored/failed) | +| `--schema` | Path to schema file | +| `--config` | Custom path to your Prisma config file | + +## Examples + +### Mark as Applied (Baselining) + +If you have existing tables and want to initialize migrations without running the SQL: + +```bash +prisma migrate resolve --applied 20240101000000_initial_migration +``` + +This tells Prisma "Assume this migration has already run". + +### Mark as Rolled Back (Fixing Failures) + +If a migration failed (e.g., syntax error) and you fixed the SQL or want to retry: + +```bash +prisma migrate resolve --rolled-back 20240115120000_failed_migration +``` + +This tells Prisma "Forget this migration run, let me try applying it again". + +## Use Cases + +1. **Baselining**: Adopting Prisma Migrate on an existing production database. +2. **Failed Migrations**: Recovering from a failed `migrate deploy` in production. +3. **Hotfixes**: reconciling manual database changes (rare). + +## References + +- [Baselining](https://www.prisma.io/docs/guides/database/developing-with-prisma-migrate/baselining) +- [Troubleshooting](https://www.prisma.io/docs/guides/database/production-troubleshooting) diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-status.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-status.md new file mode 100644 index 0000000..80a7ffa --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-status.md @@ -0,0 +1,65 @@ +# prisma migrate status + +Checks the status of your database migrations. + +## Command + +```bash +prisma migrate status [options] +``` + +## What It Does + +- Connects to the database +- Checks the `_prisma_migrations` table +- Compares applied migrations with local migration files +- Reports: + - **Status**: Database is up-to-date or behind + - **Unapplied migrations**: Count of pending migrations + - **Missing migrations**: Migrations present in DB but missing locally + - **Failed migrations**: Any migrations that failed to apply + +## Options + +| Option | Description | +|--------|-------------| +| `--schema` | Path to schema file | +| `--config` | Custom path to your Prisma config file | + +## Examples + +### Check status + +```bash +prisma migrate status +``` + +Output example (Up to date): +``` +Database schema is up to date! +``` + +Output example (Pending): +``` +Following migration have not yet been applied: + 20240115120000_add_user + +To apply migrations in development, run: + prisma migrate dev + +To apply migrations in production, run: + prisma migrate deploy +``` + +## When to Use + +- **Debugging**: Why is `migrate dev` complaining about drift? +- **CI/CD**: Verify database state before deploying +- **Production**: Check if migrations are needed (`migrate deploy`) or if a deployment failed + +## Exit Codes + +- `0`: Success (may have pending migrations, but command ran successfully) +- `1`: Error + +To check for pending migrations programmatically, you might need to parse the output or use `migrate diff` with exit code flags. diff --git a/apps/backend/.agents/skills/prisma-cli/references/studio.md b/apps/backend/.agents/skills/prisma-cli/references/studio.md new file mode 100644 index 0000000..ba71c9d --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/studio.md @@ -0,0 +1,137 @@ +# prisma studio + +Opens a visual database browser for viewing and editing data. + +## Command + +```bash +prisma studio [options] +``` + +## What It Does + +- Starts a web-based database GUI +- View all your models and records +- Create, update, and delete records +- Filter and sort data +- Navigate relations + +## Options + +| Option | Description | Default | +|--------|-------------|---------| +| `--port` / `-p` | Port to start Studio on | `5555` | +| `--browser` / `-b` | Browser to open Studio in | System default | +| `--config` | Custom path to your Prisma config file | - | +| `--url` | Database connection string (overrides the one in your Prisma config) | - | + +## Examples + +### Open Studio + +```bash +prisma studio +``` + +Opens at http://localhost:5555 + +### Custom port + +```bash +prisma studio --port 3000 +``` + +### Specific browser + +```bash +prisma studio --browser firefox +``` + +### Don't open browser + +```bash +BROWSER=none prisma studio +``` + +Useful for remote servers. + +## Features + +### View Records + +- See all records in table format +- Pagination for large datasets +- Column sorting + +### Filter Data + +- Filter by any field +- Multiple conditions +- Relation filtering + +### Edit Records + +- Click to edit inline +- Add new records +- Delete records (with confirmation) + +### Navigate Relations + +- Click relations to view related records +- See counts of related items +- Follow relation links + +## Recent Studio Capabilities + +Recent Prisma Studio releases added richer editor workflows: + +- multi-cell selection and editing +- full-table search and more intuitive filtering +- command palette shortcuts +- dark mode +- copy selections as Markdown +- back-relation navigation +- SQL workflows including raw SQL queries + +Some recent builds also expose AI-assisted SQL authoring. Treat these as interactive Studio features rather than a replacement for checked-in migrations or application queries. + +## Use Cases + +- **Development**: Quick data inspection +- **Debugging**: Check data state +- **Testing**: Verify seed data +- **Demo**: Show data to stakeholders + +## Limitations + +- Development tool only +- Not for production use +- Limited to configured database +- Prisma Studio in Prisma 7 currently targets PostgreSQL, MySQL, and SQLite first +- For reproducible application logic, prefer Prisma Client and checked-in SQL scripts + +## Common Workflow + +1. Run migrations: + ```bash + prisma migrate dev + ``` + +2. Seed data: + ```bash + prisma db seed + ``` + +3. Open Studio to verify: + ```bash + prisma studio + ``` + +4. Make manual edits if needed + +## Security Note + +Studio provides direct database access. Only run on: +- Local development machines +- Secure internal networks +- Never expose publicly diff --git a/apps/backend/.agents/skills/prisma-cli/references/validate.md b/apps/backend/.agents/skills/prisma-cli/references/validate.md new file mode 100644 index 0000000..61156c6 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-cli/references/validate.md @@ -0,0 +1,53 @@ +# prisma validate + +Validates your Prisma schema file. + +## Command + +```bash +prisma validate [options] +``` + +## What It Does + +- Parses the `schema.prisma` file +- Checks for syntax errors +- Validates model definitions, relations, and types +- Reports any errors or warnings without generating code + +## Options + +| Option | Description | +|--------|-------------| +| `--schema` | Path to schema file | +| `--config` | Custom path to your Prisma config file | + +## Examples + +### Validate default schema + +```bash +prisma validate +``` + +### Validate specific schema + +```bash +prisma validate --schema=./custom/schema.prisma +``` + +### Use in CI + +Run `validate` in your CI pipeline to catch schema errors early: + +```yaml +- name: Validate Schema + run: npx prisma validate +``` + +## Common Errors + +- Missing `@relation` fields +- Invalid types +- Duplicate model names +- Syntax errors (missing braces, etc.) diff --git a/apps/backend/.agents/skills/prisma-client-api/SKILL.md b/apps/backend/.agents/skills/prisma-client-api/SKILL.md new file mode 100644 index 0000000..57aa8a5 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/SKILL.md @@ -0,0 +1,216 @@ +--- +name: prisma-client-api +description: Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction". +license: MIT +metadata: + author: prisma + version: "7.9.1" +--- + +# Prisma Client API Reference + +Complete API reference for Prisma Client. This skill provides guidance on model queries, filtering, relations, and client methods for current Prisma projects. + +## When to Apply + +Reference this skill when: +- Writing database queries with Prisma Client +- Performing CRUD operations (create, read, update, delete) +- Filtering and sorting data +- Working with relations +- Using transactions +- Configuring client options + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Client Construction | HIGH | `constructor` | +| 2 | Model Queries | CRITICAL | `model-queries` | +| 3 | Query Shape | HIGH | `query-options` | +| 4 | Filtering | HIGH | `filters` | +| 5 | Relations | HIGH | `relations` | +| 6 | Transactions | CRITICAL | `transactions` | +| 7 | Raw SQL | CRITICAL | `raw-queries` | +| 8 | Client Methods | MEDIUM | `client-methods` | + +## Quick Reference + +- `constructor` - `PrismaClient` setup, adapter wiring, logging, and SQL commenter plugins +- `model-queries` - CRUD operations and bulk operations +- `query-options` - `select`, `include`, `omit`, sort, pagination +- `filters` - scalar and logical filter operators +- `relations` - relation reads and nested writes +- `transactions` - array and interactive transaction patterns +- `raw-queries` - `$queryRaw` and `$executeRaw` safety +- `client-methods` - lifecycle methods, extensions, and `satisfies` patterns for `prisma-client` + +## Client Instantiation + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +## Model Query Methods + +| Method | Description | +|--------|-------------| +| `findUnique()` | Find one record by unique field | +| `findUniqueOrThrow()` | Find one or throw error | +| `findFirst()` | Find first matching record | +| `findFirstOrThrow()` | Find first or throw error | +| `findMany()` | Find multiple records | +| `create()` | Create a new record | +| `createMany()` | Create multiple records | +| `createManyAndReturn()` | Create multiple and return them | +| `update()` | Update one record | +| `updateMany()` | Update multiple records | +| `updateManyAndReturn()` | Update multiple and return them | +| `upsert()` | Update or create record | +| `delete()` | Delete one record | +| `deleteMany()` | Delete multiple records | +| `count()` | Count matching records | +| `aggregate()` | Aggregate values (sum, avg, etc.) | +| `groupBy()` | Group and aggregate | + +## Query Options + +| Option | Description | +|--------|-------------| +| `where` | Filter conditions | +| `select` | Fields to include | +| `include` | Relations to load | +| `omit` | Fields to exclude | +| `orderBy` | Sort order | +| `take` | Limit results | +| `skip` | Skip results (pagination) | +| `cursor` | Cursor-based pagination | +| `distinct` | Unique values only | + +## Client Methods + +| Method | Description | +|--------|-------------| +| `$connect()` | Explicitly connect to database | +| `$disconnect()` | Disconnect from database | +| `$transaction()` | Execute transaction | +| `$queryRaw()` | Execute raw SQL query | +| `$executeRaw()` | Execute raw SQL command | +| `$on()` | Subscribe to events | +| `$extends()` | Add extensions | + +## Quick Examples + +### Find records + +```typescript +// Find by unique field +const user = await prisma.user.findUnique({ + where: { email: 'alice@prisma.io' } +}) + +// Find with filter +const users = await prisma.user.findMany({ + where: { role: 'ADMIN' }, + orderBy: { createdAt: 'desc' }, + take: 10 +}) +``` + +### Create records + +```typescript +const user = await prisma.user.create({ + data: { + email: 'alice@prisma.io', + name: 'Alice', + posts: { + create: { title: 'Hello World' } + } + }, + include: { posts: true } +}) +``` + +### Update records + +```typescript +const user = await prisma.user.update({ + where: { id: 1 }, + data: { name: 'Alice Smith' } +}) +``` + +### Delete records + +```typescript +await prisma.user.delete({ + where: { id: 1 } +}) +``` + +### Transactions + +```typescript +const [user, post] = await prisma.$transaction([ + prisma.user.create({ data: { email: 'alice@prisma.io' } }), + prisma.post.create({ data: { title: 'Hello', authorId: 1 } }) +]) +``` + +## Rule Files + +Detailed API documentation: + +``` +references/constructor.md - PrismaClient constructor options +references/model-queries.md - CRUD operations +references/query-options.md - select, include, omit, where, orderBy +references/filters.md - Filter conditions and operators +references/relations.md - Relation queries and nested operations +references/transactions.md - Transaction API +references/raw-queries.md - $queryRaw, $executeRaw +references/client-methods.md - $connect, $disconnect, $on, $extends +``` + +## Filter Operators + +| Operator | Description | +|----------|-------------| +| `equals` | Exact match | +| `not` | Not equal | +| `in` | In array | +| `notIn` | Not in array | +| `lt`, `lte` | Less than | +| `gt`, `gte` | Greater than | +| `contains` | String contains | +| `startsWith` | String starts with | +| `endsWith` | String ends with | +| `mode` | Case sensitivity | + +## Relation Filters + +| Operator | Description | +|----------|-------------| +| `some` | At least one related record matches | +| `every` | All related records match | +| `none` | No related records match | +| `is` | Related record matches (1-to-1) | +| `isNot` | Related record doesn't match | + +## Resources + +- [Prisma Client API Reference](https://www.prisma.io/docs/orm/reference/prisma-client-reference) +- [CRUD Operations](https://www.prisma.io/docs/orm/prisma-client/queries/crud) +- [Filtering and Sorting](https://www.prisma.io/docs/orm/prisma-client/queries/filtering-and-sorting) + +## How to Use + +Pick the category from the table above, then open the matching reference file for implementation details and examples. diff --git a/apps/backend/.agents/skills/prisma-client-api/references/client-methods.md b/apps/backend/.agents/skills/prisma-client-api/references/client-methods.md new file mode 100644 index 0000000..17beb1f --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/client-methods.md @@ -0,0 +1,223 @@ +# Client Methods + +Prisma Client instance methods. + +## $connect() + +Explicitly connect to the database: + +```typescript +const prisma = new PrismaClient({ adapter }) + +// Explicit connection +await prisma.$connect() +``` + +### When to use + +Usually not needed - Prisma connects automatically on first query. Use for: +- Fail fast on startup +- Health checks +- Pre-warming connections + +```typescript +async function main() { + try { + await prisma.$connect() + console.log('Database connected') + } catch (e) { + console.error('Failed to connect:', e) + process.exit(1) + } +} +``` + +## $disconnect() + +Close database connection: + +```typescript +await prisma.$disconnect() +``` + +### Graceful shutdown + +```typescript +process.on('beforeExit', async () => { + await prisma.$disconnect() +}) + +// Or with SIGTERM +process.on('SIGTERM', async () => { + await prisma.$disconnect() + process.exit(0) +}) +``` + +### In tests + +```typescript +afterAll(async () => { + await prisma.$disconnect() +}) +``` + +## $on() + +Subscribe to events: + +### Query events + +```typescript +const prisma = new PrismaClient({ + adapter, + log: [{ level: 'query', emit: 'event' }] +}) + +prisma.$on('query', (e) => { + console.log('Query:', e.query) + console.log('Params:', e.params) + console.log('Duration:', e.duration, 'ms') +}) +``` + +### Log events + +```typescript +const prisma = new PrismaClient({ + adapter, + log: [ + { level: 'info', emit: 'event' }, + { level: 'warn', emit: 'event' }, + { level: 'error', emit: 'event' } + ] +}) + +prisma.$on('info', (e) => console.log(e.message)) +prisma.$on('warn', (e) => console.warn(e.message)) +prisma.$on('error', (e) => console.error(e.message)) +``` + +## $extends() + +Add extensions for custom behavior: + +### Add custom methods + +```typescript +const prisma = new PrismaClient({ adapter }).$extends({ + client: { + $log: (message: string) => console.log(message) + } +}) + +prisma.$log('Hello!') +``` + +### Add model methods + +```typescript +const prisma = new PrismaClient({ adapter }).$extends({ + model: { + user: { + async findByEmail(email: string) { + return prisma.user.findUnique({ where: { email } }) + } + } + } +}) + +const user = await prisma.user.findByEmail('alice@prisma.io') +``` + +### Query extensions + +```typescript +const prisma = new PrismaClient({ adapter }).$extends({ + query: { + user: { + async findMany({ args, query }) { + // Add default filter + args.where = { ...args.where, deletedAt: null } + return query(args) + } + } + } +}) +``` + +### Result extensions + +```typescript +const prisma = new PrismaClient({ adapter }).$extends({ + result: { + user: { + fullName: { + needs: { firstName: true, lastName: true }, + compute(user) { + return `${user.firstName} ${user.lastName}` + } + } + } + } +}) + +const user = await prisma.user.findFirst() +console.log(user.fullName) // Computed field +``` + +### Chain extensions + +```typescript +const prisma = new PrismaClient({ adapter }) + .$extends(loggingExtension) + .$extends(softDeleteExtension) + .$extends(computedFieldsExtension) +``` + +## $transaction() + +See `transactions.md` for details. + +## $queryRaw() / $executeRaw() + +See `raw-queries.md` for details. + +## Type utilities + +### Prisma namespace + +```typescript +import { Prisma } from '../generated/client' + +// Input types +type UserCreateInput = Prisma.UserCreateInput +type UserWhereInput = Prisma.UserWhereInput + +// Output types +type User = Prisma.UserGetPayload<{}> +type UserWithPosts = Prisma.UserGetPayload<{ + include: { posts: true } +}> +``` + +### Type-safe query fragments with satisfies + +Type-safe query fragments: + +```typescript +import { Prisma } from '../generated/client' + +const userSelect = { + id: true, + email: true, + name: true +} satisfies Prisma.UserSelect + +const user = await prisma.user.findUnique({ + where: { id: 1 }, + select: userSelect +}) +``` + +With the `prisma-client` generator, use TypeScript `satisfies` for typed query fragments. You may still see older examples that use `Prisma.validator()` with `prisma-client-js`. diff --git a/apps/backend/.agents/skills/prisma-client-api/references/constructor.md b/apps/backend/.agents/skills/prisma-client-api/references/constructor.md new file mode 100644 index 0000000..a9fb5e8 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/constructor.md @@ -0,0 +1,221 @@ +# PrismaClient Constructor + +Configure Prisma Client when instantiating. + +## Basic Instantiation + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +## Constructor Options + +### adapter (Required for the SQL provider workflow) + +Driver adapter instance: + +```typescript +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### accelerateUrl (For Accelerate users) + +```typescript +import { withAccelerate } from '@prisma/extension-accelerate' + +const prisma = new PrismaClient({ + accelerateUrl: process.env.DATABASE_URL, // prisma:// URL +}).$extends(withAccelerate()) +``` + +### log + +Configure logging: + +```typescript +const prisma = new PrismaClient({ + adapter, + log: ['query', 'info', 'warn', 'error'], +}) +``` + +#### Log levels + +| Level | Description | +|-------|-------------| +| `query` | All SQL queries | +| `info` | Informational messages | +| `warn` | Warnings | +| `error` | Errors | + +#### Log to events + +```typescript +const prisma = new PrismaClient({ + adapter, + log: [ + { level: 'query', emit: 'event' }, + { level: 'error', emit: 'stdout' }, + ], +}) + +prisma.$on('query', (e) => { + console.log('Query:', e.query) + console.log('Duration:', e.duration, 'ms') +}) +``` + +### errorFormat + +Control error formatting: + +```typescript +const prisma = new PrismaClient({ + adapter, + errorFormat: 'pretty', // 'pretty' | 'colorless' | 'minimal' +}) +``` + +### comments + +Attach SQL commenter plugins for observability, tracing, or query insights: + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' +import { prismaQueryInsights } from '@prisma/sqlcommenter-query-insights' +import { queryTags, withQueryTags } from '@prisma/sqlcommenter-query-tags' +import { traceContext } from '@prisma/sqlcommenter-trace-context' + +const prisma = new PrismaClient({ + adapter: new PrismaPg(process.env.DATABASE_URL!), + comments: [prismaQueryInsights(), traceContext(), queryTags()], +}) + +await withQueryTags({ route: '/api/users', requestId: 'req-123' }, () => + prisma.user.findMany(), +) +``` + +Use `comments` only for SQL providers. This is the clean way to add trace or query-shape metadata without changing your query calls. + +### transactionOptions + +Default transaction settings: + +```typescript +const prisma = new PrismaClient({ + adapter, + transactionOptions: { + maxWait: 5000, // Max wait to acquire transaction (ms) + timeout: 10000, // Max transaction duration (ms) + isolationLevel: 'Serializable', + }, +}) +``` + +### queryPlanCacheMaxSize + +Use `queryPlanCacheMaxSize` to limit the in-memory query-plan cache: + +```typescript +const prisma = new PrismaClient({ + adapter, + queryPlanCacheMaxSize: 2_000, +}) +``` + +The value must be a non-negative integer. Set it to `0` to disable query-plan caching; omit it to use Prisma's default. Treat this as a process-local memory/performance control, not a database prepared-statement setting. + +## Singleton Pattern + +Prevent multiple client instances in development: + +```typescript +// lib/prisma.ts +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +function createPrismaClient() { + const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL! + }) + return new PrismaClient({ adapter }) +} + +export const prisma = globalForPrisma.prisma ?? createPrismaClient() + +if (process.env.NODE_ENV !== 'production') { + globalForPrisma.prisma = prisma +} +``` + +## Next.js Pattern + +```typescript +// lib/prisma.ts +import { PrismaClient } from '@/generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const createAdapter = () => new PrismaPg({ + connectionString: process.env.DATABASE_URL! +}) + +const prismaClientSingleton = () => { + return new PrismaClient({ adapter: createAdapter() }) +} + +declare const globalThis: { + prismaGlobal: ReturnType +} & typeof global + +const prisma = globalThis.prismaGlobal ?? prismaClientSingleton() + +export default prisma + +if (process.env.NODE_ENV !== 'production') { + globalThis.prismaGlobal = prisma +} +``` + +## Query Events + +Listen to query events: + +```typescript +const prisma = new PrismaClient({ + adapter, + log: [{ level: 'query', emit: 'event' }], +}) + +prisma.$on('query', (e) => { + console.log('Query:', e.query) + console.log('Params:', e.params) + console.log('Duration:', e.duration) +}) +``` + +## Log Events + +```typescript +prisma.$on('info', (e) => console.log(e.message)) +prisma.$on('warn', (e) => console.warn(e.message)) +prisma.$on('error', (e) => console.error(e.message)) +``` diff --git a/apps/backend/.agents/skills/prisma-client-api/references/filters.md b/apps/backend/.agents/skills/prisma-client-api/references/filters.md new file mode 100644 index 0000000..a9b7eea --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/filters.md @@ -0,0 +1,256 @@ +# Filter Conditions and Operators + +Filter operators for the `where` clause. + +## Equality + +```typescript +// Exact match (implicit) +where: { email: 'alice@prisma.io' } + +// Explicit equals +where: { email: { equals: 'alice@prisma.io' } } + +// Not equal +where: { email: { not: 'alice@prisma.io' } } +``` + +## Comparison + +```typescript +// Greater than +where: { age: { gt: 18 } } + +// Greater than or equal +where: { age: { gte: 18 } } + +// Less than +where: { age: { lt: 65 } } + +// Less than or equal +where: { age: { lte: 65 } } + +// Combined +where: { age: { gte: 18, lte: 65 } } +``` + +## Lists + +```typescript +// In array +where: { role: { in: ['ADMIN', 'MODERATOR'] } } + +// Not in array +where: { role: { notIn: ['GUEST', 'BANNED'] } } +``` + +## String Filters + +```typescript +// Contains +where: { email: { contains: 'prisma' } } + +// Starts with +where: { email: { startsWith: 'alice' } } + +// Ends with +where: { email: { endsWith: '@prisma.io' } } + +// Case-insensitive (default for some databases) +where: { + email: { + contains: 'PRISMA', + mode: 'insensitive' + } +} +``` + +## Null Checks + +```typescript +// Is null +where: { deletedAt: null } + +// Is not null +where: { deletedAt: { not: null } } + +// Using isSet (for optional fields) +where: { middleName: { isSet: true } } +``` + +## Logical Operators + +### AND (implicit) + +```typescript +// Multiple conditions = AND +where: { + email: { contains: '@prisma.io' }, + role: 'ADMIN' +} +``` + +### AND (explicit) + +```typescript +where: { + AND: [ + { email: { contains: '@prisma.io' } }, + { role: 'ADMIN' } + ] +} +``` + +### OR + +```typescript +where: { + OR: [ + { email: { contains: '@gmail.com' } }, + { email: { contains: '@prisma.io' } } + ] +} +``` + +### NOT + +```typescript +where: { + NOT: { + role: 'GUEST' + } +} + +// Multiple NOT conditions +where: { + NOT: [ + { role: 'GUEST' }, + { verified: false } + ] +} +``` + +### Combined + +```typescript +where: { + AND: [ + { verified: true }, + { + OR: [ + { role: 'ADMIN' }, + { role: 'MODERATOR' } + ] + } + ], + NOT: { deletedAt: { not: null } } +} +``` + +## Relation Filters + +### some + +At least one related record matches: + +```typescript +// Users with at least one published post +where: { + posts: { + some: { published: true } + } +} +``` + +### every + +All related records match: + +```typescript +// Users where all posts are published +where: { + posts: { + every: { published: true } + } +} +``` + +### none + +No related records match: + +```typescript +// Users with no published posts +where: { + posts: { + none: { published: true } + } +} +``` + +### is / isNot (1-to-1) + +```typescript +// Users with profile in specific country +where: { + profile: { + is: { country: 'USA' } + } +} + +// Users without profile +where: { + profile: { + isNot: null + } +} +``` + +## Array Field Filters + +For fields like `String[]`: + +```typescript +// Has element +where: { tags: { has: 'typescript' } } + +// Has some elements +where: { tags: { hasSome: ['typescript', 'javascript'] } } + +// Has every element +where: { tags: { hasEvery: ['typescript', 'prisma'] } } + +// Is empty +where: { tags: { isEmpty: true } } +``` + +## JSON Filters + +```typescript +// Path-based filter +where: { + metadata: { + path: ['settings', 'theme'], + equals: 'dark' + } +} + +// String contains in JSON +where: { + metadata: { + path: ['bio'], + string_contains: 'developer' + } +} +``` + +## Full-Text Search + +```typescript +// Requires @@fulltext index +where: { + content: { + search: 'prisma database' + } +} +``` diff --git a/apps/backend/.agents/skills/prisma-client-api/references/model-queries.md b/apps/backend/.agents/skills/prisma-client-api/references/model-queries.md new file mode 100644 index 0000000..0687ef5 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/model-queries.md @@ -0,0 +1,281 @@ +# Model Queries + +CRUD operations for your Prisma models. + +## Read Operations + +### findUnique + +Find a single record by unique field: + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 } +}) + +const user = await prisma.user.findUnique({ + where: { email: 'alice@prisma.io' } +}) +``` + +#### With composite unique key + +```typescript +// Model with @@unique([firstName, lastName]) +const user = await prisma.user.findUnique({ + where: { + firstName_lastName: { + firstName: 'Alice', + lastName: 'Smith' + } + } +}) +``` + +### findUniqueOrThrow + +Same as findUnique but throws if not found: + +```typescript +const user = await prisma.user.findUniqueOrThrow({ + where: { id: 1 } +}) +// Throws PrismaClientKnownRequestError if not found +``` + +### findFirst + +Find first matching record: + +```typescript +const user = await prisma.user.findFirst({ + where: { role: 'ADMIN' }, + orderBy: { createdAt: 'desc' } +}) +``` + +### findFirstOrThrow + +```typescript +const user = await prisma.user.findFirstOrThrow({ + where: { role: 'ADMIN' } +}) +``` + +### findMany + +Find multiple records: + +```typescript +const users = await prisma.user.findMany({ + where: { role: 'USER' }, + orderBy: { name: 'asc' }, + take: 10, + skip: 0 +}) +``` + +## Create Operations + +### create + +Create a single record: + +```typescript +const user = await prisma.user.create({ + data: { + email: 'alice@prisma.io', + name: 'Alice' + } +}) +``` + +#### With relations + +```typescript +const user = await prisma.user.create({ + data: { + email: 'alice@prisma.io', + posts: { + create: [ + { title: 'First Post' }, + { title: 'Second Post' } + ] + } + }, + include: { posts: true } +}) +``` + +### createMany + +Create multiple records: + +```typescript +const result = await prisma.user.createMany({ + data: [ + { email: 'alice@prisma.io', name: 'Alice' }, + { email: 'bob@prisma.io', name: 'Bob' } + ], + skipDuplicates: true // Skip records with duplicate unique fields +}) +// Returns { count: 2 } +``` + +### createManyAndReturn + +Create multiple and return them: + +```typescript +const users = await prisma.user.createManyAndReturn({ + data: [ + { email: 'alice@prisma.io', name: 'Alice' }, + { email: 'bob@prisma.io', name: 'Bob' } + ] +}) +// Returns array of created users +``` + +## Update Operations + +### update + +Update a single record: + +```typescript +const user = await prisma.user.update({ + where: { id: 1 }, + data: { name: 'Alice Smith' } +}) +``` + +#### Atomic operations + +```typescript +const post = await prisma.post.update({ + where: { id: 1 }, + data: { + views: { increment: 1 }, + likes: { decrement: 1 }, + score: { multiply: 2 }, + rating: { divide: 2 }, + version: { set: 5 } + } +}) +``` + +### updateMany + +Update multiple records: + +```typescript +const result = await prisma.user.updateMany({ + where: { role: 'USER' }, + data: { verified: true } +}) +// Returns { count: 42 } +``` + +### updateManyAndReturn + +```typescript +const users = await prisma.user.updateManyAndReturn({ + where: { role: 'USER' }, + data: { verified: true } +}) +// Returns array of updated users +``` + +### upsert + +Update or create: + +```typescript +const user = await prisma.user.upsert({ + where: { email: 'alice@prisma.io' }, + update: { name: 'Alice Smith' }, + create: { email: 'alice@prisma.io', name: 'Alice' } +}) +``` + +## Delete Operations + +### delete + +Delete a single record: + +```typescript +const user = await prisma.user.delete({ + where: { id: 1 } +}) +// Returns deleted record +``` + +### deleteMany + +Delete multiple records: + +```typescript +const result = await prisma.user.deleteMany({ + where: { role: 'GUEST' } +}) +// Returns { count: 5 } + +// Delete all +const result = await prisma.user.deleteMany({}) +``` + +## Aggregation Operations + +### count + +```typescript +const count = await prisma.user.count({ + where: { role: 'ADMIN' } +}) +``` + +### aggregate + +```typescript +const result = await prisma.post.aggregate({ + _avg: { views: true }, + _sum: { views: true }, + _min: { views: true }, + _max: { views: true }, + _count: { _all: true } +}) +``` + +### groupBy + +```typescript +const groups = await prisma.user.groupBy({ + by: ['country'], + _count: { _all: true }, + _avg: { age: true }, + having: { + age: { _avg: { gt: 30 } } + } +}) +``` + +## Return Types + +| Method | Returns | +|--------|---------| +| `findUnique` | Record \| null | +| `findUniqueOrThrow` | Record (throws if not found) | +| `findFirst` | Record \| null | +| `findFirstOrThrow` | Record (throws if not found) | +| `findMany` | Record[] | +| `create` | Record | +| `createMany` | { count: number } | +| `createManyAndReturn` | Record[] | +| `update` | Record | +| `updateMany` | { count: number } | +| `delete` | Record | +| `deleteMany` | { count: number } | +| `count` | number | +| `aggregate` | Aggregate result | +| `groupBy` | Group result[] | diff --git a/apps/backend/.agents/skills/prisma-client-api/references/query-options.md b/apps/backend/.agents/skills/prisma-client-api/references/query-options.md new file mode 100644 index 0000000..25864a4 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/query-options.md @@ -0,0 +1,276 @@ +# Query Options + +Options for controlling query behavior. + +## select + +Choose specific fields to return: + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + select: { + id: true, + name: true, + email: true, + // password: false (excluded by not including) + } +}) +// Returns: { id: 1, name: 'Alice', email: 'alice@prisma.io' } +``` + +### Select relations + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + select: { + name: true, + posts: { + select: { + title: true, + published: true + } + } + } +}) +``` + +### Select with include inside + +```typescript +const user = await prisma.user.findMany({ + select: { + name: true, + posts: { + include: { + comments: true + } + } + } +}) +``` + +### Select relation count + +```typescript +const users = await prisma.user.findMany({ + select: { + name: true, + _count: { + select: { posts: true } + } + } +}) +// Returns: { name: 'Alice', _count: { posts: 5 } } +``` + +## include + +Include related records: + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + posts: true, + profile: true + } +}) +``` + +### Filtered include + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + posts: { + where: { published: true }, + orderBy: { createdAt: 'desc' }, + take: 5 + } + } +}) +``` + +### Nested include + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + posts: { + include: { + comments: { + include: { + author: true + } + } + } + } + } +}) +``` + +### Include relation count + +```typescript +const users = await prisma.user.findMany({ + include: { + _count: { + select: { posts: true, followers: true } + } + } +}) +``` + +## omit + +Exclude specific fields: + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + omit: { + password: true + } +}) +// Returns all fields except password +``` + +### Omit in relations + +```typescript +const users = await prisma.user.findMany({ + omit: { password: true }, + include: { + posts: { + omit: { content: true } + } + } +}) +``` + +**Note:** Cannot use `select` and `omit` together. + +## where + +Filter records: + +```typescript +const users = await prisma.user.findMany({ + where: { + email: { contains: '@prisma.io' }, + role: 'ADMIN' + } +}) +``` + +See `filters.md` for detailed filter operators. + +## orderBy + +Sort results: + +```typescript +// Single field +const users = await prisma.user.findMany({ + orderBy: { name: 'asc' } +}) + +// Multiple fields +const users = await prisma.user.findMany({ + orderBy: [ + { role: 'desc' }, + { name: 'asc' } + ] +}) +``` + +### Order by relation + +```typescript +const users = await prisma.user.findMany({ + orderBy: { + posts: { _count: 'desc' } + } +}) +``` + +### Null handling + +```typescript +const users = await prisma.user.findMany({ + orderBy: { + name: { sort: 'asc', nulls: 'last' } + } +}) +``` + +## take & skip + +Pagination: + +```typescript +// First page +const users = await prisma.user.findMany({ + take: 10, + skip: 0 +}) + +// Second page +const users = await prisma.user.findMany({ + take: 10, + skip: 10 +}) +``` + +### Negative take (reverse) + +```typescript +const lastUsers = await prisma.user.findMany({ + take: -10, + orderBy: { id: 'asc' } +}) +// Returns last 10 users +``` + +## cursor + +Cursor-based pagination: + +```typescript +// First page +const firstPage = await prisma.user.findMany({ + take: 10, + orderBy: { id: 'asc' } +}) + +// Next page using cursor +const nextPage = await prisma.user.findMany({ + take: 10, + skip: 1, // Skip the cursor record + cursor: { id: firstPage[firstPage.length - 1].id }, + orderBy: { id: 'asc' } +}) +``` + +## distinct + +Return unique values: + +```typescript +const cities = await prisma.user.findMany({ + distinct: ['city'], + select: { city: true } +}) +``` + +### Multiple distinct fields + +```typescript +const locations = await prisma.user.findMany({ + distinct: ['city', 'country'] +}) +``` diff --git a/apps/backend/.agents/skills/prisma-client-api/references/raw-queries.md b/apps/backend/.agents/skills/prisma-client-api/references/raw-queries.md new file mode 100644 index 0000000..e444ce2 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/raw-queries.md @@ -0,0 +1,198 @@ +# Raw Queries + +Execute raw SQL when Prisma's query API isn't sufficient. + +## $queryRaw + +Execute SELECT queries and get typed results: + +```typescript +const users = await prisma.$queryRaw` + SELECT * FROM "User" WHERE email LIKE ${'%@prisma.io'} +` +``` + +### With type + +```typescript +type User = { id: number; email: string; name: string | null } + +const users = await prisma.$queryRaw` + SELECT id, email, name FROM "User" WHERE role = ${'ADMIN'} +` +``` + +### Dynamic table/column names + +Use `Prisma.raw()` for identifiers (not safe for user input): + +```typescript +import { Prisma } from '../generated/client' + +const column = 'email' +const users = await prisma.$queryRaw` + SELECT ${Prisma.raw(column)} FROM "User" +` +``` + +### With Prisma.sql + +Build queries dynamically: + +```typescript +import { Prisma } from '../generated/client' + +const email = 'alice@prisma.io' +const query = Prisma.sql`SELECT * FROM "User" WHERE email = ${email}` +const users = await prisma.$queryRaw(query) +``` + +### Join multiple SQL fragments + +```typescript +import { Prisma } from '../generated/client' + +const conditions = [ + Prisma.sql`role = ${'ADMIN'}`, + Prisma.sql`verified = ${true}` +] + +const users = await prisma.$queryRaw` + SELECT * FROM "User" + WHERE ${Prisma.join(conditions, ' AND ')} +` +``` + +## $executeRaw + +Execute INSERT, UPDATE, DELETE (returns affected count): + +```typescript +const count = await prisma.$executeRaw` + UPDATE "User" SET verified = true WHERE email LIKE ${'%@prisma.io'} +` +console.log(`Updated ${count} users`) +``` + +### Delete example + +```typescript +const deleted = await prisma.$executeRaw` + DELETE FROM "User" WHERE "deletedAt" < ${thirtyDaysAgo} +` +``` + +### Insert example + +```typescript +const inserted = await prisma.$executeRaw` + INSERT INTO "Log" (message, level, timestamp) + VALUES (${message}, ${level}, ${new Date()}) +` +``` + +## $queryRawUnsafe / $executeRawUnsafe + +For fully dynamic queries (use with caution!): + +```typescript +// ⚠️ SQL injection risk - only use with trusted input +const table = 'User' +const users = await prisma.$queryRawUnsafe( + `SELECT * FROM "${table}" WHERE id = $1`, + userId +) +``` + +### Parameterized unsafe query + +```typescript +const result = await prisma.$executeRawUnsafe( + 'UPDATE "User" SET name = $1 WHERE id = $2', + 'Alice', + 1 +) +``` + +## SQL Injection Prevention + +### Safe (parameterized) + +```typescript +// ✅ User input is parameterized +const email = userInput +const users = await prisma.$queryRaw` + SELECT * FROM "User" WHERE email = ${email} +` +``` + +### Unsafe (concatenation) + +```typescript +// ❌ SQL injection vulnerability! +const email = userInput +const users = await prisma.$queryRawUnsafe( + `SELECT * FROM "User" WHERE email = '${email}'` +) +``` + +## Database-Specific Features + +### PostgreSQL + +```typescript +// Array operations +const users = await prisma.$queryRaw` + SELECT * FROM "User" WHERE 'admin' = ANY(roles) +` + +// JSON operations +const users = await prisma.$queryRaw` + SELECT * FROM "User" WHERE metadata->>'theme' = 'dark' +` +``` + +### MySQL + +```typescript +// Full-text search +const posts = await prisma.$queryRaw` + SELECT * FROM Post WHERE MATCH(title, content) AGAINST(${searchTerm}) +` +``` + +## Transactions with Raw Queries + +```typescript +await prisma.$transaction(async (tx) => { + await tx.$executeRaw`UPDATE "Account" SET balance = balance - ${amount} WHERE id = ${senderId}` + await tx.$executeRaw`UPDATE "Account" SET balance = balance + ${amount} WHERE id = ${recipientId}` +}) +``` + +## Handling Results + +### BigInt handling + +PostgreSQL returns BigInt for COUNT: + +```typescript +const result = await prisma.$queryRaw<[{ count: bigint }]>` + SELECT COUNT(*) as count FROM "User" +` +const count = Number(result[0].count) +``` + +### Date handling + +```typescript +type Result = { createdAt: Date } +const users = await prisma.$queryRaw` + SELECT "createdAt" FROM "User" +` +// createdAt is already a Date object +``` + +Invalid JavaScript `Date` values passed to raw queries fail validation instead of being silently serialized as `null`. Validate date input at the application boundary; do not rely on `new Date(badValue)` reaching the database. + +When a driver adapter returns an unmapped database-specific error, Prisma surfaces `P2039` with the adapter's preserved original code/message. If those details are missing, fix the adapter mapping rather than parsing rendered error text. diff --git a/apps/backend/.agents/skills/prisma-client-api/references/relations.md b/apps/backend/.agents/skills/prisma-client-api/references/relations.md new file mode 100644 index 0000000..001c448 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/relations.md @@ -0,0 +1,308 @@ +# Relation Queries + +Query and modify related records. + +## Include Relations + +Load related records: + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + posts: true, + profile: true + } +}) +``` + +### Filtered include + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + posts: { + where: { published: true }, + orderBy: { createdAt: 'desc' }, + take: 5, + select: { id: true, title: true } + } + } +}) +``` + +### Nested include + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + posts: { + include: { + comments: { + include: { author: true } + } + } + } + } +}) +``` + +## Select Relations + +```typescript +const user = await prisma.user.findUnique({ + where: { id: 1 }, + select: { + name: true, + posts: { + select: { title: true } + } + } +}) +``` + +## Nested Writes + +### Create with relations + +```typescript +const user = await prisma.user.create({ + data: { + email: 'alice@prisma.io', + posts: { + create: [ + { title: 'Post 1' }, + { title: 'Post 2' } + ] + }, + profile: { + create: { bio: 'Hello!' } + } + } +}) +``` + +### Create or connect + +```typescript +const post = await prisma.post.create({ + data: { + title: 'New Post', + author: { + connectOrCreate: { + where: { email: 'alice@prisma.io' }, + create: { email: 'alice@prisma.io', name: 'Alice' } + } + } + } +}) +``` + +### Connect existing + +```typescript +const post = await prisma.post.create({ + data: { + title: 'New Post', + author: { + connect: { id: 1 } + } + } +}) + +// Shorthand for foreign key +const post = await prisma.post.create({ + data: { + title: 'New Post', + authorId: 1 + } +}) +``` + +## Update Relations + +### Update related records + +```typescript +const user = await prisma.user.update({ + where: { id: 1 }, + data: { + posts: { + update: { + where: { id: 1 }, + data: { title: 'Updated Title' } + } + } + } +}) +``` + +### Update many related + +```typescript +const user = await prisma.user.update({ + where: { id: 1 }, + data: { + posts: { + updateMany: { + where: { published: false }, + data: { published: true } + } + } + } +}) +``` + +### Upsert related + +```typescript +const user = await prisma.user.update({ + where: { id: 1 }, + data: { + profile: { + upsert: { + create: { bio: 'New bio' }, + update: { bio: 'Updated bio' } + } + } + } +}) +``` + +### Disconnect + +```typescript +// 1-to-1 optional +const user = await prisma.user.update({ + where: { id: 1 }, + data: { + profile: { disconnect: true } + } +}) + +// Many-to-many +const post = await prisma.post.update({ + where: { id: 1 }, + data: { + tags: { + disconnect: [{ id: 1 }, { id: 2 }] + } + } +}) +``` + +### Delete related + +```typescript +const user = await prisma.user.update({ + where: { id: 1 }, + data: { + posts: { + delete: { id: 1 } + } + } +}) + +// Delete many +const user = await prisma.user.update({ + where: { id: 1 }, + data: { + posts: { + deleteMany: { published: false } + } + } +}) +``` + +### Set (replace all) + +```typescript +// Replace all related records +const post = await prisma.post.update({ + where: { id: 1 }, + data: { + tags: { + set: [{ id: 1 }, { id: 2 }] + } + } +}) +``` + +## Relation Filters + +### some + +At least one matches: + +```typescript +const users = await prisma.user.findMany({ + where: { + posts: { some: { published: true } } + } +}) +``` + +### every + +All match: + +```typescript +const users = await prisma.user.findMany({ + where: { + posts: { every: { published: true } } + } +}) +``` + +### none + +None match: + +```typescript +const users = await prisma.user.findMany({ + where: { + posts: { none: { published: true } } + } +}) +``` + +### is / isNot (1-to-1) + +```typescript +const users = await prisma.user.findMany({ + where: { + profile: { is: { country: 'USA' } } + } +}) +``` + +## Count Relations + +```typescript +const users = await prisma.user.findMany({ + select: { + name: true, + _count: { + select: { posts: true, followers: true } + } + } +}) +// { name: 'Alice', _count: { posts: 5, followers: 100 } } +``` + +### Filter counted relations + +```typescript +const users = await prisma.user.findMany({ + select: { + name: true, + _count: { + select: { + posts: { where: { published: true } } + } + } + } +}) +``` diff --git a/apps/backend/.agents/skills/prisma-client-api/references/transactions.md b/apps/backend/.agents/skills/prisma-client-api/references/transactions.md new file mode 100644 index 0000000..c2a981a --- /dev/null +++ b/apps/backend/.agents/skills/prisma-client-api/references/transactions.md @@ -0,0 +1,184 @@ +# Transactions + +Execute multiple operations atomically. + +## Sequential Transactions + +Array of operations executed in order: + +```typescript +const [user, post] = await prisma.$transaction([ + prisma.user.create({ data: { email: 'alice@prisma.io' } }), + prisma.post.create({ data: { title: 'Hello', authorId: 1 } }) +]) +``` + +### All or nothing + +If any operation fails, all are rolled back: + +```typescript +try { + await prisma.$transaction([ + prisma.user.create({ data: { email: 'alice@prisma.io' } }), + prisma.user.create({ data: { email: 'alice@prisma.io' } }) // Duplicate! + ]) +} catch (e) { + // Both operations rolled back +} +``` + +## Interactive Transactions + +For complex logic and dependent operations: + +```typescript +await prisma.$transaction(async (tx) => { + // Decrement sender balance + const sender = await tx.account.update({ + where: { id: senderId }, + data: { balance: { decrement: amount } } + }) + + // Check balance + if (sender.balance < 0) { + throw new Error('Insufficient funds') + } + + // Increment recipient balance + await tx.account.update({ + where: { id: recipientId }, + data: { balance: { increment: amount } } + }) +}) +``` + +### Transaction options + +```typescript +await prisma.$transaction( + async (tx) => { + // operations + }, + { + maxWait: 5000, // Max wait to acquire lock (ms) + timeout: 10000, // Max transaction duration (ms) + isolationLevel: 'Serializable' // Isolation level + } +) +``` + +### Isolation levels + +| Level | Description | +|-------|-------------| +| `ReadUncommitted` | Lowest isolation, can read uncommitted changes | +| `ReadCommitted` | Only read committed changes | +| `RepeatableRead` | Consistent reads within transaction | +| `Serializable` | Highest isolation, serialized execution | + +## Nested Writes + +Automatic transactions for nested operations: + +```typescript +// This is automatically a transaction +const user = await prisma.user.create({ + data: { + email: 'alice@prisma.io', + posts: { + create: [ + { title: 'Post 1' }, + { title: 'Post 2' } + ] + }, + profile: { + create: { bio: 'Hello!' } + } + } +}) +``` + +## Transaction Client + +The `tx` parameter is a Prisma Client scoped to the transaction: + +```typescript +await prisma.$transaction(async (tx) => { + // Use tx instead of prisma + await tx.user.create({ ... }) + await tx.post.create({ ... }) + + // Can call methods + const count = await tx.user.count() +}) +``` + +## OrThrow in Transactions + +Use with interactive transactions: + +```typescript +await prisma.$transaction(async (tx) => { + // If not found, throws and rolls back entire transaction + const user = await tx.user.findUniqueOrThrow({ + where: { id: 1 } + }) + + await tx.post.create({ + data: { title: 'New Post', authorId: user.id } + }) +}) +``` + +## Best Practices + +### Keep transactions short + +```typescript +// Good - only DB operations in transaction +const data = prepareData() // Outside transaction +await prisma.$transaction(async (tx) => { + await tx.user.create({ data }) +}) +``` + +### Handle errors + +```typescript +try { + await prisma.$transaction(async (tx) => { + // operations + }) +} catch (e) { + if (e.code === 'P2002') { + // Handle unique constraint violation + } + throw e +} +``` + +### Use appropriate isolation + +```typescript +// Default is fine for most cases +await prisma.$transaction(async (tx) => { + // operations +}) + +// Use Serializable for strict consistency +await prisma.$transaction( + async (tx) => { /* operations */ }, + { isolationLevel: 'Serializable' } +) +``` + +## Sequential vs Interactive + +| Feature | Sequential | Interactive | +|---------|------------|-------------| +| Syntax | Array | Async function | +| Dependent ops | No | Yes | +| Conditional logic | No | Yes | +| Performance | Better | More flexible | +| Use case | Simple batch | Complex logic | diff --git a/apps/backend/.agents/skills/prisma-compute/SKILL.md b/apps/backend/.agents/skills/prisma-compute/SKILL.md new file mode 100644 index 0000000..f1105f9 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/SKILL.md @@ -0,0 +1,193 @@ +--- +name: prisma-compute +description: Prisma Compute deployment and hosting guide. Use whenever the user mentions Prisma Compute, `prisma.compute.ts`, `defineComputeConfig`, deploying or hosting a Prisma app, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, `PRISMA_SERVICE_TOKEN`, Compute auth/workspaces, apps/deployments/build logs/domains, localhost vs `0.0.0.0`, deploy port binding, or framework deploy readiness for Hono, Elysia, Next.js, TanStack Start, Astro, Nuxt, Svelte, Nest, Turborepo, or custom/prebuilt artifacts. +license: MIT +metadata: + author: prisma + version: "1.5.1" +--- + +# Prisma Compute + +Guide agents through Prisma Compute app creation, deployment, operations, and framework-specific deploy readiness. + +## Prisma Compute CLI Surface + +Use the Prisma Platform CLI for Compute app workflows: + +```bash +bunx @prisma/cli@latest app deploy --help +bunx @prisma/cli@latest app --help +bunx @prisma/cli@latest build logs --help +bunx create-prisma@latest --help +``` + +Use `@prisma/cli@latest` for Compute app deployment. Use `create-prisma@latest` for new-project scaffolding. + +## Send Feedback and Report CLI Issues + +The CLI has a built-in feedback channel. Use it whenever a command crashes (`UNEXPECTED_ERROR`), a failure survives troubleshooting, or the user asks to send feedback to the Prisma team: + +```bash +bunx @prisma/cli@latest feedback "app deploy crashed: " +bunx @prisma/cli@latest feedback "love the deploy flow" --email you@example.com +``` + +Crash output points here on its own: `--json` crash envelopes carry the exact pre-filled command as a `recover` entry in `nextActions` (run it verbatim), and human crash output ends with a `Tell us what happened:` hint. Feedback is anonymous unless `--email` is passed and attaches only the CLI version, node version, and OS platform/arch. Never include secrets, connection URLs, or user data in the message. + +## Source-of-Truth Order + +Use evidence in this order when deciding what to edit or run: + +1. The project's generated scripts and config, especially `prisma.compute.ts`, `compute:deploy`, framework config, and `package.json`. +2. CLI help output from `create-prisma` and `@prisma/cli`. +3. Local installed package code, generated artifacts, and type definitions. +4. Official docs. + +## When to Apply + +Use this skill for: + +- Creating a new app that can deploy to Prisma Compute +- Deploying an existing TypeScript app to Prisma Compute +- Creating or updating a typed `prisma.compute.ts` deploy config +- Deciding whether a framework is Compute-ready +- Debugging `create-prisma --deploy`, `compute:deploy`, or `app deploy` +- Managing Compute app logs, deployments, environment variables, and domains, and listing platform branches (`branch list`; there are no branch create/remove commands) +- Inspecting GitHub/Console build logs and GitHub push-to-deploy status +- Running non-interactive deploys with browser auth, multiple stored workspaces, or Prisma service tokens +- Switching, selecting, listing, or logging out local Prisma Platform workspaces for `@prisma/cli` +- Sending feedback about an unresolvable Compute CLI failure with `@prisma/cli feedback` +- Programmatic deployments with `@prisma/compute-sdk` or Management API integrations + +## Decision Tree + +1. Existing project deployment or redeploy: + Read [`references/app-deploy-cli.md`](references/app-deploy-cli.md). + +2. Typed Compute config, monorepos, deploy targets, app roots, or build/env defaults: + Read [`references/compute-config.md`](references/compute-config.md). + +3. Framework-specific build/runtime work: + Read [`references/frameworks.md`](references/frameworks.md). + +4. New project from a scaffold: + Read [`references/create-prisma.md`](references/create-prisma.md). + +5. Programmatic deployment, SDKs, APIs, or low-level App/Deployment concepts: + Read [`references/sdk-api.md`](references/sdk-api.md). + +6. Build, auth, env, deploy, or runtime failures: + Read [`references/troubleshooting.md`](references/troubleshooting.md). + +## Rules by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Command verification | CRITICAL | `verify-` | +| 2 | Auth and workspace selection | CRITICAL | `auth-` | +| 3 | Framework readiness | CRITICAL | `framework-` | +| 4 | Runtime host and port binding | CRITICAL | `runtime-` | +| 5 | Typed Compute config | HIGH | `config-` | +| 6 | Branch, environment, and database wiring | HIGH | `env-` | +| 7 | Deploy operations | HIGH | `deploy-` | +| 8 | SDK and API automation | MEDIUM | `sdk-` | + +## Quick Rules + +### 1. Command Verification + +- `verify-help-first` - Use CLI help output to confirm command syntax while working. +- `verify-prisma-vs-platform-cli` - Do not assume `prisma app deploy` exists in the ORM CLI; check whether the task should use `@prisma/cli`. +- `verify-generated-scripts` - Prefer the generated `compute:deploy` script when a project already has one. +- `verify-public-url` - After a real deploy, request the public deployment URL instead of trusting local or readiness-only checks. +- `verify-config-support` - Treat `prisma.compute.ts` as the typed Compute config; inspect the project's config and generated scripts before editing or deploying. +- `verify-auth-workspace-support` - Use `@prisma/cli auth workspace` commands for local workspace list/use/logout flows. + +### 2. Auth and Workspace Selection + +- `auth-source-precedence` - A non-empty `PRISMA_SERVICE_TOKEN` is the active auth source for commands and local OAuth workspaces are ignored for execution. If it is set but empty, the CLI should fail instead of falling back to stored OAuth. +- `auth-multi-workspace` - `auth login` can store OAuth sessions for multiple workspaces on the same machine. The active workspace pointer selects which stored OAuth grant normal commands use. +- `auth-list-before-switch` - Use `auth workspace list --json` to inspect local sessions. Agents should prefer workspace ids from JSON over names because names can be ambiguous. +- `auth-switch-explicitly` - Use `auth workspace use ` for non-interactive switching. Use `auth workspace use` with no argument only for an interactive picker or when exactly one local OAuth workspace exists. +- `auth-no-fallthrough` - If the active OAuth workspace is logged out or fails refresh, the CLI should not silently fall through to another cached workspace. Run `auth workspace use ` to choose the next workspace. +- `auth-single-workspace-logout` - Use `auth workspace logout ` or `auth logout --workspace ` to remove one local OAuth workspace session. Plain `auth logout` clears all local OAuth workspace sessions. +- `auth-service-token-switching` - While `PRISMA_SERVICE_TOKEN` is set, `auth workspace use` is unavailable because the service token is the active auth source; unset the env var to switch local OAuth workspaces. Workspace logout still only cleans local OAuth state. +- `auth-storage-awareness` - Local OAuth credentials live in the platform auth file, with workspace metadata in a sidecar context file. Project pins live in `.prisma/local.json`, and CLI app/project state lives in `.prisma/cli/state.json` near `prisma.compute.ts` when present. + +### 3. Framework Readiness + +- `framework-cli-first` - Evaluate deploy readiness against `@prisma/cli app deploy`, not against what `create-prisma` can scaffold. +- `framework-supported-cli-deploy` - Compute deploy supports `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, and `bun`. +- `framework-create-prisma-defaults-only` - `create-prisma` can provide generated defaults and `compute:deploy`, but it is not the general deploy surface for existing apps. +- `framework-build-output` - Compute needs a server entrypoint or framework artifact, not only static output. + +### 4. Runtime Host and Port Binding + +- `runtime-bind-all-interfaces` - Deployed servers must bind on all interfaces (`0.0.0.0` or the framework equivalent), not hard-coded `localhost` or `127.0.0.1`. +- `runtime-match-http-port` - The app must listen on the deployed HTTP port: read `process.env.PORT` when possible, or pass the matching `--http-port`. +- `runtime-readiness-port-only` - Compute readiness watches listening ports; a loopback-only listener can look ready while public ingress cannot reach it. +- `runtime-respond-within-60s` - The ingress gives an app 60 seconds to start responding, then returns `504 Gateway Time-out` and cancels the request. Design handlers to answer first and run longer work under `waitUntil` or from a queue, never inside the request. + +### 5. Typed Compute Config + +- `config-optional-simple-app` - `prisma.compute.ts` is not required to deploy a normal single app; use flags when there is no durable config. +- `config-init-formalizer` - Generate a fresh config with `bunx @prisma/cli@latest init`: it detects the framework, pins name/framework/httpPort (plus entry for Bun/Hono), and offers the Project link. `--format json` writes a dependency-free `prisma.compute.json` instead. `init` refuses when any config already exists, never scaffolds code, and never deploys. +- `config-use-prisma-compute-ts` - Put reusable deploy defaults in `prisma.compute.ts` with `defineComputeConfig`, not in `prisma.config.ts`. +- `config-app-vs-apps` - Use `app` for a single deploy target and `apps` for monorepos or multi-app repos; define exactly one. +- `config-monorepo-roots` - For monorepos, use `prisma.compute.ts` to declare app targets, roots, framework defaults, entrypoints, ports, and env inputs. +- `config-targets` - In multi-app configs, `@prisma/cli app deploy web` selects the `apps.web` target. Without `[app]`, commands can infer the target from the current directory; otherwise deploy can run all targets while build/run require one. +- `config-region-new-app-only` - A config `region` is only a default for newly created apps; deploys to existing apps keep the app's current region. +- `config-custom-artifact` - Use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint` for prebuilt or custom-built artifacts. +- `config-no-project-branch-secrets` - Do not commit Workspace, Project, Branch, production intent, service tokens, or secret values in `prisma.compute.ts`; keep those in flags, `.prisma/local.json`, env storage, or CI secrets. App-level defaults such as `region`, `root`, `framework`, `entry`, `httpPort`, and non-secret env file paths belong in config. +- `config-flags-win` - Explicit deploy flags such as `--framework`, `--entry`, `--http-port`, `--region`, and `--env` override matching config values. + +### 6. Branch, Environment, and Database + +- `env-do-not-leak-secrets` - Never print full `DATABASE_URL`, service tokens, or secret values. +- `env-deploy-loads-dotenv` - Generated deploy scripts may load env via `prisma.compute.ts` or `--env .env`; inspect the actual script/config before redeploy. +- `env-migrations-separate` - Redeploy scripts do not run migrations or seed data. Run the appropriate Prisma database scripts separately. +- `env-cli-token-name` - `@prisma/cli` uses `PRISMA_SERVICE_TOKEN` for service-token auth. +- `env-branch-scope` - Branch deploys, branch env vars, and branch databases must use the same branch name; pass `--branch ` explicitly when targeting a preview branch. +- `env-production-vs-preview` - Use `--role production` for production env, `--role preview` for preview template env, and `--branch ` for branch-specific overrides. +- `env-db-explicit` - Keep database and env wiring explicit through database and project env commands; deploy examples should not add database setup, and deploys do not run migrations, seed data, or create one database per app automatically. + +### 7. Deploy Operations + +- `deploy-prod-intent` - Use `--prod --yes` only when the user intends a production deploy. The first production deploy of an App auto-promotes without `--prod`; the flag gates subsequent production-branch deploys. +- `deploy-no-promote` - Use `app deploy --no-promote` for build-then-verify: it builds a candidate reachable at its own URL without touching the live deployment, promoted later with `app promote `. +- `deploy-github-default-branch` - When a Compute app is connected to GitHub push-to-deploy, a merge to the default branch is the production deploy path; check deployment records or GitHub check runs instead of telling users to redeploy the merged PR branch or run a default-branch preview deploy. +- `deploy-build-logs` - Use `@prisma/cli build logs ` for GitHub/Console build output. Use `app logs` for runtime deployment logs; the two ids are different. +- `deploy-noninteractive-auth` - Non-interactive deploys need either the correct active stored OAuth workspace or a supported service token env var; never print the token. +- `deploy-json-for-agents` - Use `--json --no-interactive` for scripts and agent-readable output. +- `deploy-create-project` - Use `--create-project ` only when the user wants deploy to create and link a new project; it conflicts with `--project` and `PRISMA_PROJECT_ID`. +- `deploy-ops-targets` - App show/open/logs/list-deploys/promote/rollback/remove and domain commands can also accept `[app]` targets from `prisma.compute.ts`. +- `deploy-report-cli-bugs` - On `UNEXPECTED_ERROR` or an unresolvable failure, report it with the feedback command; see "Send Feedback and Report CLI Issues" above. + +### 8. SDK and API + +- `sdk-use-cli-first` - Prefer `@prisma/cli app deploy` for app workflows; use `create-prisma` only to scaffold a new app unless the user is building lower-level automation. +- `sdk-result-handling` - `@prisma/compute-sdk` returns `Result` values; check `isOk()`/`isErr()` instead of relying on exceptions. +- `sdk-snapshot-detection` - Use `detectComputeApp` for repository snapshots that are not checked out to disk; enumerate workspaces yourself and call it once per candidate app root. + +## Preferred Workflow + +1. Inspect the project: package manager, template/framework, `package.json` scripts, Prisma version, Prisma client location, `prisma.compute.ts`, and existing `compute:deploy`. +2. Verify CLI help output for the package actually being used. +3. Verify auth context before project/app mutations: `auth whoami --json`, and when multiple local sessions may exist, `auth workspace list --json`. +4. Choose the path: + - existing app deploy: config-backed target when present, generated `compute:deploy`, or `@prisma/cli app build/run/deploy` flags + - new app scaffold: `create-prisma`, then generated `compute:deploy` or `@prisma/cli app deploy` + - low-level automation: `@prisma/compute-sdk` or Management API +5. Check framework readiness plus host/port/env/runtime requirements, including project and branch scope. +6. Run a local build or `app build` before deploying when feasible. +7. Deploy with JSON output when automating, then request the public URL and summarize app URL, app id, deployment id, project id, workspace id, and follow-up steps. +8. For GitHub/Console builds, inspect the `Prisma Compute Deploy` check run or `build logs ` before guessing why a build failed. + +## Avoid + +- Do not bury Compute deployment guidance in the generic `prisma-cli` skill. +- Do not run `create-prisma` inside an existing app just to deploy it; use the generated `compute:deploy` script or `@prisma/cli app deploy`. +- Do not tell users that every `create-prisma` template can auto-deploy. +- Do not deploy with placeholder `DATABASE_URL` values. +- Do not assume `next start` is the Compute runtime path; Next.js deploys need standalone output. diff --git a/apps/backend/.agents/skills/prisma-compute/references/app-deploy-cli.md b/apps/backend/.agents/skills/prisma-compute/references/app-deploy-cli.md new file mode 100644 index 0000000..0c472e0 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/references/app-deploy-cli.md @@ -0,0 +1,403 @@ +# Prisma Platform CLI App Deploy + +Use this reference for existing projects and for generated `compute:deploy` scripts. + +## Package and Command + +Compute app workflows are exposed through the Prisma Platform CLI package: + +```bash +bunx @prisma/cli@latest --help +bunx @prisma/cli@latest app --help +bunx @prisma/cli@latest app deploy --help +bunx @prisma/cli@latest build logs --help +``` + +The examples in help output may call the binary `prisma-cli`. When using package runners, prefer: + +```bash +bunx @prisma/cli@latest app deploy +npx @prisma/cli@latest app deploy +pnpm dlx @prisma/cli@latest app deploy +``` + +## Agent Skill Installation + +`@prisma/cli` can install and refresh Prisma skills for local AI coding agents: + +```bash +bunx @prisma/cli@latest agent install +bunx @prisma/cli@latest agent install --skill prisma-compute +bunx @prisma/cli@latest agent update +bunx @prisma/cli@latest agent status --json +``` + +`agent install` and `agent update` shell out to `skills@latest add prisma/skills` through the detected package runner. Use them when the user wants Prisma's agent context installed or refreshed; they are not a deployment command. + +## Typed Compute Config + +`prisma.compute.ts` is optional for normal single-app deploys and useful for reusable defaults or multi-app targets. Read [`compute-config.md`](compute-config.md) for config shapes, target selection, precedence, and monorepo rules. This reference only shows how deploy commands consume those settings. + +## Auth and Project Binding + +Useful commands: + +```bash +bunx @prisma/cli@latest auth login +bunx @prisma/cli@latest auth whoami +bunx @prisma/cli@latest project list --json +bunx @prisma/cli@latest project show +bunx @prisma/cli@latest project link +``` + +`@prisma/cli` can keep multiple local browser-login workspace sessions. Running `auth login` again for a different workspace should add/update that workspace session and make it active; it should not delete the existing workspace session. The active workspace pointer decides which stored OAuth workspace normal commands use. + +For agents, prefer this flow before project/app mutations: + +```bash +bunx @prisma/cli@latest auth whoami --json +bunx @prisma/cli@latest auth workspace list --json +bunx @prisma/cli@latest auth workspace use +``` + +Use workspace ids from `auth workspace list --json` when possible. Names are friendlier for humans but can be ambiguous. Use `auth workspace use` with no argument for a human interactive picker; headless scripts should pass an id because no-argument `use` fails non-interactively when multiple local OAuth workspaces exist. + +If the active workspace is logged out or its refresh fails, the CLI intentionally does not auto-select another cached workspace. Choose the next workspace explicitly: + +Use `auth workspace list --json`, then `auth workspace use `. + +To clean up one local OAuth workspace without clearing every stored workspace session: + +```bash +bunx @prisma/cli@latest auth workspace logout +# equivalent: +bunx @prisma/cli@latest auth logout --workspace +``` + +Plain `auth logout` clears all local OAuth workspace sessions. It does not unset `PRISMA_SERVICE_TOKEN`. + +For a new linked project: + +```bash +bunx @prisma/cli@latest project create my-app --json +``` + +For non-interactive or CI work, `@prisma/cli` accepts a workspace service token through `PRISMA_SERVICE_TOKEN`. A non-empty service token takes precedence over stored browser-login credentials, so local OAuth workspace switching does not affect command execution while the env var is set. `auth workspace list --json` may still show local OAuth sessions, but they are not switchable until the service-token env var is unset. Verify auth with `auth whoami` and never print the token value. + +If `PRISMA_SERVICE_TOKEN` is set but empty, unset it or provide a real token. The CLI should fail instead of silently falling back to local OAuth credentials. + +Local auth storage is useful for debugging but should not be printed verbatim: + +- `PRISMA_COMPUTE_AUTH_FILE` can override the auth file path. +- On macOS, the default OAuth credentials file is `~/Library/Application Support/prisma/auth.json`. +- Workspace metadata and the active workspace pointer live beside it as `auth.context.json`. +- Project pins live in `.prisma/local.json`. +- Local CLI state such as selected app and known live deployment lives in `.prisma/cli/state.json`, rooted near `prisma.compute.ts` when a config is discovered. + +## Project, Branch, Database, and Env Scope + +Compute deploys resolve a target project, app, and branch. Be explicit when the user's intent is not the already linked default project/app: + +```bash +bunx @prisma/cli@latest project show --json +bunx @prisma/cli@latest app deploy --project proj_123 --app my-api --branch feature/login --json +``` + +If `prisma.compute.ts` defines a `name` or an `apps` key, that config can provide the app name. `--app` and `PRISMA_APP_ID` rank above the config value. `[app]` selects a target from `apps`: + +```bash +bunx @prisma/cli@latest app deploy api --project proj_123 --branch feature/login --json +``` + +See [`compute-config.md`](compute-config.md) for no-argument target inference, deploy-all, and build/run target rules. + +Branch scope must line up across deploys, databases, and env vars: + +- `app deploy --branch ` creates a deployment for that branch. +- `database create --branch ` creates a Prisma Postgres database for that branch scope. +- `project env add/update/list/remove --branch ` manages branch-specific env overrides. +- `project env add/update/list/remove --role production` manages production env. +- `project env add/update/list/remove --role preview` manages preview-template env. + +Do not assume a local Git branch was used by the CLI unless the generated script or command output says so. If a user asks for `feature/login`, pass `--branch feature/login` consistently to app, database, and env commands. + +Promotion is a separate production action: `app promote ` rebuilds a deployment with production env vars. Do not treat a preview branch deploy as production promotion. + +## Deployment Story: GitHub vs CLI + +When a Compute app is connected to GitHub push-to-deploy, the default branch is the production deploy path. If a PR has been merged into `main` or another configured default branch, the natural answer is that the changes should appear in production after the production deployment completes; use CLI deploys for explicit manual deploys, local-source deploys, or repositories that are not using GitHub push-to-deploy. + +`app show`, `app list-deploys`, and `app logs` expose `--app`, `--project`, and for logs `--deployment`, not `--branch`. For branch debugging, capture the deployment id from deploy JSON and inspect that deployment or its logs. + +`app deploy --create-project ` creates and links a new Project before deploying. Use it only when the user wants a new Project. It conflicts with `--project` and `PRISMA_PROJECT_ID`, and `--yes` alone does not choose Project scope. + +`app deploy --region ` only applies when deploy creates a new app. Existing apps keep their current region. Use `prisma.compute.ts` `region` for a durable default, and use the flag only for one-off new-app placement. + +## Database and Env + +Create a Prisma Postgres database for the linked project: + +```bash +bunx @prisma/cli@latest database create main --branch main --json +``` + +Manage project env vars: + +```bash +bunx @prisma/cli@latest project env list +bunx @prisma/cli@latest project env add --file .env --role production +bunx @prisma/cli@latest project env add --file .env.preview --role preview +bunx @prisma/cli@latest project env add DATABASE_URL=postgresql://... --branch feature/foo +bunx @prisma/cli@latest project env update --file .env --role production +bunx @prisma/cli@latest project env update DATABASE_URL=postgresql://... --branch feature/foo +bunx @prisma/cli@latest project env list --branch feature/foo +bunx @prisma/cli@latest project env remove STRIPE_KEY --role preview +``` + +`app deploy --env .env` loads environment variables from a file for the deployment. A config-backed deploy can instead load env through `prisma.compute.ts` `env`. Neither path is a migration command or seed command. + +Database setup is not part of `prisma.compute.ts`. Keep database intent explicit with `database create` and project env commands. Do not add database setup to deploy examples. Treat any generated connection URL as a one-time secret. + +Database and env guardrails: + +- Deploys do not run migrations, seed data, or schema push. Run the app's own Prisma database command after deploy setup when needed. +- In deploy-all, every target on the same branch shares branch-scoped project env unless you assign app-specific env values yourself. +- Existing database env values supplied through `--env DATABASE_URL=...`, `--env DIRECT_URL=...`, an env file, or project env should be treated as the source of truth. +- Known non-PostgreSQL Prisma schema sources should not be wired to Prisma Postgres automatically. + +## Project Git, Branch, and Database Operations + +These commands are part of the same Platform CLI surface and often matter while preparing Compute deploys: + +```bash +bunx @prisma/cli@latest branch list --json +bunx @prisma/cli@latest git connect git@github.com:org/repo.git --project proj_123 +bunx @prisma/cli@latest git disconnect --project proj_123 +bunx @prisma/cli@latest database list --branch feature/foo --json +bunx @prisma/cli@latest database show db_123 --json +bunx @prisma/cli@latest database remove db_123 --confirm db_123 +bunx @prisma/cli@latest database connection list db_123 --json +bunx @prisma/cli@latest database connection create db_123 --name readonly +bunx @prisma/cli@latest database connection remove conn_123 --confirm conn_123 +bunx @prisma/cli@latest database connection rotate conn_123 --confirm conn_123 +bunx @prisma/cli@latest database usage db_123 --json +bunx @prisma/cli@latest database backup list db_123 --json +bunx @prisma/cli@latest database restore db_123 --backup bkp_123 --confirm db_123 +bunx @prisma/cli@latest project rename new-name --project proj_123 +bunx @prisma/cli@latest project transfer proj_123 --to-workspace wksp_456 --confirm proj_123 +bunx @prisma/cli@latest project remove proj_123 --confirm proj_123 +``` + +Destructive and ownership-changing commands (`remove`, `restore`, `transfer`, `connection rotate`) require exact `--confirm `; `--yes` is not enough. + +Git integration connects a Project to a GitHub repository. Console-side GitHub import can create a Compute app and trigger push-to-deploy for the connected repository, including default-branch production deploys. The CLI `git connect` command is setup, not a local deploy command; use `app deploy` for explicit CLI deploys. + +For GitHub-driven deploys, inspect the Console/build-runner state, deployment records, build logs, or the `Prisma Compute Deploy` GitHub check run instead of assuming local CLI output exists. The build runner can perform branch-aware database/env wiring: a preview branch with a Prisma schema and no `DATABASE_URL` can get a branch-scoped preview database, while production can wire a missing `DATABASE_URL` template from an existing ready database. GitHub check runs are the guided feedback path; do not promise Vercel-style PR comments. + +Database and database-connection commands never print stored secret values in list/show output. `database create` and `database connection create` return a one-time connection URL; treat it as a secret, store it immediately in env if needed, and do not echo it back in summaries. Removal requires exact `--confirm `; `--yes` is not enough. + +## Build and Run Locally + +Before deploy, verify that the app can produce a Compute artifact: + +```bash +bunx @prisma/cli@latest app build --build-type auto +bunx @prisma/cli@latest app run --build-type auto --port 3000 +``` + +For Bun/server entrypoints: + +```bash +bunx @prisma/cli@latest app build --build-type bun --entry src/index.ts +bunx @prisma/cli@latest app run --build-type bun --entry src/index.ts --port 8080 +``` + +For NestJS, use `app build` to validate the Compute artifact and run the framework's own dev command locally: + +```bash +bunx @prisma/cli@latest app build --build-type nestjs +bun run dev +``` + +With a compute config, pass the target name instead of repeating framework/entry/port flags: + +```bash +bunx @prisma/cli@latest app build api +bunx @prisma/cli@latest app run api --port 8080 +``` + +`app run --port` sets `PORT` for local development. It does not rewrite an app's explicit host binding, so a local run is not enough to prove the deployed server is reachable from ingress. + +`app run --build-type nestjs` is not supported. If a config-backed NestJS target is selected, run the Nest dev server directly instead. + +## Deploy + +Deploy with prompts: + +```bash +bunx @prisma/cli@latest app deploy +``` + +Agent/script-friendly deploy (do not assume production; add `--prod --yes` only when the user intends a production deploy, and note the first production deploy of an App auto-promotes without `--prod`): + +```bash +bunx @prisma/cli@latest app deploy \ + --json \ + --no-interactive \ + --env .env +``` + +Build-then-verify path for CI: `--no-promote` builds a candidate deployment without changing the live one; it is reachable at its own candidate URL and promoted later with `app promote `: + +```bash +bunx @prisma/cli@latest app deploy --no-promote --json --no-interactive +``` + +For preview branches, omit `--prod` unless the user explicitly intends a production deploy: + +```bash +bunx @prisma/cli@latest app deploy \ + --branch feature/foo \ + --json \ + --no-interactive \ + --env .env.preview +``` + +After a real deploy, verify the public deployment URL. Do not stop at "deploy succeeded" or a local `app run` check: + +```bash +curl -i https:// +``` + +If the deploy command returns JSON, parse the URL from the result and request that exact public URL. Do not accidentally test `localhost` or `127.0.0.1` instead of public ingress. + +Create/link a project during deploy: + +```bash +bunx @prisma/cli@latest app deploy \ + --create-project my-app \ + --prod \ + --yes \ + --env .env +``` + +Deploy with framework and port: + +```bash +bunx @prisma/cli@latest app deploy \ + --framework hono \ + --http-port 8080 \ + --prod \ + --yes \ + --env .env +``` + +Deploy a newly created app in a specific region: + +```bash +bunx @prisma/cli@latest app deploy \ + --app my-api \ + --region us-west-1 \ + --prod \ + --yes \ + --env .env +``` + +`--region` is a new-app placement hint. It does not move an existing app. + +Deploy a preview branch with framework and port: + +```bash +bunx @prisma/cli@latest app deploy \ + --framework hono \ + --branch feature/foo \ + --http-port 8080 \ + --json \ + --no-interactive \ + --env .env.preview +``` + +Bun-style app with explicit entrypoint: + +```bash +bunx @prisma/cli@latest app deploy \ + --framework bun \ + --entry src/index.ts \ + --http-port 8080 \ + --prod \ + --yes \ + --env .env +``` + +`--entry ` without `--framework` is treated as a Bun app deploy. + +Config-backed Bun-style app: + +```bash +bunx @prisma/cli@latest app deploy api --prod --yes --env .env +``` + +Use config for stable app defaults, and flags for one-off project, branch, region, env, and production choices. Keep database setup in explicit database and project-env commands. + +## Operations + +Inspect and open: + +```bash +bunx @prisma/cli@latest app show --json +bunx @prisma/cli@latest app open +``` + +Deployments: + +```bash +bunx @prisma/cli@latest app list-deploys --json +bunx @prisma/cli@latest app show-deploy --json +bunx @prisma/cli@latest app promote --yes +bunx @prisma/cli@latest app rollback --to --yes +bunx @prisma/cli@latest app remove --app my-api --yes +``` + +Logs: + +```bash +bunx @prisma/cli@latest app logs +bunx @prisma/cli@latest app logs --deployment +bunx @prisma/cli@latest app logs --json +``` + +Build logs for GitHub/Console builds: + +```bash +bunx @prisma/cli@latest build logs +bunx @prisma/cli@latest build logs --follow +bunx @prisma/cli@latest build logs --json +``` + +`build logs` streams build output keyed by a Build id from a GitHub/Console build or check run. It is separate from runtime `app logs`, which are keyed by the current app deployment or a deployment id. + +Domains: + +```bash +bunx @prisma/cli@latest app domain add shop.example.com +bunx @prisma/cli@latest app domain show shop.example.com +bunx @prisma/cli@latest app domain wait shop.example.com --timeout 15m +bunx @prisma/cli@latest app domain retry shop.example.com +bunx @prisma/cli@latest app domain remove shop.example.com +``` + +Custom domain commands target production branch runtime. Do not use a preview branch for production domain setup. + +## Output Handling + +When `--json` is available, parse the JSON and summarize: + +- project id/name +- branch name +- app id/name +- deployment id/status +- build id when present +- deployment URL +- database id/name if one was created + +Do not print secret env var values. diff --git a/apps/backend/.agents/skills/prisma-compute/references/compute-config.md b/apps/backend/.agents/skills/prisma-compute/references/compute-config.md new file mode 100644 index 0000000..633a603 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/references/compute-config.md @@ -0,0 +1,222 @@ +# Prisma Compute Config + +Use this reference when creating or updating `prisma.compute.ts`, especially for monorepos, multi-app deploys, reusable framework defaults, env inputs, ports, entrypoints, or build settings. + +`prisma.compute.ts` is not required for every deploy. A simple app can deploy with `@prisma/cli app deploy --framework ... --entry ... --http-port ... --env ...`. The config file exists to make those app-level defaults typed and repeatable. + +For monorepos or multi-app repositories, use `prisma.compute.ts`: it is the practical way to tell Compute which app target lives at which `root` and which framework/entry/env defaults belong to each target. + +## Generating a Config with `init` + +Prefer `bunx @prisma/cli@latest init` over hand-writing a fresh single-app config. It detects the framework from the same registry deploy uses, pins `name`, `framework`, and `httpPort` (plus `entry` for Bun and Hono), previews every value with its source, offers the `@prisma/compute-sdk` devDependency for editor types, and offers the Project link. Useful flags: `--framework`, `--entry`, `--http-port`, `--name`, `--no-link`, `--json`. + +`--format json` writes a dependency-free static `prisma.compute.json` instead of the TypeScript config; a later explicit `init --format ts` converts it in place when the config needs to become programmatic. `init` fails with `INIT_CONFIG_EXISTS` when any compute config already exists, never scaffolds application code, and never deploys. Multi-app monorepo configs are still written by hand. + +## File Names and Discovery + +The canonical file is `prisma.compute.ts`. The loader also accepts: + +```text +prisma.compute.mts +prisma.compute.js +prisma.compute.mjs +prisma.compute.cjs +prisma.compute.json +``` + +`prisma.compute.json` is the static, dependency-free variant of the same config; it is discovered and loaded like the others. + +Keep exactly one compute config file in a directory. If multiple names exist together, the CLI reports `COMPUTE_CONFIG_INVALID`. + +The CLI searches from the invocation directory up to the repository or workspace boundary. Boundaries include `.git`, `pnpm-workspace.yaml`, `bun.lock`, `bun.lockb`, or `package.json#workspaces`. Config-relative paths such as `root` and `env.file` resolve from the config file directory. `--env` flag paths still resolve from the invocation directory. + +When a config is discovered, its directory becomes the Compute project directory for local state: `.prisma/local.json` and `.prisma/cli/state.json` live beside that config, not necessarily inside the app root. + +## Basic Shape + +Import `defineComputeConfig` from `@prisma/compute-sdk/config`. The CLI aliases this helper when loading the config, so the command can evaluate the config without a local SDK install solely for runtime loading. + +```typescript +import { defineComputeConfig } from "@prisma/compute-sdk/config"; + +export default defineComputeConfig({ + app: { + name: "api", + framework: "hono", + httpPort: 8080, + env: ".env", + }, +}); +``` + +JavaScript configs can default-export a plain object, but prefer `prisma.compute.ts` for type checking. + +Define exactly one of: + +- `app` for a single deploy target +- `apps` for a monorepo or multi-app repository + +Do not define both. Besides `app`/`apps`, the only other allowed top-level key is `region`: a project-level default region applied when deploy creates new apps, overridable per app and by `--region`. + +## App Fields + +Each app target accepts: + +| Field | Meaning | +|-------|---------| +| `name` | Deployed app name. Defaults to the `apps` key, then CLI inference. | +| `region` | Compute region id used only when deploy creates a new app. Existing apps keep their current region. | +| `root` | App directory relative to the config file. Defaults to the config directory. | +| `framework` | Deploy framework: `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, or `bun`. | +| `entry` | Entrypoint path for Bun/Hono-style deploys, relative to the app root. | +| `httpPort` | Deployed HTTP port. Use this for fixed-port apps. | +| `env` | Dotenv file path string, or `{ file, vars }`. Paths resolve from the config directory. | +| `build` | `{ command, outputDirectory, entrypoint }`. Present means the config owns build settings for that target. | + +`env` examples: + +```typescript +export default defineComputeConfig({ + app: { + framework: "nextjs", + env: { + file: [".env", ".env.production"], + vars: { + NODE_ENV: "production", + }, + }, + }, +}); +``` + +Do not put secrets directly in committed `vars`. Keep secret values in platform env, CI secrets, or dotenv files that are intentionally managed outside version control. + +`build` examples: + +```typescript +export default defineComputeConfig({ + app: { + framework: "nextjs", + build: { + command: "pnpm build", + outputDirectory: ".next/standalone", + }, + }, +}); +``` + +Use `command: null` to skip the build step only when the app root already contains the deployable artifact. + +For a custom or prebuilt artifact, make the deploy target explicit: + +```typescript +export default defineComputeConfig({ + app: { + framework: "custom", + build: { + command: "npm run build", + outputDirectory: "build", + entrypoint: "handler.js", + }, + }, +}); +``` + +`build.entrypoint` is relative to `build.outputDirectory` when an output directory is set. For Bun/Hono configs without an output directory, an entrypoint-backed build can supply the source entrypoint. Do not set both `entry` and `build.entrypoint` unless they describe the same file. + +A config `build` block is accepted for every supported framework: the config-backed build types are `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun` (`hono` builds through the `bun` strategy). Only `custom` requires one (`build.outputDirectory` and `build.entrypoint`); for the others it overrides inferred build settings. + +## Monorepos and Multi-App Repos + +For monorepos, put `prisma.compute.ts` at the repo or workspace root and use `apps`. This keeps project binding and local `.prisma/` state at the repo root while each app builds from its own `root`. + +```typescript +import { defineComputeConfig } from "@prisma/compute-sdk/config"; + +export default defineComputeConfig({ + apps: { + web: { + root: "apps/web", + framework: "nextjs", + env: "apps/web/.env", + }, + api: { + root: "apps/api", + framework: "hono", + entry: "src/index.ts", + httpPort: 8080, + env: { + file: "apps/api/.env", + vars: { + LOG_LEVEL: "info", + }, + }, + }, + frontend: { + root: "apps/frontend", + framework: "custom", + build: { + command: "pnpm --filter frontend build", + outputDirectory: "dist/server", + entrypoint: "index.mjs", + }, + }, + }, +}); +``` + +Target selection: + +```bash +bunx @prisma/cli@latest app deploy web +bunx @prisma/cli@latest app deploy api +bunx @prisma/cli@latest app build api +bunx @prisma/cli@latest app run api --port 8080 +``` + +If no `[app]` argument is passed, commands can infer the target from the invocation directory when it is inside a configured `root`. The deepest matching root wins. If no target is inferred from a multi-app config, a bare deploy can deploy all targets in declaration order: + +```bash +bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive +``` + +Deploy-all rejects per-app overrides such as `--app`, `--framework`, `--entry`, `--http-port`, `--region`, `--env`, and `PRISMA_APP_ID`. Project, branch, production, and confirmation flags still apply to the whole run. Keep database setup in explicit database and project-env commands. + +`app build` and `app run` still need one target in multi-app configs because a local build/run command cannot operate N apps at once. + +Additional target rules: + +- A single-entry `apps` map can deploy its only target without an argument. +- With a single `app` config, `[app]` is accepted only when it equals the configured `name`. +- `[app]` without any compute config file is a usage error. + +## Precedence + +Explicit flags win over config values: + +- `--framework` overrides `framework` +- `--entry` overrides `entry` +- `--http-port` overrides `httpPort` +- `--region` overrides `region` +- any `--env` flag replaces all config env inputs +- `--app` and `PRISMA_APP_ID` rank above config app names + +`region` is not an app selector. Config `region` and `--region` are only used when deploy creates a new app. If the selected app already exists, deploy keeps that app's existing region. + +`prisma.compute.ts` never selects Workspace, Project, Branch, or production intent. Keep those in CLI flags, environment variables, `.prisma/local.json`, or CI configuration: + +```bash +bunx @prisma/cli@latest app deploy api \ + --project proj_123 \ + --branch feature/foo \ + --prod \ + --yes +``` + +## Database Scope + +The config does not declare databases. Keep database intent in `database create`, project env commands, or external automation. Read [`app-deploy-cli.md`](app-deploy-cli.md) for deploy-all, migration, and env-var guardrails. + +## Relationship to `prisma.config.ts` + +Do not put Compute deploy defaults in `prisma.config.ts`. Prisma ORM uses `prisma.config.ts`, while Compute uses `prisma.compute.ts`. diff --git a/apps/backend/.agents/skills/prisma-compute/references/create-prisma.md b/apps/backend/.agents/skills/prisma-compute/references/create-prisma.md new file mode 100644 index 0000000..ae09f92 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/references/create-prisma.md @@ -0,0 +1,117 @@ +# create-prisma Compute Flow + +Use this reference when creating a new app with Prisma and optionally deploying it to Prisma Compute. + +Do not use `create-prisma` as the deploy path for an existing app. For existing projects, use the generated `compute:deploy` script when present, or call `bunx @prisma/cli@latest app deploy` directly. + +## Reference + +Useful scaffold checks: + +```bash +bunx create-prisma@latest --help +bunx create-prisma@latest --version +``` + +Use `create-prisma@latest` for new-project scaffolding. + +## Supported Templates + +`create-prisma@latest` scaffolds `hono`, `elysia`, `nest`, `next`, `svelte`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`. + +Integrated `--deploy` support applies to `hono`, `elysia`, `nest`, `next`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`. For `turborepo`, the generated config target is usually `api`. + +The scaffold template name is `nest`, but the Compute deploy framework/config key is `nestjs`. + +`svelte` is scaffold-only for Compute because `@prisma/cli app deploy --framework` has no `svelte` key. + +## Basic Commands + +Interactive creation: + +```bash +bunx create-prisma@latest +``` + +Non-interactive scaffold only: + +```bash +bunx create-prisma@latest \ + --name my-api \ + --template hono \ + --provider postgresql \ + --no-install \ + --no-generate \ + --no-migrate-and-seed \ + --no-deploy +``` + +Create and deploy a supported template: + +```bash +bunx create-prisma@latest \ + --name my-api \ + --template hono \ + --provider postgresql \ + --deploy +``` + +## PostgreSQL and Database Behavior + +With PostgreSQL, no explicit `--database-url`, and no `--no-prisma-postgres`, the Compute flow can create: + +- a Prisma Compute project +- a `main` Prisma Postgres database on the `main` branch +- a `.env` file containing `DATABASE_URL` +- an initial Compute deployment with env vars loaded from `.env` + +`create-prisma` is the new-project path. If the user needs a later preview branch deploy, use the generated `compute:deploy` script or `@prisma/cli app deploy --branch ` after the app exists. Keep branch names aligned across `app deploy --branch`, `database create --branch`, and `project env ... --branch`. + +For unattended local tests, pass `--no-prisma-postgres` unless you intentionally want provisioning: + +```bash +bunx create-prisma@latest \ + --name smoke-app \ + --template hono \ + --provider postgresql \ + --no-prisma-postgres \ + --database-url "postgresql://USER:PASSWORD@HOST:PORT/DB" \ + --no-deploy +``` + +Do not deploy placeholder database URLs. If `DATABASE_URL` came from a placeholder default, omit it from deploy env and ask the user for a real production database. + +## Generated Deploy Script + +When the deploy flow is selected, `create-prisma` can add: + +```json +{ + "scripts": { + "compute:deploy": "bunx @prisma/cli@latest app deploy --prod --yes ..." + } +} +``` + +Use the actual generated script from `package.json`; do not reconstruct it from memory. The script redeploys app code using generated flags and/or `prisma.compute.ts`. It does not create a new project, create a new database, run migrations, or seed data. If a scaffolded project does not have `compute:deploy`, use `@prisma/cli app deploy` directly. + +Inspect the generated `package.json`, `prisma.compute.ts`, and README before editing deploy behavior. + +## Generated Files to Preserve + +Preserve generated framework runtime files and `prisma.compute.ts` unless you are intentionally changing the deploy target. For framework-specific deploy/runtime details, read [`frameworks.md`](frameworks.md). + +All Prisma 7 scaffolds: + +- use `prisma.config.ts` +- load `dotenv/config` where the runtime supports it +- generate Prisma Client into a template-local path such as `src/generated/prisma` +- use `@prisma/adapter-pg` with a `DATABASE_URL` connection string for PostgreSQL + +## Addon Notes + +`create-prisma` supports `--skills`, `--mcp`, and `--extension`. Those are separate from Compute deployment. Do not imply that enabling skills or MCP deploys the app. + +## Failure Handling + +If `--deploy` is explicit and setup cannot authenticate, cannot run the Platform CLI, or cannot complete the integrated deploy, report that deploy failed and keep the scaffolded project. Do not delete the user's files. diff --git a/apps/backend/.agents/skills/prisma-compute/references/frameworks.md b/apps/backend/.agents/skills/prisma-compute/references/frameworks.md new file mode 100644 index 0000000..915cf17 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/references/frameworks.md @@ -0,0 +1,382 @@ +# Prisma Compute Framework Readiness + +Use this reference when deciding whether and how an app can deploy to Prisma Compute. + +## CLI-First Model + +Treat `@prisma/cli app deploy` as the deployment surface. Treat `create-prisma` as a new-project scaffold that can generate useful defaults and, for some templates, a `compute:deploy` script. + +Compute deploy supports these framework keys: + +```text +nextjs +nuxt +astro +hono +nestjs +tanstack-start +custom +bun +``` + +Auto-detection: + +- Next.js: `next.config.*` or `next` dependency +- Nuxt: `nuxt.config.*` or `nuxt` dependency +- Astro: `astro.config.*` or `astro` dependency +- Hono: `hono` dependency +- NestJS: `nest-cli.json` or `@nestjs/core` dependency +- TanStack Start: `@tanstack/react-start` or `@tanstack/solid-start` +- Custom artifact: explicit `framework: "custom"` plus `build.outputDirectory` and `build.entrypoint` in `prisma.compute.ts` +- Bun: explicit `--entry ` or `--framework bun` + +If detection is ambiguous, set `framework` in `prisma.compute.ts` or pass a supported `--framework` value. If the app is a source-level plain server, use `framework: "bun"` plus `entry`, or pass `--framework bun --entry `, after verifying the server entrypoint. If the app already produces a runnable Node artifact, use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint`. + +## CLI Matrix + +| App shape | Deploy command shape | Auto-detected | Required output/entry | Notes | +|-----------|----------------------|---------------|-----------------------|-------| +| Next.js | `--framework nextjs` | Yes | standalone `server.js` output | Requires `output: "standalone"` | +| Nuxt | `--framework nuxt` | Yes | `.output/server/index.mjs` | Framework strategy supplies build defaults; a config `build` block is optional | +| Astro | `--framework astro` | Yes | standalone Node server artifact | Framework strategy supplies build defaults; a config `build` block is optional | +| Hono | `--framework hono` | Yes | Bun entry from `main`, `module`, `--entry`, or `src/index.ts` | Usually fixed port `8080` in generated config/scripts | +| NestJS | `--framework nestjs` | Yes | NestJS server artifact | Omit host or bind to `0.0.0.0`; a config `build` block is optional | +| TanStack Start | `--framework tanstack-start` | Yes | `.output/server/index.mjs` | Requires Nitro node output | +| Custom artifact | config-backed `framework: "custom"` | No | configured `build.outputDirectory` and `build.entrypoint` | Use for prebuilt/custom-built Node artifacts | +| Bun / plain server | `--framework bun --entry ` | With explicit entry | server entrypoint | Use for Elysia and custom HTTP servers | +| Elysia | `--framework bun --entry src/index.ts` | No dedicated deploy key | Bun entrypoint | Preserve port/host handling | +| SvelteKit | No deploy framework key | No | Node adapter/prebuilt artifact | Do not deploy `vite preview` | +| Turborepo | Deploy concrete app targets | No | app-specific entry/output | Prefer `prisma.compute.ts` with `apps` | + +`app build --build-type` uses the framework build type. Build types include `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun`. + +`app run --build-type` is local-dev oriented and supports `auto`, `bun`, and `nextjs`. It streams the local dev server and is not proof that the deployed app is reachable through public ingress. + +`prisma.compute.ts` can set framework, entrypoint, HTTP port, env inputs, app root, region, and build settings. A config `build` block is accepted for every supported framework; all build types are config-backed (`nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, `bun`; `hono` builds through the `bun` strategy). For Nuxt, Astro, and NestJS the framework strategy supplies the default build command and output, so a `build` block is optional and normally unnecessary, but it overrides those defaults when present. Only `custom` requires one. + +Config snippets below assume: + +```typescript +import { defineComputeConfig } from "@prisma/compute-sdk/config"; +``` + +## Universal Runtime Requirements + +Compute needs a server process: + +- It must listen on the deployed HTTP port. `@prisma/cli app deploy` defaults to the framework's default HTTP port (3000 for most frameworks, 4321 for Astro) unless `--http-port` is passed. +- It must bind on all interfaces. Do not hard-code `localhost` or `127.0.0.1` for a deployed server; use `0.0.0.0`, `server.host: true`, or the framework equivalent. +- It must have a deployable entrypoint or recognized framework output. +- It must not rely on a preview-only command such as `vite preview`. +- It must receive env vars through `--env`, project env, branch env, or external automation. + +Check host and port together. A listener on the right port but bound to loopback can appear ready while public ingress cannot reach it. + +## Next.js + +Deploy shape: + +```bash +bunx @prisma/cli@latest app deploy --framework nextjs --env .env +``` + +`next.config.ts` must include standalone output: + +```typescript +import type { NextConfig } from "next" + +const nextConfig: NextConfig = { + output: "standalone", +} + +export default nextConfig +``` + +Do not pass `--entry` with `nextjs`; the CLI derives the runtime entrypoint from framework build output. + +Do not set `HOSTNAME=localhost` or `HOSTNAME=127.0.0.1` in deploy env. If the standalone server host is overridden, use `0.0.0.0`. + +## Hono + +Deploy shape: + +```bash +bunx @prisma/cli@latest app deploy \ + --framework hono \ + --http-port 8080 \ + --env .env +``` + +Config shape: + +```typescript +export default defineComputeConfig({ + app: { + framework: "hono", + entry: "src/index.ts", + httpPort: 8080, + env: ".env", + }, +}); +``` + +Project expectations: + +- `package.json` has `main` or `module` pointing at the entrypoint, or deploy passes `--entry src/index.ts` +- server uses `@hono/node-server` +- code reads `process.env.PORT` and defaults to the same port used by `--http-port` +- code does not set `hostname` to `localhost` or `127.0.0.1`; if hostname is set explicitly, use `0.0.0.0` + +Example runtime shape: + +```typescript +const rawPort = (process.env.PORT ?? "").trim() +const parsedPort = rawPort.length > 0 ? Number(rawPort) : Number.NaN +const port = Number.isInteger(parsedPort) ? parsedPort : 8080 +serve({ fetch: app.fetch, port }) +``` + +## NestJS + +Deploy shape: + +```bash +bunx @prisma/cli@latest app deploy --framework nestjs --env .env +``` + +Config shape: + +```typescript +export default defineComputeConfig({ + app: { + framework: "nestjs", + env: ".env", + }, +}); +``` + +Project expectations: + +- detection uses `nest-cli.json` or the `@nestjs/core` dependency; pass `--framework nestjs` when neither signal is present +- `src/main.ts` or the compiled runtime must start an HTTP server +- read `process.env.PORT` and default to the same port used by `--http-port` +- omit the host argument in `app.listen(port)` or pass `"0.0.0.0"`; do not pass `"localhost"` or `"127.0.0.1"` +- use `app build --build-type nestjs` for a Compute artifact check; `app run --build-type nestjs` is not supported, so use the Nest dev server locally + +Example runtime shape: + +```typescript +const port = Number(process.env.PORT ?? "3000") +await app.listen(port) +``` + +## TanStack Start + +Deploy shape: + +```bash +bunx @prisma/cli@latest app deploy --framework tanstack-start --env .env +``` + +Expected `vite.config.ts` shape: + +```typescript +import { defineConfig } from "vite" +import viteReact from "@vitejs/plugin-react" +import { tanstackStart } from "@tanstack/react-start/plugin/vite" +import { nitro } from "nitro/vite" + +export default defineConfig({ + plugins: [tanstackStart(), nitro(), viteReact()], +}) +``` + +Preserve these details: + +- keep `nitro` in `dependencies` +- keep `import { nitro } from "nitro/vite"` +- keep `nitro()` in the Vite plugin list +- keep the React Vite plugin after `tanstackStart()` +- keep Nitro on its default node server preset; do not switch to edge, static, Cloudflare, or another non-Node preset for Compute + +The build command is `vite build`. The build must produce `.output/server/index.mjs`, and the production start shape is: + +```json +{ + "scripts": { + "build": "vite build", + "start": "node .output/server/index.mjs" + } +} +``` + +Do not deploy TanStack Start as a Bun entrypoint such as `src/router.tsx`. If `.output/server/index.mjs` is missing, fix the TanStack/Nitro build path. + +Make sure Nitro does not bind only to localhost in deployment. If host env/config is customized, use the framework's all-interface host setting rather than `localhost`. + +## Nuxt + +Deploy shape: + +```bash +bunx @prisma/cli@latest app deploy --framework nuxt --env .env +``` + +Config shape: + +```typescript +export default defineComputeConfig({ + app: { + framework: "nuxt", + env: ".env", + }, +}); +``` + +Nuxt uses Nitro output at `.output/server/index.mjs`. Keep the Nitro preset compatible with a Node server runtime. + +## Astro + +Deploy shape: + +```bash +bunx @prisma/cli@latest app deploy --framework astro --env .env +``` + +Config shape: + +```typescript +export default defineComputeConfig({ + app: { + framework: "astro", + httpPort: 4321, + env: ".env", + }, +}); +``` + +Astro Compute-style server output usually needs: + +```javascript +import { defineConfig } from "astro/config" +import node from "@astrojs/node" + +export default defineConfig({ + output: "server", + adapter: node({ mode: "standalone" }), + server: { host: true }, +}) +``` + +## Bun, Elysia, and Plain Source Servers + +Use the Bun deploy key for app shapes without a dedicated `--framework` value: + +```bash +bunx @prisma/cli@latest app deploy \ + --framework bun \ + --entry src/index.ts \ + --http-port 8080 \ + --env .env +``` + +`app deploy` also treats `--entry ` without `--framework` as a Bun app deploy. + +Requirements: + +- pass `--entry` unless `package.json` `main` or `module` points at the runtime entrypoint +- ensure the entrypoint starts an HTTP server, not only exports handlers +- read `process.env.PORT` or align `--http-port` with the fixed listener port +- bind on all interfaces + +Elysia example: + +```typescript +const port = Number(process.env.PORT ?? "8080") +app.listen({ port, hostname: "0.0.0.0" }) +``` + +## Custom Build Artifacts + +Use `framework: "custom"` when the app is already built, or when a custom command produces a runnable Node artifact that Compute should stage as-is: + +```typescript +export default defineComputeConfig({ + app: { + framework: "custom", + build: { + command: "npm run build", + outputDirectory: "build", + entrypoint: "handler.js", + }, + httpPort: 3000, + env: ".env", + }, +}); +``` + +Requirements: + +- set both `build.outputDirectory` and `build.entrypoint` +- make `build.entrypoint` relative to `build.outputDirectory` +- ensure the artifact starts an HTTP server and binds on all interfaces +- use `command: null` only when the output directory already contains the deployable artifact + +## SvelteKit and Other Frameworks + +`@prisma/cli app deploy --framework` has no `svelte` framework key. Do not claim SvelteKit is directly deployable with that name. + +For frameworks without a dedicated deploy key, use one of these paths: + +- produce a Node server artifact and deploy with config-backed `framework: "custom"`, or through a supported prebuilt/SDK flow +- if the app has a plain Node/Bun server entrypoint, deploy that entrypoint through `--framework bun --entry ` + +SvelteKit should use a Node adapter or another production server artifact. Do not use `vite preview` as the deployed runtime. + +## Turborepo + +Deploy concrete app packages, not the monorepo root by default. Prefer `prisma.compute.ts` at the repo root with one `apps` entry per deploy target. + +Checklist: + +- choose the app directory, such as `apps/api` +- run the workspace build from the correct root/package +- pass the app package's runtime entrypoint or framework +- pass the correct env file, which may live outside the app package +- keep branch env/database scope aligned with the deployed app + +Example config: + +```typescript +export default defineComputeConfig({ + apps: { + web: { root: "apps/web", framework: "nextjs" }, + api: { + root: "apps/api", + framework: "bun", + entry: "src/index.ts", + httpPort: 3000, + env: "packages/db/.env", + }, + }, +}); +``` + +Deploy one target: + +```bash +bunx @prisma/cli@latest app deploy api --branch feature/foo --json +``` + +Flag-only shape after confirming output paths: + +```bash +bun run build +bunx @prisma/cli@latest app deploy \ + --framework bun \ + --entry apps/api/dist/src/index.js \ + --http-port 3000 \ + --env packages/db/.env +``` + +Verify the actual output path before using this command. diff --git a/apps/backend/.agents/skills/prisma-compute/references/sdk-api.md b/apps/backend/.agents/skills/prisma-compute/references/sdk-api.md new file mode 100644 index 0000000..290f743 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/references/sdk-api.md @@ -0,0 +1,167 @@ +# SDK and API Automation + +Use this reference when building automation rather than using `create-prisma` or `@prisma/cli app deploy`. + +## Prefer the CLI for App Workflows + +For normal app deployment: + +1. Use generated `compute:deploy` when present. +2. Otherwise use `@prisma/cli app build/run/deploy`. +3. Use SDK/API only for custom automation, platform integrations, or tool builders. + +## Compute SDK + +Install: + +```bash +npm install @prisma/compute-sdk @prisma/management-api-sdk +``` + +Config helper: + +```typescript +import { defineComputeConfig } from "@prisma/compute-sdk/config"; +``` + +Use this import in `prisma.compute.ts` for type checking. The helper is an identity function; the CLI loader aliases the import when it evaluates config files, so a user project does not need the SDK solely to load a Compute config. + +Create an authenticated Management API client: + +```typescript +import { createManagementApiClient } from "@prisma/management-api-sdk" + +const apiClient = createManagementApiClient({ + token: process.env.PRISMA_API_TOKEN, +}) +``` + +Token naming differs by surface. `@prisma/cli app ...` uses `PRISMA_SERVICE_TOKEN` for non-interactive service-token auth. The SDK examples here use `PRISMA_API_TOKEN` as an application convention for passing a token into `createManagementApiClient`; the SDK itself only receives the `token` string. + +Deploy a prebuilt artifact: + +```typescript +import { ComputeClient, PreBuilt } from "@prisma/compute-sdk" + +const compute = new ComputeClient(apiClient) +const databaseUrl = process.env.DATABASE_URL +if (!databaseUrl) throw new Error("DATABASE_URL is required") + +const result = await compute.deploy({ + strategy: new PreBuilt({ + appPath: "./dist", + entrypoint: "index.js", + }), + projectId: "proj_abc", + appName: "my-app", + // region: "us-east-1", // optional: explicit placement for a new app + envVars: { DATABASE_URL: databaseUrl }, + portMapping: { http: 3000 }, +}) + +if (result.isOk()) { + console.log(result.value.deploymentEndpointDomain) +} else { + console.error(result.error.message) +} +``` + +SDK methods return `Result`. Check `isOk()` or `isErr()` instead of assuming errors throw. Deploy results expose app/deployment vocabulary including `appId`, `appName`, `projectId`, `region`, `deploymentId`, `deploymentEndpointDomain`, `appEndpointDomain`, `promoted`, `previousDeploymentId`, `previousDeploymentAction`, and `resolvedConfig`. + +## SDK Build Strategies + +Project Compute SDK strategies: + +- `AutoBuild`: tries supported framework strategies such as Next.js, Nuxt, Astro, NestJS, TanStack Start, then Bun +- `NextjsBuild`: requires standalone output and returns `server.js` +- `NuxtBuild`: expects `.output/server/index.mjs` +- `AstroBuild`: expects `dist/server/entry.mjs` +- `NestjsBuild`: builds a NestJS HTTP server artifact +- `TanstackStartBuild`: runs `vite build` and expects a Nitro node server at `.output/server/index.mjs`; keep `tanstackStart()` and `nitro()` in Vite config +- `CustomBuild`: runs optional configured build settings and stages a configured artifact entrypoint +- `BunBuild`: runs `bun build` and needs an explicit entrypoint or `package.json` `main` +- `PreBuilt`: uses an existing artifact directory and relative entrypoint + +## Regions + +Known SDK region ids: + +```text +us-east-1 +us-west-1 +eu-west-3 +eu-central-1 +ap-northeast-1 +ap-southeast-1 +``` + +Use `--region` in `@prisma/cli app deploy` or `region` in SDK deploy input only when creating a new Compute app. Existing apps keep their current region. + +`region` is optional on `deploy` and `createApp`. Omit it to use the Project/platform default when creating an app; do not hard-code a region unless placement is an application requirement. + +## Repository-snapshot detection + +Tooling that already has an in-memory repository tree can detect a deployable app without checking files out: + +```typescript +import { detectComputeApp } from '@prisma/compute-sdk/config' + +const detected = detectComputeApp({ + root: 'apps/api', + manifest: { + main: 'src/index.ts', + scripts: { start: 'bun src/index.ts' }, + dependencies: { hono: '^4' }, + }, + filePaths: ['apps/api/package.json', 'apps/api/src/index.ts'], +}) +``` + +The result contains `framework`, `frameworkName`, `buildType`, `httpPort`, `entrypoint`, and detection `evidence`, or `null` when nothing is deployable. Paths are repository-relative and unsafe absolute/parent-traversal entrypoints are rejected. + +The helper detects one app root. A monorepo consumer must enumerate workspaces and call it once per candidate. Detection reads `dependencies` and `devDependencies` (not peer dependencies), recognizes config files and framework packages, and can infer Bun-backed servers from valid `start`/`serve` script entrypoints. + +## Management API Concepts + +Compute resources map roughly to: + +- Project: parent container +- Branch: production or preview scope for env resolution and database/env attachment +- App: stable app endpoint and branch attachment +- Deployment: build artifact plus runtime status and preview URL + +Low-level public routes use App/Deployment names: + +- list/create apps under a project with `/v1/apps` +- get/update/delete an app +- create/list deployments for an app +- get/start/stop/delete deployments with `/v1/deployments/:deploymentId` +- promote or roll back an app using `deploymentId` +- stream logs with `/v1/deployments/:deploymentId/logs` +- manage custom domains + +Internal compatibility aliases may still appear in code. Prefer App/Deployment names in new docs, skills, and automation. + +Environment variables are not embedded directly in the low-level deployment create payload. The attached branch's role selects their scope: a preview branch resolves branch-scoped vars, while a production branch (or no branch) resolves project-scoped production vars. Use project/environment-variable APIs or CLI env commands to write env vars first, and keep the branch name consistent across app creation, database creation, and env writes. + +When using the CLI alongside SDK automation: + +```bash +bunx @prisma/cli@latest project env add --file .env.preview --branch feature/foo +bunx @prisma/cli@latest database create preview-db --branch feature/foo --json +bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive +``` + +Production promotion is not just "the same branch with another label"; `app promote ` rebuilds with production env vars. + +## Secrets and Redaction + +Management API deployment inspection exposes env var names with redacted values. Treat any value like `[redacted]` as a marker, not as the deployed value. + +Do not log: + +- service tokens +- OAuth tokens +- full database URLs +- env var values +- pre-signed upload URLs diff --git a/apps/backend/.agents/skills/prisma-compute/references/troubleshooting.md b/apps/backend/.agents/skills/prisma-compute/references/troubleshooting.md new file mode 100644 index 0000000..0489989 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-compute/references/troubleshooting.md @@ -0,0 +1,477 @@ +# Troubleshooting Prisma Compute + +Use this reference when setup, build, deploy, env, or runtime behavior fails. + +## First Checks + +Run: + +```bash +bunx @prisma/cli@latest --help +bunx @prisma/cli@latest app deploy --help +bunx @prisma/cli@latest auth whoami +bunx @prisma/cli@latest auth workspace list --json +``` + +Then inspect: + +```bash +pwd +cat package.json +find .. -maxdepth 3 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print +test -f .env && sed -n 's/=.*/=/p' .env +``` + +Do not print unredacted secrets. + +## `prisma.compute.ts` Not Picked Up + +This only matters when the project is supposed to use a config-backed deploy. A simple app without `prisma.compute.ts` can still deploy with explicit `app deploy` flags. + +Symptoms: + +- deploy ignores the expected framework, entrypoint, port, env file, or app root +- a monorepo target such as `api` is not recognized +- local state appears in the wrong `.prisma/` directory + +Check: + +```bash +pwd +find .. -maxdepth 4 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print +bunx @prisma/cli@latest app deploy --help +``` + +Fix: + +- keep exactly one compute config file in the directory where it lives +- put repo-wide or monorepo config at the repository/workspace root +- run commands from inside the repo or workspace boundary so discovery can walk up to the config +- use `[app]` targets from the `apps` keys, such as `bunx @prisma/cli@latest app deploy api` +- remember that config-relative paths such as `root` and `env.file` resolve from the config file directory + +## Compute Config Invalid + +Symptoms: + +- `COMPUTE_CONFIG_INVALID` +- `COMPUTE_CONFIG_TARGET_REQUIRED` +- `COMPUTE_CONFIG_TARGET_UNKNOWN` +- "Multiple compute config files found" + +Fix: + +- export `defineComputeConfig({ app: ... })` or `defineComputeConfig({ apps: ... })` +- define exactly one of `app` or `apps` +- remove unknown top-level keys +- pass a target for multi-app build/run commands, such as `app build web` +- pass an existing `apps` key for multi-app deploys, such as `app deploy api` +- for `nuxt`, `astro`, and `nestjs`, prefer strategy defaults unless a custom `build` override is intentional; current configs allow the override +- for `framework: "custom"`, set both `build.outputDirectory` and `build.entrypoint` +- when `build.outputDirectory` is set for a configurable framework, also set `build.entrypoint` if the framework needs a configured runtime entrypoint + +Minimal recovery config: + +```typescript +import { defineComputeConfig } from "@prisma/compute-sdk/config"; + +export default defineComputeConfig({ + app: { + framework: "hono", + entry: "src/index.ts", + httpPort: 8080, + }, +}); +``` + +## `create-prisma --yes` Did Not Deploy + +`--yes` skips prompts and does not opt into deploy. Pass `--deploy` explicitly: + +```bash +bunx create-prisma@latest --name my-api --template hono --provider postgresql --deploy +``` + +If the integrated deploy cannot complete, scaffold succeeds but deploy should be reported as failed. + +## Accidental Prisma Postgres Provisioning + +With PostgreSQL, no `--database-url`, and no `--no-prisma-postgres`, setup can provision Prisma Postgres. For local smoke tests, pass: + +```bash +--no-prisma-postgres --database-url "postgresql://USER:PASSWORD@HOST:PORT/DB" +``` + +Use a disposable real database URL if Prisma commands need to run. + +## Auth Fails + +Symptoms: + +- `project list` fails +- `auth whoami` fails +- browser login was not completed +- commands use the wrong workspace after a second login +- another workspace is stored locally but commands behave signed out +- `PRISMA_SERVICE_TOKEN` is missing, empty, expired, or lacks workspace/project permissions + +Fix: + +```bash +bunx @prisma/cli@latest auth login +bunx @prisma/cli@latest auth whoami +bunx @prisma/cli@latest auth workspace list --json +``` + +If multiple local OAuth workspaces exist, switch explicitly. Prefer ids from JSON: + +```bash +bunx @prisma/cli@latest auth workspace use +bunx @prisma/cli@latest auth whoami --json +bunx @prisma/cli@latest project list --json +``` + +For a human terminal, `auth workspace use` with no argument opens an interactive picker or selects the only local OAuth workspace without prompting. In non-interactive or `--json` mode, use `auth workspace use ` instead. + +If the active workspace was logged out or its token refresh failed, the CLI intentionally stays signed out for OAuth commands rather than falling through to another cached workspace. Recover by running `auth workspace list --json` and then `auth workspace use `. + +To remove only one local OAuth workspace session: + +```bash +bunx @prisma/cli@latest auth workspace logout +# or: +bunx @prisma/cli@latest auth logout --workspace +``` + +Use plain `auth logout` only when you want to clear all local OAuth workspace sessions. + +For CI, `@prisma/cli` can authenticate with `PRISMA_SERVICE_TOKEN`: + +```bash +test -n "${PRISMA_SERVICE_TOKEN:-}" && echo "PRISMA_SERVICE_TOKEN is set" +bunx @prisma/cli@latest auth whoami +bunx @prisma/cli@latest app deploy --json --no-interactive --prod --yes --env .env +``` + +If `PRISMA_SERVICE_TOKEN` is set and non-empty, it is the active auth source and local OAuth workspace switching is unavailable for command execution. Unset `PRISMA_SERVICE_TOKEN` before using `auth workspace use` to change local OAuth workspace context. + +If `PRISMA_SERVICE_TOKEN` is set but empty, the CLI errors before trying browser-login credentials. Unset it or provide a valid workspace service token. Never echo, log, or paste the token value; only check whether it is present. + +Local storage hints for debugging: + +- Override auth storage with `PRISMA_COMPUTE_AUTH_FILE` when isolating tests. +- Default macOS OAuth credential file: `~/Library/Application Support/prisma/auth.json`. +- Active workspace metadata sidecar: `~/Library/Application Support/prisma/auth.context.json`. +- Project binding: `.prisma/local.json`. +- Local app/project state: `.prisma/cli/state.json`, usually next to the discovered `prisma.compute.ts`. + +Do not print credential files or token values into logs. + +## Project Setup Fails + +Symptoms: + +- `PROJECT_SETUP_REQUIRED` +- non-interactive deploy cannot choose a Project +- deploy was expected to create a Project but did not + +Fix: + +```bash +bunx @prisma/cli@latest app deploy --project --json --no-interactive +bunx @prisma/cli@latest app deploy --create-project --yes +``` + +Do not rely on `--yes` alone to choose Project scope. `--project`, `--create-project`, and `PRISMA_PROJECT_ID` are mutually exclusive. + +## Missing or Placeholder `DATABASE_URL` + +Symptoms: + +- Prisma Client throws `DATABASE_URL is required` +- migration scripts fail immediately +- deploy runs but app fails on database access + +Fix: + +1. Put a real production-ready `DATABASE_URL` in `.env` or project env. +2. Run `prisma generate`. +3. Run migrations with the project's `db:migrate` or production migration command. +4. Redeploy with `--env .env` or project env configured. + +If Prisma Client generation or runtime env loading is the concrete failure, then inspect Prisma-specific config: + +```bash +test -f prisma.config.ts && sed -n '1,160p' prisma.config.ts +test -f prisma/schema.prisma && sed -n '1,220p' prisma/schema.prisma +``` + +Never deploy `postgresql://USER:PASSWORD@HOST:PORT/DATABASE` placeholder values. + +## Wrong Branch, Env, or Database + +Symptoms: + +- preview deploy reads production env +- branch deploy cannot find `DATABASE_URL` +- app is deployed to the expected branch but points at the wrong database +- logs are inspected for the current app while the failing URL belongs to a different deployment id + +Check: + +```bash +bunx @prisma/cli@latest project show --json +bunx @prisma/cli@latest project env list --role production --json +bunx @prisma/cli@latest project env list --role preview --json +bunx @prisma/cli@latest project env list --branch feature/foo --json +bunx @prisma/cli@latest app list-deploys --json +bunx @prisma/cli@latest app logs --deployment --json +``` + +Fix: + +- pass the same `--branch ` to `app deploy`, `database create`, and branch-specific `project env` commands +- use `--role production` for production env and `--role preview` for preview-template env +- capture the deployment id and URL from deploy JSON, then inspect logs with `app logs --deployment ` +- `app show`, `app list-deploys`, and `app logs` do not filter by branch; capture and use the deployment id +- treat `app promote ` as a production action because it rebuilds with production env vars +- do not expect `prisma.compute.ts` to select Project, Branch, production, or database scope; it only supplies app deploy defaults + +## Database Wiring or Schema Did Not Apply + +Symptoms: + +- deploy runs but the app cannot find `DATABASE_URL` +- database env vars exist but the database is empty +- a deploy-all run points multiple apps at the same branch database + +Fix: + +- read [`app-deploy-cli.md`](app-deploy-cli.md) `Database and Env` for the database/env guardrails +- create and assign database env vars explicitly for the intended branch/app scope +- run migrations, seed, or schema push yourself after database setup; Compute never applies schema changes for you +- for multi-app deploy-all with app-specific database isolation, create and assign those database env vars explicitly before deploy + +## Workspace plan limit reached + +When the installed CLI returns `PLAN_LIMIT_REACHED`, treat it as a workspace plan restriction rather than a Compute or database outage. + +For agent/CI handling, run the relevant database command with `--json` and branch on `error.code === "PLAN_LIMIT_REACHED"`. Read `error.meta.upgradeUrl`, `planName`, `workspaceId`, and `usageBlocked`; optional values may be `null`. This is a workspace plan restriction rather than a Compute/database outage. Use the canonical upgrade URL when returned or direct the user to Prisma Console. Do not retry as an outage or infer a plan limit from status codes or message text. + +## Next.js Standalone Missing + +Error shape: + +```text +Next.js build did not produce standalone output +``` + +Fix `next.config.ts`: + +```typescript +const nextConfig = { + output: "standalone", +} + +export default nextConfig +``` + +Then reinstall/build if needed and deploy again. + +## Next.js dependency missing after a successful build + +Symptoms in pnpm/Bun isolated workspaces can include a deployment that builds successfully but exits before useful runtime logs, often with `Cannot find module` for `styled-jsx` or another traced dependency. + +The current Compute SDK preserves in-artifact package-store symlinks and materializes only safe out-of-tree targets when staging Next standalone output. Do not manually flatten or rewrite `.next/standalone/node_modules` symlinks; that can break the isolated-store layout. + +Fix: + +1. Upgrade `@prisma/compute-sdk` and `@prisma/cli` to current versions. +2. Remove only the generated build artifact/cache appropriate to the project, then rebuild. +3. Confirm `output: "standalone"`, redeploy, and inspect the new deployment logs. +4. If it persists, report the package manager, workspace layout, first missing module, and SDK/CLI versions through `@prisma/cli feedback` without secrets. + +## Nitro Entry Missing + +Nuxt or TanStack Start error shape: + +```text +.output/server/index.mjs +``` + +General fix: + +- ensure the correct framework plugins are installed +- run the framework build locally +- avoid custom Nitro presets that produce a non-Node target +- use the default Nitro node server preset + +For TanStack Start specifically: + +- keep `nitro` in `dependencies` +- keep `import { nitro } from "nitro/vite"` in `vite.config.ts` +- keep `plugins: [tanstackStart(), nitro(), viteReact()]` or the framework-equivalent plugin order +- run `bun run build` and verify `.output/server/index.mjs` exists +- do not replace the production server with `vite preview` + +Compute detection selects TanStack Start when it sees `@tanstack/react-start` or `@tanstack/solid-start`. If the Nitro entrypoint is missing after that, fix the TanStack/Nitro build output; do not assume Compute will silently use a Bun deployment. + +## Bun Entrypoint Missing + +Error shape: + +```text +Entrypoint is required +Entrypoint file does not exist +``` + +Fix either: + +```json +{ + "main": "src/index.ts" +} +``` + +or deploy with: + +```bash +bunx @prisma/cli@latest app deploy --framework bun --entry src/index.ts +``` + +## Port Mismatch + +Symptoms: + +- deploy succeeds but the app is unreachable +- health checks fail +- logs show the server listening on a different port + +Fix: + +- read `process.env.PORT` +- pass `--http-port ` when the app has a fixed port +- use the generated `compute:deploy` script when it exists +- remember the `@prisma/cli app deploy` default is HTTP `3000`; generated Hono/Elysia projects usually configure `8080` through `prisma.compute.ts` or flag-backed `--http-port 8080` scripts +- use the template defaults: Hono/Elysia `8080`, Next/TanStack/Nuxt `3000`, Astro `4321` + +## Public URL Smoke Test Fails + +Symptoms: + +- deploy command completed +- `app show` or deploy output has a URL +- the public URL times out, returns 5xx, or returns an unexpected page + +Check: + +```bash +curl -i https:// +curl -i https:///health +bunx @prisma/cli@latest app logs --json +``` + +Fix by following the first concrete failure: + +- connection timeout or 5xx: check logs, host binding, and port mapping +- `504 Gateway Time-out` with an `openresty` body about 60s in: the ingress request timeout, not the app; see Request Timeout below +- unexpected status or body: verify the route path and app framework output +- local URL tested by mistake: rerun against the public deployment URL, not `localhost` or `127.0.0.1` + +## Localhost Binding + +Symptoms: + +- deploy says the app started or the port was observed, but the public URL is unreachable +- logs show a server listening on `localhost` or `127.0.0.1` +- `app run` works locally, but the deployed app cannot receive external traffic + +Why this happens: + +Compute's boot watcher polls `/proc/net/tcp` and `/proc/net/tcp6` for configured ports entering `LISTEN`. That readiness signal tracks the port, not whether the app bound `127.0.0.1` or all interfaces. A loopback-only listener can therefore look ready while public ingress still cannot reach it. + +Fix: + +- remove hard-coded `localhost` or `127.0.0.1` server host settings +- bind on `0.0.0.0` or the framework equivalent, such as Astro `server.host: true` +- for Next.js standalone, do not deploy with `HOSTNAME=localhost`; use `HOSTNAME=0.0.0.0` if the host is overridden +- keep port and host fixes together: `0.0.0.0:` + +## Request Timeout + +Symptoms: + +- the public URL returns `504 Gateway Time-out` with a short `openresty` body, about 60 seconds after the request was sent +- the app's own logs show the handler running, with no timeout error +- the same route works whenever it starts responding in under 60 seconds +- application timeouts set above 60 seconds never produce a response the caller sees + +Why this happens: + +Compute's ingress gives an app 60 seconds to start responding, then answers the client itself and cancels the request. The deadline covers the wait for the first bytes, not how long the response takes to finish, so a response that has already started streaming is not cut off. The app is not told directly; the cancellation surfaces as the request's abort signal. Once the request is cancelled, Compute stops counting it as in flight, so the instance can scale to zero while the handler is still working. + +Fix: + +- respond within 60 seconds; for webhooks, return `200` or `202` before doing the work +- continue the work after the response with `waitUntil` or `KeepAwakeGuard` from `@prisma/compute`, which hold the instance awake on a best-effort basis +- for work that must not be lost, persist a job and process it from a separate trigger in steps that each fit inside one request +- keep in-request timeouts (`AbortSignal.timeout`, fetch timeouts) under 60 seconds so the app's own error handling runs first +- check `req.signal` when a handler should stop work it no longer needs to finish +- docs: https://www.prisma.io/docs/compute/request-timeout + +## Env Changes Did Not Apply + +Generated `compute:deploy` scripts redeploy using the generated flags and/or `prisma.compute.ts`; they do not run migrations or seed data. + +After env changes: + +```bash +bunx @prisma/cli@latest project env list +bunx @prisma/cli@latest project env list --branch feature/foo +bunx @prisma/cli@latest app deploy --prod --yes --env .env +bunx @prisma/cli@latest app deploy --branch feature/foo --env .env.preview +``` + +If using branch-specific env, confirm the branch name and role. + +## Need Logs + +Runtime logs for the current app: + +```bash +bunx @prisma/cli@latest app logs +``` + +Specific deployment: + +```bash +bunx @prisma/cli@latest app logs --deployment +``` + +Machine-readable: + +```bash +bunx @prisma/cli@latest app logs --json +``` + +Build logs for GitHub/Console builds: + +```bash +bunx @prisma/cli@latest build logs +bunx @prisma/cli@latest build logs --follow +bunx @prisma/cli@latest build logs --json +``` + +Use `build logs` for build output keyed by a Build id from a GitHub check run, Console build page, or Management API build record. Use `app logs` for runtime logs keyed by the current app deployment or a deployment id. + +Summarize relevant errors. Do not paste secrets. + +## Report Unresolved CLI Issues + +When a CLI failure survives the checks above, or a command crashes with `UNEXPECTED_ERROR`, report it to the Prisma team: + +```bash +bunx @prisma/cli@latest feedback "app deploy crashed: " +``` + +Prefer the pre-filled command from a `--json` crash envelope's `nextActions` verbatim. Anonymous; never put secrets, connection URLs, or tokens in the message. diff --git a/apps/backend/.agents/skills/prisma-database-setup/SKILL.md b/apps/backend/.agents/skills/prisma-database-setup/SKILL.md new file mode 100644 index 0000000..51643e7 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/SKILL.md @@ -0,0 +1,192 @@ +--- +name: prisma-database-setup +description: Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup". +license: MIT +metadata: + author: prisma + version: "7.6.0" +--- + +# Prisma Database Setup + +Comprehensive guides for configuring Prisma ORM with various database providers. + +## When to Apply + +Reference this skill when: +- Initializing a new Prisma project +- Switching database providers +- Configuring connection strings and environment variables +- Troubleshooting database connection issues +- Setting up database-specific features +- Generating and instantiating Prisma Client + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Provider Guides | CRITICAL | provider names | +| 2 | Prisma Postgres | HIGH | `prisma-postgres` | +| 3 | Client Setup | CRITICAL | `prisma-client-setup` | + +## System Prerequisites + +- **Node.js 20.19.0+** +- **TypeScript 5.4.0+** + +## Bun Runtime + +If you're using Bun, run Prisma CLI commands with `bunx --bun prisma ...` so Prisma uses the Bun runtime instead of falling back to Node.js. + +## Supported Databases + +| Database | Provider String | Notes | +|----------|-----------------|-------| +| PostgreSQL | `postgresql` | Default, full feature support | +| MySQL | `mysql` | Widespread support, some JSON diffs | +| SQLite | `sqlite` | Local file-based, no enum/scalar lists | +| MongoDB | `mongodb` | Mongo-specific workflow; do not apply SQL driver-adapter guidance | +| SQL Server | `sqlserver` | Microsoft ecosystem | +| CockroachDB | `cockroachdb` | Distributed SQL, Postgres-compatible | +| Prisma Postgres | `postgresql` | Managed serverless database | + +## Configuration Files + +Your configuration shape depends on the provider and Prisma major version: + +1. **All providers** use **`prisma/schema.prisma`**. +2. **Prisma 7 SQL setups** typically use **`prisma.config.ts`** for datasource URLs. +3. **MongoDB projects should stay on Prisma 6.x**, keep `url = env("DATABASE_URL")` in the schema, and continue using the classic MongoDB setup. + +## Driver Adapters + +The standard SQL workflow uses a driver adapter. Choose the adapter and driver for your database and pass the adapter to `PrismaClient`. + +| Database | Adapter | JS Driver | +|----------|---------|-----------| +| PostgreSQL | `@prisma/adapter-pg` | `pg` | +| CockroachDB | `@prisma/adapter-pg` | `pg` | +| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` | +| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` | +| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` | +| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` | +| SQLite (Turso/LibSQL) | `@prisma/adapter-libsql` | `@libsql/client` | +| SQL Server | `@prisma/adapter-mssql` | `node-mssql` | + +MongoDB should not follow the Prisma 7 SQL adapter workflow. Use the latest Prisma 6.x release for MongoDB projects and do not install a SQL `@prisma/adapter-*` package for it. + +Example (PostgreSQL): + +```ts +import 'dotenv/config' +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) +const prisma = new PrismaClient({ adapter }) +``` + +## Prisma Client Setup (Required) + +Prisma Client must be installed and generated for any database. + +1. Install Prisma CLI and Prisma Client: + ```bash + npm install prisma --save-dev + npm install @prisma/client + ``` + +1. Add a generator block (`prisma-client` requires an explicit output path): + ```prisma + generator client { + provider = "prisma-client" + output = "../generated" + } + ``` + +1. Generate Prisma Client: + ```bash + npx prisma generate + ``` + +1. For SQL providers, instantiate Prisma Client with the database-specific driver adapter: + ```typescript + import { PrismaClient } from '../generated/client' + import { PrismaPg } from '@prisma/adapter-pg' + + const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) + const prisma = new PrismaClient({ adapter }) + ``` + +1. Re-run `prisma generate` after every schema change. + +## Quick Reference + +### PostgreSQL +```prisma +datasource db { + provider = "postgresql" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +### MySQL +```prisma +datasource db { + provider = "mysql" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +### SQLite +```prisma +datasource db { + provider = "sqlite" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +### MongoDB +```prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} +``` + +For MongoDB, stay on the latest Prisma 6.x line and keep the connection URL in `schema.prisma`. Do not move a MongoDB project to the Prisma 7 SQL adapter setup. If a MongoDB project asks about upgrading Prisma versions, route to the `prisma-mongodb-upgrade` skill (stay-on-v6 vs Prisma Next is the real decision; Prisma 7 is not an option). + +## Rule Files + +See individual rule files for detailed setup instructions: + +``` +references/postgresql.md +references/mysql.md +references/sqlite.md +references/mongodb.md +references/sqlserver.md +references/cockroachdb.md +references/prisma-postgres.md +references/prisma-client-setup.md +``` + +## How to Use + +Choose the provider reference file for your database, then apply `references/prisma-client-setup.md` to complete client generation and adapter setup. For MongoDB, use `references/mongodb.md` instead of copying the SQL adapter examples or Prisma 7 config pattern. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/cockroachdb.md b/apps/backend/.agents/skills/prisma-database-setup/references/cockroachdb.md new file mode 100644 index 0000000..38d3859 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/cockroachdb.md @@ -0,0 +1,89 @@ +# CockroachDB Setup + +Configure Prisma with CockroachDB. + +## Prerequisites + +- CockroachDB cluster + +## 1. Schema Configuration + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "cockroachdb" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +## 2. Config Configuration + +In `prisma.config.ts`: + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 3. Environment Variable + +In `.env`: + +```env +DATABASE_URL="postgresql://user:password@host:26257/db?sslmode=verify-full" +``` + +Note: CockroachDB uses the PostgreSQL wire protocol, so the URL often looks like postgresql, but the provider **MUST** be `cockroachdb` in the schema to handle specific CRDB features correctly. + +## Driver Adapter + +Use a driver adapter for the standard SQL workflow. CockroachDB is PostgreSQL-compatible, so use the PostgreSQL adapter. + +1. Install adapter and driver: + ```bash + npm install @prisma/adapter-pg pg + ``` + +2. Instantiate Prisma Client with the adapter: + ```typescript + import 'dotenv/config' + import { PrismaClient } from '../generated/client' + import { PrismaPg } from '@prisma/adapter-pg' + + const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) + const prisma = new PrismaClient({ adapter }) + ``` + +## ID Generation + +CockroachDB uses `BigInt` or `UUID` for IDs efficiently. + +```prisma +model User { + id BigInt @id @default(autoincrement()) // Uses unique_rowid() +} +``` + +Or using string UUIDs: + +```prisma +model User { + id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid +} +``` + +## Common Issues + +### Schema Introspection +Always use `provider = "cockroachdb"` to ensure correct type mapping during `db pull`. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/mongodb.md b/apps/backend/.agents/skills/prisma-database-setup/references/mongodb.md new file mode 100644 index 0000000..29dc2a0 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/mongodb.md @@ -0,0 +1,90 @@ +# MongoDB Setup + +MongoDB projects should stay on the latest Prisma 6.x release. Do not upgrade a MongoDB app to Prisma 7's SQL client path. + +## Prerequisites + +- MongoDB 4.2+ +- Replica Set configured (required for transactions) +- Latest Prisma 6.x release, or your team's pinned Prisma 6 version +- Node.js 20.19.0+ +- TypeScript 5.4.0+ + +## 1. Schema Configuration + +Use the standard Prisma 6 MongoDB setup with `prisma-client-js`. + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} +``` + +### Driver Adapters + +Do **not** apply the Prisma 7 SQL adapter setup here. MongoDB does not use a SQL `@prisma/adapter-*` package. + +### ID Field Requirement + +MongoDB models **must** have a mapped `_id` field using `@id` and `@map("_id")`, usually of type `String` with `auto()` and `db.ObjectId`. + +```prisma +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String @unique + name String? +} +``` + +### Relations + +Relations in MongoDB expect IDs to be `db.ObjectId` type. + +```prisma +model Post { + id String @id @default(auto()) @map("_id") @db.ObjectId + author User @relation(fields: [authorId], references: [id]) + authorId String @db.ObjectId +} +``` + +## 2. Environment Variable + +In `.env`: + +```env +DATABASE_URL="mongodb+srv://user:password@cluster.mongodb.net/mydb?retryWrites=true&w=majority" +``` + +## Migrations vs Introspection + +- **No Migrations**: MongoDB is schema-less. `prisma migrate` commands **do not work**. +- **db push**: Use `prisma db push` to sync indexes and constraints. +- **db pull**: Use `prisma db pull` to generate schema from existing data (sampling). + +## Current Verification Notes + +- `prisma init --datasource-provider mongodb` is still implemented in Prisma's CLI source. +- Prisma's upstream repo still contains MongoDB fixtures and tests. +- Local verification shows Prisma 7 can still recognize MongoDB inputs, but the generated client path does not provide a supported MongoDB upgrade path. +- Local verification shows Prisma 6.x works end to end with `prisma-client-js`, `prisma db push`, and `new PrismaClient()` against a MongoDB replica set. + +## Version Guidance + +- For MongoDB, stay on the latest available Prisma 6.x release. +- Treat Prisma 7 MongoDB migration attempts as unsupported until Prisma ships a real MongoDB upgrade path. + +## Common Issues + +### "Transactions not supported" +Ensure your MongoDB instance is a **Replica Set**. Standalone instances do not support transactions. Atlas clusters are replica sets by default. + +### "Invalid ObjectID" +Ensure fields referencing IDs are decorated with `@db.ObjectId` if the target is an ObjectID. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/mysql.md b/apps/backend/.agents/skills/prisma-database-setup/references/mysql.md new file mode 100644 index 0000000..eb67b18 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/mysql.md @@ -0,0 +1,126 @@ +# MySQL Setup + +Configure Prisma with MySQL (or MariaDB). + +## Prerequisites + +- MySQL or MariaDB database +- Connection string + +## 1. Schema Configuration + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "mysql" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +## 2. Config Configuration + +In `prisma.config.ts`: + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 3. Environment Variable + +In `.env`: + +```env +DATABASE_URL="mysql://user:password@localhost:3306/mydb" +``` + +### Connection String Format + +``` +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +- **USER**: Database user +- **PASSWORD**: Password +- **HOST**: Hostname +- **PORT**: Port (default 3306) +- **DATABASE**: Database name + +## Driver Adapter + +Use a driver adapter for the standard SQL workflow. + +1. Install adapter and driver: + ```bash + npm install @prisma/adapter-mariadb mariadb + ``` + +2. Instantiate Prisma Client with the adapter: + ```typescript + import 'dotenv/config' + import { PrismaClient } from '../generated/client' + import { PrismaMariaDb } from '@prisma/adapter-mariadb' + + const adapter = new PrismaMariaDb({ + host: 'localhost', + port: 3306, + connectionLimit: 5, + user: process.env.MYSQL_USER, + password: process.env.MYSQL_PASSWORD, + database: process.env.MYSQL_DATABASE, + }) + + const prisma = new PrismaClient({ adapter }) + ``` + +### Text protocol option + +If you need the MariaDB driver's text protocol instead of the default binary `execute()` path, enable `useTextProtocol` explicitly: + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaMariaDb } from '@prisma/adapter-mariadb' + +const adapter = new PrismaMariaDb(process.env.DATABASE_URL!, { + useTextProtocol: true, +}) + +const prisma = new PrismaClient({ adapter }) +``` + +Use this only when you specifically need text-protocol compatibility for your MariaDB setup. + +## PlanetScale Setup + +PlanetScale uses MySQL but requires specific settings because it doesn't support foreign key constraints. + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "mysql" + relationMode = "prisma" // Emulate foreign keys in Prisma +} +``` + +## Common Issues + +### "Too many connections" +MySQL has a connection limit. Adjust connection pool size in URL: +```env +DATABASE_URL="mysql://...?connection_limit=5" +``` + +### JSON Support +MySQL 5.7+ supports JSON. MariaDB 10.2+ supports JSON (as an alias for LONGTEXT with check constraints). Prisma handles this, but verify your version. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/postgresql.md b/apps/backend/.agents/skills/prisma-database-setup/references/postgresql.md new file mode 100644 index 0000000..ea575f6 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/postgresql.md @@ -0,0 +1,92 @@ +# PostgreSQL Setup + +Configure Prisma with PostgreSQL. + +## Prerequisites + +- PostgreSQL database (local or cloud) +- Connection string + +## 1. Schema Configuration + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "postgresql" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +## 2. Config Configuration + +In `prisma.config.ts`: + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 3. Environment Variable + +In `.env`: + +```env +DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public" +``` + +### Connection String Format + +``` +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA +``` + +- **USER**: Database user +- **PASSWORD**: Password (URL encoded if special chars) +- **HOST**: Hostname (localhost, IP, or domain) +- **PORT**: Port (default 5432) +- **DATABASE**: Database name +- **SCHEMA**: Schema name (default `public`) + +## Driver Adapter + +Use a driver adapter for the standard SQL workflow. + +1. Install adapter and driver: + ```bash + npm install @prisma/adapter-pg pg + ``` + +2. Instantiate Prisma Client with the adapter: + ```typescript + import 'dotenv/config' + import { PrismaClient } from '../generated/client' + import { PrismaPg } from '@prisma/adapter-pg' + + const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) + const prisma = new PrismaClient({ adapter }) + ``` + +## Common Issues + +### "Can't reach database server" +- Check host and port +- Check firewall settings +- Ensure database is running + +### "Authentication failed" +- Check user/password +- Special characters in password must be URL-encoded + +### "Schema does not exist" +- Ensure `?schema=public` (or your schema) is in the URL diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/prisma-client-setup.md b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-client-setup.md new file mode 100644 index 0000000..bb36932 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-client-setup.md @@ -0,0 +1,47 @@ +# Prisma Client Setup + +Generate and instantiate Prisma Client for Prisma's standard SQL provider workflow. For MongoDB, follow the provider-specific notes in `references/mongodb.md` instead of copying the SQL adapter example below. + +## 1. Install dependencies + +```bash +npm install prisma --save-dev +npm install @prisma/client +``` + +## 2. Add generator block + +In `prisma/schema.prisma`: + +```prisma +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +`prisma-client` requires an explicit `output` path and does not generate into `node_modules` by default. + +## 3. Generate Prisma Client + +```bash +npx prisma generate +``` + +Re-run `prisma generate` after every schema change to keep the client in sync. + +## 4. Instantiate Prisma Client + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) +const prisma = new PrismaClient({ adapter }) +``` + +If you change the generator `output`, update the import path to match. For the SQL provider workflow, replace `PrismaPg` with the adapter for your database. + +## 5. Use a single instance + +Each `PrismaClient` instance creates a connection pool. Reuse a single instance per app process to avoid exhausting database connections. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/prisma-postgres.md b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-postgres.md new file mode 100644 index 0000000..dc939e5 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-postgres.md @@ -0,0 +1,130 @@ +# Prisma Postgres Setup + +Configure Prisma with Prisma Postgres (Managed). + +## Overview + +Prisma Postgres is a serverless, managed PostgreSQL database optimized for Prisma. + +## Setup via CLI + +You can provision a Prisma Postgres instance directly via the CLI: + +```bash +prisma init --db +``` + +This will: +1. Log you into Prisma Data Platform. +2. Create a new project and database instance. +3. Update your `.env` with the connection string. + +## Connection String + +For Prisma CLI flows and Accelerate-style usage, you may see a `prisma+postgres://` URL. + +For Prisma Client with a driver adapter in Node.js, prefer the direct TCP connection string from the Prisma Postgres dashboard: + +```env +DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require" +``` + +## 1. Schema Configuration + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "postgresql" // Use postgresql provider +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +## 2. Config Configuration + +In `prisma.config.ts`: + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Driver Adapter + +Use a driver adapter for Prisma Postgres in the standard SQL workflow. + +### Recommended for standard Node.js apps + +1. Install adapter and driver: + ```bash + npm install @prisma/adapter-pg pg + ``` + +2. Use the direct TCP connection string from Prisma Console: + ```typescript + import 'dotenv/config' + import { PrismaClient } from '../generated/client' + import { PrismaPg } from '@prisma/adapter-pg' + + const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) + const prisma = new PrismaClient({ adapter }) + ``` + +`PrismaPg` also accepts the connection string directly: + +```typescript +const adapter = new PrismaPg(process.env.DATABASE_URL!) +const prisma = new PrismaClient({ adapter }) +``` + +For PostgreSQL prepared statement naming, pass adapter options as the second argument: + +```typescript +import { createHash } from 'node:crypto' + +const adapter = new PrismaPg(process.env.DATABASE_URL!, { + statementNameGenerator: ({ sql }) => + `prisma_${createHash('sha1').update(sql).digest('hex').slice(0, 16)}`, +}) +``` + +### Edge/serverless option + +Use the Prisma Postgres serverless driver only when you need HTTP/WebSocket transport in environments like Workers or Edge Functions: + +```bash +npm install @prisma/adapter-ppg @prisma/ppg +``` + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPostgresAdapter } from '@prisma/adapter-ppg' + +const prisma = new PrismaClient({ + adapter: new PrismaPostgresAdapter({ + connectionString: process.env.PRISMA_DIRECT_TCP_URL, + }), +}) +``` + +This serverless driver is the specialized path for HTTP/WebSocket-based edge and serverless runtimes, not the default recommendation for standard Node.js apps. + +## Features + +- **Serverless**: Scales to zero. +- **Caching**: Integrated query caching (Accelerate). +- **Real-time**: Database events (Pulse). + +## Using with Prisma Client + +Use the Prisma Postgres adapter shown above when instantiating Prisma Client. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/sqlite.md b/apps/backend/.agents/skills/prisma-database-setup/references/sqlite.md new file mode 100644 index 0000000..30e3e00 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/sqlite.md @@ -0,0 +1,106 @@ +# SQLite Setup + +Configure Prisma with SQLite. + +## Prerequisites + +- None (file-based) + +## 1. Schema Configuration + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "sqlite" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +## 2. Config Configuration + +In `prisma.config.ts`: + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 3. Environment Variable + +In `.env`: + +```env +DATABASE_URL="file:./dev.db" +``` + +### Connection String Format + +``` +file:PATH +``` + +- **PATH**: Relative path to the database file. Check `prisma.config.ts` if you need to confirm how your app resolves it. + +## Driver Adapter + +Use a driver adapter for the standard SQL workflow. + +1. Install adapter and driver: + ```bash + npm install @prisma/adapter-better-sqlite3 better-sqlite3 + ``` + +2. Instantiate Prisma Client with the adapter: + ```typescript + import { PrismaClient } from '../generated/client' + import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3' + + const adapter = new PrismaBetterSqlite3({ + url: process.env.DATABASE_URL ?? 'file:./dev.db', + }) + + const prisma = new PrismaClient({ adapter }) + ``` + +## Using Driver Adapter (LibSQL / Turso) + +For edge compatibility or Turso: + +1. Install: + ```bash + npm install @prisma/adapter-libsql @libsql/client + ``` + +2. Instantiate: + ```typescript + import { PrismaClient } from '../generated/client' + import { PrismaLibSql } from '@prisma/adapter-libsql' + + const adapter = new PrismaLibSql({ + url: process.env.TURSO_DATABASE_URL, + authToken: process.env.TURSO_AUTH_TOKEN, + }) + const prisma = new PrismaClient({ adapter }) + ``` + +## Limitations + +- **No Enums**: SQLite doesn't support enums (Prisma polyfills them or treats as String). +- **No Scalar Lists**: `String[]` is not supported directly. +- **Concurrency**: Write operations lock the file. + +## Common Issues + +### "Database file not found" +Ensure the path in `DATABASE_URL` is correct relative to where Prisma is running or the schema file. `file:./dev.db` creates it next to schema. diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/sqlserver.md b/apps/backend/.agents/skills/prisma-database-setup/references/sqlserver.md new file mode 100644 index 0000000..b519d95 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-database-setup/references/sqlserver.md @@ -0,0 +1,94 @@ +# SQL Server Setup + +Configure Prisma with Microsoft SQL Server. + +## Prerequisites + +- SQL Server 2017, 2019, 2022, or Azure SQL +- TCP/IP enabled + +## 1. Schema Configuration + +In `prisma/schema.prisma`: + +```prisma +datasource db { + provider = "sqlserver" +} + +generator client { + provider = "prisma-client" + output = "../generated" +} +``` + +## 2. Config Configuration + +In `prisma.config.ts`: + +```typescript +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 3. Environment Variable + +In `.env`: + +```env +DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=Password123;encrypt=true;trustServerCertificate=true" +``` + +### Connection String Format + +``` +sqlserver://HOST:PORT;database=DB;user=USER;password=PASS;encrypt=true;trustServerCertificate=true +``` + +- **encrypt**: Required for Azure (true). +- **trustServerCertificate**: True for self-signed certs (local dev). + +## Driver Adapter + +Use a driver adapter for the standard SQL workflow. + +1. Install adapter and driver: + ```bash + npm install @prisma/adapter-mssql mssql + ``` + +2. Instantiate Prisma Client with the adapter: + ```typescript + import 'dotenv/config' + import { PrismaClient } from '../generated/client' + import { PrismaMssql } from '@prisma/adapter-mssql' + + const adapter = new PrismaMssql({ + server: 'localhost', + port: 1433, + database: 'mydb', + user: process.env.SQLSERVER_USER, + password: process.env.SQLSERVER_PASSWORD, + options: { + encrypt: true, + trustServerCertificate: true, + }, + }) + + const prisma = new PrismaClient({ adapter }) + ``` + +## Common Issues + +### "Login failed for user" +- SQL Server auth vs Windows auth. Prisma typically uses SQL Server authentication (username/password). +- Ensure TCP/IP is enabled in SQL Server Configuration Manager. + +### "Table not found" (dbo schema) +Prisma assumes `dbo` schema by default. If using another schema, update the model or connection string? SQL Server provider mostly sticks to default schema. diff --git a/apps/backend/.agents/skills/prisma-driver-adapter-implementation/SKILL.md b/apps/backend/.agents/skills/prisma-driver-adapter-implementation/SKILL.md new file mode 100644 index 0000000..4bf3479 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-driver-adapter-implementation/SKILL.md @@ -0,0 +1,270 @@ +--- +name: prisma-driver-adapter-implementation +description: Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification. +license: MIT +metadata: + author: prisma + version: "7.9.1" +--- + +# Prisma SQL Driver Adapter Implementation + +Use this guide with the exact `@prisma/driver-adapter-utils` version installed by the target Prisma release. Driver adapters are a protocol boundary: type-compatible code can still corrupt values, leak connections, or break transactions. + +## When to Apply + +- Implementing `SqlDriverAdapterFactory`, `SqlMigrationAwareDriverAdapterFactory`, `SqlDriverAdapter`, or `Transaction` +- Adding nested-transaction/savepoint support +- Mapping driver values, column metadata, bind arguments, or database errors +- Debugging `P2039`, transaction leaks, shadow-database failures, or adapter-specific query behavior + +## Contract snapshot + +```typescript +interface SqlDriverAdapterFactory extends AdapterInfo { + connect(): Promise +} + +interface SqlMigrationAwareDriverAdapterFactory extends SqlDriverAdapterFactory { + connectToShadowDb(): Promise +} + +interface SqlDriverAdapter extends AdapterInfo { + queryRaw(query: SqlQuery): Promise + executeRaw(query: SqlQuery): Promise + executeScript(script: string): Promise + startTransaction(isolationLevel?: IsolationLevel): Promise + getConnectionInfo?(): ConnectionInfo + dispose(): Promise +} + +interface Transaction extends AdapterInfo { + readonly options: { usePhantomQuery: boolean } + queryRaw(query: SqlQuery): Promise + executeRaw(query: SqlQuery): Promise + commit(): Promise + rollback(): Promise + createSavepoint?(name: string): Promise + rollbackToSavepoint?(name: string): Promise + releaseSavepoint?(name: string): Promise +} +``` + +`IsolationLevel` currently includes `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, `SNAPSHOT`, and `SERIALIZABLE`; validate what the concrete database supports. + +## Priority rules + +| Priority | Rule | Impact | +|----------|------|--------| +| CRITICAL | One dedicated connection per transaction | Prevents interleaving and leaks | +| CRITICAL | `commit`/`rollback` are lifecycle cleanup hooks | Prevents duplicate COMMIT/ROLLBACK | +| CRITICAL | Savepoints live on `Transaction`, not adapter-global depth | Makes nested scopes connection-local | +| CRITICAL | Preserve original database error code/message | Enables useful `P2039` fallback | +| HIGH | Map arguments and result metadata exactly | Prevents silent value corruption | +| HIGH | Shadow databases are isolated and always cleaned up | Makes Migrate safe | +| HIGH | Dispose only resources the adapter owns | Prevents shutting down caller-owned pools | + +## Query implementation + +`SqlQuery` contains `sql`, `args`, and parallel `argTypes`. Map each argument using both value and `ArgType`; do not discard type/arity information. Execute in the driver's array/tuple row mode so column order is stable. + +```typescript +class ExampleQueryable { + readonly provider = 'postgres' as const + readonly adapterName = '@acme/adapter-example' + + constructor(protected readonly connection: DriverConnection) {} + + async queryRaw(query: SqlQuery): Promise { + try { + const result = await this.connection.query({ + text: query.sql, + values: query.args.map((value, index) => + mapArg(value, query.argTypes[index]), + ), + rowMode: 'array', + }) + + return { + columnNames: result.fields.map((field) => field.name), + columnTypes: result.fields.map(mapColumnType), + rows: result.rows, + } + } catch (error) { + throwAdapterError(error) + } + } + + async executeRaw(query: SqlQuery): Promise { + try { + const result = await this.connection.execute( + query.sql, + query.args.map((value, index) => mapArg(value, query.argTypes[index])), + ) + return result.rowsAffected ?? 0 + } catch (error) { + throwAdapterError(error) + } + } +} +``` + +### Result mapping + +Return `columnNames`, `columnTypes`, and `rows` with identical lengths/order. Map driver metadata to `ColumnTypeEnum` deliberately: + +- signed integer widths to `Int32`/`Int64`; preserve 64-bit values without JS number truncation +- decimal/numeric to `Numeric` using the representation expected by Prisma +- binary to `Uint8Array`/`Bytes` +- date-only, time-only, and timestamp to `Date`, `Time`, and `DateTime` +- UUID, JSON, enum, arrays, and provider-specific unknown values to their explicit types +- unsupported native types to `DriverAdapterError({ kind: 'UnsupportedNativeDataType', type })` + +Test `null`, empty arrays, array element types, big integers, decimals, byte arrays, JSON, dates, and user-defined/unknown native types. + +### Script execution + +`executeScript` must execute a migration script as the provider expects. Prefer the driver's native multi-statement/script facility or a real SQL parser. Naively splitting on `;` breaks functions, triggers, quoted strings, and dialect-specific blocks. + +## Transaction protocol + +`startTransaction` must acquire one dedicated connection, start the database transaction, apply the requested isolation level, and return a `Transaction` bound to that same connection. If setup fails, release it immediately. + +```typescript +async startTransaction(level?: IsolationLevel): Promise { + const connection = await this.pool.acquire() + try { + const tx = new ExampleTransaction(connection, () => connection.release()) + await tx.executeRaw({ sql: 'BEGIN', args: [], argTypes: [] }) + if (level) { + await tx.executeRaw({ + sql: `SET TRANSACTION ISOLATION LEVEL ${validateLevel(level)}`, + args: [], + argTypes: [], + }) + } + return tx + } catch (error) { + connection.release(error) + throwAdapterError(error) + } +} +``` + +### Commit and rollback + +Prisma coordinates the SQL `COMMIT`/`ROLLBACK` through `executeRaw`. The transaction object's `commit()` and `rollback()` methods are lifecycle hooks: detach listeners and release the dedicated connection exactly once. They must not issue a second SQL commit/rollback. + +```typescript +class ExampleTransaction extends ExampleQueryable implements Transaction { + readonly options = { usePhantomQuery: false } + #closed = false + + constructor(connection: DriverConnection, private readonly release: () => void) { + super(connection) + } + + async commit() { this.finish() } + async rollback() { this.finish() } + + private finish() { + if (this.#closed) return + this.#closed = true + this.release() + } + + async createSavepoint(name: string) { + await this.control(`SAVEPOINT ${safeSavepoint(name)}`) + } + + async rollbackToSavepoint(name: string) { + await this.control(`ROLLBACK TO SAVEPOINT ${safeSavepoint(name)}`) + } + + async releaseSavepoint(name: string) { + await this.control(`RELEASE SAVEPOINT ${safeSavepoint(name)}`) + } + + private async control(sql: string) { + await this.executeRaw({ sql, args: [], argTypes: [] }) + } +} +``` + +Implement the optional savepoint methods only where the provider supports them. Validate/quote savepoint identifiers. For providers whose savepoints are intentionally no-ops, document and test that limitation. + +Never keep transaction depth on the shared adapter. Parallel transactions make adapter-global depth incorrect; nested state belongs to the returned transaction connection and Prisma's savepoint calls. + +## Error mapping + +Wrap recognized driver failures in `DriverAdapterError`. Map known conditions to `MappedError` kinds such as constraint violations, authentication/reachability, missing table/column/database, timeouts, closed transactions, invalid input, value range, and write conflicts. + +For database errors, preserve `originalCode` and `originalMessage` even when falling back to the provider-specific raw variant: + +```typescript +import { + DriverAdapterError, + type Error as DriverAdapterErrorObject, + type MappedError, +} from '@prisma/driver-adapter-utils' + +function convertDriverError(error: DatabaseError): DriverAdapterErrorObject { + return { + originalCode: String(error.code), + originalMessage: error.message, + ...mapKnownOrRaw(error), + } +} + +function mapKnownOrRaw(error: DatabaseError): MappedError { + if (error.code === '23505') { + return { kind: 'UniqueConstraintViolation', constraint: parsedConstraint(error) } + } + return { + kind: 'postgres', + code: String(error.code ?? 'N/A'), + severity: error.severity ?? 'N/A', + message: error.message, + detail: error.detail, + column: error.column, + hint: error.hint, + } +} + +function throwAdapterError(error: unknown): never { + if (!isDatabaseError(error)) throw error + throw new DriverAdapterError(convertDriverError(error)) +} +``` + +Prisma uses preserved original details when an unmapped driver error becomes `P2039`. Do not replace every unknown exception with a fabricated `GenericJs` id; rethrow genuinely unexpected non-driver errors so programming bugs remain visible. + +## Factory, ownership, and shadow database + +- `connect()` returns a fresh usable adapter connection/pool wrapper. +- Track whether the factory created the pool. `dispose()` closes owned pools and only detaches listeners from caller-owned pools unless an explicit option transfers ownership. +- Implement `SqlMigrationAwareDriverAdapterFactory` only when `connectToShadowDb()` can create an isolated shadow database, connect to it, and drop it during disposal/failure cleanup. +- Never point the shadow adapter at the primary database. Quote generated identifiers and use cryptographically unique names. +- `getConnectionInfo()` should accurately report `schemaName`, `maxBindValues` when applicable, and `supportsRelationJoins`. + +## Verification checklist + +- [ ] Typecheck against the exact target `@prisma/driver-adapter-utils` version +- [ ] `queryRaw` preserves column order, types, nulls, and precision +- [ ] `executeRaw` reports affected rows correctly +- [ ] `executeScript` handles provider-specific multi-statement syntax +- [ ] Concurrent interactive transactions use distinct dedicated connections +- [ ] Success commits and releases once; failure rolls back and releases once +- [ ] Nested transaction tests exercise create/rollback/release savepoint hooks +- [ ] Unsupported isolation levels fail as `InvalidIsolationLevel` +- [ ] Known constraints map to structured errors +- [ ] Unmapped database errors retain original code/message and surface useful `P2039` +- [ ] Dispose ownership is tested for internal and external pools +- [ ] Shadow database creation, use, failure cleanup, and disposal are isolated +- [ ] Run Prisma Client integration/E2E tests, not only adapter unit tests + +## Source references + +- [Driver adapter interfaces](https://github.com/prisma/prisma/blob/v7/packages/driver-adapter-utils/src/types.ts) +- [PostgreSQL adapter transaction implementation](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/pg.ts) +- [PostgreSQL adapter error mapping](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/errors.ts) diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md new file mode 100644 index 0000000..99e1be7 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md @@ -0,0 +1,92 @@ +--- +name: prisma-mongodb-upgrade +description: Decision and migration guide for Prisma ORM MongoDB projects on v6, which have no upgrade path to v7. Use when a MongoDB project asks about upgrading Prisma, when "upgrade to prisma 7" comes up in a project with provider = "mongodb", or when evaluating a move to Prisma Next. Triggers on "upgrade prisma mongodb", "prisma 7 mongodb", "mongodb prisma migration", "prisma next mongodb". +license: MIT +metadata: + author: prisma + version: "0.1.0" +--- + +# Prisma MongoDB Upgrade Path + +MongoDB projects are the one Prisma cohort with no road into Prisma 7: **v6 is the terminal +classic-ORM major for MongoDB, and v7 never ships a MongoDB connector**. The successor path +is [Prisma Next](https://github.com/prisma/prisma-next), where MongoDB support is in Early +Access with GA planned after Postgres. This skill frames the real decision — migrate to +Prisma Next (the encouraged path), or stay on v6 where a hard blocker applies — and carries +the migration mechanics. + +**Never do either of these:** + +- Never advise a MongoDB project to "upgrade to Prisma 7". The connector does not exist + there. The `prisma-upgrade-v7` guide does not apply to MongoDB projects. +- Never solve the version question by rewriting the app onto a SQL database. Changing the + database engine is a separate, much larger decision that is not yours to make implicitly. + +## The version landscape + +| Version | MongoDB status | +|---------|----------------| +| Prisma ORM v6 | Fully supported (`mongodb` provider); latest 6.x is the current stable path; maintenance line | +| Prisma ORM v7 | **No MongoDB connector — not an option, ever** | +| Prisma Next | MongoDB support in **Early Access**, actively developed, GA planned after Postgres — the successor path for MongoDB projects | + +## The decision, up front + +**Migrating to Prisma Next is the encouraged path.** MongoDB support in Prisma Next is Early +Access: functional and moving quickly, with GA planned after Postgres — and the Prisma team +wants MongoDB users to migrate early and share feedback. The migration mechanics are +detailed in the references. + +**Staying on the latest v6 remains a legitimate choice where a hard blocker applies** — +stated plainly: the Next Mongo façade does not wrap transactions yet (the underlying driver +is available directly; this is expected to change soon), and pre-1.0 minors can carry +breaking changes with published upgrade recipes. + +### Decision table + +| Signal | Direction | +|--------|-----------| +| No blockers below apply | Migrate to Next; run the `verify-cutover-checklist` and share feedback with the Prisma team | +| Greenfield / prototype / internal tool | Migrate to Next | +| Codebase uses multi-document transactions (`$transaction`) — check with grep, do not ask | Plan raw-driver session equivalents first (see `client-api-mapping`), or stay on v6 until the façade wrapper lands | +| Team cannot absorb pre-1.0 breaking upgrades between minors | Stay on v6 until GA | +| Risk-averse but interested | Run a staged Next round-trip on a copy (see `verify-cutover-checklist`), then migrate | + +Note: the transactions gap is expected to close soon — this section will be updated when +façade transactions merge in Prisma Next. + +### If staying on v6: hygiene (a deliberate stay, not neglect) + +- Pin the Prisma packages to the latest 6.x line and keep taking 6.x patch releases. +- Track Prisma release notes and security advisories for the 6.x line. +- Keep the classic v6 MongoDB setup: `url = env("DATABASE_URL")` in the schema, `db push` + workflow, no SQL driver adapters (see `prisma-database-setup` for the v6 MongoDB shape). +- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved. + +## Reference files + +| Reference | What it covers | +|-----------|----------------| +| `references/decision-stay-or-migrate.md` | The full decision framing, blocker checks, and stay-hygiene detail | +| `references/schema-contract-mapping.md` | v6 schema (`mongodb` provider, `@db.ObjectId`, composite types) → Next contract concepts | +| `references/client-api-mapping.md` | v6 client calls → Next equivalents, incl. raw escape hatches and transactions — names map, parity does not | +| `references/migrations-mapping.md` | v6 `db push`-only story → Next's plan/migrate/verify/sign flow | +| `references/verify-cutover-checklist.md` | No-data-moves verification: same DB, index parity, staged round-trip before cutover | + +## Verified against + +Behavioral claims about Prisma Next in this skill were verified against +[prisma/prisma-next](https://github.com/prisma/prisma-next) at commit +`a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` (pre-1.0, ~v0.14/0.15 line). Prisma Next moves +quickly in Early Access: **before acting on any Next-side claim, verify it against the +version actually installed** (check the project's `@prisma-next/*` versions and the +prisma-next skills installed with it). Next's Mongo target requires MongoDB 8.0+ and expects +`mongodb@^7` as a user-supplied peer dependency. + +## Hand-off rule + +This skill is the **discovery bridge**, not a replacement for Prisma Next's own +documentation. After a project switches to Prisma Next, run Prisma Next's `init`/skill +installation and follow its own skills (quickstart, contract, queries, migrations, runtime) +for day-to-day work — do not keep working from this skill's summaries. diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/client-api-mapping.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/client-api-mapping.md new file mode 100644 index 0000000..242d2bd --- /dev/null +++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/client-api-mapping.md @@ -0,0 +1,61 @@ +# client-api-mapping + +How v6 Prisma Client calls map to Prisma Next's Mongo client — names map, parity does not. + +## Priority + +CRITICAL + +## Why It Matters + +The v6 and Next client APIs look superficially similar, but none of the v6 MongoDB raw +methods exist under their old names, aggregation moved to a different lane entirely, and +transactions go through the driver rather than a façade wrapper. Assuming parity produces +code that does not compile — or, in the transactions case, code that silently loses +atomicity. + +## The mapping + +| v6 call | Prisma Next equivalent | Notes | +|---------|------------------------|-------| +| `prisma.user.findMany(...)` | `db.orm.users.where(...).all()` | Fluent ORM lane; storage-name keys (see `schema-contract-mapping.md`) | +| `prisma.user.findFirst(...)` | `db.orm.users.where(...).first()` | | +| `create` / `update` / `upsert` / `delete` / `updateMany` / `deleteMany` | `create` / `update` / `upsert` / `delete` / `updateAll` / `deleteAll` on `db.orm.` | See Prisma Next's `prisma-next-queries` skill | +| `prisma.user.aggregate(...)`, `groupBy(...)` | **No ORM equivalent.** Use the typed aggregation-pipeline builder: `db.query.from(...).match(...).group(...).build()` | Prisma Next's `prisma-next-queries` skill covers the builder lane | +| `$runCommandRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#runcommandraw)) | **Name does not exist in Next.** Raw lane is `mongoRaw(...)` → a raw collection with `aggregate`, `insertOne/Many`, `updateOne/Many`, `deleteOne/Many`, `findOneAndUpdate/Delete`. For arbitrary database commands, use the underlying `mongodb` driver directly — it is a user-supplied peer dependency and fully accessible | Check the installed version's raw surface | +| `.findRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#findraw)) | `mongoRaw(...)` collection reads (e.g. `aggregate` with a `$match` stage) | No direct `findRaw` name | +| `.aggregateRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#aggregateraw)) | `mongoRaw(...).aggregate(...)` or the typed pipeline builder | | +| `$transaction(...)` — works on v6 with a replica set ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)) | The façade does not wrap `db.transaction(...)` yet, **but the underlying `mongodb` driver is directly available** (user-supplied peer dependency): multi-document atomicity works today via driver sessions (`client.startSession()` / `session.withTransaction(...)`) on a replica set | A façade wrapper is expected soon; this row will be updated when it merges | +| `$connect` / `$disconnect` | `connect()` / `close()` on the Mongo façade client | | + +## Bad + +```typescript +// Assuming v6 names exist in Prisma Next: +await db.user.$runCommandRaw({ collStats: 'users' }); // no such method +await db.transaction(async (tx) => { ... }); // no such method on the Mongo façade +``` + +## Good + +```typescript +// Raw lane under its Next name: +const raw = mongoRaw(db); +await raw.users.aggregate([{ $match: { status: 'active' } }]); + +// Aggregation through the typed pipeline builder: +const stats = await db.query.from('users').group({ _id: '$role', n: { $count: {} } }).build(); + +// Multi-document atomicity today: the mongodb driver (a direct dependency of the +// project) exposes sessions and transactions as usual: +const session = mongoClient.startSession(); +await session.withTransaction(async () => { + // ...writes... +}); +``` + +## References + +- [v6 MongoDB raw queries](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#raw-queries-with-mongodb) +- [v6 replica set requirement for transactions](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration) +- Prisma Next queries + runtime skills (`skills/prisma-next-queries`, incl. its dedicated `mongo.md`; `skills/prisma-next-runtime`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/decision-stay-or-migrate.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/decision-stay-or-migrate.md new file mode 100644 index 0000000..93feda2 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/decision-stay-or-migrate.md @@ -0,0 +1,87 @@ +# decision-stay-or-migrate + +How to decide between migrating a MongoDB project to Prisma Next and staying on Prisma v6. + +## Priority + +CRITICAL + +## Why It Matters + +MongoDB projects cannot follow the general "upgrade Prisma" advice: Prisma 7 has no MongoDB +connector, so the forward path is Prisma Next. Advising an impossible v7 upgrade, or +silently rewriting the app onto SQL, are both serious failure modes. The encouraged path is +migrating to Prisma Next — its MongoDB support is Early Access and the Prisma team wants +early adopters' feedback — with a deliberate stay on v6 where a hard blocker applies. + +## The facts the decision rests on + +Prisma Next side (verified against prisma/prisma-next @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`; +status confirmed by the Prisma team 2026-07): + +- **MongoDB support is Early Access**, actively developed, with GA planned after Postgres. +- The implementation is deep, not a stub: a full package family (ORM, typed + aggregation-pipeline builder, raw lane, driver over the official `mongodb` package), + first-class contract-driven migrations, and extensive tests against real in-memory MongoDB. +- **The Mongo client façade does not wrap `db.transaction(...)` yet** — multi-document + atomicity is done through the MongoDB driver's session API, which is directly available + (the `mongodb` package is a user-supplied peer dependency). A façade wrapper is expected; + this skill will be updated when it merges. +- Early Access means pre-1.0 minors can carry breaking changes, with published upgrade + recipes (e.g. 0.11→0.12 changed Mongo validator emission and made `mongodb` a + user-supplied peer dependency). Floor: MongoDB 8.0 and `mongodb@^7`. + +Prisma v6 side: + +- v6 fully supports MongoDB, including transactions on replica sets — "MongoDB only allows + you to start a transaction on a replica set. Prisma ORM uses transactions internally" + ([replica set configuration](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)). +- v6 MongoDB has no Prisma Migrate; the workflow is `db push` + ([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)). + +## Blocker checks before migrating + +Run these checks yourself — from the codebase, not by asking the user: + +- **Search the codebase for `$transaction` usage** (grep for `$transaction`). If present, + plan the raw-driver session equivalents before migrating (see `client-api-mapping.md`) — + or stay on v6 until the façade wrapper lands. +- **Check the MongoDB server version** (must be 8.0+ for Next; v6 tolerated older). +- **Confirm the team can absorb pre-1.0 upgrades.** Next publishes versioned upgrade recipes + between minors; someone has to run them. For a production app, confirm the user accepts + Early Access status before migrating. + +## Bad + +```text +User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?" +Agent: "Yes — here's the v7 upgrade guide. Step 1: install a driver adapter..." +``` + +Prisma 7 has no MongoDB connector; this migration is impossible and the SQL driver-adapter +steps corrupt a working v6 setup. + +## Good + +```text +User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?" +Agent: "Prisma 7 does not support MongoDB — v6 is the last classic-ORM +major for MongoDB. The path forward is Prisma Next, the successor: its MongoDB support is +Early Access and migrating is encouraged. Let me check the codebase for blockers first — +searching for $transaction usage and checking the MongoDB server version..." +``` + +## Stay-on-v6 hygiene + +Staying is a decision, not a default-by-neglect: + +- Pin `prisma` and `@prisma/client` to the latest 6.x and keep taking 6.x patches. +- Watch Prisma release notes and security advisories for the 6.x maintenance line. +- Keep the classic setup (`url = env("DATABASE_URL")` in the schema; `db push`; no SQL + driver adapters). +- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved. + +## References + +- [Prisma Next repository](https://github.com/prisma/prisma-next) +- [Prisma v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb) diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/migrations-mapping.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/migrations-mapping.md new file mode 100644 index 0000000..c666428 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/migrations-mapping.md @@ -0,0 +1,65 @@ +# migrations-mapping + +How the v6 MongoDB "no migrations" story maps onto Prisma Next's first-class migration flow. + +## Priority + +HIGH + +## Why It Matters + +This is the largest workflow change in the migration — in v6, MongoDB explicitly has no +Prisma Migrate, while in Prisma Next MongoDB participates in the full migration lifecycle. +Teams porting a `db push` habit into Next without understanding the plan/verify/sign flow +will fight the tooling or bypass its safety rails. + +## v6: `db push` only + +MongoDB on v6 has no Prisma Migrate and no plans to add it — "MongoDB projects do not rely +on internal schemas" ([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)). +The workflow is `prisma db push` to sync indexes and unique constraints, with no migration +history on disk. + +## Prisma Next: first-class, contract-driven migrations (Mongo included) + +Migration authoring in Next is first-class for Postgres **and Mongo** (prisma-next +`skills/prisma-next-migrations/SKILL.md`) — MongoDB is not a push-only special case: + +- **Flow:** contract *emit* → diff → *plan* (writes a content-hashed migration package) → + *migrate* (apply in graph order) → *verify* (live schema vs destination contract) → + *sign* (advance the marker after a verify pass). +- **Mongo migration ops** come from dedicated factories: `createCollection`, + `dropCollection`, `validatedCollection`, `setValidation`, `createIndex`, `dropIndex`, + `collMod`, and `dataTransform` for data backfills. +- **Marker storage:** Next records migration state in a document in the + `_prisma_migrations` collection (per space) — the same collection name family v6 users + know from SQL, repurposed for Mongo state. +- **DDL is not transactional on Mongo:** the runner applies operations, verifies the live + schema against the destination contract, and only advances the marker on a verify pass — + making interrupted runs resumable rather than atomic (see Prisma Next's + `prisma-next-migrations` skill). +- **Push-style alternative still exists:** `db update` diffs the live database against the + contract and applies directly without writing a migration directory — the closest + analogue to the v6 `db push` habit, at the cost of no history. +- Validators: Next emits closed `$jsonSchema` validators by default since 0.12 (prisma-next + `CHANGELOG.md`) — collections gain schema enforcement v6 never applied. + +## Bad + +```text +Porting the v6 habit: run the Next equivalent of `db push` for every change in production, +accumulating no migration history, and hand-editing collections when verification fails. +``` + +## Good + +```text +Adopt the Next lifecycle: emit the contract, plan a migration package, apply it with +migrate, let verify gate the marker, and sign. Reserve `db update` for local prototyping, +mirroring how `db push` was used on v6. +``` + +## References + +- [v6: no Prisma Migrate for MongoDB](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate) +- Prisma Next migrations skill (`skills/prisma-next-migrations`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/schema-contract-mapping.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/schema-contract-mapping.md new file mode 100644 index 0000000..fae18bb --- /dev/null +++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/schema-contract-mapping.md @@ -0,0 +1,52 @@ +# schema-contract-mapping + +How v6 MongoDB schema concepts map onto Prisma Next's contract model. + +## Priority + +HIGH + +## Why It Matters + +Prisma Next does not consume the v6 `schema.prisma` as-is: the schema becomes a *contract* +(authored in PSL or TypeScript via the contract builder), and several v6 MongoDB idioms have +different — or deliberately absent — equivalents. Translating mechanically without knowing +the mapping produces contracts that fail verification or, worse, silently change collection +addressing. + +## The mapping + +| v6 concept | Prisma Next equivalent | Notes | +|------------|------------------------|-------| +| `datasource db { provider = "mongodb" }` + `url = env(...)` ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#example)) | `defineConfig` from `@prisma-next/mongo/config` wiring the mongo family/target/adapter/driver descriptors | Next selects MongoDB by importing the `@prisma-next/mongo` façade, not by a provider string in the schema; `prisma-next init` accepts `mongodb` as a target name | +| `@id @default(auto()) @map("_id") @db.ObjectId` ([using ObjectId](https://www.prisma.io/docs/orm/overview/databases/mongodb#using-objectid)) | ObjectId-typed id field in the Next contract (PSL or TS builder) | Verify the exact attribute surface against the installed Next version's `prisma-next-contract` skill — the contract builder also exposes `index` and `valueObject` | +| Composite (embedded) types — MongoDB-only in v6 ([composite types](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)) | Value objects / embedded shapes in the Next contract (`valueObject` in the Mongo contract builder) | Same conceptual role: documents embedded in a parent document | +| Model names address the client (`prisma.user`) | **Collection storage names** address the ORM: `db.orm.users`, i.e. the `@@map(...)` name or the lowercased model name — not `db.orm.User` | prisma-next `skills/prisma-next/SKILL.md`, `skills/prisma-next-quickstart/SKILL.md`; the most common porting mistake | +| Indexes declared in schema, applied by `db push` | Indexes are contract-declared and applied through migrations (`createIndex`/`dropIndex` factories) | See `migrations-mapping.md` | +| No native polymorphism | No schema-layer polymorphism on Mongo either: `@@base`/`@@discriminator` are SQL-only in Next; model an explicit `discriminator` field | prisma-next `skills/prisma-next-contract/SKILL.md` | + +## Bad + +```typescript +// Ported from v6 and addressed by model name: +const user = await db.orm.User.first(); // undefined — Mongo ORM keys are storage names +``` + +## Good + +```typescript +// Mongo ORM keys are collection storage names (@@map or lowercased model name): +const user = await db.orm.users.first(); +``` + +## Environment requirements + +Prisma Next's Mongo target requires MongoDB 8.0+ and `mongodb@^7` installed by the user as a +peer dependency (prisma-next `CHANGELOG.md`, 0.11→0.12). v6 supports older MongoDB servers, +so check the server version before planning a migration. + +## References + +- [v6 MongoDB schema documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb) +- [v6 composite types (MongoDB-only)](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types) +- Prisma Next contract skill (`skills/prisma-next-contract`) in the prisma-next repository — authoritative for the Next side diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/verify-cutover-checklist.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/verify-cutover-checklist.md new file mode 100644 index 0000000..43144c3 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/verify-cutover-checklist.md @@ -0,0 +1,60 @@ +# verify-cutover-checklist + +Verification checklist for a v6 → Prisma Next cutover: the data never moves — only the code does. + +## Priority + +CRITICAL + +## Why It Matters + +A v6 → Next migration is a *client and workflow* migration against the **same MongoDB +database** — there is no data export/import step, and introducing one (or pointing the new +stack at a fresh database) turns a code migration into an outage. The checklist below keeps +the cutover observable and reversible. + +## Ground rules + +- **No data moves.** The Next contract is authored to describe the existing collections; + both stacks read the same database during the staged phase. +- **v6 stays runnable until cutover is verified.** Do not delete the v6 client, schema, or + dependencies until the checklist passes. + +## Checklist + +1. **Same database, verified:** the Next config points at the same connection string / + database name the v6 app uses (minus v6-specific URL parameters that the `mongodb@^7` + driver rejects — validate the URL with the driver first). +2. **Server floor:** MongoDB server is 8.0+ (Next's requirement; v6 tolerated older). + Confirm before authoring any contract. +3. **Contract round-trip on a copy:** on a staging copy (or `mongodb-memory-server`), emit + the contract, run plan → migrate → verify → sign, and confirm `verify` passes against + data copied from production shape. Verification failures here are contract-mapping bugs, + not database problems. +4. **Index parity:** enumerate indexes on every collection (`db.collection.getIndexes()`) + and confirm the Next contract declares the same set — v6 `db push` may have created + indexes the new contract must re-declare, or verification and query performance will + diverge. +5. **Validator impact assessed:** Next emits closed `$jsonSchema` validators by default; + confirm legacy documents (extra fields, drifted shapes) pass them on the staging copy + before applying to production. +6. **Storage-name addressing audited:** every ported call site uses collection storage + names (`db.orm.users`), not model names (see `schema-contract-mapping.md`). +7. **Transaction inventory mapped:** grep the v6 app for `$transaction`; each hit gets a + driver-session equivalent (the `mongodb` driver is directly available; the façade wrapper + is expected soon — see `client-api-mapping.md`). +8. **Raw call inventory mapped:** every `$runCommandRaw` / `findRaw` / `aggregateRaw` call + has an explicit Next-side replacement (`mongoRaw(...)` lane or pipeline builder). +9. **Staged read-only soak:** run the Next stack read-only against staging/production data + alongside v6 and compare outputs before allowing writes. +10. **Cutover + rollback:** switch writes to Next only after the soak; keep the v6 branch + deployable as the rollback path. Rolling back is a code rollback — the data was never + moved. + +After cutover, install and follow Prisma Next's own skills for ongoing work (see the +hand-off rule in `SKILL.md`). + +## References + +- [v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb) +- Prisma Next migrations + queries skills — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md b/apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md new file mode 100644 index 0000000..2f9925e --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md @@ -0,0 +1,263 @@ +--- +name: prisma-postgres-setup +description: Set up a new Prisma Postgres database and connect it to a local project using the Management API. Use when asked to "set up a database", "create a Prisma Postgres project", "get a connection string", "connect my app to Prisma Postgres", or "provision a database". +license: MIT +metadata: + author: prisma + version: "1.1.0" +--- + +# Prisma Postgres Setup + +Procedural skill that guides you through provisioning a new Prisma Postgres database via the Management API and connecting it to a local project. + +## When to Apply + +Use this skill when: + +- Setting up a new Prisma Postgres database for a project +- Creating a Prisma Postgres project and connecting it locally +- Obtaining a connection string for Prisma Postgres +- Provisioning a database via the Management API (not the Console UI) + +Do **not** use this skill when: + +- Setting up CI/CD preview databases — use `prisma-postgres-cicd` +- Building multi-tenant database provisioning into an app — use `prisma-postgres-integrator` +- Working with a database that already exists and is connected (schema/migration tasks are standard Prisma CLI) + +## Prerequisites + +- Node.js 18+ +- A Prisma Postgres workspace (create one at https://console.prisma.io if needed) +- A workspace service token (see `references/auth.md`) + +## UX Guidelines + +When presenting choices to the user (region selection, project deletion, etc.), **use your platform's interactive selection mechanism** (e.g., `ask` tool in Claude Code, structured prompts in other agents). Do not print static tables and ask the user to type a value — present selectable options so the user can pick with minimal effort. + +## Workflow + +Follow these steps in order. Each step includes the API call to make and how to handle the response. + +### Step 1: Authenticate + +You need a service token. Try these methods in order: + +**1a. Token in the user's prompt** + +Check if the user included a service token in their initial message (e.g., "Set up Prisma Postgres with token eyJ..."). If so, use it **exactly as provided** — do not truncate, re-encode, or round-trip it through a file. Store it in a shell variable for subsequent calls. + +**1b. Token in the environment** + +Check for `PRISMA_SERVICE_TOKEN` in the environment or `.env` file. + +**1c. Ask the user to create one** + +If no token is available, instruct the user: + +> Create a service token in Prisma Console → Workspace Settings → Service Tokens. +> Copy the token and paste it here. + +Read `references/auth.md` for details on service token creation. + +Once you have a token, store it in a shell variable (`PRISMA_SERVICE_TOKEN`) and use it for all subsequent API calls. + +### Step 2: List available regions + +Fetch the list of available Prisma Postgres regions to let the user choose where to deploy. + +```bash +curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \ + https://api.prisma.io/v1/regions/postgres +``` + +The response contains an array of regions with `id`, `name`, and `status`. Only present regions where `status` is `available`. + +**Present the regions as an interactive menu** — let the user pick from options rather than typing a region ID manually. + +Read `references/endpoints.md` for the full response shape. + +### Step 3: Create a project with a database + +```bash +curl -s -X POST https://api.prisma.io/v1/projects \ + -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "", + "region": "", + "createDatabase": true + }' +``` + +Use the current directory name as the project name by default. + +The response is wrapped in `{ "data": { ... } }`. Extract: + +- `data.id` — the project ID (prefixed with `proj_`) +- `data.database.id` — the database ID (prefixed with `db_`) +- `data.database.connections[0].endpoints.direct.connectionString` — the direct PostgreSQL connection string + +Use the **direct** connection string (`endpoints.direct.connectionString`). Do not use the pooled or accelerate endpoints — those are for legacy Accelerate setups and not needed for new projects. + +If the response status is `provisioning`, wait a few seconds and poll `GET /v1/databases/` until `status` is `ready`. + +**If creation fails due to a database limit**, list the user's existing projects and present them as an interactive menu for deletion. After the user picks one, delete it and retry. + +Read `references/endpoints.md` for the full request/response shapes. + +### Step 4: Create a named connection (optional) + +If you need a dedicated connection (e.g., per-developer or per-environment), create one: + +```bash +curl -s -X POST https://api.prisma.io/v1/databases//connections \ + -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ "name": "dev" }' +``` + +Extract the direct connection string from `data.endpoints.direct.connectionString`. + +### Step 5: Configure the local project + +1. Install dependencies: + +```bash +npm install prisma @prisma/client @prisma/adapter-pg pg dotenv +``` + +All five packages are required: +- `prisma` — CLI for migrations, schema push, client generation +- `@prisma/client` — the generated query client +- `@prisma/adapter-pg` — Prisma 7 driver adapter for direct PostgreSQL connections +- `pg` — Node.js PostgreSQL driver (used by the adapter) +- `dotenv` — loads `.env` variables for `prisma.config.ts` + +2. Write the direct connection string to `.env`. **Append** to the file if it already exists — do not overwrite existing entries: + +``` +DATABASE_URL="" +``` + +3. Verify `.gitignore` includes `.env`. Create `.gitignore` if it does not exist. Warn the user if `.env` is not gitignored. + +4. Ensure `package.json` has `"type": "module"` set (Prisma 7 generates ESM output). + +5. If `prisma/schema.prisma` does not exist, run `npx prisma init` to scaffold the project. This creates both `prisma/schema.prisma` and `prisma.config.ts`. + +6. Ensure `schema.prisma` has the `postgresql` provider and **no** `url` or `directUrl` in the datasource block (Prisma 7 manages connection URLs in `prisma.config.ts`, not in the schema): + +```prisma +datasource db { + provider = "postgresql" +} +``` + +7. Ensure `prisma.config.ts` loads the connection URL from the environment: + +```typescript +import path from 'node:path' +import { defineConfig } from 'prisma/config' +import 'dotenv/config' + +export default defineConfig({ + earlyAccess: true, + schema: path.join(import.meta.dirname, 'prisma', 'schema.prisma'), + datasource: { + url: process.env.DATABASE_URL!, + }, +}) +``` + +**Important Prisma 7 notes:** +- Connection URLs go in `prisma.config.ts`, never in `schema.prisma` +- The provider in `schema.prisma` must be `"postgresql"` (not `"prismaPostgres"`) +- `dotenv/config` must be imported in `prisma.config.ts` to load `.env` variables + +### Step 6: Define schema and push + +If the schema already has models, skip to pushing. Otherwise, **present these options as an interactive menu**: + +1. **"I'll define my schema manually"** — Tell the user to edit `prisma/schema.prisma` and come back when ready. Wait for them before proceeding. +2. **"Give me a starter schema"** — Add a Blog starter schema (User, Post, Comment with relations) to `prisma/schema.prisma`. Show the user what was added and ask if they want to adjust it before pushing. +3. **"I'll describe what I need"** — Ask the user to describe their data model in natural language (e.g., "I'm building a task manager with projects, tasks, and team members"). Generate a schema from the description, show it, and ask for confirmation before pushing. + +Once the schema has models and the user is ready, create a migration and generate the client: + +```bash +npx prisma migrate dev --name init +``` + +This creates migration files in `prisma/migrations/` **and** generates the client in one step. Migration history is essential for CI/CD workflows (`prisma migrate deploy`) and production deployments. + +Only use `npx prisma db push` if the user explicitly asks for prototyping-only mode (no migration history). In that case, follow it with `npx prisma generate`. + +### Step 7: Verify the connection + +After generating the client, create and run a quick verification script to confirm everything works end-to-end. This is **critical** — do not skip this step. + +Create a file named `test-connection.ts`: + +```typescript +import 'dotenv/config' +import pg from 'pg' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from './generated/prisma/client.js' + +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }) +const adapter = new PrismaPg(pool) +const prisma = new PrismaClient({ adapter }) + +const result = await prisma.$queryRawUnsafe('SELECT 1 as connected') +console.log('Connected to Prisma Postgres:', result) + +await prisma.$disconnect() +await pool.end() +``` + +Run it: + +```bash +npx tsx test-connection.ts +``` + +**Prisma 7 client instantiation rules:** +- Import from `./generated/prisma/client.js` (not `./generated/prisma`) +- Create a `pg.Pool` with the `DATABASE_URL` connection string +- Wrap it in a `PrismaPg` adapter +- Pass `{ adapter }` to the `PrismaClient` constructor +- Do **not** use `datasourceUrl` — that option does not exist in Prisma 7 +- Do **not** use `new PrismaClient()` with no arguments — it will throw + +After verification succeeds, delete `test-connection.ts`. + +Then share links for the user to explore their database: + +- **Prisma Studio (CLI):** `npx prisma studio` — opens a visual data browser locally +- **Console:** `https://console.prisma.io////dashboard` — strip the prefixes (`wksp_`, `proj_`, `db_`) from the IDs returned in Step 3 to build this URL + +Read `references/prisma7-client.md` for the full client instantiation reference. + +## Error Handling + +Read `references/api-basics.md` for the full error reference. Key self-correction patterns: + +| HTTP Status | Error Code | Action | +|---|---|---| +| 401 | `authentication-failed` | Service token is invalid or expired. Ask the user to create a new one in Console → Workspace Settings → Service Tokens. | +| 404 | `resource-not-found` | Check that the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). | +| 422 | `validation-error` | Check request body against the endpoint schema. Common: missing `name`, invalid `region`. | +| 429 | `rate-limit-exceeded` | Back off and retry after a few seconds. | + +## Reference Files + +Detailed API and usage information is in: + +``` +references/auth.md — Service token creation and usage +references/api-basics.md — Base URL, envelope, IDs, errors, pagination +references/endpoints.md — Endpoint details for projects, databases, connections, regions +references/prisma7-client.md — Prisma 7 client instantiation and usage patterns +``` diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/api-basics.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/api-basics.md new file mode 100644 index 0000000..272fff4 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/api-basics.md @@ -0,0 +1,102 @@ +# api-basics + +Core conventions for the Prisma Management API. All three `prisma-postgres-*` skills share these patterns. + +## Base URL + +``` +https://api.prisma.io/v1 +``` + +API documentation: https://api.prisma.io/v1/doc + +## Response Envelope + +### Single resource + +```json +{ + "data": { + "id": "proj_clx7abc123def456", + "type": "project", + "name": "My Project", + "createdAt": "2025-06-15T10:30:00.000Z" + } +} +``` + +### Collection + +```json +{ + "data": [ + { "id": "proj_aaa", "type": "project", "name": "Alpha" }, + { "id": "proj_bbb", "type": "project", "name": "Beta" } + ], + "pagination": { + "hasMore": true, + "nextCursor": "clx7cursor123" + } +} +``` + +## Resource ID Prefixes + +Every resource ID carries a type prefix: + +| Prefix | Resource | +|---|---| +| `proj_` | Project | +| `db_` | Database | +| `con_` | Connection | +| `wksp_` | Workspace | + +Always include the prefix when sending IDs in API requests. + +## Pagination + +Collection endpoints use cursor-based pagination: + +``` +GET /v1/projects?limit=10 +GET /v1/projects?cursor=clx7abc123&limit=10 +``` + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `cursor` | string | — | Opaque cursor from `nextCursor` | +| `limit` | number | 100 | Maximum items per page | + +Continue fetching while `pagination.hasMore` is `true`, using `pagination.nextCursor` as the `cursor` parameter. + +## Error Responses + +All errors follow this shape: + +```json +{ + "error": { + "code": "resource-not-found", + "message": "database with id db_abc not found" + } +} +``` + +### Error codes by HTTP status + +| HTTP Status | Error Code | Meaning | +|---|---|---| +| 400 | `client-error` | Malformed request | +| 401 | `authentication-failed` | Missing or invalid token | +| 403 | `permission-denied` | Token lacks required access | +| 404 | `resource-not-found` | Resource does not exist or is not accessible | +| 422 | `validation-error` | Request body failed validation | +| 429 | `rate-limit-exceeded` | Too many requests | +| 500 | `internal-server-error` | Server error — retry after a delay | + +### Self-correction patterns + +- **401**: Token is invalid or expired. Create a new service token in Console → Workspace Settings → Service Tokens. +- **404**: Verify the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). Use `GET /v1/projects` or `GET /v1/databases` to list available resources. +- **422**: Check the request body against the endpoint schema. Common issues: missing required fields, invalid region ID, empty `name`. +- **429**: Wait 2–5 seconds and retry. If repeated, increase the backoff interval. diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/auth.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/auth.md new file mode 100644 index 0000000..b341a41 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/auth.md @@ -0,0 +1,46 @@ +# auth + +How to authenticate with the Prisma Management API using service tokens. + +## Service Tokens + +Service tokens authenticate server-to-server requests. They are scoped to a workspace and grant access to all resources within it. + +### Creating a service token + +1. Open https://console.prisma.io +2. Navigate to **Workspace Settings** → **Service Tokens** +3. Click **Create Token** +4. Copy the token immediately — it is only shown once + +### Using a service token + +Set the token as an environment variable: + +```bash +export PRISMA_SERVICE_TOKEN="eyJ..." +``` + +Include it in the `Authorization` header of every API request: + +```bash +curl -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \ + https://api.prisma.io/v1/projects +``` + +### Token scope + +Service tokens are workspace-scoped. A single token grants access to all projects, databases, and connections within the workspace. There are no project-scoped tokens at this time. + +### Security practices + +- Store tokens in environment variables or secret managers, never in source code +- Add `.env` to `.gitignore` to prevent accidental commits +- Rotate tokens periodically via Console → Workspace Settings → Service Tokens +- In CI/CD, store tokens as encrypted secrets (e.g., GitHub Secrets) + +## OAuth 2.0 (for user-scoped access) + +OAuth is used when acting on behalf of a user, typically in partner/integrator flows. See the `prisma-postgres-integrator` skill for OAuth details. + +For standard database setup, service tokens are the recommended authentication method. diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/endpoints.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/endpoints.md new file mode 100644 index 0000000..f5c9713 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/endpoints.md @@ -0,0 +1,223 @@ +# endpoints + +Management API endpoint details for database setup workflows. + +## List regions + +``` +GET /v1/regions/postgres +``` + +No request body. Returns available Prisma Postgres regions. + +**Response:** + +```json +{ + "data": [ + { + "id": "us-east-1", + "type": "region", + "name": "US East (N. Virginia)", + "status": "available" + }, + { + "id": "eu-west-1", + "type": "region", + "name": "EU West (Ireland)", + "status": "available" + } + ] +} +``` + +Only use regions where `status` is `available`. + +## Create project (with database) + +``` +POST /v1/projects +``` + +**Request body:** + +```json +{ + "name": "my-project", + "region": "us-east-1", + "createDatabase": true +} +``` + +| Field | Type | Required | Default | Description | +|---|---|---|---|---| +| `name` | string | No | Auto-generated | Project display name | +| `region` | string | No | `us-east-1` | Region for the database | +| `createDatabase` | boolean | No | `true` | Create a default database with the project | + +**Response** (with `createDatabase: true`): + +```json +{ + "data": { + "id": "proj_clx7abc123", + "type": "project", + "url": "https://api.prisma.io/v1/projects/proj_clx7abc123", + "name": "my-project", + "createdAt": "2025-06-15T10:30:00.000Z", + "defaultRegion": "us-east-1", + "workspace": { + "id": "wksp_xyz789", + "url": "https://api.prisma.io/v1/workspaces/wksp_xyz789", + "name": "My Workspace" + }, + "database": { + "id": "db_def456", + "type": "database", + "url": "https://api.prisma.io/v1/databases/db_def456", + "name": "my-project", + "status": "ready", + "createdAt": "2025-06-15T10:30:00.000Z", + "isDefault": true, + "defaultConnectionId": "con_ghi789", + "connections": [ + { + "id": "con_ghi789", + "type": "connection", + "url": "https://api.prisma.io/v1/connections/con_ghi789", + "name": "Default", + "createdAt": "2025-06-15T10:30:00.000Z", + "kind": "postgres", + "endpoints": { + "direct": { + "host": "db.prisma.io", + "port": 5432, + "connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require" + } + } + } + ], + "region": { + "id": "us-east-1", + "name": "US East (N. Virginia)" + } + } + } +} +``` + +Key field to extract: + +- `data.database.connections[0].endpoints.direct.connectionString` → use as `DATABASE_URL` + +The response also includes `pooled` and `accelerate` endpoints — ignore these for new projects. The direct connection string is all you need. + +If `data.database.status` is `provisioning`, poll `GET /v1/databases/{id}` until `status` is `ready`. + +## Get database + +``` +GET /v1/databases/{databaseId} +``` + +Use to check database status after creation or to retrieve database details. + +**Response:** + +```json +{ + "data": { + "id": "db_def456", + "type": "database", + "url": "https://api.prisma.io/v1/databases/db_def456", + "name": "my-project", + "status": "ready", + "createdAt": "2025-06-15T10:30:00.000Z", + "isDefault": true, + "defaultConnectionId": "con_ghi789", + "connections": [], + "project": { + "id": "proj_clx7abc123", + "url": "https://api.prisma.io/v1/projects/proj_clx7abc123", + "name": "my-project" + }, + "region": { + "id": "us-east-1", + "name": "US East (N. Virginia)" + } + } +} +``` + +## Create connection + +``` +POST /v1/databases/{databaseId}/connections +``` + +Creates a new named connection string for a database. Use for per-developer or per-environment connections. + +**Request body:** + +```json +{ + "name": "dev" +} +``` + +| Field | Type | Required | Description | +|---|---|---|---| +| `name` | string | Yes | Display name for the connection | + +**Response:** + +```json +{ + "data": { + "id": "con_newcon123", + "type": "connection", + "url": "https://api.prisma.io/v1/connections/con_newcon123", + "name": "dev", + "createdAt": "2025-06-15T10:31:00.000Z", + "kind": "postgres", + "endpoints": { + "direct": { + "host": "db.prisma.io", + "port": 5432, + "connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require" + } + }, + "database": { + "id": "db_def456", + "url": "https://api.prisma.io/v1/databases/db_def456", + "name": "my-project" + } + } +} +``` + +Extract: `data.endpoints.direct.connectionString` → use as `DATABASE_URL`. + +## Delete database + +``` +DELETE /v1/databases/{databaseId} +``` + +Permanently deletes a database and all its connections. Returns `204 No Content` on success. + +## List projects + +``` +GET /v1/projects +``` + +Returns all projects in the workspace. Supports cursor-based pagination (`?cursor=...&limit=...`). + +## Delete project + +``` +DELETE /v1/projects/{projectId} +``` + +Permanently deletes a project and all its databases. Returns `204 No Content` on success. diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/prisma7-client.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/prisma7-client.md new file mode 100644 index 0000000..6fbc003 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/prisma7-client.md @@ -0,0 +1,82 @@ +# Prisma 7 Client Instantiation + +Prisma 7 changed how PrismaClient connects to databases. The CLI (`prisma db push`, `prisma migrate`) reads the URL from `prisma.config.ts`. But at **runtime**, you must provide a driver adapter to PrismaClient explicitly. + +## Required packages + +```bash +npm install @prisma/client @prisma/adapter-pg pg +``` + +- `@prisma/adapter-pg` — the Prisma adapter for the `pg` PostgreSQL driver +- `pg` — the underlying Node.js PostgreSQL driver + +## Basic instantiation + +```typescript +import 'dotenv/config' +import pg from 'pg' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from './generated/prisma/client.js' + +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }) +const adapter = new PrismaPg(pool) +const prisma = new PrismaClient({ adapter }) +``` + +## Key rules + +1. **Import path**: Always `./generated/prisma/client.js` — not `./generated/prisma` and not `@prisma/client`. + +2. **Adapter is mandatory**: `new PrismaClient()` with no arguments throws. `new PrismaClient({ datasourceUrl: '...' })` also throws — `datasourceUrl` does not exist in Prisma 7. + +3. **ESM required**: The generated client uses ESM. Ensure `package.json` has `"type": "module"`. + +4. **Pool lifecycle**: Call `await pool.end()` when shutting down (after `prisma.$disconnect()`). + +## Usage in application code + +```typescript +import 'dotenv/config' +import pg from 'pg' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from './generated/prisma/client.js' + +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }) +const adapter = new PrismaPg(pool) +const prisma = new PrismaClient({ adapter }) + +// Create +const user = await prisma.user.create({ + data: { email: 'alice@example.com', name: 'Alice' }, +}) + +// Read with relations +const posts = await prisma.post.findMany({ + where: { published: true }, + include: { author: true }, +}) + +// Update +await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, +}) + +// Delete +await prisma.post.delete({ where: { id: 1 } }) + +// Cleanup +await prisma.$disconnect() +await pool.end() +``` + +## Common mistakes + +| Mistake | Error | Fix | +|---|---|---| +| `import { PrismaClient } from './generated/prisma'` | `Cannot find module` | Use `./generated/prisma/client.js` | +| `new PrismaClient()` | `PrismaClient needs non-empty options` | Pass `{ adapter }` | +| `new PrismaClient({ datasourceUrl: url })` | `Unknown property datasourceUrl` | Use adapter pattern instead | +| Missing `"type": "module"` in package.json | ESM import errors | Add `"type": "module"` | +| `import { PrismaClient } from '@prisma/client'` | Wrong export | Use `./generated/prisma/client.js` | diff --git a/apps/backend/.agents/skills/prisma-postgres/SKILL.md b/apps/backend/.agents/skills/prisma-postgres/SKILL.md new file mode 100644 index 0000000..568543f --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres/SKILL.md @@ -0,0 +1,145 @@ +--- +name: prisma-postgres +description: Prisma Postgres setup and operations guidance across Console, create-db CLI, Management API, and Management API SDK. Use when creating Prisma Postgres databases, working in Prisma Console, provisioning with create-db/create-pg/create-postgres, or integrating programmatic provisioning with service tokens or OAuth. +license: MIT +metadata: + author: prisma + version: "7.9.1" +--- + +# Prisma Postgres + +Guidance for creating, managing, and integrating Prisma Postgres across interactive and programmatic workflows. + +## When to Apply + +Reference this skill when: +- Setting up Prisma Postgres from Prisma Console +- Provisioning instant temporary databases with `create-db` +- Linking an existing local project with `prisma postgres link` +- Managing Prisma Postgres resources via Management API +- Using `@prisma/management-api-sdk` in TypeScript/JavaScript +- Handling claim URLs, connection strings, regions, and auth flows + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | CLI Provisioning | CRITICAL | `create-db-cli` | +| 2 | Management API | CRITICAL | `management-api` | +| 3 | Management API SDK | HIGH | `management-api-sdk` | +| 4 | Console and Connections | HIGH | `console-and-connections` | + +## Quick Reference + +- `create-db-cli` - instant databases and current CLI flags (`--ttl`, `--copy`, `--quiet`, `--open`) +- `management-api` - service token and OAuth API workflows +- `management-api-sdk` - typed SDK usage with token storage +- `console-and-connections` - Console operations, `prisma postgres link`, direct TCP connections, and serverless-driver choices + +## Core Workflows + +### 1. Console-first workflow + +Use Prisma Console for manual setup and operations: + +- Open `https://console.prisma.io` +- Create/select workspace and project +- Use Studio in the project sidebar to view/edit data +- Retrieve direct connection details from the project UI + +### 2. Quick provisioning with create-db + +Use `create-db` when you need a database immediately: + +```bash +npx create-db@latest +``` + +Aliases: + +```bash +npx create-pg@latest +npx create-postgres@latest +``` + +For app integrations, you can also use the programmatic API (`create()` / `regions()`) from the `create-db` npm package. + +Temporary databases auto-delete after ~24 hours unless claimed. + +### 2b. Persistent databases with the Platform CLI + +For databases that belong to a Project (not throwaway `create-db` databases), use `@prisma/cli`: + +```bash +npx -y @prisma/cli@latest database create --help +npx -y @prisma/cli@latest database list --json +npx -y @prisma/cli@latest database connection create db_123 +npx -y @prisma/cli@latest database usage db_123 +npx -y @prisma/cli@latest database backup list db_123 +``` + +`database create` and `database connection create` print a one-time connection URL; store it immediately. Destructive commands (`remove`, `restore`) require exact `--confirm `. + +For automation, prefer `--json --no-interactive`, resolve ids before mutations, and verify the installed command's help because this CLI is beta. + +### 3. Link an existing local project + +Use `prisma postgres link` when the database already exists and you want to wire a local project to it: + +```bash +prisma postgres link +``` + +For CI or other non-interactive environments: + +```bash +prisma postgres link --api-key "" --database "db_..." +``` + +This flow updates your local `.env` with `DATABASE_URL`, then you can run `prisma generate` and `prisma migrate dev`. + +### 4. Programmatic provisioning with Management API + +Use API endpoints on: + +```text +https://api.prisma.io/v1 +``` + +Explore the schema and endpoints using: + +- OpenAPI docs: `https://api.prisma.io/v1/doc` +- Swagger Editor: `https://api.prisma.io/v1/swagger-editor` + +Auth options: + +- Service token (workspace server-to-server) +- OAuth 2.0 (act on behalf of users) + +### 5. Type-safe integration with Management API SDK + +Install and use: + +```bash +npm install @prisma/management-api-sdk +``` + +Use `createManagementApiClient` for existing tokens, or `createManagementApiSdk` for OAuth + token refresh. + +The SDK exposes typed workspace service-token list, create, and revoke routes. A newly created token value is returned exactly once. Let the installed SDK types or OpenAPI document settle exact beta endpoint shapes. + +## Rule Files + +Detailed guidance lives in: + +``` +references/console-and-connections.md +references/create-db-cli.md +references/management-api.md +references/management-api-sdk.md +``` + +## How to Use + +Start with `references/create-db-cli.md` for fast setup, then switch to `references/management-api.md` or `references/management-api-sdk.md` when you need programmatic provisioning. diff --git a/apps/backend/.agents/skills/prisma-postgres/references/console-and-connections.md b/apps/backend/.agents/skills/prisma-postgres/references/console-and-connections.md new file mode 100644 index 0000000..4025d12 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres/references/console-and-connections.md @@ -0,0 +1,69 @@ +# console-and-connections + +Use Prisma Console workflows for project visibility, data inspection, and connection setup. + +## Priority + +HIGH + +## Why It Matters + +Many Prisma Postgres tasks are quickest in the Console: viewing Studio data, checking metrics, and retrieving connection details. This avoids unnecessary API or CLI work for simple operational tasks. + +## Console workflow + +1. Open `https://console.prisma.io`. +2. Select workspace and project. +3. Use dashboard metrics for usage and billing visibility. +4. Open the **Studio** tab in the sidebar to inspect and edit data. + +## Local Studio + +You can also inspect data locally: + +```bash +npx prisma studio +``` + +## Linking an existing project + +If the Prisma Postgres database already exists, link the local project instead of provisioning a new one: + +```bash +prisma postgres link +``` + +For CI or non-interactive usage: + +```bash +prisma postgres link --api-key "" --database "db_..." +``` + +This command updates or creates `.env` with `DATABASE_URL`. If the project is already linked, use `--force` to re-link. After linking, run `prisma generate`, then `prisma migrate dev` if you need to apply the schema. + +## Connection setup + +For direct PostgreSQL tools and drivers: + +- Generate/copy direct connection credentials from the project connection UI. +- Use the resulting PostgreSQL URL as `DATABASE_URL` for `pg` and `@prisma/adapter-pg`. +- For Prisma Postgres direct TCP, include `sslmode=require`. + +Typical direct TCP format: + +```env +DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require" +``` + +Management API connection responses expose both `endpoints.direct` (`db.prisma.io:5432`) and `endpoints.pooled` (`pooled.db.prisma.io:5432`); prefer those fields over the deprecated flat `connectionString`. Connection secrets are shown once at creation (one-time view); store them immediately. + +## Adapter choices + +- Standard Node.js apps: prefer `@prisma/adapter-pg` with the direct TCP URL above. +- Edge/serverless runtimes: use `@prisma/adapter-ppg` with `@prisma/ppg` only when you specifically need the Prisma Postgres serverless driver. + +## References + +- [Prisma Postgres overview](https://www.prisma.io/docs/postgres/introduction/overview) +- [Viewing data](https://www.prisma.io/docs/postgres/integrations/viewing-data) +- [Direct connections](https://www.prisma.io/docs/postgres/database/direct-connections) diff --git a/apps/backend/.agents/skills/prisma-postgres/references/create-db-cli.md b/apps/backend/.agents/skills/prisma-postgres/references/create-db-cli.md new file mode 100644 index 0000000..7359b78 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres/references/create-db-cli.md @@ -0,0 +1,136 @@ +# create-db-cli + +Use `create-db` for instant Prisma Postgres provisioning from the terminal. + +## Priority + +CRITICAL + +## Why It Matters + +`create-db` is the fastest way to get a working Prisma Postgres instance for development, demos, and CI previews. It can also emit machine-readable output and write env variables directly. + +## Commands + +```bash +npx create-db@latest +npx create-db@latest create [options] +npx create-db@latest regions +``` + +Aliases: + +```bash +npx create-pg@latest +npx create-postgres@latest +``` + +## Command discovery (`--help`) + +Always use `--help` first when integrating CLI commands: + +```bash +npx create-db@latest --help +npx create-db@latest create --help +npx create-db@latest regions --help +``` + +Top-level commands currently exposed: + +- `create` (default) to provision a database +- `regions` to list available regions + +## `create` options + +| Flag | Shorthand | Description | +|---|---|---| +| `--region [string]` | `-r` | Region choice: `ap-southeast-1`, `ap-northeast-1`, `eu-central-1`, `eu-west-3`, `us-east-1`, `us-west-1` | +| `--interactive [boolean]` | `-i` | Open region selector | +| `--json [boolean]` | `-j` | Output machine-readable JSON | +| `--env [string]` | `-e` | Write `DATABASE_URL` and `CLAIM_URL` into a target `.env` | +| `--ttl [string]` | `-t` | Auto-delete after a TTL like `30m` or `1h-24h` | +| `--copy [boolean]` | `-c` | Copy the connection string to the clipboard | +| `--quiet [boolean]` | `-q` | Only print the connection string | +| `--open [boolean]` | `-o` | Open the claim URL in your browser | + +## Lifecycle and claim flow + +- Databases are temporary by default. +- Unclaimed databases are auto-deleted after ~24 hours. +- Claim the database using the URL shown in command output to keep it permanently. + +## Programmatic usage (library API) + +You can also use `create-db` programmatically in Node.js/Bun instead of shelling out to the CLI. + +Install: + +```bash +npm install create-db +# or +bun add create-db +``` + +Create a database: + +```ts +import { create, isDatabaseSuccess, isDatabaseError } from "create-db"; + +const result = await create({ + region: "us-east-1", + userAgent: "my-app/1.0.0", +}); + +if (isDatabaseSuccess(result)) { + console.log(result.connectionString); + console.log(result.claimUrl); + console.log(result.deletionDate); +} + +if (isDatabaseError(result)) { + console.error(result.error, result.message); +} +``` + +List regions programmatically: + +```ts +import { regions } from "create-db"; + +const available = await regions(); +console.log(available); +``` + +Programmatic `create()` defaults to `us-east-1` if no region is passed. + +## Common patterns + +```bash +# quick database +npx create-db@latest + +# region-specific database +npx create-db@latest --region eu-central-1 + +# interactive region selection +npx create-db@latest --interactive + +# write env vars for app bootstrap +npx create-db@latest --env .env + +# auto-delete sooner +npx create-db@latest --ttl 2h + +# copy connection string to clipboard +npx create-db@latest --copy + +# print only the connection string +npx create-db@latest --quiet + +# CI-friendly output +npx create-db@latest --json +``` + +## References + +- [npx create-db docs](https://www.prisma.io/docs/postgres/introduction/npx-create-db) diff --git a/apps/backend/.agents/skills/prisma-postgres/references/management-api-sdk.md b/apps/backend/.agents/skills/prisma-postgres/references/management-api-sdk.md new file mode 100644 index 0000000..026aa5f --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres/references/management-api-sdk.md @@ -0,0 +1,70 @@ +# management-api-sdk + +Use `@prisma/management-api-sdk` for typed API integration with optional OAuth and token refresh. + +The Platform API evolves independently from Prisma ORM. Inspect the installed package's generated `api.d.ts` for exact paths and request/response shapes. + +## Priority + +HIGH + +## Why It Matters + +The SDK provides typed endpoint methods and removes boilerplate around auth and refresh handling, which reduces errors in production provisioning flows. + +## Install + +```bash +npm install @prisma/management-api-sdk +``` + +## Simple client (existing token) + +```typescript +import { createManagementApiClient } from '@prisma/management-api-sdk' + +const client = createManagementApiClient({ token: process.env.PRISMA_SERVICE_TOKEN! }) +const { data: workspaces } = await client.GET('/v1/workspaces') +``` + +Check the generated client result before using `data`; typed clients surface HTTP failures separately. Never log a full response from connection/key creation because it may contain one-time credentials. + +## Workspace service tokens + +The typed client exposes routes to list, create, and revoke workspace service tokens: + +- `GET /v1/workspaces/{workspaceId}/service-tokens` +- `POST /v1/workspaces/{workspaceId}/service-tokens` +- `DELETE /v1/workspaces/{workspaceId}/service-tokens/{serviceTokenId}` + +Creation accepts a display `name`. The response's `data.value` is the complete token and is returned exactly once; transfer it directly to the intended secret store without logging the response. Later list calls return metadata and `valueHint`, not the token value. Treat revocation as destructive and resolve both ids explicitly. + +## Full SDK (OAuth + refresh) + +```typescript +import { createManagementApiSdk, type TokenStorage } from '@prisma/management-api-sdk' + +const tokenStorage: TokenStorage = { + async getTokens() { return null }, + async setTokens(tokens) {}, + async clearTokens() {}, +} + +const api = createManagementApiSdk({ + clientId: process.env.PRISMA_CLIENT_ID!, + redirectUri: 'https://your-app.com/auth/callback', + tokenStorage, +}) +``` + +## OAuth SDK flow + +1. Call `getLoginUrl()` and persist `state` + `verifier`. +2. Redirect user to login URL. +3. Handle callback with `handleCallback()`. +4. Use `api.client` for typed endpoint calls. +5. Call `logout()` when needed. + +## References + +- [Management API SDK docs](https://www.prisma.io/docs/postgres/introduction/management-api-sdk) diff --git a/apps/backend/.agents/skills/prisma-postgres/references/management-api.md b/apps/backend/.agents/skills/prisma-postgres/references/management-api.md new file mode 100644 index 0000000..4e4e76f --- /dev/null +++ b/apps/backend/.agents/skills/prisma-postgres/references/management-api.md @@ -0,0 +1,79 @@ +# management-api + +Use Prisma Management API for programmatic provisioning and workspace/project/database management. + +## Priority + +CRITICAL + +## Why It Matters + +When you need backend automation, multi-tenant onboarding flows, or controlled resource provisioning, the Management API is the source of truth and is more reliable than interactive workflows. + +## Base URL + +```text +https://api.prisma.io/v1 +``` + +## API exploration + +- OpenAPI docs: `https://api.prisma.io/v1/doc` +- Swagger Editor: `https://api.prisma.io/v1/swagger-editor` + +## Authentication methods + +- Service token: best for server-to-server operations in your own workspace +- OAuth 2.0: best for acting on behalf of users across workspaces + +## Service token flow + +1. Create token in Prisma Console workspace settings. +2. Send token as Bearer auth: + +```text +Authorization: Bearer $TOKEN +``` + +## OAuth flow summary + +1. Redirect user to `https://auth.prisma.io/authorize` with `client_id`, `redirect_uri`, `response_type=code`, and scopes. +2. Receive `code` on callback. +3. Exchange code at `https://auth.prisma.io/token`. +4. Use returned access token in Management API requests. + +## Resource model + +Workspace -> Project -> Branch -> Database. Branches are a first-class resource: databases attach to a Branch, and branch-scoped env/databases are how preview isolation works. + +## Current resource inventory + +The 1.55 OpenAPI surface includes: + +- workspaces, subscriptions, workspace integrations, workspace service tokens, and current-user metadata +- projects, transfers, project databases, and project/branch environment variables +- branches under a project plus branch get/update/delete operations +- databases, usage, backups, restore, connections, and connection rotation +- apps, deployments, promotion/rollback, runtime logs, domains, and build logs +- buckets and bucket keys +- source repositories, SCM installations/install intents, and repositories +- integrations and regions + +App/deployment, branch mutation, SCM, and bucket routes include experimental surfaces. Read the installed SDK types or live OpenAPI before building durable automation around them. + +Connection create/rotate responses reveal credentials once. Later reads redact or omit the secret, so store the URL immediately. Use the structured direct/pooled endpoint returned by the concrete operation; do not assume a historical flat response shape. + +Workspace service-token creation also returns the complete token value exactly once. List calls expose only metadata and a `valueHint`; delete revokes the token. Keep workspace and token ids opaque, and never log a create response. + +Database create supports explicit project, region, branch, and source context. A source may be empty, a backup, or another database. Backup records are incremental; rely on current fields and documented units rather than old full-backup examples. + +## Notes + +- Management API mutation responses may include direct connection credentials; treat the entire response as secret until redacted. +- Prefer an API-provided connection string over manually assembling one from fields. + +## References + +- [Management API docs](https://www.prisma.io/docs/postgres/introduction/management-api) +- [OpenAPI docs](https://api.prisma.io/v1/doc) +- [Swagger Editor](https://api.prisma.io/v1/swagger-editor) diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md b/apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md new file mode 100644 index 0000000..23d4956 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md @@ -0,0 +1,259 @@ +--- +name: prisma-upgrade-v7 +description: Complete migration guide from Prisma ORM v6 to v7 covering all breaking changes. Use when upgrading Prisma versions, encountering v7 errors, or migrating existing projects. Triggers on "upgrade to prisma 7", "prisma 7 migration", "prisma-client generator", "driver adapter required". +license: MIT +metadata: + author: prisma + version: "7.6.0" +--- + +# Upgrade to Prisma ORM 7 + +Complete guide for migrating from Prisma ORM v6 to v7. This upgrade introduces significant breaking changes around the new `prisma-client` generator, driver adapters, `prisma.config.ts`, explicit environment loading, and generated client entrypoints. + +## When to Apply + +Reference this skill when: +- Upgrading from Prisma v6 to v7 +- Updating to the `prisma-client` generator +- Setting up driver adapters +- Configuring `prisma.config.ts` +- Fixing import errors after upgrade + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Schema Migration | CRITICAL | `schema-changes` | +| 2 | Database Connectivity | CRITICAL | `driver-adapters` | +| 3 | Module System | CRITICAL | `esm-support` | +| 4 | Config and Env | HIGH | `prisma-config`, `env-variables` | +| 5 | Removed Features | HIGH | `removed-features` | +| 6 | Accelerate | HIGH | `accelerate-users` | + +## Quick Reference + +- `schema-changes` - generator migration, required output paths, generated entrypoints, and `Prisma.validator` replacement +- `driver-adapters` - required adapter installation for SQL providers, pool differences, and Prisma Postgres adapter choices +- `esm-support` - ESM-first setup plus CommonJS fallback with `moduleFormat = "cjs"` +- `prisma-config` - creating and using `prisma.config.ts` +- `env-variables` - explicit environment loading +- `removed-features` - removed middleware, metrics, and legacy CLI behavior +- `accelerate-users` - migration notes for Accelerate users + +## Using MongoDB? This guide does not apply + +Prisma 7 has no MongoDB connector. Do not apply any step in this guide to a project with +`provider = "mongodb"` — see the `prisma-mongodb-upgrade` skill for the actual decision +(stay on v6 deliberately vs migrate to Prisma Next). + +## Important Notes + +- **MongoDB projects should stay on Prisma 6.x or migrate to Prisma Next** - do not migrate MongoDB apps to Prisma 7's SQL client path (see `prisma-mongodb-upgrade`) +- **Node.js 20.19.0+** required +- **TypeScript 5.4.0+** required +- **Latest stable Prisma ORM version**: `7.6.0` + +## Upgrade Steps Overview + +1. Update packages to v7 +2. Choose your module format (`esm` by default, `cjs` if needed) +3. Update TypeScript configuration +4. Update the schema generator block +5. Create `prisma.config.ts` +6. Install and configure a driver adapter for SQL providers +7. Update Prisma Client imports +8. Update client instantiation +9. Replace deprecated helper patterns like `Prisma.validator` +10. Run `prisma generate` and test + +## Quick Upgrade Commands + +```bash +# Update packages +npm install @prisma/client@7 +npm install -D prisma@7 + +# Install a driver adapter (PostgreSQL or Prisma Postgres via direct TCP) +npm install @prisma/adapter-pg pg + +# Install dotenv for env loading +npm install dotenv + +# Regenerate client +npx prisma generate +``` + +## Breaking Changes Summary + +| Change | v6 | v7 | +|--------|----|----| +| Module format | Implicit / mixed | ESM-first, `moduleFormat = "cjs"` supported | +| Generator provider | `prisma-client-js` | `prisma-client` is the default, while `prisma-client-js` still exists for legacy setups | +| Output path | Auto (node_modules) | Required explicit | +| Driver adapters | Optional | Required for SQL providers | +| Config file | `.env` + schema | `prisma.config.ts` | +| Env loading | Automatic | Manual (dotenv) | +| Generated entrypoints | Single package export | `client`, `browser`, `models`, `enums` entrypoints | +| Type-safe query fragments | `Prisma.validator()` | TypeScript `satisfies` | +| Middleware | `$use()` | Client Extensions | +| Metrics | Preview feature | Removed | + +## Rule Files + +Detailed migration guides for each breaking change: + +``` +references/esm-support.md - ESM and CommonJS configuration +references/schema-changes.md - Generator, output, imports, and generated entrypoints +references/driver-adapters.md - Required driver adapter setup +references/prisma-config.md - New configuration file +references/env-variables.md - Environment variable loading +references/removed-features.md - Middleware, metrics, and CLI flags +references/accelerate-users.md - Special handling for Accelerate +``` + +## Step-by-Step Migration + +### 1. Update package.json for ESM-first projects + +```json +{ + "type": "module" +} +``` + +If you need to stay on CommonJS, keep your app as CJS and set `moduleFormat = "cjs"` in the generator block instead of forcing ESM. + +### 2. Update tsconfig.json + +```json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ES2023", + "strict": true, + "esModuleInterop": true + } +} +``` + +### 3. Update schema.prisma + +```prisma +// Before (v6) +generator client { + provider = "prisma-client-js" +} + +// After (v7) +generator client { + provider = "prisma-client" + output = "../generated/prisma" + // Optional if you need CommonJS: + // moduleFormat = "cjs" +} +``` + +### 4. Create prisma.config.ts + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +### 5. Install a driver adapter (SQL providers only) + +```bash +# PostgreSQL +npm install @prisma/adapter-pg pg + +# MySQL +npm install @prisma/adapter-mariadb mariadb + +# SQLite +npm install @prisma/adapter-better-sqlite3 better-sqlite3 + +# Prisma Postgres in standard Node.js apps (recommended) +npm install @prisma/adapter-pg pg + +# Prisma Postgres serverless driver (edge/serverless) +npm install @prisma/adapter-ppg @prisma/ppg + +# Neon +npm install @prisma/adapter-neon +``` + +MongoDB does not have a SQL `@prisma/adapter-*` package in the published Prisma 7.6.0 packages. If you're upgrading a MongoDB project, stop and keep that project on the latest Prisma 6.x release instead of following the standard Prisma 7 migration path. + +### 6. Update client instantiation + +```typescript +// Before (v6) +import { PrismaClient } from '@prisma/client' +const prisma = new PrismaClient() + +// After (v7) +import { PrismaClient } from '../generated/prisma/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### 7. Replace Prisma.validator with satisfies + +```typescript +import { Prisma } from '../generated/prisma/client' + +const userSelect = { + id: true, + email: true, + name: true, +} satisfies Prisma.UserSelect +``` + +### 8. Run migrations and generate + +```bash +npx prisma generate +npx prisma migrate dev # if needed +``` + +## Troubleshooting + +### "Cannot find module" errors +- Check that the generator `output` path matches your import path +- Ensure `prisma generate` ran successfully + +### SSL certificate errors +- Add `ssl: { rejectUnauthorized: false }` to the adapter config if you need to preserve old behavior +- Or configure your certificates properly with `NODE_EXTRA_CA_CERTS` / OpenSSL CA settings + +### Connection timeout issues +- Driver adapters use the underlying driver's defaults, which differ from v6 +- Configure pool settings explicitly on the adapter if needed + +## Resources + +- [Official v7 Upgrade Guide](https://www.prisma.io/docs/orm/more/upgrades/to-v7) +- [Driver Adapters Documentation](https://www.prisma.io/docs/orm/core-concepts/supported-databases/database-drivers) +- [Prisma Config Reference](https://www.prisma.io/docs/orm/reference/prisma-config-reference) + +## How to Use + +Follow `references/schema-changes.md` and `references/driver-adapters.md` first, then apply the remaining reference files based on your project setup. diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/accelerate-users.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/accelerate-users.md new file mode 100644 index 0000000..893e341 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/accelerate-users.md @@ -0,0 +1,151 @@ +# Prisma Accelerate Users + +Special migration instructions for users of Prisma Accelerate or Prisma Postgres with `prisma://` or `prisma+postgres://` URLs. + +## Important + +**Do NOT pass Accelerate URLs to driver adapters.** + +Driver adapters (like `PrismaPg`) expect direct database connection strings. They will fail with `prisma://` or `prisma+postgres://` URLs. + +## Correct v7 Setup for Accelerate + +### 1. Keep your Accelerate URL + +```env +# .env +DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=..." +# or +DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..." +``` + +### 2. Install Accelerate extension + +```bash +npm install @prisma/extension-accelerate +``` + +### 3. Configure prisma.config.ts + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), // Accelerate URL works here + }, +}) +``` + +### 4. Instantiate client with accelerateUrl + +```typescript +import { PrismaClient } from '../generated/client' +import { withAccelerate } from '@prisma/extension-accelerate' + +// Use accelerateUrl instead of adapter +export const prisma = new PrismaClient({ + accelerateUrl: process.env.DATABASE_URL, +}).$extends(withAccelerate()) +``` + +## What NOT to Do + +```typescript +// ❌ WRONG - Don't use adapter with Accelerate URL +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL // This will fail with prisma:// +}) +``` + +## Migrations with Accelerate + +For migrations, you may need a direct database connection: + +### Option 1: Use Accelerate URL for everything + +Accelerate URLs work with Prisma CLI commands: + +```bash +# Works with Accelerate URL +prisma migrate deploy +prisma db push +``` + +### Option 2: Use direct URL for migrations + +```env +DATABASE_URL="prisma+postgres://..." # For app +DIRECT_DATABASE_URL="postgresql://..." # For migrations +``` + +```typescript +// prisma.config.ts +export default defineConfig({ + datasource: { + url: env('DIRECT_DATABASE_URL'), // Direct URL for CLI + }, +}) +``` + +## Prisma Postgres (Cloud) + +If using Prisma Postgres cloud database: + +### Same approach + +```typescript +import { PrismaClient } from '../generated/client' +import { withAccelerate } from '@prisma/extension-accelerate' + +export const prisma = new PrismaClient({ + accelerateUrl: process.env.DATABASE_URL, // prisma+postgres:// URL +}).$extends(withAccelerate()) +``` + +## Switching Away from Accelerate + +If you later switch to direct TCP connection: + +```typescript +// Change from accelerateUrl to adapter +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL // Direct postgres:// URL +}) + +export const prisma = new PrismaClient({ adapter }) +``` + +## Caching with Accelerate + +The extension enables caching: + +```typescript +const users = await prisma.user.findMany({ + cacheStrategy: { + ttl: 60, // Cache for 60 seconds + swr: 120, // Stale-while-revalidate for 120 seconds + }, +}) +``` + +## Edge Runtime + +Accelerate works great in edge runtimes: + +```typescript +// Works in Vercel Edge, Cloudflare Workers, etc. +import { PrismaClient } from '../generated/client' +import { withAccelerate } from '@prisma/extension-accelerate' + +export const prisma = new PrismaClient({ + accelerateUrl: process.env.DATABASE_URL, +}).$extends(withAccelerate()) +``` diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/driver-adapters.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/driver-adapters.md new file mode 100644 index 0000000..bc5b892 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/driver-adapters.md @@ -0,0 +1,267 @@ +# Driver Adapters + +Prisma v7 requires driver adapters for SQL database connections. This is the standard SQL execution path in current Prisma releases. + +MongoDB should not follow this path. There is no published MongoDB `@prisma/adapter-*` package, and MongoDB projects should remain on the latest Prisma 6.x release instead of trying to fit into the Prisma 7 SQL adapter model. + +## Why Driver Adapters? + +- No native engine binary in the Prisma Client SQL path +- Smaller bundle size +- Better serverless/edge compatibility +- Uses native Node.js database drivers +- More control over connection pooling + +## Available Adapters + +| Database | Adapter Package | Underlying Driver | +|----------|-----------------|-------------------| +| PostgreSQL | `@prisma/adapter-pg` | `pg` | +| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` | +| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` | +| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` | +| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` | +| SQL Server | `@prisma/adapter-mssql` | `mssql` | +| Neon | `@prisma/adapter-neon` | `@neondatabase/serverless` | +| PlanetScale | `@prisma/adapter-planetscale` | `@planetscale/database` | +| Turso/libSQL | `@prisma/adapter-libsql` | `@libsql/client` | +| D1 (Cloudflare) | `@prisma/adapter-d1` | Cloudflare D1 | + +## Installation + +### PostgreSQL + +```bash +npm install @prisma/adapter-pg +``` + +### MySQL + +```bash +npm install @prisma/adapter-mariadb mariadb +``` + +### SQLite + +```bash +npm install @prisma/adapter-better-sqlite3 +``` + +### Prisma Postgres + +```bash +npm install @prisma/adapter-pg pg +``` + +### SQL Server + +```bash +npm install @prisma/adapter-mssql mssql +``` + +## Configuration + +### PostgreSQL + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### MySQL + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaMariaDb } from '@prisma/adapter-mariadb' + +const adapter = new PrismaMariaDb({ + host: 'localhost', + port: 3306, + connectionLimit: 5, + user: process.env.MYSQL_USER, + password: process.env.MYSQL_PASSWORD, + database: process.env.MYSQL_DATABASE, +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### SQLite + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3' + +const adapter = new PrismaBetterSqlite3({ + url: process.env.DATABASE_URL || 'file:./dev.db' +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### Neon (Serverless PostgreSQL) + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaNeon } from '@prisma/adapter-neon' + +const adapter = new PrismaNeon({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### Prisma Postgres + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL, +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### Prisma Postgres serverless driver + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPostgresAdapter } from '@prisma/adapter-ppg' + +const prisma = new PrismaClient({ + adapter: new PrismaPostgresAdapter({ + connectionString: process.env.PRISMA_DIRECT_TCP_URL, + }), +}) +``` + +### SQL Server + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaMssql } from '@prisma/adapter-mssql' + +const adapter = new PrismaMssql({ + server: 'localhost', + port: 1433, + database: 'mydb', + user: process.env.SQLSERVER_USER, + password: process.env.SQLSERVER_PASSWORD, + options: { + encrypt: true, + trustServerCertificate: true, + }, +}) + +const prisma = new PrismaClient({ adapter }) +``` + +## Connection Pool Configuration + +Driver adapters use the underlying driver's pool settings, which differ from v6 defaults. + +### PostgreSQL with custom pool + +```typescript +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL, + // Pool configuration + max: 10, // Maximum connections + idleTimeoutMillis: 30000, // Close idle connections after 30s + connectionTimeoutMillis: 5000, // Connection timeout (v6 default was 5s) +}) +``` + +### Matching v6 behavior + +```typescript +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, // v6 used 5 second timeout +}) +``` + +## SSL Configuration + +### Accept self-signed certificates + +```typescript +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL, + ssl: { + rejectUnauthorized: false // Accept self-signed certs + } +}) +``` + +### Proper SSL configuration + +```typescript +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL, + ssl: { + ca: fs.readFileSync('/path/to/ca-cert.pem'), + rejectUnauthorized: true + } +}) +``` + +## Migration from v6 + +### Before (v6) + +```typescript +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient({ + datasources: { + db: { url: process.env.DATABASE_URL } + } +}) +``` + +### After (v7) + +```typescript +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL +}) + +const prisma = new PrismaClient({ adapter }) +``` + +## Singleton Pattern + +```typescript +// lib/prisma.ts +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL! +}) + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') { + globalForPrisma.prisma = prisma +} +``` diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/env-variables.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/env-variables.md new file mode 100644 index 0000000..fb67e89 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/env-variables.md @@ -0,0 +1,161 @@ +# Environment Variables + +Prisma v7 no longer automatically loads environment variables. You must load them explicitly. + +## The Change + +### v6 Behavior + +Prisma CLI automatically loaded `.env` files. + +### v7 Behavior + +You must manually load environment variables using `dotenv` or similar. + +## Setup + +### 1. Install dotenv + +```bash +npm install dotenv +``` + +### 2. Import in prisma.config.ts + +```typescript +import 'dotenv/config' // Must be first import +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Bun Users + +Bun automatically loads `.env` files. No additional setup needed: + +```typescript +// prisma.config.ts (Bun) +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Multiple .env Files + +### Using dotenv-cli + +```bash +npm install -D dotenv-cli +``` + +```json +{ + "scripts": { + "db:migrate": "dotenv -e .env.local -- prisma migrate dev", + "db:push": "dotenv -e .env.development -- prisma db push" + } +} +``` + +### Using dotenv with path + +```typescript +// prisma.config.ts +import { config } from 'dotenv' +import path from 'path' + +// Load specific .env file +config({ path: path.join(__dirname, '.env.local') }) + +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Application Code + +For your application, load env vars at startup: + +### Entry point + +```typescript +// index.ts +import 'dotenv/config' + +import { PrismaClient } from '../generated/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ + connectionString: process.env.DATABASE_URL! +}) + +const prisma = new PrismaClient({ adapter }) +``` + +### Or use dotenv explicitly + +```typescript +import { config } from 'dotenv' +config() + +// Now process.env.DATABASE_URL is available +``` + +## Removed Environment Variables + +These Prisma-specific env vars are removed in v7: + +| Removed Variable | Alternative | +|-----------------|-------------| +| `PRISMA_CLI_QUERY_ENGINE_TYPE` | Not needed (no engines) | +| `PRISMA_CLIENT_ENGINE_TYPE` | Not needed (no engines) | +| `PRISMA_QUERY_ENGINE_BINARY` | Not needed | +| `PRISMA_QUERY_ENGINE_LIBRARY` | Not needed | +| `PRISMA_GENERATE_SKIP_AUTOINSTALL` | Not needed | +| `PRISMA_SKIP_POSTINSTALL_GENERATE` | Not needed | +| `PRISMA_GENERATE_IN_POSTINSTALL` | Not needed | +| `PRISMA_GENERATE_DATAPROXY` | Migrate to `prisma-client` with driver adapters | +| `PRISMA_GENERATE_NO_ENGINE` | Migrate to `prisma-client` with driver adapters | +| `PRISMA_CLIENT_NO_RETRY` | Configure on adapter | +| `PRISMA_MIGRATE_SKIP_GENERATE` | Not needed (auto-generate removed) | +| `PRISMA_MIGRATE_SKIP_SEED` | Not needed (auto-seed removed) | + +## TypeScript env() Helper + +The `env()` function from `prisma/config` provides type safety: + +```typescript +import { env } from 'prisma/config' + +// Type-safe environment variable access +const url = env('DATABASE_URL') // string +``` + +Note: This only works within `prisma.config.ts`, not in your application code. + +## CI/CD Considerations + +Ensure environment variables are set in your CI environment: + +```yaml +# GitHub Actions +env: + DATABASE_URL: ${{ secrets.DATABASE_URL }} + +steps: + - run: npx prisma migrate deploy +``` + +No need for dotenv in CI if variables are set directly. diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/esm-support.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/esm-support.md new file mode 100644 index 0000000..bf2697b --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/esm-support.md @@ -0,0 +1,128 @@ +# ESM and CommonJS Support + +Prisma ORM v7 is ESM-first, but the `prisma-client` generator can target either ESM or CommonJS. Use ESM by default, and opt into CommonJS with `moduleFormat = "cjs"` if your project still needs it. + +## ESM Projects + +Add `"type": "module"` to `package.json` and use an ESM-compatible `tsconfig.json`: + +```json +{ + "type": "module", + "scripts": { + "build": "tsc", + "start": "node dist/index.js" + } +} +``` + +```json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "outDir": "dist" + }, + "include": ["src/**/*", "prisma/**/*"] +} +``` + +## CommonJS Projects + +If the rest of your app is still CommonJS, keep that setup and make the generated Prisma Client CommonJS too: + +```json +{ + "compilerOptions": { + "module": "CommonJS", + "moduleResolution": "node", + "target": "ES2022", + "esModuleInterop": true + } +} +``` + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" + moduleFormat = "cjs" +} +``` + +## Generator Fields That Matter + +- `moduleFormat`: `esm` or `cjs` +- `runtime`: `nodejs`, `bun`, `deno`, `workerd`, `vercel-edge`, `react-native` +- `generatedFileExtension`: `ts`, `mts`, or `cts` +- `importFileExtension`: `ts`, `mts`, `cts`, `js`, `mjs`, `cjs`, or empty + +Example: + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" + runtime = "nodejs" + moduleFormat = "esm" + generatedFileExtension = "ts" + importFileExtension = "ts" +} +``` + +## Import Paths + +### Server Code + +```typescript +import { PrismaClient } from '../generated/prisma/client' +``` + +### Browser-Safe Types + +```typescript +import { Prisma } from '../generated/prisma/browser' +import { Role } from '../generated/prisma/enums' +import type { UserModel } from '../generated/prisma/models/User' +``` + +## File Extensions + +With `moduleResolution: "Node16"` or `"NodeNext"`, use `.js`/`.mjs`/`.cjs` extensions that match your emitted files. + +With `moduleResolution: "bundler"`, bare relative imports are usually fine. + +## Minimum Versions + +| Requirement | Minimum Version | +|-------------|-----------------| +| Node.js | 20.19.0 | +| TypeScript | 5.4.0 | + +## Framework Considerations + +### Next.js + +Next.js works well with the default ESM output. If you need generated types in client components, import them from `browser`, `models`, or `enums`, not from `client`. + +### Bun + +Bun loads `.env` files automatically, so ESM plus `env()` is the smoothest default. You can still choose `moduleFormat = "cjs"` if the rest of your project requires it. + +## Troubleshooting + +### "ERR_REQUIRE_ESM" + +Your generated client is ESM, but your app is requiring it as CommonJS. Either switch the project to ESM or set `moduleFormat = "cjs"` and regenerate. + +### "Cannot use import statement outside a module" + +Your app is still being executed as CommonJS. Add `"type": "module"` or use `moduleFormat = "cjs"` instead. + +### TypeScript compilation errors + +Ensure `module`, `moduleResolution`, and your generator's `moduleFormat` agree with one another. diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/prisma-config.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/prisma-config.md new file mode 100644 index 0000000..65b5128 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/prisma-config.md @@ -0,0 +1,203 @@ +# Prisma Config + +Prisma v7 introduces `prisma.config.ts` as the central configuration file for the Prisma CLI. + +## Location + +Place `prisma.config.ts` at your project root (next to `package.json`). + +## Basic Configuration + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## Configuration Options + +### schema + +Path to your Prisma schema file: + +```typescript +schema: 'prisma/schema.prisma' +``` + +### datasource.url + +Database connection URL: + +```typescript +datasource: { + url: env('DATABASE_URL'), +} +``` + +### datasource.directUrl + +Direct connection URL (bypassing connection pooler): + +```typescript +datasource: { + url: env('DATABASE_URL'), + directUrl: env('DIRECT_DATABASE_URL'), +} +``` + +### datasource.shadowDatabaseUrl + +Shadow database for migrations: + +```typescript +datasource: { + url: env('DATABASE_URL'), + shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), +} +``` + +### migrations.path + +Directory for migration files: + +```typescript +migrations: { + path: 'prisma/migrations', +} +``` + +### migrations.seed + +Seed command for `prisma db seed`: + +```typescript +migrations: { + path: 'prisma/migrations', + seed: 'tsx prisma/seed.ts', +} +``` + +## Full Example + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + // Schema location + schema: 'prisma/schema.prisma', + + // Migration configuration + migrations: { + path: 'prisma/migrations', + seed: 'tsx prisma/seed.ts', + }, + + // Database connection + datasource: { + url: env('DATABASE_URL'), + directUrl: env('DIRECT_DATABASE_URL'), + shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), + }, +}) +``` + +## Environment Variables + +### The env() helper + +Use `env()` to reference environment variables: + +```typescript +import { env } from 'prisma/config' + +datasource: { + url: env('DATABASE_URL'), +} +``` + +This provides type safety but does NOT load .env files automatically. + +### Loading .env files + +Install and import dotenv: + +```bash +npm install dotenv +``` + +```typescript +import 'dotenv/config' // Must be first import +import { defineConfig, env } from 'prisma/config' +``` + +## Migrating from v6 + +### Before (v6) - schema.prisma + +```prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directUrl = env("DIRECT_URL") +} +``` + +### After (v7) - prisma.config.ts + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: env('DATABASE_URL'), + directUrl: env('DIRECT_URL'), + }, +}) +``` + +And update schema.prisma: + +```prisma +datasource db { + provider = "postgresql" + // URLs now in prisma.config.ts +} +``` + +## Custom Config Path + +Use `--config` flag with CLI commands: + +```bash +prisma migrate dev --config ./config/prisma.config.ts +``` + +## Monorepo Configuration + +```typescript +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' +import path from 'path' + +export default defineConfig({ + schema: path.join(__dirname, 'packages/database/prisma/schema.prisma'), + migrations: { + path: path.join(__dirname, 'packages/database/prisma/migrations'), + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/removed-features.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/removed-features.md new file mode 100644 index 0000000..0d77eaf --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/removed-features.md @@ -0,0 +1,230 @@ +# Removed Features + +Several features have been removed in Prisma v7. Here's how to migrate. + +## Client Middleware + +### Removed + +```typescript +// ❌ No longer works in v7 +prisma.$use(async (params, next) => { + const before = Date.now() + const result = await next(params) + const after = Date.now() + console.log(`Query took ${after - before}ms`) + return result +}) +``` + +### Use Client Extensions Instead + +```typescript +// ✅ v7 approach +const prisma = new PrismaClient({ adapter }).$extends({ + query: { + $allModels: { + async $allOperations({ operation, model, args, query }) { + const before = Date.now() + const result = await query(args) + const after = Date.now() + console.log(`${model}.${operation} took ${after - before}ms`) + return result + }, + }, + }, +}) +``` + +### Common Middleware Patterns + +#### Soft delete + +```typescript +const prisma = new PrismaClient({ adapter }).$extends({ + query: { + user: { + async delete({ args, query }) { + // Convert delete to soft delete + return prisma.user.update({ + where: args.where, + data: { deletedAt: new Date() }, + }) + }, + async findMany({ args, query }) { + // Filter out soft-deleted records + args.where = { ...args.where, deletedAt: null } + return query(args) + }, + }, + }, +}) +``` + +#### Logging + +```typescript +const prisma = new PrismaClient({ adapter }).$extends({ + query: { + $allModels: { + async $allOperations({ operation, model, args, query }) { + console.log(`${model}.${operation}`, JSON.stringify(args)) + return query(args) + }, + }, + }, +}) +``` + +## Metrics + +### Removed + +The Metrics preview feature has been removed. + +```typescript +// ❌ No longer works +const metrics = await prisma.$metrics.json() +``` + +### Alternatives + +#### Custom counter with extensions + +```typescript +let totalQueries = 0 + +const prisma = new PrismaClient({ adapter }).$extends({ + client: { + async $totalQueries() { + return totalQueries + }, + }, + query: { + $allModels: { + async $allOperations({ query, args }) { + totalQueries += 1 + return query(args) + }, + }, + }, +}) + +// Usage +const count = await prisma.$totalQueries() +``` + +#### Use driver-level metrics + +Access metrics from the underlying driver adapter. + +## CLI Flags Removed + +### --skip-generate + +Removed from `migrate dev` and `db push`. + +```bash +# v6 +prisma migrate dev --skip-generate + +# v7 - generate is not run automatically +prisma migrate dev +prisma generate # Run explicitly if needed +``` + +Local verification with Prisma `7.6.0` showed no generated client files emitted by `migrate dev` or `db push`, even though some CLI help text still says `migrate dev` "trigger[s] generators". + +### --skip-seed + +Removed from `migrate dev`. More importantly, Prisma v7 no longer auto-runs seeds during `migrate dev` or `migrate reset`, so seed explicitly when you need it. + +```bash +# v6 +prisma migrate dev --skip-seed + +# v7 - seed is not run automatically +prisma migrate dev +prisma db seed # Run explicitly if needed +``` + +### --schema and --url from db execute + +```bash +# v6 +prisma db execute --file ./script.sql --url "$DATABASE_URL" + +# v7 - configure in prisma.config.ts +prisma db execute --file ./script.sql +``` + +## migrate diff Options + +| Removed | Replacement | +|---------|-------------| +| `--from-url` | `--from-config-datasource` | +| `--to-url` | `--to-config-datasource` | +| `--from-schema-datasource` | `--from-config-datasource` | +| `--to-schema-datasource` | `--to-config-datasource` | +| `--shadow-database-url` | Configure in `prisma.config.ts` | + +### Example + +```bash +# v6 +prisma migrate diff --from-url "$DATABASE_URL" --to-schema schema.prisma + +# v7 +prisma migrate diff --from-config-datasource --to-schema schema.prisma +``` + +## Automatic Behaviors Removed + +### Auto-generate after migrate + +```bash +# v7 workflow +prisma migrate dev --name add_field +prisma generate # Must run explicitly +``` + +### Auto-seed after migrate + +```bash +# v7 workflow +prisma migrate reset --force +prisma db seed # Must run explicitly +``` + +## Prisma.validator + +The `prisma-client` generator no longer exposes `Prisma.validator`. Use TypeScript's `satisfies` operator instead. + +```typescript +import { Prisma } from '../generated/prisma/client' + +const userSelect = { + id: true, + email: true, +} satisfies Prisma.UserSelect +``` + +## rejectOnNotFound + +Removed in v5.0.0 (already deprecated). + +```typescript +// ❌ Removed +const prisma = new PrismaClient({ + rejectOnNotFound: true, +}) + +// ✅ Use OrThrow methods +const user = await prisma.user.findUniqueOrThrow({ + where: { id: 1 }, +}) + +const user = await prisma.user.findFirstOrThrow({ + where: { email: 'test@example.com' }, +}) +``` diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/schema-changes.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/schema-changes.md new file mode 100644 index 0000000..6c817a5 --- /dev/null +++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/schema-changes.md @@ -0,0 +1,164 @@ +# Schema Changes + +Prisma v7 promotes `prisma-client` to the default generator. Update your generator block, output path, and imports accordingly. + +This guide is for projects that are actually migrating to Prisma 7. Do not apply these schema changes to MongoDB projects; keep those on Prisma 6.x. + +## Generator Block (v7) + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} +``` + +## Key Changes + +### 1. Provider name + +Use `prisma-client` in Prisma v7. The older `prisma-client-js` generator still exists in the repo for legacy setups, but `prisma-client` is the default path for current projects. + +### 2. Output is required + +The `output` field is mandatory when using `prisma-client`. Prisma Client no longer generates to `node_modules` with this generator. + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} +``` + +### 3. engineType changed + +Legacy Rust engine settings are gone. With `prisma-client`, the relevant value is `engineType = "client"` if you want to state it explicitly, although it is typically inferred and can be omitted. + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" + engineType = "client" +} +``` + +### 4. moduleFormat is explicit when needed + +If you must stay on CommonJS: + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" + moduleFormat = "cjs" +} +``` + +## Example Output Paths + +### Standard project + +```prisma +output = "../generated/prisma" +``` + +Creates files like: + +```text +generated/prisma/ + client.ts + browser.ts + enums.ts + models.ts + models/ +``` + +### Monorepo + +```prisma +output = "../../packages/database/generated/prisma" +``` + +### Same directory as schema + +```prisma +output = "./generated/prisma" +``` + +Creates: `prisma/generated/prisma/client.ts` + +## Datasource Block + +The `url`, `directUrl`, and `shadowDatabaseUrl` fields in the `datasource` block are deprecated in Prisma v7. Move them to `prisma.config.ts` and keep only the provider in `schema.prisma`: + +```prisma +datasource db { + provider = "postgresql" +} +``` + +```typescript +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + directUrl: env('DIRECT_URL'), + shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), + }, +}) +``` + +## After Schema Changes + +1. Run `prisma generate`: + ```bash + npx prisma generate + ``` + +2. Update imports throughout your codebase: + ```typescript + import { PrismaClient } from '../generated/prisma/client' + ``` + +3. Update `.gitignore` if you manage this manually: + ``` + /generated/prisma + ``` + +4. Replace `Prisma.validator()` with TypeScript `satisfies` when using `prisma-client`: + ```typescript + import { Prisma } from '../generated/prisma/client' + + const userSelect = { + id: true, + email: true, + } satisfies Prisma.UserSelect + ``` + +## Generated Entrypoints + +- `client` - server-side Prisma Client and Prisma namespace +- `browser` - browser-safe types and enums without a real `PrismaClient` +- `enums` - slim enum-only entrypoint +- `models` - model types and derived helper types + +## Preview Features + +Preview features still work as before: + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" + previewFeatures = ["relationJoins", "fullTextSearch"] +} +``` + +Recent preview-feature examples also include `partialIndexes` for PostgreSQL, SQLite, SQL Server, and CockroachDB: + +```prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" + previewFeatures = ["partialIndexes"] +} +``` diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 951c986..891ba73 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -18,4 +18,79 @@ EMAIL_SERVER_HOST="" EMAIL_SERVER_PORT="587" EMAIL_SERVER_USER="" EMAIL_SERVER_PASSWORD="" -EMAIL_FROM="Gruperly " \ No newline at end of file +EMAIL_FROM="Gruperly " + +# Mercado Pago (OAuth, Authorization Code + PKCE) +MP_CLIENT_ID="" +MP_CLIENT_SECRET="" +# Debe coincidir exactamente con la "Redirect URL" de la app en el panel de MP. +# El panel exige HTTPS (rechaza http://localhost): en local usá un túnel +# (p. ej. ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000) y cargá +# la URL del túnel acá y en el panel. +MP_REDIRECT_URI="" +# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM). +# Generar con: openssl rand -base64 32 +TOKEN_ENCRYPTION_KEY="" + +# Suscripción a Gruperly Pro (ver docs/billing.md). Argentina la cobra con +# Suscripciones de Mercado Pago; el resto de los países, con Stripe. +# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina (no +# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503). +MP_PLATFORM_ACCESS_TOKEN_AR="" +MP_PLATFORM_WEBHOOK_SECRET_AR="" +# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda +# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook +# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países. +STRIPE_SECRET_KEY="" +STRIPE_WEBHOOK_SECRET="" +# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro. +BILLING_ENFORCEMENT="off" +# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando. +BILLING_GRACE_DAYS="7" + +# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie. +ADMIN_EMAILS="" + +# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md). +# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta). +WHATSAPP_PROVIDER="openwa" +# Pausa entre dos envíos del mismo profesor, en ms (OpenWA recomienda < 15 msg/min). +WHATSAPP_SEND_INTERVAL_MS="5000" + +# OpenWA (se instala aparte). En local: docker run, ver docs/whatsapp.md. +OPENWA_API_URL="http://localhost:2785/api" +# Key OPERATOR sin allowedSessions, creada con la key ADMIN de /app/data/.api-key. +OPENWA_API_KEY="" +# Opcional. Sin webhook la vinculación funciona (el status hace polling), pero no +# llegan las confirmaciones de entrega/lectura. Si lo cargás, el secreto es obligatorio. +OPENWA_WEBHOOK_URL="" +# 16+ caracteres. Generar con: openssl rand -hex 24 +OPENWA_WEBHOOK_SECRET="" + +# Kapso (WHATSAPP_PROVIDER="kapso"). Las URLs tienen que ser públicas (túnel en local). +KAPSO_API_KEY="" +KAPSO_CALLBACK_URL="" +KAPSO_WEBHOOK_URL="" +# El mismo secreto del project webhook configurado en el dashboard de Kapso. +KAPSO_WEBHOOK_SECRET="" +# KAPSO_API_URL="https://api.kapso.ai" + +# App de alumnos (acceso sin contraseña por link de un solo uso; ver AGENTS.md). +# Comprobantes de pago: storage privado compatible con S3 (RustFS, MinIO, R2, AWS). +# Sin estas cuatro variables, "Informar pago" responde 503 storage_not_available. +S3_ENDPOINT="http://localhost:9000" +S3_BUCKET="gruperly-receipts" +S3_ACCESS_KEY_ID="" +S3_SECRET_ACCESS_KEY="" +S3_REGION="us-east-1" +# on = URLs estilo AWS (bucket.endpoint). RustFS/MinIO usan path-style: dejalo vacío. +S3_VIRTUAL_HOSTED="" +# Días que se guarda un comprobante después de que el profe lo revisó. 0 = para siempre. +RECEIPT_RETENTION_DAYS="0" +# WebAuthn (Face ID / huella del alumno). Por defecto salen de WEB_URL; cambialos +# solo si la web se sirve desde otro origen (p. ej. un túnel para probar en el teléfono). +# WEBAUTHN_RP_ID="localhost" +# WEBAUTHN_ORIGIN="http://localhost:6173" +# Proxies delante de la API que agregan X-Forwarded-For (1 = solo nginx; 2 = Traefik + nginx). +# Define qué IP cuenta para el rate limit de "Pedir un link a mi mail". +TRUSTED_PROXY_HOPS="1" diff --git a/apps/backend/docker-entrypoint.sh b/apps/backend/docker-entrypoint.sh new file mode 100755 index 0000000..d30ad75 --- /dev/null +++ b/apps/backend/docker-entrypoint.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Production entrypoint for the backend: applies the migrations and starts the +# server in the same container. +# +# This is POSIX sh, not bash: the image is alpine and does not ship bash +# installed (adding it would be ~10MB for a shebang). +# +# Set RUN_MIGRATIONS=false to start without touching the database (for example, +# a database already migrated by hand, or one managed outside this deployment). +set -e + +: "${DATABASE_URL:?falta DATABASE_URL}" + +if [ "${RUN_MIGRATIONS:-true}" = "false" ]; then + echo "migrate: omitido (RUN_MIGRATIONS=false)" +else + attempts="${MIGRATE_ATTEMPTS:-30}" + delay="${MIGRATE_RETRY_DELAY:-5}" + i=1 + + # The database may still be starting up when this container is already + # running, and a deploy usually overlaps a Postgres restart. + while [ "$i" -le "$attempts" ]; do + if bun run db:deploy; then + echo "migrate: listo" + break + fi + + if [ "$i" -eq "$attempts" ]; then + echo "migrate: fallo tras $attempts intentos; no se levanta el servidor" >&2 + exit 1 + fi + + echo "migrate: intento $i/$attempts fallo; reintento en ${delay}s" >&2 + i=$((i + 1)) + sleep "$delay" + done +fi + +# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop` +# (the server uses it to close Bun.serve and disconnect Prisma). +exec "$@" diff --git a/apps/backend/package.json b/apps/backend/package.json index a8cd5f6..acabfd0 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -9,11 +9,13 @@ "build": "prisma generate && tsc", "typecheck": "tsc --noEmit", "test": "bun test", + "test:db": "DB_TESTS=1 bun test test/db", "test:watch": "bun test --watch", "lint": "biome check .", "lint:fix": "biome check . --write", "db:generate": "prisma generate", "db:migrate": "prisma migrate dev", + "db:deploy": "prisma migrate deploy", "db:push": "prisma db push", "db:studio": "prisma studio" }, @@ -22,11 +24,15 @@ "@gruperly/shared": "workspace:*", "@prisma/adapter-pg": "^7.10.0", "@prisma/client": "^7.10.0", + "@simplewebauthn/server": "13.3.3", "better-auth": "1.7.2", + "dotenv": "^16.4.5", "hono": "^4.13.3", + "nanoid": "^3.3.19", "nodemailer": "^9.0.6", "pino": "^9.5.0", "pino-pretty": "^13.0.0", + "prisma": "^7.10.0", "zod": "3.24.2" }, "devDependencies": { @@ -35,8 +41,6 @@ "@types/bun": "^1.4.0", "@types/node": "^20.17.0", "@types/nodemailer": "^8.0.1", - "dotenv": "^16.4.5", - "prisma": "^7.10.0", "typescript": "^5.7.0" } } \ No newline at end of file diff --git a/apps/backend/prisma/migrations/20260917120000_rename_student_to_attendee/migration.sql b/apps/backend/prisma/migrations/20260917120000_rename_student_to_attendee/migration.sql new file mode 100644 index 0000000..377bea5 --- /dev/null +++ b/apps/backend/prisma/migrations/20260917120000_rename_student_to_attendee/migration.sql @@ -0,0 +1,16 @@ +-- Rename Student model (students table) to Attendee (attendees table) + +-- AlterTable +ALTER TABLE "students" RENAME TO "attendees"; + +-- AlterTable +ALTER TABLE "payments" RENAME COLUMN "studentId" TO "attendeeId"; + +-- RenameIndex +ALTER INDEX "students_groupId_idx" RENAME TO "attendees_groupId_idx"; + +-- RenameIndex +ALTER INDEX "payments_studentId_idx" RENAME TO "payments_attendeeId_idx"; + +-- RenameForeignKey +ALTER TABLE "payments" RENAME CONSTRAINT "payments_studentId_fkey" TO "payments_attendeeId_fkey"; \ No newline at end of file diff --git a/apps/backend/prisma/migrations/20260918123119_add_onboarding_complete/migration.sql b/apps/backend/prisma/migrations/20260918123119_add_onboarding_complete/migration.sql new file mode 100644 index 0000000..084b0f7 --- /dev/null +++ b/apps/backend/prisma/migrations/20260918123119_add_onboarding_complete/migration.sql @@ -0,0 +1,45 @@ +-- CreateEnum +CREATE TYPE "WeekDay" AS ENUM ('MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'); + +-- CreateEnum +CREATE TYPE "BillingType" AS ENUM ('MONTHLY', 'PER_CLASS'); + +-- CreateEnum +CREATE TYPE "PaymentProvider" AS ENUM ('MERCADO_PAGO', 'STRIPE'); + +-- AlterTable +ALTER TABLE "attendees" RENAME CONSTRAINT "students_pkey" TO "attendees_pkey"; + +-- AlterTable +ALTER TABLE "groups" ADD COLUMN "billingType" "BillingType", +ADD COLUMN "capacity" INTEGER, +ADD COLUMN "days" "WeekDay"[], +ADD COLUMN "dueDay" INTEGER, +ADD COLUMN "price" DECIMAL(10,2), +ADD COLUMN "time" TEXT; + +-- AlterTable +ALTER TABLE "users" ADD COLUMN "onboardingCompleted" BOOLEAN NOT NULL DEFAULT false; + +-- CreateTable +CREATE TABLE "merchant_accounts" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "provider" "PaymentProvider" NOT NULL, + "accessToken" TEXT, + "sandbox" BOOLEAN NOT NULL DEFAULT true, + "connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "merchant_accounts_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "merchant_accounts_userId_key" ON "merchant_accounts"("userId"); + +-- RenameForeignKey +ALTER TABLE "attendees" RENAME CONSTRAINT "students_groupId_fkey" TO "attendees_groupId_fkey"; + +-- AddForeignKey +ALTER TABLE "merchant_accounts" ADD CONSTRAINT "merchant_accounts_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/migrations/20260918130000_add_group_invite_token/migration.sql b/apps/backend/prisma/migrations/20260918130000_add_group_invite_token/migration.sql new file mode 100644 index 0000000..13b84c6 --- /dev/null +++ b/apps/backend/prisma/migrations/20260918130000_add_group_invite_token/migration.sql @@ -0,0 +1,5 @@ +-- AlterTable +ALTER TABLE "groups" ADD COLUMN "inviteToken" TEXT; + +-- CreateIndex +CREATE UNIQUE INDEX "groups_inviteToken_key" ON "groups"("inviteToken"); diff --git a/apps/backend/prisma/migrations/20260922191756_add_group_waitlist/migration.sql b/apps/backend/prisma/migrations/20260922191756_add_group_waitlist/migration.sql new file mode 100644 index 0000000..a1dc578 --- /dev/null +++ b/apps/backend/prisma/migrations/20260922191756_add_group_waitlist/migration.sql @@ -0,0 +1,23 @@ +-- CreateTable +CREATE TABLE "group_waitlist_entries" ( + "id" TEXT NOT NULL, + "groupId" TEXT NOT NULL, + "fullName" TEXT NOT NULL, + "phone" TEXT NOT NULL, + "email" TEXT, + "notes" TEXT, + "status" "WaitlistStatus" NOT NULL DEFAULT 'PENDING', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "group_waitlist_entries_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "group_waitlist_entries_groupId_idx" ON "group_waitlist_entries"("groupId"); + +-- CreateIndex +CREATE UNIQUE INDEX "group_waitlist_entries_groupId_phone_key" ON "group_waitlist_entries"("groupId", "phone"); + +-- AddForeignKey +ALTER TABLE "group_waitlist_entries" ADD CONSTRAINT "group_waitlist_entries_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql b/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql new file mode 100644 index 0000000..6384f24 --- /dev/null +++ b/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql @@ -0,0 +1,68 @@ +-- CreateEnum +CREATE TYPE "AttendanceStatus" AS ENUM ('PRESENT', 'ABSENT', 'EXCUSED'); + +-- AlterTable +ALTER TABLE "attendees" ADD COLUMN "notifyToken" TEXT; + +-- CreateTable +CREATE TABLE "class_sessions" ( + "id" TEXT NOT NULL, + "groupId" TEXT NOT NULL, + "startsAt" TIMESTAMP(3) NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "class_sessions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "attendances" ( + "id" TEXT NOT NULL, + "attendeeId" TEXT NOT NULL, + "classSessionId" TEXT NOT NULL, + "status" "AttendanceStatus" NOT NULL, + "markedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "attendances_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "slot_releases" ( + "id" TEXT NOT NULL, + "attendeeId" TEXT NOT NULL, + "classSessionId" TEXT NOT NULL, + "isClaimed" BOOLEAN NOT NULL DEFAULT false, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "slot_releases_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "class_sessions_groupId_startsAt_key" ON "class_sessions"("groupId", "startsAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "attendances_attendeeId_classSessionId_key" ON "attendances"("attendeeId", "classSessionId"); + +-- CreateIndex +CREATE UNIQUE INDEX "slot_releases_attendeeId_classSessionId_key" ON "slot_releases"("attendeeId", "classSessionId"); + +-- CreateIndex +CREATE UNIQUE INDEX "attendees_notifyToken_key" ON "attendees"("notifyToken"); + +-- AddForeignKey +ALTER TABLE "class_sessions" ADD CONSTRAINT "class_sessions_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "attendances" ADD CONSTRAINT "attendances_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "attendances" ADD CONSTRAINT "attendances_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- Backfill: tokens de aviso de ausencia para alumnos existentes +UPDATE "attendees" SET "notifyToken" = gen_random_uuid()::text WHERE "notifyToken" IS NULL; diff --git a/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql b/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql new file mode 100644 index 0000000..66cabe9 --- /dev/null +++ b/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql @@ -0,0 +1,5 @@ +-- CreateEnum +CREATE TYPE "AttendeeStatus" AS ENUM ('ACTIVE', 'PAUSED', 'DROPPED'); + +-- AlterTable +ALTER TABLE "attendees" ADD COLUMN "status" "AttendeeStatus" NOT NULL DEFAULT 'ACTIVE'; diff --git a/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql b/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql new file mode 100644 index 0000000..1c25d68 --- /dev/null +++ b/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql @@ -0,0 +1,26 @@ +-- CreateEnum +CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED'); + +-- CreateTable +CREATE TABLE "group_pre_registrations" ( + "id" TEXT NOT NULL, + "groupId" TEXT NOT NULL, + "fullName" TEXT NOT NULL, + "phone" TEXT NOT NULL, + "email" TEXT, + "status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING', + "reviewedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId"); + +-- CreateIndex +CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone"); + +-- AddForeignKey +ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/migrations/20261001162911_snake_case_columns/migration.sql b/apps/backend/prisma/migrations/20261001162911_snake_case_columns/migration.sql new file mode 100644 index 0000000..5204a2a --- /dev/null +++ b/apps/backend/prisma/migrations/20261001162911_snake_case_columns/migration.sql @@ -0,0 +1,128 @@ +-- Rename camelCase columns to snake_case without recreating them or losing data. + +-- accounts +ALTER TABLE "accounts" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "accounts" RENAME COLUMN "providerId" TO "provider_id"; +ALTER TABLE "accounts" RENAME COLUMN "accountId" TO "account_id"; +ALTER TABLE "accounts" RENAME COLUMN "accessToken" TO "access_token"; +ALTER TABLE "accounts" RENAME COLUMN "refreshToken" TO "refresh_token"; +ALTER TABLE "accounts" RENAME COLUMN "idToken" TO "id_token"; +ALTER TABLE "accounts" RENAME COLUMN "accessTokenExpiresAt" TO "access_token_expires_at"; +ALTER TABLE "accounts" RENAME COLUMN "refreshTokenExpiresAt" TO "refresh_token_expires_at"; +ALTER TABLE "accounts" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "accounts" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- attendances +ALTER TABLE "attendances" RENAME COLUMN "attendeeId" TO "attendee_id"; +ALTER TABLE "attendances" RENAME COLUMN "classSessionId" TO "class_session_id"; +ALTER TABLE "attendances" RENAME COLUMN "markedAt" TO "marked_at"; + +-- attendees +ALTER TABLE "attendees" RENAME COLUMN "groupId" TO "group_id"; +ALTER TABLE "attendees" RENAME COLUMN "fullName" TO "full_name"; +ALTER TABLE "attendees" RENAME COLUMN "guardianName" TO "guardian_name"; +ALTER TABLE "attendees" RENAME COLUMN "guardianPhone" TO "guardian_phone"; +ALTER TABLE "attendees" RENAME COLUMN "notifyToken" TO "notify_token"; +ALTER TABLE "attendees" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "attendees" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- class_sessions +ALTER TABLE "class_sessions" RENAME COLUMN "groupId" TO "group_id"; +ALTER TABLE "class_sessions" RENAME COLUMN "startsAt" TO "starts_at"; +ALTER TABLE "class_sessions" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "class_sessions" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- group_members +ALTER TABLE "group_members" RENAME COLUMN "groupId" TO "group_id"; +ALTER TABLE "group_members" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "group_members" RENAME COLUMN "joinedAt" TO "joined_at"; + +-- group_pre_registrations +ALTER TABLE "group_pre_registrations" RENAME COLUMN "groupId" TO "group_id"; +ALTER TABLE "group_pre_registrations" RENAME COLUMN "fullName" TO "full_name"; +ALTER TABLE "group_pre_registrations" RENAME COLUMN "reviewedAt" TO "reviewed_at"; +ALTER TABLE "group_pre_registrations" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "group_pre_registrations" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- group_waitlist_entries +ALTER TABLE "group_waitlist_entries" RENAME COLUMN "groupId" TO "group_id"; +ALTER TABLE "group_waitlist_entries" RENAME COLUMN "fullName" TO "full_name"; +ALTER TABLE "group_waitlist_entries" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "group_waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- groups +ALTER TABLE "groups" RENAME COLUMN "billingType" TO "billing_type"; +ALTER TABLE "groups" RENAME COLUMN "dueDay" TO "due_day"; +ALTER TABLE "groups" RENAME COLUMN "inviteToken" TO "invite_token"; +ALTER TABLE "groups" RENAME COLUMN "createdById" TO "created_by_id"; +ALTER TABLE "groups" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "groups" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- invitations +ALTER TABLE "invitations" RENAME COLUMN "organizationId" TO "organization_id"; +ALTER TABLE "invitations" RENAME COLUMN "inviterId" TO "inviter_id"; +ALTER TABLE "invitations" RENAME COLUMN "expiresAt" TO "expires_at"; +ALTER TABLE "invitations" RENAME COLUMN "createdAt" TO "created_at"; + +-- members +ALTER TABLE "members" RENAME COLUMN "organizationId" TO "organization_id"; +ALTER TABLE "members" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "members" RENAME COLUMN "createdAt" TO "created_at"; + +-- merchant_accounts +ALTER TABLE "merchant_accounts" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "merchant_accounts" RENAME COLUMN "accessToken" TO "access_token"; +ALTER TABLE "merchant_accounts" RENAME COLUMN "connectedAt" TO "connected_at"; +ALTER TABLE "merchant_accounts" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "merchant_accounts" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- organizations +ALTER TABLE "organizations" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "organizations" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- passkeys +ALTER TABLE "passkeys" RENAME COLUMN "publicKey" TO "public_key"; +ALTER TABLE "passkeys" RENAME COLUMN "credentialID" TO "credential_id"; +ALTER TABLE "passkeys" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "passkeys" RENAME COLUMN "deviceType" TO "device_type"; +ALTER TABLE "passkeys" RENAME COLUMN "backedUp" TO "backed_up"; +ALTER TABLE "passkeys" RENAME COLUMN "createdAt" TO "created_at"; + +-- payments +ALTER TABLE "payments" RENAME COLUMN "groupId" TO "group_id"; +ALTER TABLE "payments" RENAME COLUMN "attendeeId" TO "attendee_id"; +ALTER TABLE "payments" RENAME COLUMN "dueDate" TO "due_date"; +ALTER TABLE "payments" RENAME COLUMN "paidAt" TO "paid_at"; +ALTER TABLE "payments" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "payments" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- sessions +ALTER TABLE "sessions" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "sessions" RENAME COLUMN "expiresAt" TO "expires_at"; +ALTER TABLE "sessions" RENAME COLUMN "ipAddress" TO "ip_address"; +ALTER TABLE "sessions" RENAME COLUMN "userAgent" TO "user_agent"; +ALTER TABLE "sessions" RENAME COLUMN "activeOrganizationId" TO "active_organization_id"; +ALTER TABLE "sessions" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "sessions" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- slot_releases +ALTER TABLE "slot_releases" RENAME COLUMN "attendeeId" TO "attendee_id"; +ALTER TABLE "slot_releases" RENAME COLUMN "classSessionId" TO "class_session_id"; +ALTER TABLE "slot_releases" RENAME COLUMN "isClaimed" TO "is_claimed"; +ALTER TABLE "slot_releases" RENAME COLUMN "createdAt" TO "created_at"; + +-- users +ALTER TABLE "users" RENAME COLUMN "emailVerified" TO "email_verified"; +ALTER TABLE "users" RENAME COLUMN "onboardingCompleted" TO "onboarding_completed"; +ALTER TABLE "users" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "users" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- verifications +ALTER TABLE "verifications" RENAME COLUMN "expiresAt" TO "expires_at"; +ALTER TABLE "verifications" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "verifications" RENAME COLUMN "updatedAt" TO "updated_at"; + +-- waitlist_entries +ALTER TABLE "waitlist_entries" RENAME COLUMN "userId" TO "user_id"; +ALTER TABLE "waitlist_entries" RENAME COLUMN "createdAt" TO "created_at"; +ALTER TABLE "waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at"; diff --git a/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql b/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql new file mode 100644 index 0000000..dd94bf1 --- /dev/null +++ b/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql @@ -0,0 +1,56 @@ +-- Mercado Pago OAuth (Authorization Code + PKCE). Replaces the simulated +-- payment setup, where a fake access token was stored in plaintext. + +-- CreateEnum +CREATE TYPE "MpAccountStatus" AS ENUM ('ACTIVE', 'REQUIRES_REAUTH', 'REVOKED'); + +-- CreateTable +CREATE TABLE "mp_accounts" ( + "id" TEXT NOT NULL, + "owner_id" TEXT NOT NULL, + "mp_user_id" TEXT NOT NULL, + "access_token_enc" TEXT NOT NULL, + "refresh_token_enc" TEXT NOT NULL, + "expires_at" TIMESTAMP(3) NOT NULL, + "scope" TEXT, + "live_mode" BOOLEAN NOT NULL DEFAULT false, + "status" "MpAccountStatus" NOT NULL DEFAULT 'ACTIVE', + "connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "mp_accounts_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "mp_oauth_states" ( + "state" TEXT NOT NULL, + "owner_id" TEXT NOT NULL, + "code_verifier" TEXT NOT NULL, + "return_to" TEXT NOT NULL, + "expires_at" TIMESTAMP(3) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "mp_oauth_states_pkey" PRIMARY KEY ("state") +); + +-- CreateIndex +CREATE INDEX "mp_accounts_status_expiresAt_idx" ON "mp_accounts"("status", "expires_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "mp_accounts_ownerId_key" ON "mp_accounts"("owner_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "mp_accounts_mpUserId_key" ON "mp_accounts"("mp_user_id"); + +-- CreateIndex +CREATE INDEX "mp_oauth_states_expiresAt_idx" ON "mp_oauth_states"("expires_at"); + +-- AddForeignKey +ALTER TABLE "mp_accounts" ADD CONSTRAINT "mp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- DropTable +DROP TABLE "merchant_accounts"; + +-- DropEnum +DROP TYPE "PaymentProvider"; diff --git a/apps/backend/prisma/migrations/20261007120000_add_country_and_payment_links/migration.sql b/apps/backend/prisma/migrations/20261007120000_add_country_and_payment_links/migration.sql new file mode 100644 index 0000000..18e8659 --- /dev/null +++ b/apps/backend/prisma/migrations/20261007120000_add_country_and_payment_links/migration.sql @@ -0,0 +1,13 @@ +-- Country of the professor (onboarding) + Mercado Pago Checkout Pro payment links. + +-- AlterTable (users) +ALTER TABLE "users" ADD COLUMN "country_code" TEXT; + +-- AlterTable (payments) +ALTER TABLE "payments" ADD COLUMN "description" TEXT; +ALTER TABLE "payments" ADD COLUMN "checkout_url" TEXT; +ALTER TABLE "payments" ADD COLUMN "mp_preference_id" TEXT; +ALTER TABLE "payments" ADD COLUMN "mp_payment_id" TEXT; + +-- CreateIndex +CREATE UNIQUE INDEX "payments_mp_preference_id_key" ON "payments"("mp_preference_id"); \ No newline at end of file diff --git a/apps/backend/prisma/migrations/20261021233531_add_whatsapp_messaging/migration.sql b/apps/backend/prisma/migrations/20261021233531_add_whatsapp_messaging/migration.sql new file mode 100644 index 0000000..733ad96 --- /dev/null +++ b/apps/backend/prisma/migrations/20261021233531_add_whatsapp_messaging/migration.sql @@ -0,0 +1,129 @@ +-- WhatsApp messaging: linked accounts (provider-agnostic), Kapso templates, +-- outbound message log and webhook dedupe; plus the per-group automation switches. + +-- CreateEnum +CREATE TYPE "MessagingProviderId" AS ENUM ('OPENWA', 'KAPSO'); + +-- CreateEnum +CREATE TYPE "WhatsappAccountStatus" AS ENUM ('PENDING', 'ACTIVE', 'DISCONNECTED'); + +-- CreateEnum +CREATE TYPE "WhatsappMessageKind" AS ENUM ('PAYMENT_REMINDER', 'REENGAGEMENT'); + +-- CreateEnum +CREATE TYPE "OutboundMessageStatus" AS ENUM ('QUEUED', 'SENT', 'DELIVERED', 'READ', 'FAILED', 'SKIPPED'); + +-- CreateEnum +CREATE TYPE "WhatsappTemplateStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'DISABLED'); + +-- AlterTable +ALTER TABLE "groups" ADD COLUMN "auto_payment_reminders" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "auto_reengagement" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable (pre-existing drift: the schema already declares this default) +ALTER TABLE "payments" ALTER COLUMN "currency" SET DEFAULT 'ARS'; + +-- CreateTable +CREATE TABLE "whatsapp_accounts" ( + "id" TEXT NOT NULL, + "owner_id" TEXT NOT NULL, + "provider" "MessagingProviderId" NOT NULL, + "status" "WhatsappAccountStatus" NOT NULL DEFAULT 'PENDING', + "external_id" TEXT, + "display_phone_number" TEXT, + "provider_data" JSONB, + "connected_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "whatsapp_accounts_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "whatsapp_templates" ( + "id" TEXT NOT NULL, + "account_id" TEXT NOT NULL, + "kind" "WhatsappMessageKind" NOT NULL, + "name" TEXT NOT NULL, + "language" TEXT NOT NULL, + "meta_template_id" TEXT, + "status" "WhatsappTemplateStatus" NOT NULL DEFAULT 'PENDING', + "rejected_reason" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "whatsapp_templates_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "outbound_messages" ( + "id" TEXT NOT NULL, + "owner_id" TEXT NOT NULL, + "group_id" TEXT NOT NULL, + "attendee_id" TEXT NOT NULL, + "payment_id" TEXT, + "kind" "WhatsappMessageKind" NOT NULL, + "provider" "MessagingProviderId" NOT NULL, + "period_key" TEXT NOT NULL, + "to_phone" TEXT NOT NULL, + "provider_message_id" TEXT, + "status" "OutboundMessageStatus" NOT NULL DEFAULT 'QUEUED', + "error_code" TEXT, + "error_message" TEXT, + "sent_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "outbound_messages_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "whatsapp_webhook_events" ( + "provider" "MessagingProviderId" NOT NULL, + "dedupe_key" TEXT NOT NULL, + "received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "whatsapp_webhook_events_pkey" PRIMARY KEY ("provider","dedupe_key") +); + +-- CreateIndex +CREATE UNIQUE INDEX "whatsapp_accounts_ownerId_key" ON "whatsapp_accounts"("owner_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "whatsapp_accounts_provider_externalId_key" ON "whatsapp_accounts"("provider", "external_id"); + +-- CreateIndex +CREATE INDEX "whatsapp_templates_status_idx" ON "whatsapp_templates"("status"); + +-- CreateIndex +CREATE UNIQUE INDEX "whatsapp_templates_accountId_kind_key" ON "whatsapp_templates"("account_id", "kind"); + +-- CreateIndex +CREATE INDEX "outbound_messages_attendeeId_kind_createdAt_idx" ON "outbound_messages"("attendee_id", "kind", "created_at"); + +-- CreateIndex +CREATE INDEX "outbound_messages_groupId_createdAt_idx" ON "outbound_messages"("group_id", "created_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "outbound_messages_kind_attendeeId_periodKey_key" ON "outbound_messages"("kind", "attendee_id", "period_key"); + +-- CreateIndex +CREATE UNIQUE INDEX "outbound_messages_provider_providerMessageId_key" ON "outbound_messages"("provider", "provider_message_id"); + +-- CreateIndex +CREATE INDEX "whatsapp_webhook_events_receivedAt_idx" ON "whatsapp_webhook_events"("received_at"); + +-- AddForeignKey +ALTER TABLE "whatsapp_accounts" ADD CONSTRAINT "whatsapp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "whatsapp_templates" ADD CONSTRAINT "whatsapp_templates_accountId_fkey" FOREIGN KEY ("account_id") REFERENCES "whatsapp_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_groupId_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_attendeeId_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_paymentId_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql b/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql new file mode 100644 index 0000000..826d695 --- /dev/null +++ b/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql @@ -0,0 +1,74 @@ +-- CreateEnum +CREATE TYPE "SubscriptionStatus" AS ENUM ('PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED'); + +-- AlterTable +ALTER TABLE "users" ADD COLUMN "plan_selected_at" TIMESTAMP(3); + +-- CreateTable +CREATE TABLE "billing_subscriptions" ( + "id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "country_code" TEXT NOT NULL, + "currency" TEXT NOT NULL, + "amount" DECIMAL(12,2) NOT NULL, + "payer_email" TEXT NOT NULL, + "mp_preapproval_id" TEXT, + "status" "SubscriptionStatus" NOT NULL DEFAULT 'PENDING', + "requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "authorized_at" TIMESTAMP(3), + "next_payment_date" TIMESTAMP(3), + "paid_through" TIMESTAMP(3), + "last_synced_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "billing_subscriptions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "billing_charges" ( + "id" TEXT NOT NULL, + "subscription_id" TEXT NOT NULL, + "mp_authorized_payment_id" TEXT NOT NULL, + "amount" DECIMAL(12,2) NOT NULL, + "currency" TEXT NOT NULL, + "status" TEXT NOT NULL, + "paid_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "billing_charges_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "billing_webhook_events" ( + "country_code" TEXT NOT NULL, + "dedupe_key" TEXT NOT NULL, + "received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "billing_webhook_events_pkey" PRIMARY KEY ("country_code","dedupe_key") +); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_subscriptions_userId_key" ON "billing_subscriptions"("user_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_subscriptions_mpPreapprovalId_key" ON "billing_subscriptions"("mp_preapproval_id"); + +-- CreateIndex +CREATE INDEX "billing_subscriptions_status_lastSyncedAt_idx" ON "billing_subscriptions"("status", "last_synced_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_charges_mpAuthorizedPaymentId_key" ON "billing_charges"("mp_authorized_payment_id"); + +-- CreateIndex +CREATE INDEX "billing_charges_subscriptionId_createdAt_idx" ON "billing_charges"("subscription_id", "created_at"); + +-- CreateIndex +CREATE INDEX "billing_webhook_events_receivedAt_idx" ON "billing_webhook_events"("received_at"); + +-- AddForeignKey +ALTER TABLE "billing_subscriptions" ADD CONSTRAINT "billing_subscriptions_userId_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "billing_charges" ADD CONSTRAINT "billing_charges_subscriptionId_fkey" FOREIGN KEY ("subscription_id") REFERENCES "billing_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/migrations/20261026120000_add_billing_providers/migration.sql b/apps/backend/prisma/migrations/20261026120000_add_billing_providers/migration.sql new file mode 100644 index 0000000..9f6504f --- /dev/null +++ b/apps/backend/prisma/migrations/20261026120000_add_billing_providers/migration.sql @@ -0,0 +1,26 @@ +-- Pro billing behind a provider port: Mercado Pago (AR) or Stripe (the rest). +-- Columns are renamed, not dropped, so existing Mercado Pago rows keep their ids. + +-- CreateEnum +CREATE TYPE "BillingProviderId" AS ENUM ('MERCADO_PAGO', 'STRIPE'); + +-- billing_subscriptions: provider + provider-neutral ids +ALTER TABLE "billing_subscriptions" ADD COLUMN "provider" "BillingProviderId" NOT NULL DEFAULT 'MERCADO_PAGO'; +ALTER TABLE "billing_subscriptions" ADD COLUMN "checkout_ref" TEXT; +ALTER TABLE "billing_subscriptions" RENAME COLUMN "mp_preapproval_id" TO "external_id"; +ALTER INDEX "billing_subscriptions_mpPreapprovalId_key" RENAME TO "billing_subscriptions_externalId_key"; +CREATE UNIQUE INDEX "billing_subscriptions_checkoutRef_key" ON "billing_subscriptions"("checkout_ref"); + +-- billing_charges: provider-neutral id and normalized status +ALTER TABLE "billing_charges" RENAME COLUMN "mp_authorized_payment_id" TO "external_id"; +ALTER INDEX "billing_charges_mpAuthorizedPaymentId_key" RENAME TO "billing_charges_externalId_key"; +UPDATE "billing_charges" +SET "status" = CASE + WHEN "status" = 'approved' THEN 'approved' + WHEN "status" IN ('rejected', 'cancelled', 'refunded', 'charged_back') THEN 'rejected' + ELSE 'pending' +END; + +-- billing_webhook_events: dedupe per sending account (`mp:` or `stripe`) +ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source"; +UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source"; diff --git a/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql b/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql new file mode 100644 index 0000000..cd6de18 --- /dev/null +++ b/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql @@ -0,0 +1,20 @@ +-- CreateEnum +CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT'); + +-- CreateTable +CREATE TABLE "attendee_alert_resolutions" ( + "id" TEXT NOT NULL, + "attendee_id" TEXT NOT NULL, + "kind" "StudentAlertKind" NOT NULL, + "signature" TEXT NOT NULL, + "resolved_by_id" TEXT NOT NULL, + "resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind"); + +-- AddForeignKey +ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/migrations/20261027212531_add_student_access/migration.sql b/apps/backend/prisma/migrations/20261027212531_add_student_access/migration.sql new file mode 100644 index 0000000..158166d --- /dev/null +++ b/apps/backend/prisma/migrations/20261027212531_add_student_access/migration.sql @@ -0,0 +1,248 @@ +-- CreateEnum +CREATE TYPE "StudentTokenKind" AS ENUM ('INVITATION', 'RECOVERY', 'EMAIL_CONFIRMATION'); + +-- CreateEnum +CREATE TYPE "WebauthnChallengePurpose" AS ENUM ('REGISTER', 'LOGIN'); + +-- CreateEnum +CREATE TYPE "AbsenceReason" AS ENUM ('HEALTH', 'TRAVEL', 'WORK_STUDY', 'OTHER'); + +-- CreateEnum +CREATE TYPE "ReportedPaymentStatus" AS ENUM ('REPORTED', 'CONFIRMED', 'REJECTED'); + +-- AlterTable +ALTER TABLE "users" ADD COLUMN "transfer_alias" TEXT, +ADD COLUMN "transfer_holder" TEXT; + +-- CreateTable +CREATE TABLE "student_accounts" ( + "id" TEXT NOT NULL, + "name" TEXT NOT NULL, + "recovery_email" TEXT, + "recovery_email_verified_at" TIMESTAMP(3), + "pending_recovery_email" TEXT, + "welcomed_at" TIMESTAMP(3), + "created_by_id" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "student_accounts_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "student_account_attendees" ( + "account_id" TEXT NOT NULL, + "attendee_id" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "student_account_attendees_pkey" PRIMARY KEY ("account_id","attendee_id") +); + +-- CreateTable +CREATE TABLE "student_access_tokens" ( + "id" TEXT NOT NULL, + "token_hash" TEXT NOT NULL, + "account_id" TEXT NOT NULL, + "kind" "StudentTokenKind" NOT NULL, + "email" TEXT, + "expires_at" TIMESTAMP(3) NOT NULL, + "used_at" TIMESTAMP(3), + "revoked_at" TIMESTAMP(3), + "created_by_id" TEXT, + "used_ip" TEXT, + "used_user_agent" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "student_access_tokens_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "student_sessions" ( + "id" TEXT NOT NULL, + "account_id" TEXT NOT NULL, + "token_hash" TEXT NOT NULL, + "device" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "last_used_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "expires_at" TIMESTAMP(3) NOT NULL, + "revoked_at" TIMESTAMP(3), + + CONSTRAINT "student_sessions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "student_passkeys" ( + "id" TEXT NOT NULL, + "account_id" TEXT NOT NULL, + "credential_id" TEXT NOT NULL, + "public_key" BYTEA NOT NULL, + "counter" INTEGER NOT NULL DEFAULT 0, + "transports" TEXT[], + "device" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "last_used_at" TIMESTAMP(3), + + CONSTRAINT "student_passkeys_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "student_webauthn_challenges" ( + "id" TEXT NOT NULL, + "challenge" TEXT NOT NULL, + "account_id" TEXT, + "purpose" "WebauthnChallengePurpose" NOT NULL, + "expires_at" TIMESTAMP(3) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "student_webauthn_challenges_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "rate_limit_events" ( + "id" TEXT NOT NULL, + "key" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "rate_limit_events_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "absence_notices" ( + "id" TEXT NOT NULL, + "attendee_id" TEXT NOT NULL, + "class_session_id" TEXT NOT NULL, + "account_id" TEXT, + "reason" "AbsenceReason", + "message" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "cancelled_at" TIMESTAMP(3), + + CONSTRAINT "absence_notices_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "reported_payments" ( + "id" TEXT NOT NULL, + "attendee_id" TEXT NOT NULL, + "group_id" TEXT NOT NULL, + "account_id" TEXT, + "total_amount" DECIMAL(10,2) NOT NULL, + "currency" TEXT NOT NULL, + "receipt_key" TEXT, + "receipt_mime" TEXT NOT NULL, + "receipt_name" TEXT NOT NULL, + "receipt_size" INTEGER NOT NULL, + "status" "ReportedPaymentStatus" NOT NULL DEFAULT 'REPORTED', + "reviewed_by_id" TEXT, + "reviewed_at" TIMESTAMP(3), + "rejection_reason" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "reported_payments_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "reported_payment_items" ( + "reported_payment_id" TEXT NOT NULL, + "payment_id" TEXT NOT NULL, + + CONSTRAINT "reported_payment_items_pkey" PRIMARY KEY ("reported_payment_id","payment_id") +); + +-- CreateIndex +CREATE INDEX "student_accounts_recovery_email_idx" ON "student_accounts"("recovery_email"); + +-- CreateIndex +CREATE INDEX "student_accounts_created_by_id_idx" ON "student_accounts"("created_by_id"); + +-- CreateIndex +CREATE INDEX "student_account_attendees_attendee_id_idx" ON "student_account_attendees"("attendee_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "student_access_tokens_token_hash_key" ON "student_access_tokens"("token_hash"); + +-- CreateIndex +CREATE INDEX "student_access_tokens_account_id_kind_idx" ON "student_access_tokens"("account_id", "kind"); + +-- CreateIndex +CREATE UNIQUE INDEX "student_sessions_token_hash_key" ON "student_sessions"("token_hash"); + +-- CreateIndex +CREATE INDEX "student_sessions_account_id_idx" ON "student_sessions"("account_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "student_passkeys_credential_id_key" ON "student_passkeys"("credential_id"); + +-- CreateIndex +CREATE INDEX "student_passkeys_account_id_idx" ON "student_passkeys"("account_id"); + +-- CreateIndex +CREATE INDEX "student_webauthn_challenges_expires_at_idx" ON "student_webauthn_challenges"("expires_at"); + +-- CreateIndex +CREATE INDEX "rate_limit_events_key_created_at_idx" ON "rate_limit_events"("key", "created_at"); + +-- CreateIndex +CREATE INDEX "absence_notices_attendee_id_class_session_id_idx" ON "absence_notices"("attendee_id", "class_session_id"); + +-- CreateIndex +CREATE INDEX "absence_notices_class_session_id_idx" ON "absence_notices"("class_session_id"); + +-- CreateIndex +CREATE INDEX "reported_payments_group_id_status_idx" ON "reported_payments"("group_id", "status"); + +-- CreateIndex +CREATE INDEX "reported_payments_attendee_id_idx" ON "reported_payments"("attendee_id"); + +-- CreateIndex +CREATE INDEX "reported_payment_items_payment_id_idx" ON "reported_payment_items"("payment_id"); + +-- AddForeignKey +ALTER TABLE "student_accounts" ADD CONSTRAINT "student_accounts_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_access_tokens" ADD CONSTRAINT "student_access_tokens_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_sessions" ADD CONSTRAINT "student_sessions_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_passkeys" ADD CONSTRAINT "student_passkeys_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_webauthn_challenges" ADD CONSTRAINT "student_webauthn_challenges_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_class_session_id_fkey" FOREIGN KEY ("class_session_id") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_reported_payment_id_fkey" FOREIGN KEY ("reported_payment_id") REFERENCES "reported_payments"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_payment_id_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- At most one active (not cancelled) absence notice per attendee and class. +-- Partial index: Prisma can't express it in the schema. +CREATE UNIQUE INDEX "absence_notices_active_attendee_class_key" ON "absence_notices"("attendee_id", "class_session_id") WHERE "cancelled_at" IS NULL; diff --git a/apps/backend/prisma/migrations/20261028120000_add_reported_payment_note/migration.sql b/apps/backend/prisma/migrations/20261028120000_add_reported_payment_note/migration.sql new file mode 100644 index 0000000..28c4ff1 --- /dev/null +++ b/apps/backend/prisma/migrations/20261028120000_add_reported_payment_note/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT; diff --git a/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql b/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql new file mode 100644 index 0000000..a67892f --- /dev/null +++ b/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql @@ -0,0 +1,182 @@ +-- A person (contact data, per teacher) can now be in several groups: `attendees` +-- becomes the membership and points to `people`. Existing attendees of the same +-- teacher with the same phone (digits only) are merged into one person, and +-- their student-app accounts into one account. + +-- All or nothing: a half-applied data migration cannot be retried. +BEGIN; + +-- CreateTable +CREATE TABLE "people" ( + "id" TEXT NOT NULL, + "created_by_id" TEXT NOT NULL, + "full_name" TEXT NOT NULL, + "email" TEXT, + "phone" TEXT, + "guardian_name" TEXT, + "guardian_phone" TEXT, + "notes" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "people_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "student_account_people" ( + "account_id" TEXT NOT NULL, + "person_id" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "student_account_people_pkey" PRIMARY KEY ("account_id","person_id") +); + +-- Grouping: same teacher + same phone digits. `group_rank` splits the (rare) +-- rows that already shared a phone inside one group, which the per-group unique +-- membership would reject: the extra ones become their own person. +CREATE TEMP TABLE "_attendee_keys" AS +SELECT + a."id" AS attendee_id, + a."group_id", + a."created_at", + g."created_by_id", + NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') AS phone_digits, + ROW_NUMBER() OVER ( + PARTITION BY g."created_by_id", a."group_id", NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') + ORDER BY a."created_at", a."id" + ) AS group_rank +FROM "attendees" a +JOIN "groups" g ON g."id" = a."group_id"; + +CREATE TEMP TABLE "_attendee_person" AS +SELECT + k.attendee_id, + k.created_by_id, + -- The person reuses the id of its oldest attendee. + FIRST_VALUE(k.attendee_id) OVER ( + PARTITION BY k.created_by_id, + CASE WHEN k.phone_digits IS NULL THEN k.attendee_id ELSE k.phone_digits || '#' || k.group_rank END + ORDER BY k.created_at, k.attendee_id + ) AS person_id, + (k.phone_digits IS NOT NULL AND k.group_rank > 1) AS phone_clash +FROM "_attendee_keys" k; + +INSERT INTO "people" ("id", "created_by_id", "full_name", "email", "phone", "guardian_name", "guardian_phone", "notes", "created_at", "updated_at") +SELECT + p.person_id, + MIN(p.created_by_id), + MIN(rep."full_name"), + (ARRAY_AGG(a."email" ORDER BY a."created_at") FILTER (WHERE a."email" IS NOT NULL))[1], + CASE WHEN BOOL_OR(p.phone_clash) THEN NULL ELSE NULLIF(TRIM(MIN(rep."phone")), '') END, + (ARRAY_AGG(a."guardian_name" ORDER BY a."created_at") FILTER (WHERE a."guardian_name" IS NOT NULL))[1], + (ARRAY_AGG(a."guardian_phone" ORDER BY a."created_at") FILTER (WHERE a."guardian_phone" IS NOT NULL))[1], + NULLIF(CONCAT_WS(E'\n\n', + STRING_AGG(DISTINCT NULLIF(TRIM(a."notes"), ''), E'\n\n'), + CASE WHEN BOOL_OR(p.phone_clash) THEN 'Teléfono: ' || MIN(rep."phone") END + ), ''), + MIN(a."created_at"), + CURRENT_TIMESTAMP +FROM "_attendee_person" p +JOIN "attendees" a ON a."id" = p.attendee_id +JOIN "attendees" rep ON rep."id" = p.person_id +GROUP BY p.person_id; + +-- AlterTable: attendees -> membership +ALTER TABLE "attendees" ADD COLUMN "person_id" TEXT; +UPDATE "attendees" a SET "person_id" = p.person_id FROM "_attendee_person" p WHERE p.attendee_id = a."id"; +ALTER TABLE "attendees" ALTER COLUMN "person_id" SET NOT NULL; + +-- Student accounts: link them to the person instead of the membership. +INSERT INTO "student_account_people" ("account_id", "person_id", "created_at") +SELECT sa."account_id", p.person_id, MIN(sa."created_at") +FROM "student_account_attendees" sa +JOIN "_attendee_person" p ON p.attendee_id = sa."attendee_id" +GROUP BY sa."account_id", p.person_id; + +-- A merged person may end up with several accounts: keep the one used most +-- recently (else the oldest) and fold the others into it. +CREATE TEMP TABLE "_account_merge" AS +WITH ranked AS ( + SELECT + sap."person_id", + sap."account_id", + ROW_NUMBER() OVER ( + PARTITION BY sap."person_id" + ORDER BY ( + SELECT MAX(s."last_used_at") FROM "student_sessions" s + WHERE s."account_id" = sap."account_id" AND s."revoked_at" IS NULL + ) DESC NULLS LAST, acc."created_at", acc."id" + ) AS rn + FROM "student_account_people" sap + JOIN "student_accounts" acc ON acc."id" = sap."account_id" +) +SELECT DISTINCT ON (d."account_id") d."account_id" AS old_id, k."account_id" AS keep_id +FROM ranked d +JOIN ranked k ON k."person_id" = d."person_id" AND k.rn = 1 +WHERE d.rn > 1 AND d."account_id" <> k."account_id" +ORDER BY d."account_id"; + +INSERT INTO "student_account_people" ("account_id", "person_id", "created_at") +SELECT m.keep_id, sap."person_id", sap."created_at" +FROM "student_account_people" sap +JOIN "_account_merge" m ON m.old_id = sap."account_id" +ON CONFLICT DO NOTHING; + +UPDATE "absence_notices" n SET "account_id" = m.keep_id FROM "_account_merge" m WHERE n."account_id" = m.old_id; +UPDATE "reported_payments" r SET "account_id" = m.keep_id FROM "_account_merge" m WHERE r."account_id" = m.old_id; + +UPDATE "student_accounts" k +SET "recovery_email" = o."recovery_email", "recovery_email_verified_at" = o."recovery_email_verified_at" +FROM "_account_merge" m +JOIN "student_accounts" o ON o."id" = m.old_id +WHERE k."id" = m.keep_id AND k."recovery_email" IS NULL AND o."recovery_email" IS NOT NULL; + +-- Sessions, tokens and passkeys of the folded accounts go with them (cascade); +-- their links are removed by hand because that FK is created further down. +DELETE FROM "student_account_people" WHERE "account_id" IN (SELECT old_id FROM "_account_merge"); +DELETE FROM "student_accounts" WHERE "id" IN (SELECT old_id FROM "_account_merge"); + +-- DropTable +DROP TABLE "student_account_attendees"; + +-- AlterTable +ALTER TABLE "attendees" + DROP COLUMN "full_name", + DROP COLUMN "email", + DROP COLUMN "phone", + DROP COLUMN "guardian_name", + DROP COLUMN "guardian_phone", + DROP COLUMN "notes"; + +-- CreateIndex +CREATE INDEX "people_created_by_id_idx" ON "people"("created_by_id"); + +-- One person per phone and teacher. Partial: Prisma does not model it. +CREATE UNIQUE INDEX "people_owner_phone_key" ON "people"("created_by_id", "phone") WHERE "phone" IS NOT NULL; + +-- CreateIndex +CREATE INDEX "student_account_people_person_id_idx" ON "student_account_people"("person_id"); + +-- CreateIndex +CREATE INDEX "attendees_person_id_idx" ON "attendees"("person_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "attendees_group_id_person_id_key" ON "attendees"("group_id", "person_id"); + +-- AddForeignKey +ALTER TABLE "people" ADD CONSTRAINT "people_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "attendees" ADD CONSTRAINT "attendees_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +DROP TABLE "_account_merge"; +DROP TABLE "_attendee_person"; +DROP TABLE "_attendee_keys"; + +COMMIT; diff --git a/apps/backend/prisma/migrations/20261103130000_add_user_locale/migration.sql b/apps/backend/prisma/migrations/20261103130000_add_user_locale/migration.sql new file mode 100644 index 0000000..ab20115 --- /dev/null +++ b/apps/backend/prisma/migrations/20261103130000_add_user_locale/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "users" ADD COLUMN "locale" TEXT; diff --git a/apps/backend/prisma/models/attendance.prisma b/apps/backend/prisma/models/attendance.prisma new file mode 100644 index 0000000..02f95e3 --- /dev/null +++ b/apps/backend/prisma/models/attendance.prisma @@ -0,0 +1,51 @@ +// Attendance & class sessions + +enum AttendanceStatus { + PRESENT + ABSENT + EXCUSED +} + +model ClassSession { + id String @id @default(cuid()) + groupId String @map("group_id") + startsAt DateTime @map("starts_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey") + attendances Attendance[] + slotReleases SlotRelease[] + absenceNotices AbsenceNotice[] + + @@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key") + @@map("class_sessions") +} + +model Attendance { + id String @id @default(cuid()) + attendeeId String @map("attendee_id") + classSessionId String @map("class_session_id") + status AttendanceStatus + markedAt DateTime @default(now()) @map("marked_at") + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "attendances_attendeeId_fkey") + classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "attendances_classSessionId_fkey") + + @@unique([attendeeId, classSessionId], map: "attendances_attendeeId_classSessionId_key") + @@map("attendances") +} + +model SlotRelease { + id String @id @default(cuid()) + attendeeId String @map("attendee_id") + classSessionId String @map("class_session_id") + isClaimed Boolean @default(false) @map("is_claimed") + createdAt DateTime @default(now()) @map("created_at") + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "slot_releases_attendeeId_fkey") + classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "slot_releases_classSessionId_fkey") + + @@unique([attendeeId, classSessionId], map: "slot_releases_attendeeId_classSessionId_key") + @@map("slot_releases") +} diff --git a/apps/backend/prisma/models/auth.prisma b/apps/backend/prisma/models/auth.prisma index cc10dc1..c7cc6eb 100644 --- a/apps/backend/prisma/models/auth.prisma +++ b/apps/backend/prisma/models/auth.prisma @@ -1,61 +1,75 @@ // Auth (Better Auth) - required tables model User { - id String @id @default(cuid()) - name String - email String @unique - emailVerified Boolean @default(false) - image String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + name String + email String @unique + emailVerified Boolean @default(false) @map("email_verified") + image String? + onboardingCompleted Boolean @default(false) @map("onboarding_completed") + country String? @map("country_code") + // UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device. + locale String? @map("locale") + // When the professor chose Free or Pro in the onboarding (mandatory step). + planSelectedAt DateTime? @map("plan_selected_at") + // Bank transfer details shown to students when they report a payment. + transferAlias String? @map("transfer_alias") + transferHolder String? @map("transfer_holder") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - accounts Account[] - sessions Session[] - passkeys Passkey[] - groupsMember GroupMember[] - groupsOwner Group[] @relation("OwnerGroups") - orgMemberships Member[] - orgInvitations Invitation[] @relation("InvitedBy") - waitlist WaitlistEntry[] + accounts Account[] + sessions Session[] + passkeys Passkey[] + groupsMember GroupMember[] + groupsOwner Group[] @relation("OwnerGroups") + orgMemberships Member[] + orgInvitations Invitation[] @relation("InvitedBy") + waitlist WaitlistEntry[] + mpAccount MpAccount? + whatsappAccount WhatsappAccount? + subscription BillingSubscription? + studentAccounts StudentAccount[] @relation("StudentAccountsCreated") + people Person[] @relation("OwnerPeople") @@map("users") } model Account { - id String @id @default(cuid()) - userId String - providerId String - accountId String + id String @id @default(cuid()) + userId String @map("user_id") + providerId String @map("provider_id") + accountId String @map("account_id") issuer String - accessToken String? - refreshToken String? - idToken String? - accessTokenExpiresAt DateTime? - refreshTokenExpiresAt DateTime? + accessToken String? @map("access_token") + refreshToken String? @map("refresh_token") + idToken String? @map("id_token") + accessTokenExpiresAt DateTime? @map("access_token_expires_at") + refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at") scope String? password String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "accounts_userId_fkey") - @@unique([issuer, accountId]) - @@index([userId]) + @@unique([issuer, accountId], map: "accounts_issuer_accountId_key") + @@index([userId], map: "accounts_userId_idx") @@map("accounts") } model Session { id String @id @default(cuid()) - userId String + userId String @map("user_id") token String @unique - expiresAt DateTime - ipAddress String? - userAgent String? - activeOrganizationId String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + expiresAt DateTime @map("expires_at") + ipAddress String? @map("ip_address") + userAgent String? @map("user_agent") + activeOrganizationId String? @map("active_organization_id") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "sessions_userId_fkey") @@map("sessions") } @@ -64,9 +78,9 @@ model Verification { id String @id @default(cuid()) identifier String value String - expiresAt DateTime - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + expiresAt DateTime @map("expires_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") @@unique([identifier, value]) @@map("verifications") @@ -79,8 +93,8 @@ model Organization { slug String @unique logo String? metadata Json? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") members Member[] invitations Invitation[] @@ -90,32 +104,32 @@ model Organization { model Member { id String @id @default(cuid()) - organizationId String - userId String + organizationId String @map("organization_id") + userId String @map("user_id") role String @default("member") - createdAt DateTime @default(now()) + createdAt DateTime @default(now()) @map("created_at") - organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "members_organizationId_fkey") + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "members_userId_fkey") - @@unique([organizationId, userId]) + @@unique([organizationId, userId], map: "members_organizationId_userId_key") @@map("members") } model Invitation { id String @id @default(cuid()) - organizationId String + organizationId String @map("organization_id") email String role String status String @default("pending") - inviterId String - expiresAt DateTime - createdAt DateTime @default(now()) + inviterId String @map("inviter_id") + expiresAt DateTime @map("expires_at") + createdAt DateTime @default(now()) @map("created_at") - organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) - inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "invitations_organizationId_fkey") + inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade, map: "invitations_inviterId_fkey") - @@index([organizationId]) + @@index([organizationId], map: "invitations_organizationId_idx") @@map("invitations") } @@ -123,18 +137,18 @@ model Invitation { model Passkey { id String @id @default(cuid()) name String? - publicKey String - credentialID String @unique - userId String + publicKey String @map("public_key") + credentialID String @unique(map: "passkeys_credentialID_key") @map("credential_id") + userId String @map("user_id") counter Int - deviceType String - backedUp Boolean + deviceType String @map("device_type") + backedUp Boolean @map("backed_up") transports String? - createdAt DateTime @default(now()) + createdAt DateTime @default(now()) @map("created_at") aaguid String? - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "passkeys_userId_fkey") - @@index([userId]) + @@index([userId], map: "passkeys_userId_idx") @@map("passkeys") -} \ No newline at end of file +} diff --git a/apps/backend/prisma/models/billing.prisma b/apps/backend/prisma/models/billing.prisma new file mode 100644 index 0000000..895bab2 --- /dev/null +++ b/apps/backend/prisma/models/billing.prisma @@ -0,0 +1,82 @@ +// Gruperly's own billing: the professor pays a monthly Pro subscription, +// collected by Mercado Pago Subscriptions (preapproval, Argentina) or Stripe +// (every other country), see `modules/billing/providers/`. Not to be confused +// with `Payment`, which is what students pay the professor. + +enum BillingProviderId { + MERCADO_PAGO + STRIPE +} + +enum SubscriptionStatus { + PENDING + AUTHORIZED + PAUSED + CANCELLED +} + +model BillingSubscription { + id String @id @default(cuid()) + userId String @unique(map: "billing_subscriptions_userId_key") @map("user_id") + country String @map("country_code") + currency String + amount Decimal @db.Decimal(12, 2) + payerEmail String @map("payer_email") + // Who collects it. Sync and cancel always follow this, never the current country. + provider BillingProviderId @default(MERCADO_PAGO) + // The provider's subscription id (MP preapproval, Stripe subscription). Null + // until the provider creates it: right after MP answers, or once the + // professor completes Stripe Checkout. + externalId String? @unique(map: "billing_subscriptions_externalId_key") @map("external_id") + // Stripe Checkout Session of the current attempt; null for Mercado Pago. + checkoutRef String? @unique(map: "billing_subscriptions_checkoutRef_key") @map("checkout_ref") + status SubscriptionStatus @default(PENDING) + // When the current attempt started: re-subscribing reuses the row. + requestedAt DateTime @default(now()) @map("requested_at") + authorizedAt DateTime? @map("authorized_at") + nextPaymentDate DateTime? @map("next_payment_date") + // Last day covered by an approved charge. Pro lasts until then plus the grace + // period, even after a cancellation or a failed renewal. + paidThrough DateTime? @map("paid_through") + lastSyncedAt DateTime? @map("last_synced_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "billing_subscriptions_userId_fkey") + charges BillingCharge[] + + // The reconciliation job walks PENDING and stale AUTHORIZED rows. + @@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx") + @@map("billing_subscriptions") +} + +// One monthly invoice of a subscription (MP authorized payment, Stripe invoice). +model BillingCharge { + id String @id @default(cuid()) + subscriptionId String @map("subscription_id") + externalId String @unique(map: "billing_charges_externalId_key") @map("external_id") + amount Decimal @db.Decimal(12, 2) + currency String + // Normalized across providers: approved, pending or rejected. + status String + paidAt DateTime? @map("paid_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey") + + @@index([subscriptionId, createdAt], map: "billing_charges_subscriptionId_createdAt_idx") + @@map("billing_charges") +} + +// Deduplication of billing webhook deliveries, per sending account: `mp:` +// (one Mercado Pago account per country) or `stripe`. +model BillingWebhookEvent { + source String @map("source") + dedupeKey String @map("dedupe_key") + receivedAt DateTime @default(now()) @map("received_at") + + @@id([source, dedupeKey], map: "billing_webhook_events_pkey") + @@index([receivedAt], map: "billing_webhook_events_receivedAt_idx") + @@map("billing_webhook_events") +} diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index 1b13f2c..3dacdf2 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -1,32 +1,62 @@ // Domain models model Group { - id String @id @default(cuid()) - name String - description String? - createdById String - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + name String + description String? + days WeekDay[] + time String? + capacity Int? + price Decimal? @db.Decimal(10, 2) + billingType BillingType? @map("billing_type") + dueDay Int? @map("due_day") + // Weekly WhatsApp automations, off until the teacher turns them on. + autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders") + autoReengagement Boolean @default(false) @map("auto_reengagement") + inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token") + createdById String @map("created_by_id") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade) - members GroupMember[] - students Student[] - payments Payment[] + owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey") + members GroupMember[] + attendees Attendee[] + payments Payment[] + waitlist GroupWaitlistEntry[] + preRegistrations GroupPreRegistration[] + classSessions ClassSession[] + outboundMessages OutboundMessage[] + reportedPayments ReportedPayment[] @@map("groups") } +enum WeekDay { + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY + SUNDAY +} + +enum BillingType { + MONTHLY + PER_CLASS +} + model GroupMember { - id String @id @default(cuid()) - groupId String - userId String - role Role @default(MEMBER) // OWNER, ADMIN, MEMBER - joinedAt DateTime @default(now()) + id String @id @default(cuid()) + groupId String @map("group_id") + userId String @map("user_id") + role Role @default(MEMBER) // OWNER, ADMIN, MEMBER + joinedAt DateTime @default(now()) @map("joined_at") - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_members_groupId_fkey") + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "group_members_userId_fkey") - @@unique([groupId, userId]) + @@unique([groupId, userId], map: "group_members_groupId_userId_key") @@map("group_members") } @@ -36,42 +66,109 @@ enum Role { MEMBER } -model Student { - id String @id @default(cuid()) - groupId String - fullName String - email String? - phone String? - guardianName String? - guardianPhone String? - notes String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt +enum AttendeeStatus { + ACTIVE + PAUSED + DROPPED +} - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) - payments Payment[] +// A person the teacher works with (student, or the guardian's child). Contact +// data lives here once; `Attendee` is their membership in each group, so one +// person can be in several groups of the same teacher. The phone is unique per +// teacher through a hand-written partial index (`people_owner_phone_key`, +// `WHERE phone IS NOT NULL`): Prisma does not model it. +model Person { + id String @id @default(cuid()) + createdById String @map("created_by_id") + fullName String @map("full_name") + email String? + phone String? + guardianName String? @map("guardian_name") + guardianPhone String? @map("guardian_phone") + notes String? + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - @@index([groupId]) - @@map("students") + owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade) + attendees Attendee[] + studentAccounts StudentAccountPerson[] + + @@index([createdById]) + @@map("people") +} + +// Membership of a person in a group. Status, attendance, fees and the absence +// link (`notifyToken`) are per group. +model Attendee { + id String @id @default(cuid()) + groupId String @map("group_id") + personId String @map("person_id") + notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token") + status AttendeeStatus @default(ACTIVE) + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey") + person Person @relation(fields: [personId], references: [id], onDelete: Cascade) + payments Payment[] + attendances Attendance[] + slotReleases SlotRelease[] + outboundMessages OutboundMessage[] + alertResolutions AttendeeAlertResolution[] + absenceNotices AbsenceNotice[] + reportedPayments ReportedPayment[] + + @@unique([groupId, personId]) + @@index([groupId], map: "attendees_groupId_idx") + @@index([personId]) + @@map("attendees") +} + +enum StudentAlertKind { + ATTENDANCE + PAYMENT +} + +// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind: +// it hides the alert while its signature (last absence / overdue fees) stays +// the same, so a new absence or a new overdue fee brings it back on its own. +model AttendeeAlertResolution { + id String @id @default(cuid()) + attendeeId String @map("attendee_id") + kind StudentAlertKind + signature String + resolvedById String @map("resolved_by_id") + resolvedAt DateTime @default(now()) @map("resolved_at") + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) + + @@unique([attendeeId, kind]) + @@map("attendee_alert_resolutions") } model Payment { - id String @id @default(cuid()) - groupId String - studentId String - amount Decimal @db.Decimal(10, 2) - currency String @default("MXN") - status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED - dueDate DateTime - paidAt DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + groupId String @map("group_id") + attendeeId String @map("attendee_id") + amount Decimal @db.Decimal(10, 2) + currency String @default("ARS") + status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED + dueDate DateTime @map("due_date") + description String? @map("description") + checkoutUrl String? @map("checkout_url") + mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id") + mpPaymentId String? @map("mp_payment_id") + paidAt DateTime? @map("paid_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) - student Student @relation(fields: [studentId], references: [id], onDelete: Cascade) + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey") + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey") + outboundMessages OutboundMessage[] + reportedItems ReportedPaymentItem[] - @@index([groupId]) - @@index([studentId]) + @@index([groupId], map: "payments_groupId_idx") + @@index([attendeeId], map: "payments_attendeeId_idx") @@map("payments") } @@ -83,24 +180,113 @@ enum PaymentStatus { } model WaitlistEntry { - id String @id @default(cuid()) + id String @id @default(cuid()) email String name String? status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - userId String? @unique + userId String? @unique(map: "waitlist_entries_userId_key") @map("user_id") - user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull, map: "waitlist_entries_userId_fkey") @@unique([email]) @@map("waitlist_entries") } +model GroupWaitlistEntry { + id String @id @default(cuid()) + groupId String @map("group_id") + fullName String @map("full_name") + phone String + email String? + notes String? + status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_waitlist_entries_groupId_fkey") + + @@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key") + @@index([groupId], map: "group_waitlist_entries_groupId_idx") + @@map("group_waitlist_entries") +} + enum WaitlistStatus { PENDING INVITED JOINED DECLINED -} \ No newline at end of file +} + +enum PreRegistrationStatus { + PENDING + APPROVED + REJECTED +} + +model GroupPreRegistration { + id String @id @default(cuid()) + groupId String @map("group_id") + fullName String @map("full_name") + phone String + email String? + status PreRegistrationStatus @default(PENDING) + reviewedAt DateTime? @map("reviewed_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey") + + @@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key") + @@index([groupId], map: "group_pre_registrations_groupId_idx") + @@map("group_pre_registrations") +} + +enum MpAccountStatus { + ACTIVE + REQUIRES_REAUTH + REVOKED +} + +// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE). +// Tokens are stored encrypted (AES-256-GCM); there is a single active account per +// teacher and a Mercado Pago user cannot be linked to two teachers. +model MpAccount { + id String @id @default(cuid()) + ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id") + mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id") + accessTokenEnc String @map("access_token_enc") + refreshTokenEnc String @map("refresh_token_enc") + expiresAt DateTime @map("expires_at") + scope String? + liveMode Boolean @default(false) @map("live_mode") + status MpAccountStatus @default(ACTIVE) + connectedAt DateTime @default(now()) @map("connected_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey") + + // The daily refresh job looks for ACTIVE accounts expiring within 30 days. + @@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx") + @@map("mp_accounts") +} + +// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE +// `code_verifier`. The `state` is the primary key because consuming it (deleting +// the row) is what makes it single use. +model MpOAuthState { + state String @id + ownerId String @map("owner_id") + codeVerifier String @map("code_verifier") + // Constrained to 'onboarding' | 'settings'; decides where the callback lands. + returnTo String @map("return_to") + expiresAt DateTime @map("expires_at") + createdAt DateTime @default(now()) @map("created_at") + + // Expired rows are swept on every new authorization request. + @@index([expiresAt], map: "mp_oauth_states_expiresAt_idx") + @@map("mp_oauth_states") +} diff --git a/apps/backend/prisma/models/student-access.prisma b/apps/backend/prisma/models/student-access.prisma new file mode 100644 index 0000000..0dd705b --- /dev/null +++ b/apps/backend/prisma/models/student-access.prisma @@ -0,0 +1,240 @@ +// Student access (attendees or their guardians), without passwords. +// +// The teacher sends a single-use invitation link over WhatsApp; consuming it +// creates a long sliding session on that device. Passkeys and a recovery email +// are optional and let the student get back in without the teacher. None of +// this goes through Better Auth: students have no mandatory email and their +// session must never pass the teacher's endpoints (separate cookie and +// middleware under /api/v1/student). + +// The person who signs in: the attendee or a guardian. Linked to one or more +// attendees (a guardian may have several children), always by the teacher. +model StudentAccount { + id String @id @default(cuid()) + name String + // Verified recovery email (the student loads it, optional). + recoveryEmail String? @map("recovery_email") + recoveryEmailVerifiedAt DateTime? @map("recovery_email_verified_at") + // Email waiting for its confirmation link; never used to recover. + pendingRecoveryEmail String? @map("pending_recovery_email") + // First sign-in done: the welcome screen is shown only once. + welcomedAt DateTime? @map("welcomed_at") + createdById String @map("created_by_id") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade) + people StudentAccountPerson[] + tokens StudentAccessToken[] + sessions StudentSession[] + passkeys StudentPasskey[] + challenges StudentWebauthnChallenge[] + absenceNotices AbsenceNotice[] + reportedPayments ReportedPayment[] + + @@index([recoveryEmail]) + @@index([createdById]) + @@map("student_accounts") +} + +// The account is linked to people, not to memberships: it sees every group the +// person is in (also the ones added later). A guardian may be linked to several +// children (N:N). +model StudentAccountPerson { + accountId String @map("account_id") + personId String @map("person_id") + createdAt DateTime @default(now()) @map("created_at") + + account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade) + person Person @relation(fields: [personId], references: [id], onDelete: Cascade) + + @@id([accountId, personId]) + @@index([personId]) + @@map("student_account_people") +} + +enum StudentTokenKind { + INVITATION + RECOVERY + EMAIL_CONFIRMATION +} + +// Link token. Only its SHA-256 is stored. Consuming it is a conditional update +// (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now()`), so the +// first device wins and the link dies. +model StudentAccessToken { + id String @id @default(cuid()) + tokenHash String @unique @map("token_hash") + accountId String @map("account_id") + kind StudentTokenKind + // EMAIL_CONFIRMATION only: the address being confirmed. + email String? + expiresAt DateTime @map("expires_at") + usedAt DateTime? @map("used_at") + // A new invitation revokes the account's pending tokens. + revokedAt DateTime? @map("revoked_at") + // Teacher who generated the invitation (null for recovery/confirmation). + createdById String? @map("created_by_id") + usedIp String? @map("used_ip") + usedUserAgent String? @map("used_user_agent") + createdAt DateTime @default(now()) @map("created_at") + + account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade) + + @@index([accountId, kind]) + @@map("student_access_tokens") +} + +// Long sliding session (90 days, renewed on use). The cookie carries the raw +// token; only its hash is stored. +model StudentSession { + id String @id @default(cuid()) + accountId String @map("account_id") + tokenHash String @unique @map("token_hash") + // Human readable, derived from the user agent ("iPhone · Safari"). + device String + createdAt DateTime @default(now()) @map("created_at") + lastUsedAt DateTime @default(now()) @map("last_used_at") + expiresAt DateTime @map("expires_at") + revokedAt DateTime? @map("revoked_at") + + account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade) + + @@index([accountId]) + @@map("student_sessions") +} + +model StudentPasskey { + id String @id @default(cuid()) + accountId String @map("account_id") + credentialId String @unique @map("credential_id") + publicKey Bytes @map("public_key") + counter Int @default(0) + transports String[] + device String + createdAt DateTime @default(now()) @map("created_at") + lastUsedAt DateTime? @map("last_used_at") + + account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade) + + @@index([accountId]) + @@map("student_passkeys") +} + +enum WebauthnChallengePurpose { + REGISTER + LOGIN +} + +// Pending WebAuthn challenge, single use (deleted when verified), 5 minutes. +model StudentWebauthnChallenge { + id String @id @default(cuid()) + challenge String + // Registration only: the signed-in account. Login is discoverable (no account). + accountId String? @map("account_id") + purpose WebauthnChallengePurpose + expiresAt DateTime @map("expires_at") + createdAt DateTime @default(now()) @map("created_at") + + account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: Cascade) + + @@index([expiresAt]) + @@map("student_webauthn_challenges") +} + +// Generic sliding-window rate limit: one row per hit, counted by key within +// the window (e.g. "recovery:email:", "recovery:ip:"). +model RateLimitEvent { + id String @id @default(cuid()) + key String + createdAt DateTime @default(now()) @map("created_at") + + @@index([key, createdAt]) + @@map("rate_limit_events") +} + +enum AbsenceReason { + HEALTH + TRAVEL + WORK_STUDY + OTHER +} + +// Absence notice from the student. It only marks the attendance as EXCUSED +// (which already doesn't count for the attendance risk rules); the teacher +// sees it. At most one active (not cancelled) notice per attendee and class: +// enforced by a partial unique index in the migration. +model AbsenceNotice { + id String @id @default(cuid()) + attendeeId String @map("attendee_id") + classSessionId String @map("class_session_id") + accountId String? @map("account_id") + reason AbsenceReason? + message String? + createdAt DateTime @default(now()) @map("created_at") + cancelledAt DateTime? @map("cancelled_at") + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) + classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade) + account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull) + + @@index([attendeeId, classSessionId]) + @@index([classSessionId]) + @@map("absence_notices") +} + +enum ReportedPaymentStatus { + REPORTED + CONFIRMED + REJECTED +} + +// Payment reported by the student with a receipt. It stays REPORTED until the +// teacher confirms it (the fees become PAID) or rejects it. `Payment.status` is +// not touched while REPORTED: the MP reconciliation and the overdue job keep +// working as before, and "Requiere atención" skips fees covered by a REPORTED +// report. +model ReportedPayment { + id String @id @default(cuid()) + attendeeId String @map("attendee_id") + groupId String @map("group_id") + accountId String? @map("account_id") + totalAmount Decimal @map("total_amount") @db.Decimal(10, 2) + currency String + // Private object key in the storage; null once the retention policy deletes it. + receiptKey String? @map("receipt_key") + receiptMime String @map("receipt_mime") + receiptName String @map("receipt_name") + receiptSize Int @map("receipt_size") + // Optional message from the student to the teacher. + note String? + status ReportedPaymentStatus @default(REPORTED) + reviewedById String? @map("reviewed_by_id") + reviewedAt DateTime? @map("reviewed_at") + rejectionReason String? @map("rejection_reason") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) + account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull) + items ReportedPaymentItem[] + + @@index([groupId, status]) + @@index([attendeeId]) + @@map("reported_payments") +} + +// Fees a report covers. A fee can't be in two REPORTED reports at once +// (checked in the use-case, inside the transaction). +model ReportedPaymentItem { + reportedPaymentId String @map("reported_payment_id") + paymentId String @map("payment_id") + + reportedPayment ReportedPayment @relation(fields: [reportedPaymentId], references: [id], onDelete: Cascade) + payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade) + + @@id([reportedPaymentId, paymentId]) + @@index([paymentId]) + @@map("reported_payment_items") +} diff --git a/apps/backend/prisma/models/whatsapp.prisma b/apps/backend/prisma/models/whatsapp.prisma new file mode 100644 index 0000000..e653073 --- /dev/null +++ b/apps/backend/prisma/models/whatsapp.prisma @@ -0,0 +1,130 @@ +// WhatsApp messaging (automated payment reminders and re-engagement). +// +// Nothing here is tied to one provider: the teacher links their own number +// through whichever `MessagingProvider` the server runs (OpenWA for the MVP, +// Kapso afterwards) and the row records which one it was linked with. Changing +// `WHATSAPP_PROVIDER` leaves the old rows behind as "requires reconnect". + +enum MessagingProviderId { + OPENWA + KAPSO +} + +enum WhatsappAccountStatus { + PENDING + ACTIVE + DISCONNECTED +} + +enum WhatsappMessageKind { + PAYMENT_REMINDER + REENGAGEMENT +} + +enum OutboundMessageStatus { + QUEUED + SENT + DELIVERED + READ + FAILED + SKIPPED +} + +enum WhatsappTemplateStatus { + PENDING + APPROVED + REJECTED + DISABLED +} + +// The teacher's linked WhatsApp. One per teacher. +model WhatsappAccount { + id String @id @default(cuid()) + ownerId String @unique(map: "whatsapp_accounts_ownerId_key") @map("owner_id") + provider MessagingProviderId + status WhatsappAccountStatus @default(PENDING) + // OpenWA: session id. Kapso: phone_number_id (null until the setup finishes). + externalId String? @map("external_id") + displayPhoneNumber String? @map("display_phone_number") + // Provider-specific identifiers (Kapso: customerId, setupLinkId, businessAccountId). + // Never secrets: API keys and webhook secrets live in the environment. + providerData Json? @map("provider_data") + connectedAt DateTime? @map("connected_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "whatsapp_accounts_ownerId_fkey") + templates WhatsappTemplate[] + + // A number (or session) cannot be linked to two teachers. + @@unique([provider, externalId], map: "whatsapp_accounts_provider_externalId_key") + @@map("whatsapp_accounts") +} + +// Message templates submitted to Meta for one account (Kapso only: OpenWA sends +// free text). Meta approves them per WhatsApp Business Account. +model WhatsappTemplate { + id String @id @default(cuid()) + accountId String @map("account_id") + kind WhatsappMessageKind + name String + language String + metaTemplateId String? @map("meta_template_id") + status WhatsappTemplateStatus @default(PENDING) + rejectedReason String? @map("rejected_reason") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + account WhatsappAccount @relation(fields: [accountId], references: [id], onDelete: Cascade, map: "whatsapp_templates_accountId_fkey") + + @@unique([accountId, kind], map: "whatsapp_templates_accountId_kind_key") + @@index([status], map: "whatsapp_templates_status_idx") + @@map("whatsapp_templates") +} + +// One automated message to one member. It is the send log and the idempotency +// key at once: the row is created before calling the provider, and the unique +// (kind, attendee, week) is what stops a second run of the weekly job from +// writing to the same person twice. +model OutboundMessage { + id String @id @default(cuid()) + ownerId String @map("owner_id") + groupId String @map("group_id") + attendeeId String @map("attendee_id") + paymentId String? @map("payment_id") + kind WhatsappMessageKind + provider MessagingProviderId + // ISO week the job ran for, e.g. "2026-W43". + periodKey String @map("period_key") + toPhone String @map("to_phone") + providerMessageId String? @map("provider_message_id") + status OutboundMessageStatus @default(QUEUED) + errorCode String? @map("error_code") + errorMessage String? @map("error_message") + sentAt DateTime? @map("sent_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey") + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey") + payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey") + + @@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key") + @@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key") + // Re-engagement cooldown: "was this member written to in the last 14 days?" + @@index([attendeeId, kind, createdAt], map: "outbound_messages_attendeeId_kind_createdAt_idx") + @@index([groupId, createdAt], map: "outbound_messages_groupId_createdAt_idx") + @@map("outbound_messages") +} + +// Webhook deliveries already processed. Both providers deliver at least once and +// retry, so the delivery's idempotency key is burned here before applying it. +model WhatsappWebhookEvent { + provider MessagingProviderId + dedupeKey String @map("dedupe_key") + receivedAt DateTime @default(now()) @map("received_at") + + @@id([provider, dedupeKey], map: "whatsapp_webhook_events_pkey") + @@index([receivedAt], map: "whatsapp_webhook_events_receivedAt_idx") + @@map("whatsapp_webhook_events") +} diff --git a/apps/backend/prisma/schema.prisma b/apps/backend/prisma/schema.prisma index 9415ac3..06c7663 100644 --- a/apps/backend/prisma/schema.prisma +++ b/apps/backend/prisma/schema.prisma @@ -7,4 +7,4 @@ generator client { datasource db { provider = "postgresql" -} \ No newline at end of file +} diff --git a/apps/backend/skills-lock.json b/apps/backend/skills-lock.json new file mode 100644 index 0000000..56573ed --- /dev/null +++ b/apps/backend/skills-lock.json @@ -0,0 +1,59 @@ +{ + "version": 1, + "skills": { + "prisma-cli": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-cli/SKILL.md", + "computedHash": "129e77cba93984b88d66cf0f66d5788f5487431f17f189a1ab2d839976874e3b" + }, + "prisma-client-api": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-client-api/SKILL.md", + "computedHash": "cbbabff961c8e16b2d59f8c1ffb4e7e20be52154e778ab95121e0211d6d09969" + }, + "prisma-compute": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-compute/SKILL.md", + "computedHash": "c84ca5f84cc5cfca9f8e2dada066b1833143d6f325f70c12a16746c3c4eee2ed" + }, + "prisma-database-setup": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-database-setup/SKILL.md", + "computedHash": "6a991a2530a6da7131e3fc71c353e8278702d0146b8b6e1d2fdfc2d3d0a21bd2" + }, + "prisma-driver-adapter-implementation": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-driver-adapter-implementation/SKILL.md", + "computedHash": "cc487f1bf36f616ddb3a9478b3527d288dd706d77a9e5dbee9af52dca1eee8e4" + }, + "prisma-mongodb-upgrade": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-mongodb-upgrade/SKILL.md", + "computedHash": "b94149ad5f1ec269dfd717b321538de6d39943b2ae6721a0d82302057f57ae18" + }, + "prisma-postgres": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-postgres/SKILL.md", + "computedHash": "0422727e18019add9208b86ce862964025acc011ff31fba1d59a01b836bd6272" + }, + "prisma-postgres-setup": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-postgres-setup/SKILL.md", + "computedHash": "5dbcf5a488d7cb7136340b86dcf781d6d92cf793f92c105ef644ac31ccac4d3b" + }, + "prisma-upgrade-v7": { + "source": "prisma/skills", + "sourceType": "github", + "skillPath": "prisma-upgrade-v7/SKILL.md", + "computedHash": "0e07dc2831f86cf27627df914db43d862b0fc75d72c1f9070434aab7940bad7c" + } + } +} diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 4faf921..3a064d7 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -10,12 +10,27 @@ import { requestLoggerMiddleware } from '@/http/request-logger'; import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers'; import { sessionAuthMiddleware } from '@/http/session-auth'; import { logger } from '@/logger'; +import { adminRoutes } from './modules/admin'; +import { + groupsRiskOverviewRoute, + studentStatusRoutes, +} from './modules/analytics'; +import { attendeesRoutes } from './modules/attendees'; +import { attentionRoutes } from './modules/attention'; import { authRoutes } from './modules/auth'; +import { billingRoutes, planReadOnlyMiddleware } from './modules/billing'; +import { classesRoutes } from './modules/classes'; import { groupsRoutes } from './modules/groups'; import { healthCheckRoutes } from './modules/health-check'; +import { homeRoutes } from './modules/home'; +import { invitationsRoutes } from './modules/invitations'; +import { mpRoutes } from './modules/mp'; +import { onboardingRoutes } from './modules/onboarding'; import { paymentsRoutes } from './modules/payments'; -import { studentsRoutes } from './modules/students'; +import { peopleRoutes } from './modules/people'; +import { studentPortalRoutes } from './modules/student-portal'; import { waitlistRoutes } from './modules/waitlist'; +import { whatsappRoutes } from './modules/whatsapp'; const app = new Hono(); @@ -30,12 +45,32 @@ const api = app.basePath('/api/v1'); api.use('*', sessionAuthMiddleware); +// Read-only accounts (Free over its limits) cannot write domain data. Billing, +// onboarding and the MP/WhatsApp links stay open: that is how they get out of it. +const planReadOnly = planReadOnlyMiddleware(); +for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/students', '/waitlist']) { + api.use(`${prefix}/*`, planReadOnly); +} + +api.route('/admin', adminRoutes); api.route('/auth', authRoutes); api.route('/health', healthCheckRoutes); +api.route('/invitations', invitationsRoutes); api.route('/groups', groupsRoutes); -api.route('/students', studentsRoutes); +api.route('/home', homeRoutes); +api.route('/onboarding', onboardingRoutes); +api.route('/mp', mpRoutes); +api.route('/whatsapp', whatsappRoutes); +api.route('/attendees', attendeesRoutes); api.route('/payments', paymentsRoutes); +api.route('/billing', billingRoutes); api.route('/waitlist', waitlistRoutes); +api.route('/classes', classesRoutes); +api.route('/students', studentStatusRoutes); +api.route('/groups-risk', groupsRiskOverviewRoute); +api.route('/attention', attentionRoutes); +api.route('/people', peopleRoutes); +api.route('/student-portal', studentPortalRoutes); app.notFound((c) => { return problemJson(c, notFoundProblem(c.req.path)); diff --git a/apps/backend/src/assets/logotipo-y-organica.png b/apps/backend/src/assets/logotipo-y-organica.png new file mode 100644 index 0000000..4179ead Binary files /dev/null and b/apps/backend/src/assets/logotipo-y-organica.png differ diff --git a/apps/backend/src/http/env.ts b/apps/backend/src/http/env.ts index d68d3d7..4e6288a 100644 --- a/apps/backend/src/http/env.ts +++ b/apps/backend/src/http/env.ts @@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth'; type AuthSession = typeof auth.$Infer.Session; +/** Signed-in student (attendee or guardian): set only on /student-portal. */ +export type StudentContext = { accountId: string; sessionId: string }; + export type BackendEnv = { Variables: { user: AuthSession['user'] | null; session: AuthSession['session'] | null; requestId: string; + student: StudentContext | null; }; }; @@ -15,5 +19,6 @@ declare module 'hono' { user: AuthSession['user'] | null; session: AuthSession['session'] | null; requestId: string; + student: StudentContext | null; } } \ No newline at end of file diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts index 1b63bd7..6db2820 100644 --- a/apps/backend/src/http/problem-builders.ts +++ b/apps/backend/src/http/problem-builders.ts @@ -21,6 +21,7 @@ export function conflictProblem(params: { detail: string; code?: string; instance?: string; + params?: ProblemDetails['params']; }): ProblemDetails { return { type: `${PROBLEM_DOMAIN}/problems/conflict`, @@ -29,6 +30,7 @@ export function conflictProblem(params: { detail: params.detail, instance: params.instance, code: params.code, + ...(params.params ? { params: params.params } : {}), }; } @@ -47,23 +49,6 @@ export function forbiddenProblem(params: { }; } -export function organizationNotFoundProblem(id: string): ProblemDetails { - return { - type: `${PROBLEM_DOMAIN}/problems/organization-not-found`, - title: 'Not Found', - status: 404, - detail: `Organization ${id} was not found.`, - code: 'organization_not_found', - }; -} - -export function groupOwnerRequiredProblem(): ProblemDetails { - return forbiddenProblem({ - detail: 'Only the organization owner can create the group.', - code: 'group_owner_required', - }); -} - export function databaseUnavailableProblem(params?: { instance?: string; }): ProblemDetails { @@ -86,4 +71,251 @@ export function noGroupAccessProblem(): ProblemDetails { export function notFoundResourceProblem(resourceName: string, id: string): ProblemDetails { return notFoundProblem(`${resourceName} ${id}`); -} \ No newline at end of file +} + +export function mpNotConnectedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'No tenés una cuenta de Mercado Pago vinculada.', + code: 'mp_not_connected', + }); +} + +export function mpRequiresReauthProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Tu cuenta de Mercado Pago necesita volver a vincularse.', + code: 'mp_requires_reauth', + }); +} + +export function mpAccountInUseProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.', + code: 'mp_account_in_use', + }); +} + +/** The server is missing MP_CLIENT_ID / MP_CLIENT_SECRET / MP_REDIRECT_URI. */ +export function mpNotConfiguredProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/mercadopago-not-configured`, + title: 'Service Unavailable', + status: 503, + detail: 'La vinculación con Mercado Pago no está disponible en este momento.', + code: 'mp_not_configured', + }; +} + +/** Mercado Pago refused the request, or could not be reached. */ +export function mpProviderErrorProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/mercadopago-unavailable`, + title: 'Bad Gateway', + status: 502, + detail: 'No pudimos completar la vinculación con Mercado Pago.', + code: 'mp_provider_error', + }; +} + +/** The server is missing the variables of the active WhatsApp provider. */ +export function whatsappNotConfiguredProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/whatsapp-not-configured`, + title: 'Service Unavailable', + status: 503, + detail: 'La vinculación con WhatsApp no está disponible en este momento.', + code: 'whatsapp_not_configured', + }; +} + +export function whatsappNotConnectedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'No tenés un WhatsApp vinculado.', + code: 'whatsapp_not_connected', + }); +} + +export function whatsappNumberInUseProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Ese número de WhatsApp ya está vinculado a otro profesor.', + code: 'whatsapp_number_in_use', + }); +} + +export function whatsappLinkingNotStartedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Empezá la vinculación de WhatsApp antes de pedir el código.', + code: 'whatsapp_linking_not_started', + }); +} + +/** The provider links by QR or redirect only (Kapso). */ +export function whatsappPairingUnsupportedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Este proveedor de WhatsApp no permite vincular con el número de teléfono.', + code: 'whatsapp_pairing_unsupported', + }); +} + +/** The session is not ready to hand out a code yet; retryable in seconds. */ +export function whatsappPairingNotReadyProblem(): ProblemDetails { + return conflictProblem({ + detail: 'WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.', + code: 'whatsapp_pairing_not_ready', + }); +} + +/** The WhatsApp gateway refused the request, or could not be reached. */ +export function whatsappProviderErrorProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/whatsapp-unavailable`, + title: 'Bad Gateway', + status: 502, + detail: 'No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos.', + code: 'whatsapp_provider_error', + }; +} + +export function onboardingAlreadyCompletedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Ya completaste el onboarding de Gruperly.', + code: 'onboarding_already_completed', + }); +} + +export function capacityReachedProblem(capacity: number | null): ProblemDetails { + return conflictProblem({ + detail: capacity + ? `El grupo alcanzó su cupo máximo de ${capacity} miembros.` + : 'El grupo alcanzó su cupo máximo de miembros.', + code: 'group_capacity_reached', + ...(capacity ? { params: { capacity } } : {}), + }); +} + +export function alreadyWaitlistedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Este número de teléfono ya está en la lista de espera del grupo.', + code: 'already_waitlisted', + }); +} + +export function attendeeHasPaymentsProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.', + code: 'attendee_has_payments', + }); +} + +export function groupWithoutPriceProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Definí el precio del grupo antes de generar los cobros.', + code: 'group_without_price', + }); +} + +export function noAttendeesToBillProblem(): ProblemDetails { + return conflictProblem({ + detail: 'No hay miembros activos con un cobro pendiente para este grupo.', + code: 'no_attendees_to_bill', + }); +} +function paymentRequiredProblem(params: { + detail: string; + code: string; + params?: ProblemDetails['params']; +}): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/plan`, + title: 'Payment Required', + status: 402, + detail: params.detail, + code: params.code, + ...(params.params ? { params: params.params } : {}), + }; +} + +export type PlanLimitKind = 'groups' | 'attendees'; + +/** The Free plan does not allow one more group or attendee. */ +export function planLimitReachedProblem(limit: PlanLimitKind, max: number): ProblemDetails { + return paymentRequiredProblem({ + detail: + limit === 'groups' + ? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.` + : `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`, + code: 'plan_limit_reached', + params: { limit, max }, + }); +} + +/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */ +export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails { + return paymentRequiredProblem({ + detail: + feature === 'mpCharges' + ? 'Cobrar con Mercado Pago está disponible en el plan Pro.' + : 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.', + code: 'plan_feature_required', + params: { feature }, + }); +} + +/** Free plan with more usage than its limits: only reads and deletes. */ +export function planReadOnlyProblem(): ProblemDetails { + return paymentRequiredProblem({ + detail: + 'Tu cuenta está en solo lectura porque superás los límites del plan Free. Pasate a Pro o reducí el uso para volver a editar.', + code: 'plan_read_only', + }); +} + +/** The billing provider of the professor's country is not configured. */ +export function billingNotAvailableProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/billing-not-available`, + title: 'Service Unavailable', + status: 503, + detail: 'La suscripción a Pro todavía no está disponible en tu país.', + code: 'billing_not_available', + }; +} + +/** The billing provider (Mercado Pago or Stripe) refused the request, or could not be reached. */ +export function billingProviderErrorProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`, + title: 'Bad Gateway', + status: 502, + detail: 'No pudimos comunicarnos con el procesador de pagos. Intentá de nuevo en unos minutos.', + code: 'billing_provider_error', + }; +} + +/** Mercado Pago makes the payer log in with this exact email, so it cannot be left out. */ +export function payerEmailRequiredProblem(): ProblemDetails { + return validationProblem({ + detail: 'Ingresá el email de tu cuenta de Mercado Pago.', + errors: { payerEmail: ['Ingresá el email de tu cuenta de Mercado Pago.'] }, + }); +} + +export function subscriptionAlreadyActiveProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Ya tenés una suscripción a Pro activa.', + code: 'subscription_already_active', + }); +} + +export function noActiveSubscriptionProblem(): ProblemDetails { + return conflictProblem({ + detail: 'No tenés una suscripción para cancelar.', + code: 'no_active_subscription', + }); +} + +export function planNotSelectedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Elegí un plan antes de crear tu primer grupo.', + code: 'plan_not_selected', + }); +} diff --git a/apps/backend/src/http/security-headers.ts b/apps/backend/src/http/security-headers.ts index a659b24..83b3ba4 100644 --- a/apps/backend/src/http/security-headers.ts +++ b/apps/backend/src/http/security-headers.ts @@ -14,7 +14,7 @@ export const corsMiddleware: MiddlewareHandler = honoCors({ return ''; }, allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], - allowHeaders: ['Content-Type', 'Authorization'], + allowHeaders: ['Content-Type', 'Authorization', 'Cache-Control'], maxAge: 600, credentials: true, }); diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts index fe459df..cf0c3f7 100644 --- a/apps/backend/src/http/session-auth.ts +++ b/apps/backend/src/http/session-auth.ts @@ -27,10 +27,39 @@ export function isPublicApiRequest(method: string, path: string): boolean { const normalizedPath = normalizePath(path); + // Absence notice sent with the attendee's personal token (no session). + if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') { + return true; + } + if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') { + return true; + } + // WhatsApp provider webhooks: no session, authenticated by their HMAC signature. + if ( + method === 'POST' + && (normalizedPath === '/api/v1/whatsapp/webhooks/openwa' + || normalizedPath === '/api/v1/whatsapp/webhooks/kapso') + ) { + return true; + } + // Mercado Pago notifications about Pro subscriptions, one URL per country: + // no session, authenticated by Mercado Pago's `x-signature`. + if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) { + return true; + } + // Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`. + if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') { + return true; + } + return ( normalizedPath === '/api/v1/health' || matchesPublicPrefix(normalizedPath, '/api/v1/auth') || matchesPublicPrefix(normalizedPath, '/api/auth') + || matchesPublicPrefix(normalizedPath, '/api/v1/invitations') + // Student app: its own cookie and middleware (modules/student-portal), never + // the teacher's session. + || matchesPublicPrefix(normalizedPath, '/api/v1/student-portal') ); } @@ -39,5 +68,8 @@ function matchesPublicPrefix(path: string, prefix: string): boolean { } function normalizePath(path: string): string { - return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path; + const withoutQuery = path.split('?')[0]?.split('#')[0] ?? path; + return withoutQuery.length > 1 && withoutQuery.endsWith('/') + ? withoutQuery.slice(0, -1) + : withoutQuery; } \ No newline at end of file diff --git a/apps/backend/src/lib/email.ts b/apps/backend/src/lib/email.ts index e2269e9..dd62ad2 100644 --- a/apps/backend/src/lib/email.ts +++ b/apps/backend/src/lib/email.ts @@ -1,13 +1,61 @@ +import { readFileSync } from 'node:fs' import nodemailer, { type Transporter } from 'nodemailer' type VerificationEmailData = { email: string; url: string; name?: string } type PasswordResetEmailData = { email: string; url: string; name?: string } type InvitationEmailData = { email: string; url: string; organizationName: string } +type StudentEmailConfirmationData = { email: string; url: string; name: string } +type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] } +type StudentPaymentReviewedData = { + email: string + name: string + confirmed: boolean + amount: string + reason?: string | null +} -interface EmailProvider { +// Brand colors (same system as the web app: index.css in apps/web). +const BRAND_600 = '#2544ea' +const TEXT_STRONG = '#0f172a' +const TEXT_MUTED = '#475569' +const ON_ACCENT = '#ffffff' +const LINK_BG = BRAND_600 + +// Logo embedded as a data URI so the emails don't depend on hosting. +function loadLogoTypoDataUri(): string { + try { + const base64 = readFileSync( + new URL('../assets/logotipo-y-organica.png', import.meta.url), + ).toString('base64') + return `data:image/png;base64,${base64}` + } catch { + return '' + } +} + +const LOGO_DATA_URI = loadLogoTypoDataUri() + +export interface EmailProvider { sendVerificationEmail(data: VerificationEmailData): Promise sendPasswordResetEmail(data: PasswordResetEmailData): Promise sendOrganizationInvitation(data: InvitationEmailData): Promise + sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise + sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise + sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise +} + +// Names come from what teachers and students type: never raw into the HTML. +function escapeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +function button(url: string, label: string): string { + return `${escapeHtml(label)}` } class SMTPEmailProvider implements EmailProvider { @@ -30,17 +78,21 @@ class SMTPEmailProvider implements EmailProvider { } private layout(title: string, body: string) { + const header = LOGO_DATA_URI + ? `Gruperly` + : '

Gruperly

' + return ` -
-

Gruperly

-

${title}

-

${body}

+
+
${header}
+

${title}

+

${body}

` } private async send(to: string, subject: string, html: string) { - // Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso + // With no SMTP configured (dev) the flow still doesn't break: it only logs a warning if (!process.env.EMAIL_SERVER_HOST) { console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`) return @@ -49,7 +101,7 @@ class SMTPEmailProvider implements EmailProvider { } async sendVerificationEmail({ email, url, name }: VerificationEmailData) { - const link = `Verificar email` + const link = `Verificar email` await this.send( email, 'Verifica tu email en Gruperly', @@ -61,7 +113,7 @@ class SMTPEmailProvider implements EmailProvider { } async sendPasswordResetEmail({ email, url, name }: PasswordResetEmailData) { - const link = `Restablecer contraseña` + const link = `Restablecer contraseña` await this.send( email, 'Restablece tu contraseña en Gruperly', @@ -73,7 +125,7 @@ class SMTPEmailProvider implements EmailProvider { } async sendOrganizationInvitation({ email, url, organizationName }: InvitationEmailData) { - const link = `Unirme a ${organizationName}` + const link = `Unirme a ${organizationName}` await this.send( email, `Te invitaron a ${organizationName} en Gruperly`, @@ -83,10 +135,51 @@ class SMTPEmailProvider implements EmailProvider { ), ) } + + async sendStudentEmailConfirmation({ email, url, name }: StudentEmailConfirmationData) { + await this.send( + email, + 'Confirmá tu mail de recuperación en Gruperly', + this.layout( + 'Confirmá tu mail', + `Hola ${escapeHtml(name)}, confirmá este mail para poder pedir un link de ingreso si perdés el acceso a la app (el enlace vence en 24 horas). Si no fuiste vos, ignorá este mail.

${button(url, 'Confirmar mail')}`, + ), + ) + } + + async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) { + // A guardian may have one account per child with the same email: one button each. + const buttons = links + .map((link) => + links.length > 1 + ? `

${escapeHtml(link.name)}

${button(link.url, 'Ingresar')}` + : button(link.url, 'Ingresar'), + ) + .join('
') + await this.send( + email, + 'Tu link para ingresar a Gruperly', + this.layout( + 'Tu link de ingreso', + `Pediste un link para volver a entrar. Sirve una sola vez y vence en 15 minutos. Si no fuiste vos, ignorá este mail.

${buttons}`, + ), + ) + } + + async sendStudentPaymentReviewed({ email, name, confirmed, amount, reason }: StudentPaymentReviewedData) { + const body = confirmed + ? `Hola ${escapeHtml(name)}, tu profe confirmó el pago de ${escapeHtml(amount)}. ¡Gracias!` + : `Hola ${escapeHtml(name)}, tu profe no pudo confirmar el pago de ${escapeHtml(amount)}.${reason ? `

Motivo: ${escapeHtml(reason)}` : ''}

Podés volver a informarlo desde la app.` + await this.send( + email, + confirmed ? 'Tu pago fue confirmado' : 'Tu pago no fue confirmado', + this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body), + ) + } } -// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark). -// Añadir implementaciones y alternar con EMAIL_PROVIDER. +// Future: transactional providers (Resend, SendGrid, Postmark). +// Add implementations and switch between them with EMAIL_PROVIDER. export function createEmailProvider(): EmailProvider { return new SMTPEmailProvider() } diff --git a/apps/backend/src/lib/file-type.ts b/apps/backend/src/lib/file-type.ts new file mode 100644 index 0000000..23bc7fa --- /dev/null +++ b/apps/backend/src/lib/file-type.ts @@ -0,0 +1,36 @@ +/* Real type of an uploaded file from its first bytes (magic numbers), never + from the name or the Content-Type the browser claims. */ + +export type ReceiptMime = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/heic' | 'application/pdf'; + +export const RECEIPT_MAX_BYTES = 10 * 1024 * 1024; + +export const RECEIPT_EXTENSIONS: Record = { + 'image/jpeg': 'jpg', + 'image/png': 'png', + 'image/webp': 'webp', + 'image/heic': 'heic', + 'application/pdf': 'pdf', +}; + +// ISO-BMFF brands used by HEIC/HEIF photos (iPhone camera). +const HEIF_BRANDS = new Set(['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1']); + +function ascii(bytes: Uint8Array, start: number, length: number): string { + return String.fromCharCode(...bytes.subarray(start, start + length)); +} + +export function detectReceiptType(bytes: Uint8Array): ReceiptMime | null { + if (bytes.length < 12) return null; + if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'; + if ( + bytes[0] === 0x89 && ascii(bytes, 1, 3) === 'PNG' + && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a + ) { + return 'image/png'; + } + if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'image/webp'; + if (ascii(bytes, 4, 4) === 'ftyp' && HEIF_BRANDS.has(ascii(bytes, 8, 4))) return 'image/heic'; + if (ascii(bytes, 0, 5) === '%PDF-') return 'application/pdf'; + return null; +} diff --git a/apps/backend/src/lib/storage.ts b/apps/backend/src/lib/storage.ts new file mode 100644 index 0000000..bd8612c --- /dev/null +++ b/apps/backend/src/lib/storage.ts @@ -0,0 +1,54 @@ +import { S3Client } from 'bun'; + +/* Private file storage (payment receipts). Behind a port, like the WhatsApp and + billing providers: the use-cases never talk to S3 directly, and the tests + inject an in-memory fake. Objects are never public; the teacher sees them + through short-lived signed URLs. */ +export interface FileStorage { + put(key: string, body: Uint8Array, contentType: string): Promise; + /** GET URL valid for `expiresInSeconds`. */ + signedUrl(key: string, expiresInSeconds: number): string; + remove(key: string): Promise; +} + +/* Any S3-compatible service (RustFS, MinIO, R2, AWS). Path-style addressing by + default, which is what self-hosted services expect; S3_VIRTUAL_HOSTED=on for + AWS-style bucket subdomains. */ +class S3FileStorage implements FileStorage { + constructor(private readonly client: S3Client) {} + + async put(key: string, body: Uint8Array, contentType: string): Promise { + await this.client.write(key, body, { type: contentType }); + } + + signedUrl(key: string, expiresInSeconds: number): string { + return this.client.presign(key, { method: 'GET', expiresIn: expiresInSeconds }); + } + + async remove(key: string): Promise { + await this.client.delete(key); + } +} + +let storage: FileStorage | null | undefined; + +/** null when S3 isn't configured: the endpoints that need it answer 503. */ +export function getFileStorage(): FileStorage | null { + if (storage !== undefined) return storage; + const { S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY } = process.env; + if (!S3_ENDPOINT || !S3_BUCKET || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) { + storage = null; + return storage; + } + storage = new S3FileStorage( + new S3Client({ + endpoint: S3_ENDPOINT, + bucket: S3_BUCKET, + region: process.env.S3_REGION || 'us-east-1', + accessKeyId: S3_ACCESS_KEY_ID, + secretAccessKey: S3_SECRET_ACCESS_KEY, + virtualHostedStyle: process.env.S3_VIRTUAL_HOSTED === 'on', + }), + ); + return storage; +} diff --git a/apps/backend/src/modules/admin/features/get-account/route.ts b/apps/backend/src/modules/admin/features/get-account/route.ts new file mode 100644 index 0000000..5ec9959 --- /dev/null +++ b/apps/backend/src/modules/admin/features/get-account/route.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { GetAccount } from './use-case'; + +const route = new Hono(); + +route.get('/accounts/:accountId', async (c) => { + const result = await new GetAccount().execute(c.req.param('accountId')); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/admin/features/get-account/use-case.ts b/apps/backend/src/modules/admin/features/get-account/use-case.ts new file mode 100644 index 0000000..fab9353 --- /dev/null +++ b/apps/backend/src/modules/admin/features/get-account/use-case.ts @@ -0,0 +1,95 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok, PLAN_LIMITS } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib'; +import { accountPlan, toAccountListItem } from '../../lib'; + +const RECENT_CHARGES = 12; + +type GetAccountDeps = { + db?: Pick; + enforced?: boolean; + graceDays?: number; + now?: () => Date; +}; + +/** One professor's account: plan, links, groups and the latest Pro charges. */ +export class GetAccount { + constructor(private readonly deps: GetAccountDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const context = { + now: this.deps.now?.() ?? new Date(), + graceDays: this.deps.graceDays ?? getGraceDays(), + }; + + const user = await db.user.findUnique({ + where: { id: userId }, + include: { + subscription: true, + mpAccount: { select: { status: true } }, + whatsappAccount: { select: { status: true } }, + groupsOwner: { + select: { + id: true, + name: true, + createdAt: true, + _count: { select: { attendees: { where: { status: 'ACTIVE' } } } }, + }, + orderBy: { createdAt: 'desc' }, + }, + }, + }); + if (!user) return err(notFoundResourceProblem('User', userId)); + + const charges = await db.billingCharge.findMany({ + where: { subscription: { userId } }, + orderBy: { createdAt: 'desc' }, + take: RECENT_CHARGES, + }); + + const groups = user.groupsOwner.map((group) => ({ + id: group.id, + name: group.name, + createdAt: group.createdAt.toISOString(), + attendeesCount: group._count.attendees, + })); + const usage = { + groupsCount: groups.length, + attendeesCount: groups.reduce((sum, group) => sum + group.attendeesCount, 0), + }; + const summary = toAccountListItem(user, usage, context); + const { graceUntil } = accountPlan(user, context); + const enforced = this.deps.enforced ?? isBillingEnforced(); + const subscription = user.subscription; + + return ok({ + ...summary, + planSelectedAt: user.planSelectedAt?.toISOString() ?? null, + graceUntil: graceUntil?.toISOString() ?? null, + // Same rule as the PlanGuard: an account without a plan is held to Free. + readOnly: + enforced + && exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], { + groups: usage.groupsCount, + attendees: usage.attendeesCount, + }), + subscription: + summary.subscription && subscription + ? { + ...summary.subscription, + payerEmail: subscription.payerEmail, + authorizedAt: subscription.authorizedAt?.toISOString() ?? null, + requestedAt: subscription.requestedAt.toISOString(), + } + : null, + mpStatus: user.mpAccount?.status ?? null, + whatsappStatus: user.whatsappAccount?.status ?? null, + groups, + charges: charges.map(toBillingChargeDto), + }); + } +} diff --git a/apps/backend/src/modules/admin/features/list-accounts/route.ts b/apps/backend/src/modules/admin/features/list-accounts/route.ts new file mode 100644 index 0000000..f6cb10e --- /dev/null +++ b/apps/backend/src/modules/admin/features/list-accounts/route.ts @@ -0,0 +1,16 @@ +import type { AdminAccountQuery } from '@gruperly/shared'; +import { AdminAccountQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListAccounts } from './use-case'; + +const route = new Hono(); + +route.get('/accounts', validate.query(AdminAccountQuerySchema), async (c) => { + const query = c.req.valid('query') as AdminAccountQuery; + const result = await new ListAccounts().execute(query); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/admin/features/list-accounts/use-case.ts b/apps/backend/src/modules/admin/features/list-accounts/use-case.ts new file mode 100644 index 0000000..0343d35 --- /dev/null +++ b/apps/backend/src/modules/admin/features/list-accounts/use-case.ts @@ -0,0 +1,65 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AdminAccountList, AdminAccountQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; +import { getGraceDays } from '@/modules/billing/lib'; +import { type AccountUsage, buildAccountWhere, toAccountListItem } from '../../lib'; + +type ListAccountsDeps = { + db?: Pick; + graceDays?: number; + now?: () => Date; +}; + +/** Every professor's account, newest first, with plan and usage. */ +export class ListAccounts { + constructor(private readonly deps: ListAccountsDeps = {}) {} + + async execute(query: AdminAccountQuery): Promise> { + const db = this.deps.db ?? prisma; + const context = { + now: this.deps.now?.() ?? new Date(), + graceDays: this.deps.graceDays ?? getGraceDays(), + }; + const where = buildAccountWhere(query, context); + + const [users, total] = await Promise.all([ + db.user.findMany({ + where, + include: { subscription: true }, + skip: getPaginationOffset(query), + take: query.pageSize, + orderBy: { createdAt: 'desc' }, + }), + db.user.count({ where }), + ]); + + // Usage of the whole page in one query, same rule as the plan limits: + // groups the professor owns and their ACTIVE attendees. + const groups = users.length + ? await db.group.findMany({ + where: { createdById: { in: users.map((user) => user.id) } }, + select: { + createdById: true, + _count: { select: { attendees: { where: { status: 'ACTIVE' } } } }, + }, + }) + : []; + const usage = new Map(); + for (const group of groups) { + const current = usage.get(group.createdById) ?? { groupsCount: 0, attendeesCount: 0 }; + usage.set(group.createdById, { + groupsCount: current.groupsCount + 1, + attendeesCount: current.attendeesCount + group._count.attendees, + }); + } + + return ok({ + data: users.map((user) => + toAccountListItem(user, usage.get(user.id) ?? { groupsCount: 0, attendeesCount: 0 }, context), + ), + pagination: getPaginationMetadata(query, total), + }); + } +} diff --git a/apps/backend/src/modules/admin/features/me/route.ts b/apps/backend/src/modules/admin/features/me/route.ts new file mode 100644 index 0000000..f36974c --- /dev/null +++ b/apps/backend/src/modules/admin/features/me/route.ts @@ -0,0 +1,16 @@ +import type { AdminMeDto } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, unauthorizedProblem } from '@/http/problem-details'; +import { isAdminEmail } from '../../lib'; + +const route = new Hono(); + +// Open to every signed-in user: the web asks it to decide whether to show the backoffice. +route.get('/me', (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + return c.json({ isAdmin: isAdminEmail(user.email) } satisfies AdminMeDto); +}); + +export default route; diff --git a/apps/backend/src/modules/admin/index.ts b/apps/backend/src/modules/admin/index.ts new file mode 100644 index 0000000..bd2b614 --- /dev/null +++ b/apps/backend/src/modules/admin/index.ts @@ -0,0 +1 @@ +export { default as adminRoutes } from './routes'; diff --git a/apps/backend/src/modules/admin/lib/access.ts b/apps/backend/src/modules/admin/lib/access.ts new file mode 100644 index 0000000..0534bda --- /dev/null +++ b/apps/backend/src/modules/admin/lib/access.ts @@ -0,0 +1,39 @@ +import type { MiddlewareHandler } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { forbiddenProblem } from '@/http/problem-builders'; +import { problemJson, unauthorizedProblem } from '@/http/problem-details'; + +/** + * The backoffice is for Gruperly's own staff, listed by email in `ADMIN_EMAILS` + * (comma separated, case-insensitive). An empty or missing list means nobody. + */ +export function isAdminEmail( + email: string | null | undefined, + env: Record = process.env, +): boolean { + if (!email) return false; + const allowed = (env.ADMIN_EMAILS ?? '') + .split(',') + .map((entry) => entry.trim().toLowerCase()) + .filter(Boolean); + return allowed.includes(email.trim().toLowerCase()); +} + +export function adminOnlyMiddleware( + env: Record = process.env, +): MiddlewareHandler { + return async (c, next) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + if (!isAdminEmail(user.email, env)) { + return problemJson( + c, + forbiddenProblem({ + detail: 'Solo el equipo de Gruperly puede entrar al backoffice.', + code: 'admin_required', + }), + ); + } + await next(); + }; +} diff --git a/apps/backend/src/modules/admin/lib/account-summary.ts b/apps/backend/src/modules/admin/lib/account-summary.ts new file mode 100644 index 0000000..52e1bb8 --- /dev/null +++ b/apps/backend/src/modules/admin/lib/account-summary.ts @@ -0,0 +1,94 @@ +import type { BillingSubscription, Prisma } from '@generated/prisma/client'; +import type { AdminAccountListItem, AdminAccountQuery, Plan } from '@gruperly/shared'; +import { countryCodeSchema } from '@gruperly/shared'; +import { proSubscriptionWhere, resolvePlan } from '@/modules/billing/lib'; + +export type AccountRecord = { + id: string; + name: string; + email: string; + country: string | null; + createdAt: Date; + onboardingCompleted: boolean; + planSelectedAt: Date | null; + subscription: BillingSubscription | null; +}; + +export type AccountUsage = { groupsCount: number; attendeesCount: number }; + +export type PlanContext = { now: Date; graceDays: number }; + +/** Pro by its subscription; otherwise Free once chosen, `null` while not chosen. */ +export function accountPlan( + account: Pick, + { now, graceDays }: PlanContext, +): { plan: Plan | null; graceUntil: Date | null } { + const resolution = resolvePlan(account.subscription, now, graceDays); + if (resolution.plan === 'PRO') return resolution; + return { plan: account.planSelectedAt ? 'FREE' : null, graceUntil: null }; +} + +export function toAccountListItem( + account: AccountRecord, + usage: AccountUsage, + context: PlanContext, +): AdminAccountListItem { + const country = countryCodeSchema.safeParse(account.country); + const subscription = account.subscription; + return { + id: account.id, + name: account.name, + email: account.email, + country: country.success ? country.data : null, + createdAt: account.createdAt.toISOString(), + onboardingCompleted: account.onboardingCompleted, + plan: accountPlan(account, context).plan, + subscription: subscription + ? { + provider: subscription.provider, + status: subscription.status, + amount: Number(subscription.amount.toString()), + currency: subscription.currency, + paidThrough: subscription.paidThrough?.toISOString() ?? null, + nextPaymentDate: + subscription.status === 'AUTHORIZED' + ? (subscription.nextPaymentDate?.toISOString() ?? null) + : null, + } + : null, + ...usage, + }; +} + +/** The list filters as a `user` query. The plan follows `accountPlan`. */ +export function buildAccountWhere( + query: Pick, + { now, graceDays }: PlanContext, +): Prisma.UserWhereInput { + const and: Prisma.UserWhereInput[] = []; + + if (query.search) { + and.push({ + OR: [ + { name: { contains: query.search, mode: 'insensitive' } }, + { email: { contains: query.search, mode: 'insensitive' } }, + ], + }); + } + if (query.country) and.push({ country: query.country }); + + if (query.subscriptionStatus === 'NONE') { + and.push({ subscription: { is: null } }); + } else if (query.subscriptionStatus) { + and.push({ subscription: { is: { status: query.subscriptionStatus } } }); + } + + if (query.plan) { + const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } }; + if (query.plan === 'PRO') and.push(isPro); + if (query.plan === 'FREE') and.push({ planSelectedAt: { not: null }, NOT: isPro }); + if (query.plan === 'NOT_SELECTED') and.push({ planSelectedAt: null, NOT: isPro }); + } + + return and.length > 0 ? { AND: and } : {}; +} diff --git a/apps/backend/src/modules/admin/lib/index.ts b/apps/backend/src/modules/admin/lib/index.ts new file mode 100644 index 0000000..08efd7f --- /dev/null +++ b/apps/backend/src/modules/admin/lib/index.ts @@ -0,0 +1,9 @@ +export { adminOnlyMiddleware, isAdminEmail } from './access'; +export { + type AccountRecord, + type AccountUsage, + accountPlan, + buildAccountWhere, + type PlanContext, + toAccountListItem, +} from './account-summary'; diff --git a/apps/backend/src/modules/admin/routes.ts b/apps/backend/src/modules/admin/routes.ts new file mode 100644 index 0000000..1abc5a9 --- /dev/null +++ b/apps/backend/src/modules/admin/routes.ts @@ -0,0 +1,17 @@ +import { Hono } from 'hono'; +import getAccountRoute from './features/get-account/route'; +import listAccountsRoute from './features/list-accounts/route'; +import meRoute from './features/me/route'; +import { adminOnlyMiddleware } from './lib'; + +const routes = new Hono(); + +routes.route('/', meRoute); + +// Everything below `/me` is the backoffice itself. +routes.use('/accounts', adminOnlyMiddleware()); +routes.use('/accounts/*', adminOnlyMiddleware()); +routes.route('/', listAccountsRoute); +routes.route('/', getAccountRoute); + +export default routes; diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts new file mode 100644 index 0000000..b023827 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts @@ -0,0 +1,21 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetAttendeeHistory } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/attendees/:attendeeId/history', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const groupId = c.req.param('groupId'); + const attendeeId = c.req.param('attendeeId'); + const useCase = new GetAttendeeHistory(); + const result = await useCase.execute(groupId, attendeeId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts new file mode 100644 index 0000000..67733fa --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts @@ -0,0 +1,97 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + AttendanceStatus, + AttendeeHistory, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { flattenPerson } from '@/modules/attendees/lib/helpers'; +import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; + +export const HISTORY_SESSIONS_LIMIT = 20; + +type GetAttendeeHistoryDeps = { + db?: AnalyticsAccessDb & Pick; +}; + +export class GetAttendeeHistory { + constructor(private readonly deps: GetAttendeeHistoryDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { id: true, createdAt: true, person: { select: { fullName: true } } }, + }).then((row) => row && flattenPerson(row)); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + // Same effective join date as the risk rule (`toMemberAttendance`): an + // attendee loaded after their first classes were already recorded starts + // at that first class, not at `createdAt`. Otherwise this screen said + // "1 de 3 clases" while the group list said "1 de 5" for the same person. + const firstAttendance = await db.attendance.findFirst({ + where: { attendeeId }, + orderBy: { classSession: { startsAt: 'asc' } }, + select: { classSession: { select: { startsAt: true } } }, + }); + const firstClassAt = firstAttendance?.classSession.startsAt; + const since = + firstClassAt && firstClassAt < attendee.createdAt ? firstClassAt : attendee.createdAt; + + const sessions = await db.classSession.findMany({ + where: { groupId, startsAt: { gte: since } }, + orderBy: { startsAt: 'desc' }, + take: HISTORY_SESSIONS_LIMIT, + select: { id: true, startsAt: true }, + }); + const sessionIds = sessions.map((session) => session.id); + + const attendances = sessionIds.length + ? await db.attendance.findMany({ + where: { attendeeId, classSessionId: { in: sessionIds } }, + select: { classSessionId: true, status: true }, + }) + : []; + + const statusBySession = new Map( + attendances.map((record) => [record.classSessionId, record.status]), + ); + + const orderedSessions = sessions + .slice() + .reverse() + .map((session) => ({ + classSessionId: session.id, + startsAt: session.startsAt.toISOString(), + status: statusBySession.get(session.id) ?? null, + })); + + const presentCount = attendances.filter((record) => record.status === 'PRESENT').length; + const attendanceRate = + sessions.length > 0 ? Math.round((presentCount / sessions.length) * 100) : 0; + + return ok({ + attendeeId: attendee.id, + fullName: attendee.fullName, + groupId, + groupName: access.value.name, + attendanceRate, + sessions: orderedSessions, + }); + } +} diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts new file mode 100644 index 0000000..af7e136 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetGroupsRiskOverview } from './use-case'; + +const route = new Hono(); + +route.get('/overview', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const useCase = new GetGroupsRiskOverview(); + const result = await useCase.execute(user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts new file mode 100644 index 0000000..4521b38 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts @@ -0,0 +1,198 @@ +import { Prisma } from '@generated/prisma/client'; +import type { + AttendanceStatus, + GroupRiskLevel, + GroupRiskSummary, + GroupsRiskOverview, + ProblemDetails, + Result, + UrgentMemberSummary, +} from '@gruperly/shared'; +import { + ATTENDANCE_RISK_RULES, + getGroupAttendanceSummary, + ok, + URGENT_MEMBERS_LIMIT, +} from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { flattenPerson } from '@/modules/attendees/lib/helpers'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; +import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; + +type GetGroupsRiskOverviewDeps = { + db?: { + group: Prisma.GroupDelegate; + classSession: Prisma.ClassSessionDelegate; + attendee: Prisma.AttendeeDelegate; + attendance: Prisma.AttendanceDelegate; + }; + now?: Date; +}; + +type GroupRow = { + id: string; + name: string; + capacity: number | null; + /** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */ + _count: { waitlist: number }; +}; +type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date }; +type SessionRow = { id: string; groupId: string; startsAt: Date }; +type AttendanceRow = { + attendeeId: string; + classSessionId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; + +// Risk summary per group for the group listing and Home. Everything comes from +// the domain rule (`getGroupAttendanceSummary`): the status light is the worst +// level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the +// "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree. +export class GetGroupsRiskOverview { + constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); + + const groups = (await db.group.findMany({ + where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, + select: { + id: true, + name: true, + capacity: true, + _count: { select: { waitlist: { where: { status: 'PENDING' } } } }, + }, + })) as unknown as GroupRow[]; + + if (groups.length === 0) { + return ok({ items: [] }); + } + + const groupIds = groups.map((group) => group.id); + + const [attendees, sessions, attendances] = await Promise.all([ + db.attendee.findMany({ + where: { groupId: { in: groupIds }, status: 'ACTIVE' }, + select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } }, + }).then((rows): AttendeeRow[] => rows.map(flattenPerson)), + db.classSession.findMany({ + where: { groupId: { in: groupIds }, startsAt: { gte: since } }, + select: { id: true, groupId: true, startsAt: true }, + orderBy: { startsAt: 'desc' }, + }) as Promise, + /* No date filter, as before: the status light streak counts over the + attendee's full history, not over the monthly window. No cap either: + the cut to the last 20 classes is done by `memberSessions`, over the + group's classes and not over these rows. */ + db.attendance.findMany({ + where: { attendee: { groupId: { in: groupIds } } }, + select: { + attendeeId: true, + classSessionId: true, + status: true, + classSession: { select: { startsAt: true } }, + }, + orderBy: { classSession: { startsAt: 'desc' } }, + }) as Promise, + ]); + + const sessionsByGroup = new Map(); + for (const session of sessions) { + const list = sessionsByGroup.get(session.groupId) ?? []; + list.push(session); + sessionsByGroup.set(session.groupId, list); + } + + const streamByAttendee = groupAttendanceByAttendee(attendances); + + const items: GroupRiskSummary[] = groups.map((group) => + buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now), + ); + + return ok({ items }); + } +} + +/** + * The per-level summary consumed by the listing card and Home. It comes from + * `getGroupAttendanceSummary`, the same domain function that + * `test/attendance-risk.test.ts` exercises, so the rule doesn't have two + * copies: one here and another in the client. + * + * `libres` and `enEspera` come from here and not from the `Attendee` count: the + * summary counts the group members and the card needs the capacity slots to + * paint the indicator. + */ +function buildSummary( + group: GroupRow, + attendees: AttendeeRow[], + sessionsByGroup: Map, + attendanceByAttendee: Map, + now: Date, +): GroupRiskSummary { + const resumen = getGroupAttendanceSummary({ + groupId: group.id, + capacity: group.capacity, + waitlistCount: group._count.waitlist, + now, + members: attendees + .filter((attendee) => attendee.groupId === group.id) + .map((attendee) => + toMemberAttendance( + attendee, + sessionsByGroup.get(group.id) ?? [], + attendanceByAttendee.get(attendee.id) ?? [], + ), + ), + }); + + // Why there is risk, over every member and not only the urgent ones sent to + // the client. Disjoint: an absence streak counts in the first and only + // there; the second groups the rest (inactivity or a declining trend). + const atRisk = resumen.urgentes.filter((member) => member.level !== 'ok'); + const absenceStreakCount = atRisk.filter( + (member) => member.consecutiveAbsences >= ATTENDANCE_RISK_RULES.attentionAbsenceStreak, + ).length; + + const urgentes: UrgentMemberSummary[] = resumen.urgentes + .slice(0, URGENT_MEMBERS_LIMIT) + .map((urgente) => ({ + attendeeId: urgente.attendeeId, + fullName: urgente.fullName, + level: urgente.level, + consecutiveAbsences: urgente.consecutiveAbsences, + daysSinceLastAttendance: urgente.daysSinceLastAttendance, + attendanceRate: urgente.attendanceRate, + })); + + const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE'; + + return { + groupId: group.id, + groupName: group.name, + riskLevel, + absenceStreakCount, + lowAttendanceCount: atRisk.length - absenceStreakCount, + riesgoAlto: resumen.riesgoAlto, + atencion: resumen.atencion, + ok: resumen.ok, + libres: resumen.libres, + enEspera: resumen.enEspera, + asistencia: resumen.asistencia, + urgentes, + }; +} + +function groupAttendanceByAttendee(rows: AttendanceRow[]): Map { + const byAttendee = new Map(); + for (const row of rows) { + const list = byAttendee.get(row.attendeeId) ?? []; + list.push(row); + byAttendee.set(row.attendeeId, list); + } + return byAttendee; +} diff --git a/apps/backend/src/modules/analytics/features/get-overview/route.ts b/apps/backend/src/modules/analytics/features/get-overview/route.ts new file mode 100644 index 0000000..94e4997 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-overview/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetGroupAnalytics } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/analytics', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const groupId = c.req.param('groupId'); + const useCase = new GetGroupAnalytics(); + const result = await useCase.execute(groupId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-overview/use-case.ts new file mode 100644 index 0000000..6d848eb --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-overview/use-case.ts @@ -0,0 +1,55 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { GroupAnalytics, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; + +export const ANALYTICS_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; + +type GetGroupAnalyticsDeps = { + db?: AnalyticsAccessDb & Pick; + now?: Date; +}; + +export class GetGroupAnalytics { + constructor(private readonly deps: GetGroupAnalyticsDeps = {}) {} + + async execute( + groupId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const [sessions, attendances, recoveredSlots] = await Promise.all([ + db.classSession.findMany({ + where: { groupId, startsAt: { gte: since } }, + select: { id: true }, + }), + db.attendance.findMany({ + where: { classSession: { groupId, startsAt: { gte: since } } }, + select: { status: true }, + }), + db.slotRelease.count({ + where: { classSession: { groupId, startsAt: { gte: since } } }, + }), + ]); + + const totalClasses = sessions.length; + const totalMarked = attendances.length; + const totalPresent = attendances.filter((record) => record.status === 'PRESENT').length; + + return ok({ + attendanceRate: totalMarked > 0 ? Math.round((totalPresent / totalMarked) * 100) : 0, + totalPresent, + totalClasses, + recoveredSlots, + }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts new file mode 100644 index 0000000..bcec58c --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetStudentsAtRisk } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/students-at-risk', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const groupId = c.req.param('groupId'); + const useCase = new GetStudentsAtRisk(); + const result = await useCase.execute(groupId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts new file mode 100644 index 0000000..d3ea984 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts @@ -0,0 +1,143 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + AttendanceStatus, + ProblemDetails, + Result, + StudentAtRisk, + StudentsAtRisk, +} from '@gruperly/shared'; +import { ok, summarizeMemberAttendance } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { flattenPerson } from '@/modules/attendees/lib/helpers'; +import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; +import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; +import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk'; +import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; + +type GetStudentsAtRiskDeps = { + db?: AnalyticsAccessDb & StudentsAtRiskDb; + now?: Date; +}; + +type AttendanceStreamRow = { + attendeeId: string; + classSessionId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; + +export class GetStudentsAtRisk { + constructor(private readonly deps: GetStudentsAtRiskDeps = {}) {} + + async execute( + groupId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const atRisk = await findStudentsAtRisk(db, groupId, now); + + return ok({ + groupName: access.value.name, + data: atRisk, + }); + } +} + +export type StudentsAtRiskDb = Pick; + +/** + * The ACTIVE members of a group who are at risk, most urgent first. Shared by + * the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged + * with the same domain rule as the group listing and Home + * (`summarizeMemberAttendance`), so every screen agrees on who is at risk. + * Does not check access: callers do. + */ +export async function findStudentsAtRisk( + db: StudentsAtRiskDb, + groupId: string, + now: Date, +): Promise { + const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); + + const [windowSessions, attendees, attendances] = await Promise.all([ + db.classSession.findMany({ + where: { groupId, startsAt: { gte: since } }, + select: { id: true, startsAt: true }, + orderBy: { startsAt: 'desc' }, + }), + db.attendee.findMany({ + where: { groupId, status: 'ACTIVE' }, + select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } }, + }).then((rows) => rows.map(flattenPerson)), + db.attendance.findMany({ + where: { attendee: { groupId } }, + select: { + attendeeId: true, + classSessionId: true, + status: true, + classSession: { select: { startsAt: true } }, + }, + orderBy: { classSession: { startsAt: 'desc' } }, + }), + ]); + + const totalWindowSessions = windowSessions.length; + const streamByAttendee = groupAttendanceByAttendee(attendances); + + const atRisk: StudentAtRisk[] = []; + for (const attendee of attendees) { + const rows = streamByAttendee.get(attendee.id) ?? []; + const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now); + const riskLevel = toRiskLevel(signals.level); + if (!riskLevel) { + continue; + } + // Display only: the verdict is the domain's. The rate keeps counting + // unrecorded classes as missed, which is what "asistencia mensual" says. + const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt })); + const consecutiveAbsences = signals.consecutiveAbsences; + const attendedAt = lastAttendedAt(stream); + const monthlyRate = monthlyAttendanceRate( + stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()), + totalWindowSessions, + ); + atRisk.push({ + attendeeId: attendee.id, + fullName: attendee.fullName, + phone: attendee.phone, + riskLevel, + consecutiveAbsences, + lastAttendedAt: attendedAt ? attendedAt.toISOString() : null, + monthlyAttendanceRate: monthlyRate, + }); + } + + atRisk.sort((a, b) => { + if (a.riskLevel !== b.riskLevel) { + return a.riskLevel === 'HIGH' ? -1 : 1; + } + if (a.consecutiveAbsences !== b.consecutiveAbsences) { + return b.consecutiveAbsences - a.consecutiveAbsences; + } + return a.monthlyAttendanceRate - b.monthlyAttendanceRate; + }); + + return atRisk; +} + +function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map { + const byAttendee = new Map(); + for (const row of rows) { + const list = byAttendee.get(row.attendeeId) ?? []; + list.push(row); + byAttendee.set(row.attendeeId, list); + } + return byAttendee; +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts b/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts new file mode 100644 index 0000000..d46c4b8 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts @@ -0,0 +1,24 @@ +import type { UpdateStudentStatus } from '@gruperly/shared'; +import { UpdateStudentStatusSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { UpdateAttendeeStatus } from './use-case'; + +const route = new Hono(); + +route.post('/:studentId/status', validate.json(UpdateStudentStatusSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const studentId = c.req.param('studentId'); + const payload = c.req.valid('json') as UpdateStudentStatus; + const useCase = new UpdateAttendeeStatus(); + const result = await useCase.execute(studentId, user.id, payload); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts b/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts new file mode 100644 index 0000000..30cc3c7 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts @@ -0,0 +1,53 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + UpdateStudentStatus, + UpdateStudentStatusResult, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; + +type UpdateAttendeeStatusDeps = { + db?: Pick; +}; + +export class UpdateAttendeeStatus { + constructor(private readonly deps: UpdateAttendeeStatusDeps = {}) {} + + async execute( + studentId: string, + userId: string, + payload: UpdateStudentStatus, + ): Promise> { + const db = this.deps.db ?? prisma; + + const attendee = await db.attendee.findUnique({ + where: { id: studentId }, + include: { group: { include: { members: { where: { userId } } } } }, + }); + + if (!attendee) { + return err(notFoundResourceProblem('Attendee', studentId)); + } + + const isOwner = attendee.group.createdById === userId; + const isMember = attendee.group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + if (attendee.status === payload.status) { + return ok({ attendeeId: studentId, status: payload.status }); + } + + const updated = await db.attendee.update({ + where: { id: studentId }, + data: { status: payload.status }, + select: { id: true, status: true }, + }); + + return ok({ attendeeId: updated.id, status: updated.status }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/index.ts b/apps/backend/src/modules/analytics/index.ts new file mode 100644 index 0000000..4b66d93 --- /dev/null +++ b/apps/backend/src/modules/analytics/index.ts @@ -0,0 +1,3 @@ +export { default as groupsRiskOverviewRoute } from './features/get-groups-risk-overview/route'; +export { default as studentStatusRoutes } from './features/update-attendee-status/route'; +export { default as analyticsRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/lib/access.ts b/apps/backend/src/modules/analytics/lib/access.ts new file mode 100644 index 0000000..91c803a --- /dev/null +++ b/apps/backend/src/modules/analytics/lib/access.ts @@ -0,0 +1,37 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; + +export type AnalyticsAccessDb = Pick; + +type GroupWithAccess = { + id: string; + name: string; + createdById: string; + members: { userId: string }[]; +}; + +// Verifies the user is the group owner or a member. Returns the group if they have access. +export async function findGroupForUser( + db: AnalyticsAccessDb, + groupId: string, + userId: string, +): Promise> { + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { members: { where: { userId } } }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + return ok(group); +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/lib/member-attendance.ts b/apps/backend/src/modules/analytics/lib/member-attendance.ts new file mode 100644 index 0000000..cc3cd65 --- /dev/null +++ b/apps/backend/src/modules/analytics/lib/member-attendance.ts @@ -0,0 +1,81 @@ +import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberClassSession, RiskLevel } from '@gruperly/shared'; + +/* How many classes we look back per attendee. That is the real ceiling of the + model: `class_sessions` are not created on their own, they get materialized + when someone opens "today's classes", so pulling years of rows makes no + sense. 20 classes is enough for the streak, for the 6-class window and for + the attendance rate the card shows. */ +export const MEMBER_HISTORY_LIMIT = 20; + +export type MemberAttendeeRow = { id: string; fullName: string; createdAt: Date }; +export type MemberSessionRow = { id: string; startsAt: Date }; +export type MemberAttendanceRow = { + classSessionId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; + +/** + * The input of the domain risk rule (`summarizeMemberAttendance` in shared) for + * one attendee. The group listing, Home, the "Alumnos en riesgo" screen and the + * re-engagement job all build it here, so they can't disagree on who is at risk. + * + * `groupSessions` must come most recent first (as the queries order them). + */ +export function toMemberAttendance( + attendee: MemberAttendeeRow, + groupSessions: MemberSessionRow[], + attendances: MemberAttendanceRow[], +): MemberAttendance { + // If the attendee has attendances before their enrollment date in the DB + // (e.g. created today but with past classes already recorded), their + // effective join date is the first class they were marked for. + const earliestAttendance = attendances.reduce( + (earliest, att) => + !earliest || att.classSession.startsAt < earliest ? att.classSession.startsAt : earliest, + null, + ); + const enrolledAt = + earliestAttendance && earliestAttendance < attendee.createdAt + ? earliestAttendance + : attendee.createdAt; + + return { + attendeeId: attendee.id, + fullName: attendee.fullName, + enrolledAt: enrolledAt.toISOString(), + sessions: memberSessions(groupSessions, attendances), + }; +} + +/** The domain level as the at-risk endpoints speak it; `null` for `ok`. */ +export function toRiskLevel(level: AttendanceRiskLevel): RiskLevel | null { + if (level === 'riesgo_alto') return 'HIGH'; + if (level === 'atencion') return 'MEDIUM'; + return null; +} + +/* The universe of classes is the group's, not the `Attendance` rows'. + Attendance is recorded attendee by attendee and only when someone marks a + class, so "this class happened and this attendee has no record" is a real + and frequent state, not an absence. If the list were built from the + attendance rows those classes wouldn't exist and the streak wouldn't break: + two absences separated by an unmarked class would count as three in a row. + The domain already treats them as neutral (`status: null`), so all that is + left here is to pick the right universe and keep the criterion on one side. + `sessions` comes from most recent to oldest, so keeping the first + `MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee + and not global, so a group with a long history doesn't steal window from + the groups listed after it. */ +function memberSessions( + sessions: MemberSessionRow[], + attendances: MemberAttendanceRow[], +): MemberClassSession[] { + const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status])); + + return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({ + sessionId: session.id, + startsAt: session.startsAt.toISOString(), + status: statusBySession.get(session.id) ?? null, + })); +} diff --git a/apps/backend/src/modules/analytics/lib/risk.ts b/apps/backend/src/modules/analytics/lib/risk.ts new file mode 100644 index 0000000..26fb94c --- /dev/null +++ b/apps/backend/src/modules/analytics/lib/risk.ts @@ -0,0 +1,27 @@ +export type AttendanceStreamEntry = { + status: 'PRESENT' | 'ABSENT' | 'EXCUSED'; + occurredAt: Date; +}; + +// Date of the last class the attendee showed up to (PRESENT), or null. +export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null { + for (const entry of entries) { + if (entry.status === 'PRESENT') { + return entry.occurredAt; + } + } + return null; +} + +// Attendance rate over the total number of sessions in the period. +// Sessions with no record count as not attended. +export function monthlyAttendanceRate( + entries: AttendanceStreamEntry[], + totalSessions: number, +): number { + if (totalSessions <= 0) { + return 0; + } + const present = entries.filter((entry) => entry.status === 'PRESENT').length; + return Math.round((present / totalSessions) * 100); +} diff --git a/apps/backend/src/modules/analytics/routes.ts b/apps/backend/src/modules/analytics/routes.ts new file mode 100644 index 0000000..7054589 --- /dev/null +++ b/apps/backend/src/modules/analytics/routes.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import getAttendeeHistoryRoute from './features/get-attendee-history/route'; +import getOverviewRoute from './features/get-overview/route'; +import getStudentsAtRiskRoute from './features/get-students-at-risk/route'; + +const routes = new Hono(); + +routes.route('/', getOverviewRoute); +routes.route('/', getStudentsAtRiskRoute); +routes.route('/', getAttendeeHistoryRoute); + +export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/add-to-group/route.ts b/apps/backend/src/modules/attendees/features/add-to-group/route.ts new file mode 100644 index 0000000..9e17479 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/add-to-group/route.ts @@ -0,0 +1,24 @@ +import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared'; +import { AddAttendeeToGroupSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { AddAttendeeToGroup } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new AddAttendeeToGroup(); + const result = await useCase.execute({ + groupId: c.req.param('groupId'), + attendeeId: c.req.param('attendeeId'), + userId: user.id, + targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId, + }); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts b/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts new file mode 100644 index 0000000..af24c3b --- /dev/null +++ b/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts @@ -0,0 +1,88 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers'; +import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote'; +import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people'; +import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers'; + +type AddAttendeeToGroupDeps = { + db?: Pick; + unitOfWork?: Pick; +}; + +type AddAttendeeToGroupCommand = { + groupId: string; + attendeeId: string; + userId: string; + targetGroupId: string; +}; + +/* "Agregar a otro grupo": the same person gets a membership in another group of + the teacher and keeps this one. It does not take a new student slot of the + plan (the person is already counted) but the target's capacity applies. A + former membership there (DROPPED) is reactivated, history included. */ +export class AddAttendeeToGroup { + constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {} + + async execute(command: AddAttendeeToGroupCommand): Promise> { + const { groupId, attendeeId, userId, targetGroupId } = command; + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + const sourceResult = await findGroupOwnedByUser(db, groupId, userId); + if (!sourceResult.ok) return sourceResult; + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { personId: true }, + }); + if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + + if (targetGroupId === groupId) { + return err( + conflictProblem({ + detail: 'El miembro ya pertenece a este grupo.', + code: 'attendee_same_group', + }), + ); + } + + const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId); + if (!targetResult.ok) return targetResult; + const target = targetResult.value; + + try { + return await unitOfWork.executeResult( + async (tx: Prisma.TransactionClient): Promise> => { + const former = await tx.attendee.findFirst({ + where: { groupId: targetGroupId, personId: attendee.personId }, + select: { id: true, status: true }, + }); + if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem()); + + const canJoin = await checkCanJoinGroup(tx, target, null); + if (!canJoin.ok) return canJoin; + + const membership = former + ? await tx.attendee.update({ + where: { id: former.id }, + data: { status: 'ACTIVE' }, + include: attendeeWithPerson, + }) + : await tx.attendee.create({ + data: { groupId: targetGroupId, personId: attendee.personId }, + include: attendeeWithPerson, + }); + return ok(toAttendeeDto(membership)); + }, + ); + } catch (error) { + // Two clicks at once: the unique (group, person) lets only one through. + if (isUniqueViolation(error)) return err(alreadyInGroupProblem()); + throw error; + } + } +} diff --git a/apps/backend/src/modules/attendees/features/add-to-waitlist/route.ts b/apps/backend/src/modules/attendees/features/add-to-waitlist/route.ts new file mode 100644 index 0000000..e03c04e --- /dev/null +++ b/apps/backend/src/modules/attendees/features/add-to-waitlist/route.ts @@ -0,0 +1,21 @@ +import { type CreateGroupWaitlistEntry, CreateGroupWaitlistEntrySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { AddToGroupWaitlist } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/waitlist', validate.json(CreateGroupWaitlistEntrySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const body = c.req.valid('json') as CreateGroupWaitlistEntry; + const useCase = new AddToGroupWaitlist(); + const result = await useCase.execute(groupId, user.id, body); + return resultJson(c, result, { status: 201 }); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts b/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts new file mode 100644 index 0000000..c4e186c --- /dev/null +++ b/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts @@ -0,0 +1,110 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CreateGroupWaitlistEntry, GroupWaitlistEntryDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + alreadyWaitlistedProblem, + conflictProblem, + noGroupAccessProblem, + notFoundResourceProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { phoneVariants } from '@/modules/people/lib/people'; +import { normalizePhone } from '../../lib/helpers'; + +type AddToGroupWaitlistDeps = { + db?: Pick; +}; + +type GroupWaitlistRecord = { + id: string; + groupId: string; + fullName: string; + phone: string; + email: string | null; + notes: string | null; + status: GroupWaitlistEntryDto['status']; + createdAt: Date; + updatedAt: Date; +}; + +function toGroupWaitlistEntryDto(record: GroupWaitlistRecord): GroupWaitlistEntryDto { + return { + id: record.id, + groupId: record.groupId, + fullName: record.fullName, + phone: record.phone, + email: record.email, + notes: record.notes, + status: record.status, + createdAt: record.createdAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + }; +} + +export class AddToGroupWaitlist { + constructor(private readonly deps: AddToGroupWaitlistDeps = {}) {} + + async execute( + groupId: string, + userId: string, + payload: CreateGroupWaitlistEntry, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { + members: { where: { userId } }, + }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + const phone = normalizePhone(payload.phone); + + const existingAttendee = await db.attendee.findFirst({ + where: { + groupId, + person: { phone: { in: phoneVariants(payload.phone) } }, + }, + }); + + if (existingAttendee) { + return err( + conflictProblem({ + detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.', + code: 'attendee_already_registered', + }), + ); + } + + const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({ + where: { groupId, phone }, + }); + + if (existingWaitlistEntry) { + return err(alreadyWaitlistedProblem()); + } + + const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); + const entry = await db.groupWaitlistEntry.create({ + data: { + groupId, + fullName, + phone, + email: payload.email?.trim() || null, + notes: payload.notes?.trim() || null, + }, + }); + + return ok(toGroupWaitlistEntryDto(entry as unknown as GroupWaitlistRecord)); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/bulk-create/route.ts b/apps/backend/src/modules/attendees/features/bulk-create/route.ts new file mode 100644 index 0000000..bafd8b3 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/bulk-create/route.ts @@ -0,0 +1,21 @@ +import { type BulkCreateAttendees, BulkCreateAttendeesSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { BulkCreateAttendeesUseCase } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/attendees/bulk', validate.json(BulkCreateAttendeesSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const body = c.req.valid('json') as BulkCreateAttendees; + const useCase = new BulkCreateAttendeesUseCase(); + const result = await useCase.execute(groupId, user.id, body); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts new file mode 100644 index 0000000..0edc689 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts @@ -0,0 +1,154 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + BulkCreateAttendees, + BulkCreateAttendeesResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { type AttendeeRecord, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; + +type BulkCreateAttendeesDeps = { + db?: Pick; + planGuard?: Pick; +}; + +export class BulkCreateAttendeesUseCase { + constructor(private readonly deps: BulkCreateAttendeesDeps = {}) {} + + async execute( + groupId: string, + userId: string, + payload: BulkCreateAttendees, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { + members: { where: { userId } }, + }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + /* The teacher's people by phone: a row whose phone is already someone they + have is added to this group as that person (linked), unless that person + is already in the group (duplicate). */ + const people = await db.person.findMany({ + where: { createdById: group.createdById, phone: { not: null } }, + select: { + id: true, + phone: true, + attendees: { select: { groupId: true, status: true } }, + }, + }); + const peopleByPhone = new Map(); + for (const person of people) { + if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person); + } + + let duplicatesCount = 0; + let invalidCount = 0; + // Only people not active in any group take a new slot of the plan. + let newlyCounted = 0; + const seenPhones = new Set(); + const toLink: string[] = []; + const toCreate: Array<{ + fullName: string; + phone: string; + email: string | null; + notes: string | null; + }> = []; + + for (const item of payload.attendees) { + const phone = normalizePhone(item.phone || ''); + const rawFullName = item.fullName?.trim() || `${item.firstName?.trim() ?? ''} ${item.lastName?.trim() ?? ''}`.trim(); + + if (!rawFullName || !phone) { + invalidCount++; + continue; + } + + const existing = peopleByPhone.get(phone); + if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) { + duplicatesCount++; + continue; + } + seenPhones.add(phone); + + if (existing) { + toLink.push(existing.id); + if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++; + continue; + } + + newlyCounted++; + toCreate.push({ + fullName: rawFullName, + phone, + email: item.email?.trim() || null, + notes: item.notes?.trim() || null, + }); + } + + // All or nothing: a partial import that stops at the limit is harder to + // reason about than a clear "your plan allows N". + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees( + group.createdById, + newlyCounted, + ); + if (!allowed.ok) { + return allowed; + } + + const createdRecords: AttendeeRecord[] = []; + for (const personId of toLink) { + createdRecords.push( + await db.attendee.create({ + data: { groupId, personId }, + include: attendeeWithPerson, + }), + ); + } + for (const data of toCreate) { + createdRecords.push( + await db.attendee.create({ + data: { + group: { connect: { id: groupId } }, + person: { create: { ...data, createdById: group.createdById } }, + }, + include: attendeeWithPerson, + }), + ); + } + + const createdCount = createdRecords.length; + const linkedCount = toLink.length; + const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : ''; + const message = duplicatesCount > 0 + ? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.` + : `${createdCount} alumnos agregados con éxito${linkedNote}.`; + + return ok({ + totalProcessed: payload.attendees.length, + createdCount, + linkedCount, + duplicatesCount, + invalidCount, + message, + created: createdRecords.map(toAttendeeDto), + }); + } +} diff --git a/apps/backend/src/modules/attendees/features/create/route.ts b/apps/backend/src/modules/attendees/features/create/route.ts new file mode 100644 index 0000000..8f6f33a --- /dev/null +++ b/apps/backend/src/modules/attendees/features/create/route.ts @@ -0,0 +1,22 @@ +import { type CreateAttendee, CreateAttendeeSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { CreateAttendeeUseCase } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/attendees', validate.json(CreateAttendeeSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const body = c.req.valid('json') as CreateAttendee; + const allowOverflow = c.req.query('allowOverflow') === 'true'; + const useCase = new CreateAttendeeUseCase(); + const result = await useCase.execute(groupId, user.id, body, { allowOverflow }); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/create/use-case.ts b/apps/backend/src/modules/attendees/features/create/use-case.ts new file mode 100644 index 0000000..814600d --- /dev/null +++ b/apps/backend/src/modules/attendees/features/create/use-case.ts @@ -0,0 +1,175 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CreateAttendee, CreateAttendeeResult, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + alreadyWaitlistedProblem, + capacityReachedProblem, + noGroupAccessProblem, + notFoundResourceProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { + alreadyInGroupProblem, + findPersonByPhone, + isUniqueViolation, + personExistsProblem, +} from '@/modules/people/lib/people'; +import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; + +type CreateAttendeeDeps = { + db?: Pick; + planGuard?: Pick; +}; + +type CreateAttendeeOptions = { + allowOverflow?: boolean; +}; + +export class CreateAttendeeUseCase { + constructor(private readonly deps: CreateAttendeeDeps = {}) {} + + async execute( + groupId: string, + userId: string, + payload: CreateAttendee, + options: CreateAttendeeOptions = {}, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { + members: { where: { userId } }, + }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + const phone = normalizePhone(payload.phone); + + /* The person: the one the form picked (`personId`, after the "ya existe" + hint) or a new one. A phone the teacher already has is never duplicated. */ + let person: { id: string; fullName: string } | null = null; + if (payload.personId) { + person = await db.person.findFirst({ + where: { id: payload.personId, createdById: group.createdById }, + select: { id: true, fullName: true }, + }); + if (!person) { + return err(notFoundResourceProblem('Person', payload.personId)); + } + } else { + const samePhone = await findPersonByPhone(db, group.createdById, payload.phone); + if (samePhone) { + return err( + samePhone.attendees.some((membership) => membership.groupId === groupId) + ? alreadyInGroupProblem() + : personExistsProblem(), + ); + } + } + + // A former member (DROPPED) comes back on the same membership: history included. + const membership = person + ? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } }) + : null; + if (membership && membership.status !== 'DROPPED') { + return err(alreadyInGroupProblem()); + } + + const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); + + if (group.capacity !== null) { + const currentCount = await db.attendee.count({ + where: { groupId, status: 'ACTIVE' }, + }); + + if (currentCount >= group.capacity) { + if (isOwner && !options.allowOverflow) { + return err(capacityReachedProblem(group.capacity)); + } + + if (!isOwner) { + const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({ + where: { groupId, phone }, + }); + + if (existingWaitlistEntry) { + return err(alreadyWaitlistedProblem()); + } + + await db.groupWaitlistEntry.create({ + data: { + groupId, + fullName, + phone, + email: payload.email?.trim() || null, + notes: payload.notes?.trim() || null, + }, + }); + + return ok({ + outcome: 'waitlisted', + message: `${fullName} fue agregado a la lista de espera del grupo.`, + }); + } + } + } + + // The owner's plan pays for the attendee, whoever adds it. It counts people: + // someone already active in another group does not take a new slot. + const alreadyCounted = person + ? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0 + : false; + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees( + group.createdById, + alreadyCounted ? 0 : 1, + ); + if (!allowed.ok) { + return allowed; + } + + try { + const attendee = membership + ? await db.attendee.update({ + where: { id: membership.id }, + data: { status: 'ACTIVE' }, + include: attendeeWithPerson, + }) + : await db.attendee.create({ + data: { + group: { connect: { id: groupId } }, + person: person + ? { connect: { id: person.id } } + : { + create: { + createdById: group.createdById, + fullName, + phone, + email: payload.email?.trim() || null, + notes: payload.notes?.trim() || null, + }, + }, + }, + include: attendeeWithPerson, + }); + + return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) }); + } catch (error) { + // Lost a race: someone created that person or membership meanwhile. + if (isUniqueViolation(error)) { + return err(person ? alreadyInGroupProblem() : personExistsProblem()); + } + throw error; + } + } +} diff --git a/apps/backend/src/modules/attendees/features/get-all/route.ts b/apps/backend/src/modules/attendees/features/get-all/route.ts new file mode 100644 index 0000000..4f91c26 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-all/route.ts @@ -0,0 +1,18 @@ +import type { AttendeeQuery } from '@gruperly/shared'; +import { AttendeeQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListAttendees } from './use-case'; + +const route = new Hono(); + +route.get('/', validate.query(AttendeeQuerySchema), async (c) => { + const query = c.req.valid('query') as AttendeeQuery; + const useCase = new ListAttendees(); + const result: Awaited> = await useCase.execute(query); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/get-all/use-case.ts b/apps/backend/src/modules/attendees/features/get-all/use-case.ts new file mode 100644 index 0000000..e9e4726 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-all/use-case.ts @@ -0,0 +1,55 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; + +import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers'; + +type ListAttendeesDeps = { + db?: Pick; +}; + +export class ListAttendees { + constructor(private readonly deps: ListAttendeesDeps = {}) {} + + async execute(query: AttendeeQuery): Promise> { + const db = this.deps.db ?? prisma; + const where = query.groupId ? { groupId: query.groupId } : undefined; + + const [records, total] = await Promise.all([ + /* Each row's summary travels in the same query instead of being built + with one request per member. Both relations are capped on purpose: + the payments table grows one row per month forever, and the listing + only needs each person's current state. */ + db.attendee.findMany({ + ...(where ? { where } : {}), + skip: getPaginationOffset(query), + take: query.pageSize, + orderBy: { createdAt: 'desc' }, + include: { + ...attendeeWithPerson, + // By class date, not by `markedAt`: marking attendance late must not + // change which class counts as recent. + attendances: { + orderBy: { classSession: { startsAt: 'desc' } }, + take: RECENT_ATTENDANCE_LIMIT, + select: { status: true }, + }, + payments: { + where: { status: { not: 'CANCELLED' } }, + orderBy: { dueDate: 'desc' }, + take: 3, + select: { status: true, dueDate: true }, + }, + }, + }), + where ? db.attendee.count({ where }) : db.attendee.count(), + ]); + + return ok({ + data: records.map((record) => toAttendeeListItemDto(record)), + pagination: getPaginationMetadata(query, total), + }); + } +} diff --git a/apps/backend/src/modules/attendees/features/get-by-id/route.ts b/apps/backend/src/modules/attendees/features/get-by-id/route.ts new file mode 100644 index 0000000..a954c68 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-by-id/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetAttendee } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/attendees/:attendeeId', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const attendeeId = c.req.param('attendeeId'); + const useCase = new GetAttendee(); + const result = await useCase.execute(groupId, attendeeId, user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts new file mode 100644 index 0000000..60b220e --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts @@ -0,0 +1,66 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AttendeeDetailDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; +import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people'; +import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers'; + +type GetAttendeeDeps = { + db?: Pick; + now?: () => Date; +}; + +export class GetAttendee { + constructor(private readonly deps: GetAttendeeDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const billingPeriod = currentMonthRange((this.deps.now ?? (() => new Date()))()); + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + include: { + person: { select: { ...personContactSelect, ...personMembershipsSelect } }, + payments: { + where: { + status: { not: 'CANCELLED' }, + dueDate: { gte: billingPeriod.start, lt: billingPeriod.end }, + }, + orderBy: { dueDate: 'desc' }, + take: 1, + select: { status: true, dueDate: true }, + }, + }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + const { attendees: memberships, ...person } = attendee.person; + return ok( + toAttendeeDetailDto({ + ...attendee, + person, + otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)), + }), + ); + } +} + +function currentMonthRange(now: Date) { + return { + start: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)), + end: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)), + }; +} diff --git a/apps/backend/src/modules/attendees/features/get-stats/route.ts b/apps/backend/src/modules/attendees/features/get-stats/route.ts new file mode 100644 index 0000000..6bf75f3 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-stats/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetAttendeeStats } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/attendees/:attendeeId/stats', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const attendeeId = c.req.param('attendeeId'); + const useCase = new GetAttendeeStats(); + const result = await useCase.execute(groupId, attendeeId, user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/get-stats/use-case.ts b/apps/backend/src/modules/attendees/features/get-stats/use-case.ts new file mode 100644 index 0000000..95144b1 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-stats/use-case.ts @@ -0,0 +1,59 @@ +import type { AttendanceStatus, PrismaClient } from '@generated/prisma/client'; +import type { AttendeeStats, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; + +type GetAttendeeStatsDeps = { + db?: Pick; +}; + +export class GetAttendeeStats { + constructor(private readonly deps: GetAttendeeStatsDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { id: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + const rows = await db.attendance.groupBy({ + by: ['status'], + where: { attendeeId }, + _count: { _all: true }, + }); + + const countByStatus = (status: AttendanceStatus): number => + rows.find((row) => row.status === status)?._count._all ?? 0; + + const presentCount = countByStatus('PRESENT'); + const absentCount = countByStatus('ABSENT'); + const excusedCount = countByStatus('EXCUSED'); + const totalMarked = presentCount + absentCount + excusedCount; + + return ok({ + attendeeId, + groupId, + presentCount, + absentCount, + excusedCount, + totalMarked, + attendanceRate: totalMarked > 0 ? Math.round((presentCount / totalMarked) * 100) : 0, + }); + } +} diff --git a/apps/backend/src/modules/attendees/features/move/route.ts b/apps/backend/src/modules/attendees/features/move/route.ts new file mode 100644 index 0000000..2b74ba0 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/move/route.ts @@ -0,0 +1,24 @@ +import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared'; +import { MoveAttendeeSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { MoveAttendee } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new MoveAttendee(); + const result = await useCase.execute({ + groupId: c.req.param('groupId'), + attendeeId: c.req.param('attendeeId'), + userId: user.id, + targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId, + }); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/move/use-case.ts b/apps/backend/src/modules/attendees/features/move/use-case.ts new file mode 100644 index 0000000..5fd2394 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/move/use-case.ts @@ -0,0 +1,77 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers'; +import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote'; +import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers'; + +type MoveAttendeeDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + now?: () => Date; +}; + +type MoveAttendeeCommand = { + groupId: string; + attendeeId: string; + userId: string; + targetGroupId: string; +}; + +/* Moves a member to another group of the same teacher. It is the same attendee + with another `groupId`: past attendance, fees (they stay owed to the old + group) and the student app access go with them. Only what was booked for + the old group's future classes is undone: absence notices, the EXCUSED rows + they left and the released slots. */ +export class MoveAttendee { + constructor(private readonly deps: MoveAttendeeDeps = {}) {} + + async execute(command: MoveAttendeeCommand): Promise> { + const { groupId, attendeeId, userId, targetGroupId } = command; + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const now = this.deps.now?.() ?? new Date(); + + const sourceResult = await findGroupOwnedByUser(db, groupId, userId); + if (!sourceResult.ok) return sourceResult; + + const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } }); + if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + + if (targetGroupId === groupId) { + return err( + conflictProblem({ + detail: 'El miembro ya pertenece a este grupo.', + code: 'attendee_same_group', + }), + ); + } + + const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId); + if (!targetResult.ok) return targetResult; + + return unitOfWork.executeResult( + async (tx: Prisma.TransactionClient): Promise> => { + const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId); + if (!canJoin.ok) return canJoin; + + const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } }; + await tx.absenceNotice.updateMany({ + where: { attendeeId, cancelledAt: null, ...futureOldClasses }, + data: { cancelledAt: now }, + }); + await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } }); + await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } }); + + const moved = await tx.attendee.update({ + where: { id: attendeeId }, + data: { groupId: targetGroupId }, + include: attendeeWithPerson, + }); + return ok(toAttendeeDto(moved)); + }, + ); + } +} diff --git a/apps/backend/src/modules/attendees/features/remove/route.ts b/apps/backend/src/modules/attendees/features/remove/route.ts new file mode 100644 index 0000000..6596ffc --- /dev/null +++ b/apps/backend/src/modules/attendees/features/remove/route.ts @@ -0,0 +1,24 @@ +import { type RemoveAttendeeQuery, RemoveAttendeeQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { RemoveAttendee } from './use-case'; + +const route = new Hono(); + +route.delete('/:groupId/attendees/:attendeeId', validate.query(RemoveAttendeeQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const attendeeId = c.req.param('attendeeId'); + const query = c.req.valid('query') as RemoveAttendeeQuery; + const useCase = new RemoveAttendee(); + const result = await useCase.execute(groupId, attendeeId, user.id, { + promoteFromWaitlist: query.promoteFromWaitlist, + }); + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/remove/use-case.ts b/apps/backend/src/modules/attendees/features/remove/use-case.ts new file mode 100644 index 0000000..9201822 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/remove/use-case.ts @@ -0,0 +1,80 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, RemoveAttendeeResult, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { attendeeHasPaymentsProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { + findGroupOwnedByUser, + toGroupWaitlistEntryDto, +} from '@/modules/group-waitlist/lib/helpers'; +import { promoteFirstPendingWaitlistEntry } from '@/modules/group-waitlist/lib/promote'; + +type RemoveAttendeeDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; +}; + +type RemoveAttendeeOptions = { + promoteFromWaitlist?: boolean; +}; + +export class RemoveAttendee { + constructor(private readonly deps: RemoveAttendeeDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + options: RemoveAttendeeOptions = {}, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + const groupResult = await findGroupOwnedByUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + const group = groupResult.value; + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { personId: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + const paymentsCount = await db.payment.count({ where: { attendeeId } }); + if (paymentsCount > 0) { + return err(attendeeHasPaymentsProblem()); + } + + return unitOfWork.executeResult( + async (tx: Prisma.TransactionClient): Promise> => { + await tx.attendee.delete({ where: { id: attendeeId } }); + // Their last group: the person goes too (with their student app link). + await tx.person.deleteMany({ + where: { id: attendee.personId, attendees: { none: {} } }, + }); + + if (!options.promoteFromWaitlist) { + return ok({ removedAttendeeId: attendeeId, promoted: null }); + } + + const promoteResult = await promoteFirstPendingWaitlistEntry(tx, group); + if (!promoteResult.ok) { + return err(promoteResult.error); + } + if (!promoteResult.value) { + return ok({ removedAttendeeId: attendeeId, promoted: null }); + } + + await tx.groupWaitlistEntry.delete({ where: { id: promoteResult.value.entry.id } }); + return ok({ + removedAttendeeId: attendeeId, + promoted: toGroupWaitlistEntryDto(promoteResult.value.entry), + }); + }, + ); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/update/route.ts b/apps/backend/src/modules/attendees/features/update/route.ts new file mode 100644 index 0000000..507b5ac --- /dev/null +++ b/apps/backend/src/modules/attendees/features/update/route.ts @@ -0,0 +1,24 @@ +import type { UpdateAttendee } from '@gruperly/shared'; +import { UpdateAttendeeSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { UpdateAttendeeDetails } from './use-case'; + +const route = new Hono(); + +route.patch('/:groupId/attendees/:attendeeId', validate.json(UpdateAttendeeSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new UpdateAttendeeDetails(); + const result = await useCase.execute({ + groupId: c.req.param('groupId'), + attendeeId: c.req.param('attendeeId'), + userId: user.id, + input: c.req.valid('json') as UpdateAttendee, + }); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/update/use-case.ts b/apps/backend/src/modules/attendees/features/update/use-case.ts new file mode 100644 index 0000000..1af86d7 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/update/use-case.ts @@ -0,0 +1,64 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AttendeeDto, ProblemDetails, Result, UpdateAttendee } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; +import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people'; +import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; + +type UpdateAttendeeDeps = { + db?: Pick; +}; + +type UpdateAttendeeCommand = { + groupId: string; + attendeeId: string; + userId: string; + input: UpdateAttendee; +}; + +export class UpdateAttendeeDetails { + constructor(private readonly deps: UpdateAttendeeDeps = {}) {} + + async execute(command: UpdateAttendeeCommand): Promise> { + const { groupId, attendeeId, userId, input } = command; + const db = this.deps.db ?? prisma; + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) return access; + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { personId: true }, + }); + if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + + // Contact data is the person's: the change shows in every group they are in. + try { + await db.person.update({ + where: { id: attendee.personId }, + data: normalizeEditableFields(input), + }); + } catch (error) { + if (isUniqueViolation(error)) return err(personPhoneTakenProblem()); + throw error; + } + + const updated = await db.attendee.findUniqueOrThrow({ + where: { id: attendeeId }, + include: attendeeWithPerson, + }); + return ok(toAttendeeDto(updated)); + } +} + +function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee { + return Object.fromEntries( + Object.entries(input).map(([key, value]) => { + if (value === '') return [key, null]; + // Same normalization as the add form, so the phone keeps matching. + if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)]; + return [key, value]; + }), + ); +} diff --git a/apps/backend/src/modules/attendees/index.ts b/apps/backend/src/modules/attendees/index.ts new file mode 100644 index 0000000..ef72296 --- /dev/null +++ b/apps/backend/src/modules/attendees/index.ts @@ -0,0 +1 @@ +export { default as attendeesRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts new file mode 100644 index 0000000..066bd00 --- /dev/null +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -0,0 +1,126 @@ +import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared'; + +/* Contact data of the person behind an attendee (shared by all their groups). */ +export const personContactSelect = { + id: true, + fullName: true, + email: true, + phone: true, + guardianName: true, + guardianPhone: true, + notes: true, +} as const; + +/* `include` for any attendee query that ends up in `toAttendeeDto`. */ +export const attendeeWithPerson = { person: { select: personContactSelect } } as const; + +export type PersonContactRecord = { + id: string; + fullName: string; + email: string | null; + phone: string | null; + guardianName: string | null; + guardianPhone: string | null; + notes: string | null; +}; + +export type AttendeeRecord = { + id: string; + groupId: string; + personId: string; + notifyToken?: string | null; + createdAt: Date; + updatedAt: Date; + person: PersonContactRecord; +}; + +/** Listing item with the attendance and payment summary already resolved. */ +export type AttendeeListItemRecord = AttendeeRecord & { + attendances: { status: AttendeeListItem['recentAttendance'][number] }[]; + payments: { + status: NonNullable['status']; + dueDate: Date; + }[]; +}; + +export type AttendeeDetailRecord = AttendeeRecord & { + payments: AttendeeListItemRecord['payments']; + otherGroups: AttendeeDetailDto['otherGroups']; +}; + +export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { + return { + id: record.id, + groupId: record.groupId, + personId: record.personId, + fullName: record.person.fullName, + email: record.person.email, + phone: record.person.phone, + guardianName: record.person.guardianName, + guardianPhone: record.person.guardianPhone, + notes: record.person.notes, + notifyToken: record.notifyToken ?? null, + createdAt: record.createdAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + }; +} + +/* The row that summarizes the current charge. If something is unpaid the + oldest due date wins: someone carrying an old charge has to see how many + days late they are, not the due date of a new charge. If nothing is left + unpaid, the last closed payment serves to mark the row as ok. */ +function pickRelevantPayment( + payments: AttendeeListItemRecord['payments'], +): AttendeeListItem['payment'] { + // CANCELLED is not a charge. The query already filters them out, but dropping + // them here too keeps a voided charge from winning the row for being the oldest. + const byDueDate = payments + .filter((payment) => payment.status !== 'CANCELLED') + .sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime()); + const outstanding = byDueDate.find((payment) => payment.status !== 'PAID'); + const relevant = outstanding ?? byDueDate[byDueDate.length - 1]; + + if (!relevant) { + return null; + } + return { status: relevant.status, dueDate: relevant.dueDate.toISOString() }; +} + +export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetailDto { + return { + ...toAttendeeDto(record), + payment: pickRelevantPayment(record.payments), + otherGroups: record.otherGroups, + }; +} + +/* The query comes in descending order; the row shows them from oldest to most + recent so the dot on the right is the latest event. */ +export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem { + return { + ...toAttendeeDto(record), + recentAttendance: [...record.attendances].reverse().map((attendance) => attendance.status), + payment: pickRelevantPayment(record.payments), + }; +} + +/** + * Normalizes phone numbers by stripping spaces, dashes, parentheses and dots. + * Keeps a leading '+' for international numbers. + */ +export function normalizePhone(rawPhone: string): string { + const trimmed = rawPhone.trim(); + const hasPlus = trimmed.startsWith('+'); + const digitsOnly = trimmed.replace(/\D/g, ''); + return hasPlus ? `+${digitsOnly}` : digitsOnly; +} + +/* For queries that select a few person fields next to the attendee's: turns + `{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading + flat rows stays as it was. */ +export function flattenPerson( + row: TRow, +): Omit & TRow['person'] { + const { person, ...rest } = row; + return { ...rest, ...person }; +} diff --git a/apps/backend/src/modules/students/routes.ts b/apps/backend/src/modules/attendees/routes.ts similarity index 100% rename from apps/backend/src/modules/students/routes.ts rename to apps/backend/src/modules/attendees/routes.ts diff --git a/apps/backend/src/modules/attention/features/get-overview/route.ts b/apps/backend/src/modules/attention/features/get-overview/route.ts new file mode 100644 index 0000000..1d981ce --- /dev/null +++ b/apps/backend/src/modules/attention/features/get-overview/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetAttentionOverview } from './use-case'; + +const route = new Hono(); + +route.get('/', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const useCase = new GetAttentionOverview(); + const result = await useCase.execute(user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attention/features/get-overview/use-case.ts b/apps/backend/src/modules/attention/features/get-overview/use-case.ts new file mode 100644 index 0000000..aeec72e --- /dev/null +++ b/apps/backend/src/modules/attention/features/get-overview/use-case.ts @@ -0,0 +1,188 @@ +import type { Prisma } from '@generated/prisma/client'; +import type { + AttendanceStatus, + AttentionGroup, + AttentionMember, + AttentionOverview, + ProblemDetails, + Result, + StudentAlertType, +} from '@gruperly/shared'; +import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance'; +import { flattenPerson } from '@/modules/attendees/lib/helpers'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { contactPhone } from '@/modules/people/lib/people'; +import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind'; + +type GetAttentionOverviewDeps = { + db?: { + group: Prisma.GroupDelegate; + attendee: Prisma.AttendeeDelegate; + classSession: Prisma.ClassSessionDelegate; + attendance: Prisma.AttendanceDelegate; + payment: Prisma.PaymentDelegate; + attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate; + user: Prisma.UserDelegate; + }; + now?: Date; +}; + +type GroupRow = { id: string; name: string; capacity: number | null }; +type AttendeeRow = { + id: string; + groupId: string; + fullName: string; + phone: string | null; + guardianPhone: string | null; + createdAt: Date; +}; +type SessionRow = { id: string; groupId: string; startsAt: Date }; +type AttendanceRow = { + attendeeId: string; + classSessionId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; +type PaymentRow = { + id: string; + attendeeId: string; + amount: Prisma.Decimal; + currency: string; + dueDate: Date; + checkoutUrl: string | null; +}; +type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string }; + +/* Every ACTIVE member of the user's groups with their alerts ("Requiere + atención"). The list screen draws all the avatars from here, so it returns + members without alerts too. The rule is `computeStudentAlerts` (shared) over + the same attendance input the risk overview builds (`toMemberAttendance`). */ +export class GetAttentionOverview { + constructor(private readonly deps: GetAttentionOverviewDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const groups = (await db.group.findMany({ + where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, + select: { id: true, name: true, capacity: true }, + orderBy: { createdAt: 'asc' }, + })) as GroupRow[]; + + if (groups.length === 0) { + return ok({ groups: [] }); + } + + const groupIds = groups.map((group) => group.id); + + const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([ + // Phones are stored the way people write them (`11 2345-6789`): the + // professor's country settles the calling code, as in the WhatsApp jobs. + db.user.findUnique({ where: { id: userId }, select: { country: true } }), + db.attendee.findMany({ + where: { groupId: { in: groupIds }, status: 'ACTIVE' }, + select: { + id: true, + groupId: true, + createdAt: true, + person: { select: { fullName: true, phone: true, guardianPhone: true } }, + }, + orderBy: { createdAt: 'asc' }, + }).then((rows): AttendeeRow[] => rows.map(flattenPerson)), + // Past classes only, most recent first: `toMemberAttendance` keeps the + // last 20 per attendee, more than the 6-class window needs. + db.classSession.findMany({ + where: { groupId: { in: groupIds }, startsAt: { lte: now } }, + select: { id: true, groupId: true, startsAt: true }, + orderBy: { startsAt: 'desc' }, + }) as Promise, + db.attendance.findMany({ + where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } }, + select: { + attendeeId: true, + classSessionId: true, + status: true, + classSession: { select: { startsAt: true } }, + }, + }) as Promise, + db.payment.findMany({ + where: { + groupId: { in: groupIds }, + status: 'OVERDUE', + attendee: { status: 'ACTIVE' }, + // A fee the student reported (with a receipt) is out of the alert while + // the teacher reviews it; a rejection brings it back. + reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } }, + }, + select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true }, + orderBy: { dueDate: 'asc' }, + }) as Promise, + db.attendeeAlertResolution.findMany({ + where: { attendee: { groupId: { in: groupIds } } }, + select: { attendeeId: true, kind: true, signature: true }, + }) as Promise, + ]); + + const country = countryCodeSchema.safeParse(owner?.country); + const sessionsByGroup = groupBy(sessions, (session) => session.groupId); + const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId); + const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId); + const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId); + const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId); + + const items: AttentionGroup[] = groups.map((group) => ({ + groupId: group.id, + groupName: group.name, + capacity: group.capacity, + members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => { + const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({ + id: payment.id, + amount: Number(payment.amount), + currency: payment.currency, + dueDate: payment.dueDate.toISOString(), + checkoutUrl: payment.checkoutUrl, + })); + const alerts = computeStudentAlerts( + { + attendance: toMemberAttendance( + attendee, + sessionsByGroup.get(group.id) ?? [], + attendanceByAttendee.get(attendee.id) ?? [], + ), + overduePayments, + }, + now, + ); + const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({ + tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType, + firma: row.signature, + })); + + const phone = contactPhone(attendee); + return { + attendeeId: attendee.id, + fullName: attendee.fullName, + phone, + whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null, + alerts: applyResolutions(alerts, resolved), + overduePayments, + }; + }), + })); + + return ok({ groups: items }); + } +} + +function groupBy(rows: T[], key: (row: T) => string): Map { + const map = new Map(); + for (const row of rows) { + const list = map.get(key(row)) ?? []; + list.push(row); + map.set(key(row), list); + } + return map; +} diff --git a/apps/backend/src/modules/attention/features/resolve/route.ts b/apps/backend/src/modules/attention/features/resolve/route.ts new file mode 100644 index 0000000..62ed14e --- /dev/null +++ b/apps/backend/src/modules/attention/features/resolve/route.ts @@ -0,0 +1,23 @@ +import type { ResolveAlert } from '@gruperly/shared'; +import { ResolveAlertSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ResolveStudentAlert } from './use-case'; + +const route = new Hono(); + +route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const payload = c.req.valid('json') as ResolveAlert; + const useCase = new ResolveStudentAlert(); + const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attention/features/resolve/use-case.ts b/apps/backend/src/modules/attention/features/resolve/use-case.ts new file mode 100644 index 0000000..fce1418 --- /dev/null +++ b/apps/backend/src/modules/attention/features/resolve/use-case.ts @@ -0,0 +1,49 @@ +import type { Prisma } from '@generated/prisma/client'; +import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind'; + +type ResolveAlertDeps = { + db?: { + attendee: Prisma.AttendeeDelegate; + attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate; + }; +}; + +export type ResolveAlertResult = ResolveAlert & { attendeeId: string }; + +/* "Resuelto": stores the signature of the alert the professor saw. One row per + attendee and type, overwritten on each resolve, so the table never grows past + two rows per attendee. An attendee outside the user's groups is a 404, not a + 403: we don't confirm that the id exists. */ +export class ResolveStudentAlert { + constructor(private readonly deps: ResolveAlertDeps = {}) {} + + async execute( + attendeeId: string, + userId: string, + payload: ResolveAlert, + ): Promise> { + const db = this.deps.db ?? prisma; + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput }, + select: { id: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + const kind = ALERT_TYPE_TO_KIND[payload.tipo]; + await db.attendeeAlertResolution.upsert({ + where: { attendeeId_kind: { attendeeId, kind } }, + create: { attendeeId, kind, signature: payload.firma, resolvedById: userId }, + update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() }, + }); + + return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma }); + } +} diff --git a/apps/backend/src/modules/attention/index.ts b/apps/backend/src/modules/attention/index.ts new file mode 100644 index 0000000..b7196c4 --- /dev/null +++ b/apps/backend/src/modules/attention/index.ts @@ -0,0 +1 @@ +export { default as attentionRoutes } from './routes'; diff --git a/apps/backend/src/modules/attention/lib/alert-kind.ts b/apps/backend/src/modules/attention/lib/alert-kind.ts new file mode 100644 index 0000000..777e155 --- /dev/null +++ b/apps/backend/src/modules/attention/lib/alert-kind.ts @@ -0,0 +1,13 @@ +import type { StudentAlertKind } from '@generated/prisma/client'; +import type { StudentAlertType } from '@gruperly/shared'; + +/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */ +export const ALERT_KIND_TO_TYPE: Record = { + ATTENDANCE: 'asistencia', + PAYMENT: 'pago', +}; + +export const ALERT_TYPE_TO_KIND: Record = { + asistencia: 'ATTENDANCE', + pago: 'PAYMENT', +}; diff --git a/apps/backend/src/modules/attention/routes.ts b/apps/backend/src/modules/attention/routes.ts new file mode 100644 index 0000000..ba1c069 --- /dev/null +++ b/apps/backend/src/modules/attention/routes.ts @@ -0,0 +1,10 @@ +import { Hono } from 'hono'; +import getOverviewRoute from './features/get-overview/route'; +import resolveRoute from './features/resolve/route'; + +const routes = new Hono(); + +routes.route('/', getOverviewRoute); +routes.route('/', resolveRoute); + +export default routes; diff --git a/apps/backend/src/modules/auth/auth.ts b/apps/backend/src/modules/auth/auth.ts index cb1d572..8f9458e 100644 --- a/apps/backend/src/modules/auth/auth.ts +++ b/apps/backend/src/modules/auth/auth.ts @@ -1,4 +1,5 @@ import { passkey } from '@better-auth/passkey'; +import { appLocaleSchema } from '@gruperly/shared'; import { betterAuth } from 'better-auth'; import { prismaAdapter } from 'better-auth/adapters/prisma'; import { organization } from 'better-auth/plugins/organization'; @@ -11,9 +12,22 @@ export const auth = betterAuth({ database: prismaAdapter(getPrismaClient(), { provider: 'postgresql', }), + user: { + additionalFields: { + // UI language chosen in Ajustes; null means "follow the device". The web + // saves it with updateUser and reads it back from the session. + locale: { + type: 'string', + required: false, + input: true, + validator: { input: appLocaleSchema.nullable() }, + }, + }, + }, emailAndPassword: { enabled: true, minPasswordLength: 8, + revokeSessionsOnPasswordReset: true, sendResetPassword: async ({ user, url }) => { await emailProvider.sendPasswordResetEmail({ email: user.email, diff --git a/apps/backend/src/modules/billing/features/cancel/route.ts b/apps/backend/src/modules/billing/features/cancel/route.ts new file mode 100644 index 0000000..ec19a5f --- /dev/null +++ b/apps/backend/src/modules/billing/features/cancel/route.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { CancelSubscription } from './use-case'; + +const route = new Hono(); + +route.post('/cancel', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const result = await new CancelSubscription().execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/cancel/use-case.ts b/apps/backend/src/modules/billing/features/cancel/use-case.ts new file mode 100644 index 0000000..9821dd1 --- /dev/null +++ b/apps/backend/src/modules/billing/features/cancel/use-case.ts @@ -0,0 +1,49 @@ +import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noActiveSubscriptionProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { subscriptionRefOf } from '../../lib'; +import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers'; + +type CancelSubscriptionDeps = { + db?: Pick; + providers?: BillingProviderResolver; +}; + +/** + * Stops the monthly charge with the provider that collects it. `paidThrough` + * stays: the professor keeps Pro until the end of what they already paid + * (plus the grace period). + */ +export class CancelSubscription { + constructor(private readonly deps: CancelSubscriptionDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + + const subscription = await db.billingSubscription.findUnique({ where: { userId } }); + if ( + !subscription + || (!subscription.externalId && !subscription.checkoutRef) + || subscription.status === 'CANCELLED' + ) { + return err(noActiveSubscriptionProblem()); + } + + try { + await (this.deps.providers ?? getBillingProvider)(subscription.provider).cancel( + subscriptionRefOf(subscription), + ); + } catch (error) { + return err(toBillingProblem(error)); + } + + await db.billingSubscription.update({ + where: { id: subscription.id }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + + return ok({ status: 'CANCELLED' }); + } +} diff --git a/apps/backend/src/modules/billing/features/charges/route.ts b/apps/backend/src/modules/billing/features/charges/route.ts new file mode 100644 index 0000000..5cc6c0f --- /dev/null +++ b/apps/backend/src/modules/billing/features/charges/route.ts @@ -0,0 +1,19 @@ +import type { BillingChargesQuery } from '@gruperly/shared'; +import { BillingChargesQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListBillingCharges } from './use-case'; + +const route = new Hono(); + +route.get('/charges', validate.query(BillingChargesQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const query = c.req.valid('query') as BillingChargesQuery; + const result = await new ListBillingCharges().execute(query, user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/charges/use-case.ts b/apps/backend/src/modules/billing/features/charges/use-case.ts new file mode 100644 index 0000000..8873b6e --- /dev/null +++ b/apps/backend/src/modules/billing/features/charges/use-case.ts @@ -0,0 +1,36 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { BillingChargeList, BillingChargesQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; +import { toBillingChargeDto } from '../../lib'; + +type ListBillingChargesDeps = { db?: Pick }; + +/** The professor's own Pro charges, newest first. */ +export class ListBillingCharges { + constructor(private readonly deps: ListBillingChargesDeps = {}) {} + + async execute( + query: BillingChargesQuery, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const where = { subscription: { userId } }; + + const [charges, total] = await Promise.all([ + db.billingCharge.findMany({ + where, + orderBy: { createdAt: 'desc' }, + skip: getPaginationOffset(query), + take: query.pageSize, + }), + db.billingCharge.count({ where }), + ]); + + return ok({ + data: charges.map(toBillingChargeDto), + pagination: getPaginationMetadata(query, total), + }); + } +} diff --git a/apps/backend/src/modules/billing/features/status/route.ts b/apps/backend/src/modules/billing/features/status/route.ts new file mode 100644 index 0000000..b79fe1c --- /dev/null +++ b/apps/backend/src/modules/billing/features/status/route.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetBillingStatus } from './use-case'; + +const route = new Hono(); + +route.get('/status', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const result = await new GetBillingStatus().execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/status/use-case.ts b/apps/backend/src/modules/billing/features/status/use-case.ts new file mode 100644 index 0000000..42130ef --- /dev/null +++ b/apps/backend/src/modules/billing/features/status/use-case.ts @@ -0,0 +1,78 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared'; +import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { countryOf, PlanGuard, SyncSubscription } from '../../lib'; +import { type BillingProviderResolver, getBillingProvider } from '../../providers'; + +/** A PENDING subscription is re-read from Mercado Pago at most this often. */ +const PENDING_SYNC_INTERVAL_MS = 30 * 1000; + +type GetBillingStatusDeps = { + db?: Pick; + guard?: PlanGuard; + sync?: Pick; + providers?: BillingProviderResolver; + now?: () => Date; +}; + +export class GetBillingStatus { + constructor(private readonly deps: GetBillingStatusDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now?.() ?? new Date(); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) return err(notFoundResourceProblem('User', userId)); + const country = countryOf(user); + + let subscription = await db.billingSubscription.findUnique({ where: { userId } }); + + // Coming back from the provider's checkout, the webhook may not have + // arrived yet (or may never arrive in local dev): ask directly, throttled. + if ( + subscription?.status === 'PENDING' + && (subscription.externalId || subscription.checkoutRef) + && (!subscription.lastSyncedAt + || now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS) + ) { + const synced = await (this.deps.sync ?? new SyncSubscription()).execute(subscription.id); + if (synced.ok && synced.value.synced) { + subscription = await db.billingSubscription.findUnique({ where: { userId } }); + } + } + + const entitlements = await (this.deps.guard ?? new PlanGuard()).getEntitlements(userId); + // A live subscription keeps the price it was created with; otherwise the + // current price of the country is what subscribing would cost. + const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null; + // An authorized subscription stays with its provider; a new attempt (or + // retrying a PENDING one) goes to the country's current provider. + const provider = (this.deps.providers ?? getBillingProvider)( + live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country), + ); + + return ok({ + plan: entitlements.plan, + status: subscription?.status ?? null, + readOnly: entitlements.readOnly, + graceUntil: entitlements.graceUntil?.toISOString() ?? null, + paidThrough: subscription?.paidThrough?.toISOString() ?? null, + nextPaymentDate: + subscription?.status === 'AUTHORIZED' + ? (subscription.nextPaymentDate?.toISOString() ?? null) + : null, + payerEmail: subscription?.payerEmail ?? null, + priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country], + currency: live ? live.currency : COUNTRY_CURRENCY[country], + country, + provider: provider.id, + availableInCountry: provider.isAvailable(country), + enforced: entitlements.enforced, + usage: entitlements.usage, + limits: entitlements.limits, + }); + } +} diff --git a/apps/backend/src/modules/billing/features/subscribe/route.ts b/apps/backend/src/modules/billing/features/subscribe/route.ts new file mode 100644 index 0000000..4013de7 --- /dev/null +++ b/apps/backend/src/modules/billing/features/subscribe/route.ts @@ -0,0 +1,21 @@ +import type { SubscribeInput } from '@gruperly/shared'; +import { SubscribeInputSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { Subscribe } from './use-case'; + +const route = new Hono(); + +// Returns `{ checkoutUrl }`: the browser navigates there to authorize the +// subscription in Mercado Pago, the same way `/mp/connect` works. +route.post('/subscribe', validate.json(SubscribeInputSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const input = c.req.valid('json') as SubscribeInput; + const result = await new Subscribe().execute(user.id, input); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/subscribe/use-case.ts b/apps/backend/src/modules/billing/features/subscribe/use-case.ts new file mode 100644 index 0000000..52ecbe0 --- /dev/null +++ b/apps/backend/src/modules/billing/features/subscribe/use-case.ts @@ -0,0 +1,115 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared'; +import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { + billingNotAvailableProblem, + notFoundResourceProblem, + payerEmailRequiredProblem, + subscriptionAlreadyActiveProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { getWebOrigin } from '@/modules/mp/lib'; +import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib'; +import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers'; + +type SubscribeDeps = { + db?: Pick; + providers?: BillingProviderResolver; + webOrigin?: string; + now?: () => Date; +}; + +/** + * Starts a monthly Pro subscription with the billing provider of the + * professor's country and returns where the browser goes to authorize it. + * + * The row is written PENDING before calling the provider (it is the source of + * truth, like `Payment` rows in the batch). A previous subscription that was + * never authorized is voided first, with whichever provider it was created, so + * the professor can fix the payer email (or switch country) by trying again. + */ +export class Subscribe { + constructor(private readonly deps: SubscribeDeps = {}) {} + + async execute(userId: string, input: SubscribeInput): Promise> { + const db = this.deps.db ?? prisma; + const providers = this.deps.providers ?? getBillingProvider; + const now = this.deps.now?.() ?? new Date(); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) return err(notFoundResourceProblem('User', userId)); + + const country = countryOf(user); + const provider = providers(billingProviderForCountry(country)); + if (!provider.isAvailable(country)) return err(billingNotAvailableProblem()); + if (provider.requiresPayerEmail && !input.payerEmail) return err(payerEmailRequiredProblem()); + + const existing = await db.billingSubscription.findUnique({ where: { userId } }); + if (existing?.status === 'AUTHORIZED') { + return err(subscriptionAlreadyActiveProblem()); + } + + if ((existing?.externalId || existing?.checkoutRef) && existing.status !== 'CANCELLED') { + try { + await providers(existing.provider).cancel(subscriptionRefOf(existing)); + } catch { + // A stale attempt that cannot be voided is harmless: it was never + // authorized, and its notifications no longer match our row. + logger.warn({ userId }, 'Could not void the previous Pro subscription attempt'); + } + } + + const amount = PRO_PRICE_BY_COUNTRY[country]; + const currency = COUNTRY_CURRENCY[country]; + const fields = { + country, + currency, + amount, + provider: provider.id, + // Stripe asks for the email in its checkout; the sync stores the real one. + payerEmail: input.payerEmail ?? user.email, + }; + + const row = await db.billingSubscription.upsert({ + where: { userId }, + create: { userId, ...fields, status: 'PENDING', requestedAt: now }, + update: { + ...fields, + status: 'PENDING', + requestedAt: now, + externalId: null, + checkoutRef: null, + authorizedAt: null, + nextPaymentDate: null, + }, + }); + + // Re-subscribing before the paid period ends: the first charge waits for it, + // so nobody pays twice for the same month. + const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined; + + let started: Awaited>; + try { + started = await provider.start({ + userId, + country, + amount, + currency, + payerEmail: input.payerEmail ?? null, + backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo), + startDate, + }); + } catch (error) { + logger.error({ userId, provider: provider.id }, 'Could not start the Pro subscription'); + return err(toBillingProblem(error)); + } + + await db.billingSubscription.update({ + where: { id: row.id }, + data: { externalId: started.externalId, checkoutRef: started.checkoutRef, lastSyncedAt: now }, + }); + + return ok({ checkoutUrl: started.checkoutUrl }); + } +} diff --git a/apps/backend/src/modules/billing/features/webhook/route.ts b/apps/backend/src/modules/billing/features/webhook/route.ts new file mode 100644 index 0000000..e055182 --- /dev/null +++ b/apps/backend/src/modules/billing/features/webhook/route.ts @@ -0,0 +1,41 @@ +import type { BillingProviderId } from '@gruperly/shared'; +import type { Context } from 'hono'; +import { Hono } from 'hono'; +import { logger } from '@/logger'; +import { type BillingWebhookFailure, HandleBillingWebhook } from './use-case'; + +/** + * Public endpoints (see `isPublicApiRequest`): the providers call them, not the + * browser, so there is no session; each adapter checks its own signature. + * Mercado Pago has one URL per country, because each country is a different + * Gruperly account with its own secret; Stripe is a single account. + */ +const route = new Hono(); + +const FAILURE_STATUS: Record = { + invalid_signature: 401, + unknown_country: 404, + not_configured: 503, + sync_failed: 500, +}; + +async function handle(c: Context, providerId: BillingProviderId, routeParam: string | null) { + const result = await new HandleBillingWebhook().execute(providerId, { + routeParam, + rawBody: await c.req.text(), + headers: c.req.raw.headers, + query: new URL(c.req.url).searchParams, + }); + + if (!result.ok) { + logger.warn({ provider: providerId, reason: result.error }, 'Billing webhook rejected'); + return c.body(null, FAILURE_STATUS[result.error]); + } + + return c.json({ received: true, duplicate: result.value.duplicate }); +} + +route.post('/webhooks/mp/:country', (c) => handle(c, 'MERCADO_PAGO', c.req.param('country'))); +route.post('/webhooks/stripe', (c) => handle(c, 'STRIPE', null)); + +export default route; diff --git a/apps/backend/src/modules/billing/features/webhook/use-case.ts b/apps/backend/src/modules/billing/features/webhook/use-case.ts new file mode 100644 index 0000000..d4a700c --- /dev/null +++ b/apps/backend/src/modules/billing/features/webhook/use-case.ts @@ -0,0 +1,82 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { BillingProviderId, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { SyncSubscription } from '../../lib'; +import { + type BillingProviderResolver, + type BillingWebhookFailure, + type BillingWebhookRequest, + getBillingProvider, +} from '../../providers'; + +export type { BillingWebhookFailure, BillingWebhookRequest } from '../../providers'; + +type HandleBillingWebhookDeps = { + db?: Pick; + providers?: BillingProviderResolver; + sync?: Pick; +}; + +/** Prisma's unique-constraint violation: this delivery was already processed. */ +const UNIQUE_VIOLATION = 'P2002'; + +/** + * Applies one provider notification about a Pro subscription. + * + * The provider adapter checks the signature and says which subscription the + * notification is about; the subscription is then fetched again from the + * provider and synced (`SyncSubscription`). The body is never trusted for a + * status. If syncing fails the dedupe key is removed, so the provider's retry + * gets another chance (same rule as the WhatsApp webhook). + */ +export class HandleBillingWebhook { + constructor(private readonly deps: HandleBillingWebhookDeps = {}) {} + + async execute( + providerId: BillingProviderId, + request: BillingWebhookRequest, + ): Promise> { + const parsed = await (this.deps.providers ?? getBillingProvider)(providerId).parseWebhook(request); + if (!parsed.ok) return parsed; + const hint = parsed.value; + + if (!hint.externalId) return ok({ duplicate: false, applied: false }); + + const db = this.deps.db ?? prisma; + const dedupe = hint.dedupeKey ? { source: hint.source, dedupeKey: hint.dedupeKey } : null; + if (dedupe) { + try { + await db.billingWebhookEvent.create({ data: dedupe }); + } catch (error) { + if ((error as { code?: string }).code === UNIQUE_VIOLATION) { + return ok({ duplicate: true, applied: false }); + } + throw error; + } + } + + const unburn = async () => { + if (!dedupe) return; + await db.billingWebhookEvent + .delete({ where: { source_dedupeKey: dedupe } }) + .catch(() => undefined); + }; + + try { + const synced = await (this.deps.sync ?? new SyncSubscription()).byExternalId( + providerId, + hint.externalId, + hint.country, + ); + if (!synced.ok) { + await unburn(); + return err('sync_failed'); + } + return ok({ duplicate: false, applied: synced.value.synced }); + } catch { + await unburn(); + return err('sync_failed'); + } + } +} diff --git a/apps/backend/src/modules/billing/index.ts b/apps/backend/src/modules/billing/index.ts new file mode 100644 index 0000000..c664a9e --- /dev/null +++ b/apps/backend/src/modules/billing/index.ts @@ -0,0 +1,4 @@ +export { startBillingJobs } from './jobs'; +export { PlanGuard } from './lib/entitlements'; +export { planReadOnlyMiddleware } from './lib/read-only-middleware'; +export { default as billingRoutes } from './routes'; diff --git a/apps/backend/src/modules/billing/jobs/index.ts b/apps/backend/src/modules/billing/jobs/index.ts new file mode 100644 index 0000000..01574f3 --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/index.ts @@ -0,0 +1,2 @@ +export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions'; +export { startBillingJobs } from './schedule'; diff --git a/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts b/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts new file mode 100644 index 0000000..0c3e15d --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts @@ -0,0 +1,71 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { SyncSubscription } from '../lib'; + +const BATCH_SIZE = 50; +const DAY_MS = 24 * 60 * 60 * 1000; +/** A subscription nobody authorized within this window is given up. */ +const PENDING_TTL_MS = 7 * DAY_MS; +/** Authorized subscriptions are re-checked at least daily (renewals, cancellations in MP). */ +const AUTHORIZED_STALE_MS = DAY_MS; + +type ReconcileSubscriptionsDeps = { + db?: Pick; + sync?: Pick; + now?: () => Date; +}; + +export type ReconcileTotals = { checked: number; synced: number; failed: number; expired: number }; + +/** + * Polling fallback for the billing webhook: the webhook can be lost, and in + * local dev it usually never arrives. Every sync is idempotent, so the webhook + * and this job racing over the same row is harmless. + */ +export class ReconcileSubscriptions { + constructor(private readonly deps: ReconcileSubscriptionsDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const sync = this.deps.sync ?? new SyncSubscription(); + const now = this.deps.now?.() ?? new Date(); + const totals: ReconcileTotals = { checked: 0, synced: 0, failed: 0, expired: 0 }; + + const pendingCutoff = new Date(now.getTime() - PENDING_TTL_MS); + const expired = await db.billingSubscription.updateMany({ + where: { status: 'PENDING', requestedAt: { lt: pendingCutoff } }, + data: { status: 'CANCELLED' }, + }); + totals.expired = expired.count; + + const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS); + const rows = await db.billingSubscription.findMany({ + where: { + AND: [ + { OR: [{ externalId: { not: null } }, { checkoutRef: { not: null } }] }, + { + OR: [ + { status: 'PENDING' }, + { + status: { in: ['AUTHORIZED', 'PAUSED'] }, + OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }], + }, + ], + }, + ], + }, + select: { id: true }, + orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } }, + take: BATCH_SIZE, + }); + + for (const row of rows) { + totals.checked += 1; + const result = await sync.execute(row.id); + if (result.ok && result.value.synced) totals.synced += 1; + else if (!result.ok) totals.failed += 1; + } + + return totals; + } +} diff --git a/apps/backend/src/modules/billing/jobs/schedule.ts b/apps/backend/src/modules/billing/jobs/schedule.ts new file mode 100644 index 0000000..5e9b60f --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/schedule.ts @@ -0,0 +1,24 @@ +import { logger } from '@/logger'; +import { ReconcileSubscriptions } from './reconcile-subscriptions'; + +const RECONCILE_CRON = '*/30 * * * *'; + +/** + * Registers the billing background jobs. Called once from `server.ts`, with the + * same guards as `startPaymentJobs`: a rejected promise inside Bun's cron would + * crash the process, and `unref` keeps the job from holding it alive. + */ +export function startBillingJobs(): void { + Bun.cron( + RECONCILE_CRON, + async () => { + try { + const totals = await new ReconcileSubscriptions().execute(); + logger.info(totals, 'Pro subscriptions reconciliation finished'); + } catch (error) { + logger.error({ err: error }, 'Pro subscriptions reconciliation failed'); + } + }, + { tz: 'UTC' }, + ).unref(); +} diff --git a/apps/backend/src/modules/billing/lib/config.ts b/apps/backend/src/modules/billing/lib/config.ts new file mode 100644 index 0000000..4dbb7bd --- /dev/null +++ b/apps/backend/src/modules/billing/lib/config.ts @@ -0,0 +1,16 @@ +const DEFAULT_GRACE_DAYS = 7; + +/** + * Plan limits only apply with `BILLING_ENFORCEMENT=on`. Anything else (unset + * included) treats everyone as Pro, so the module can ship before the existing + * professors are moved to a plan. + */ +export function isBillingEnforced(env: Record = process.env): boolean { + return env.BILLING_ENFORCEMENT?.trim().toLowerCase() === 'on'; +} + +/** Days a lapsed Pro keeps working after its last paid period. */ +export function getGraceDays(env: Record = process.env): number { + const value = Number(env.BILLING_GRACE_DAYS); + return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS; +} diff --git a/apps/backend/src/modules/billing/lib/entitlements.ts b/apps/backend/src/modules/billing/lib/entitlements.ts new file mode 100644 index 0000000..ab8746d --- /dev/null +++ b/apps/backend/src/modules/billing/lib/entitlements.ts @@ -0,0 +1,176 @@ +import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; +import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok, PLAN_LIMITS } from '@gruperly/shared'; +import { + planFeatureRequiredProblem, + planLimitReachedProblem, + planReadOnlyProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { getGraceDays, isBillingEnforced } from './config'; + +const DAY_MS = 24 * 60 * 60 * 1000; + +export type SubscriptionSnapshot = { + status: SubscriptionStatus; + authorizedAt: Date | null; + paidThrough: Date | null; +}; + +export type PlanResolution = { + plan: Plan; + /** Set while Pro survives a lapse (failed renewal or cancellation) on grace. */ + graceUntil: Date | null; +}; + +/** + * Pro lasts while a charge covers today, plus the grace period after the last + * paid day. That one rule covers a cancelled subscription (Pro until the end of + * what was paid) and a failed renewal (Mercado Pago keeps retrying meanwhile). + * + * An AUTHORIZED subscription with no approved charge yet is Pro too, for the + * grace period after the authorization: the first charge is in flight. + */ +export function resolvePlan( + subscription: SubscriptionSnapshot | null, + now: Date, + graceDays: number, +): PlanResolution { + if (!subscription) return { plan: 'FREE', graceUntil: null }; + const graceMs = graceDays * DAY_MS; + + if (subscription.paidThrough) { + if (subscription.paidThrough > now) return { plan: 'PRO', graceUntil: null }; + const graceUntil = new Date(subscription.paidThrough.getTime() + graceMs); + return graceUntil > now ? { plan: 'PRO', graceUntil } : { plan: 'FREE', graceUntil: null }; + } + + if (subscription.status === 'AUTHORIZED' && subscription.authorizedAt) { + const graceUntil = new Date(subscription.authorizedAt.getTime() + graceMs); + if (graceUntil > now) return { plan: 'PRO', graceUntil: null }; + } + + return { plan: 'FREE', graceUntil: null }; +} + +/** + * `resolvePlan` written as a query, for listing accounts by plan: a + * subscription is Pro when its paid period (or, before the first charge, its + * authorization) is younger than the grace period. Keep both in step. + */ +export function proSubscriptionWhere(now: Date, graceDays: number): Prisma.BillingSubscriptionWhereInput { + const cutoff = new Date(now.getTime() - graceDays * DAY_MS); + return { + OR: [ + { paidThrough: { gt: cutoff } }, + { paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } }, + ], + }; +} + +export type PlanUsage = { groups: number; attendees: number }; + +export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean { + return ( + (limits.maxGroups !== null && usage.groups > limits.maxGroups) + || (limits.maxAttendees !== null && usage.attendees > limits.maxAttendees) + ); +} + +export type Entitlements = PlanResolution & { + limits: PlanLimits; + usage: PlanUsage; + /** Free with more usage than its limits. Always false when not enforced. */ + readOnly: boolean; + enforced: boolean; +}; + +type PlanGuardDeps = { + db?: Pick; + enforced?: boolean; + graceDays?: number; + now?: () => Date; +}; + +/** + * What a professor's plan allows. Every check is about the **owner** of the + * group (`group.createdById`): an ADMIN acting on someone else's group spends + * the owner's plan, not their own. + * + * With enforcement off the checks pass without touching the database. + */ +export class PlanGuard { + constructor(private readonly deps: PlanGuardDeps = {}) {} + + private get enforced(): boolean { + return this.deps.enforced ?? isBillingEnforced(); + } + + async getEntitlements(ownerId: string): Promise { + const db = this.deps.db ?? prisma; + const now = this.deps.now?.() ?? new Date(); + + const [subscription, groups, attendees] = await Promise.all([ + db.billingSubscription.findUnique({ + where: { userId: ownerId }, + select: { status: true, authorizedAt: true, paidThrough: true }, + }), + db.group.count({ where: { createdById: ownerId } }), + // People, not memberships: someone in three groups is one student. + db.person.count({ + where: { createdById: ownerId, attendees: { some: { status: 'ACTIVE' } } }, + }), + ]); + + const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays()); + const limits = PLAN_LIMITS[resolution.plan]; + const usage = { groups, attendees }; + const enforced = this.enforced; + + return { + ...resolution, + limits, + usage, + readOnly: enforced && exceedsLimits(limits, usage), + enforced, + }; + } + + async requireWritable(ownerId: string): Promise> { + if (!this.enforced) return ok(undefined); + const entitlements = await this.getEntitlements(ownerId); + return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined); + } + + async canCreateGroup(ownerId: string): Promise> { + if (!this.enforced) return ok(undefined); + const { readOnly, limits, usage } = await this.getEntitlements(ownerId); + if (readOnly) return err(planReadOnlyProblem()); + if (limits.maxGroups !== null && usage.groups + 1 > limits.maxGroups) { + return err(planLimitReachedProblem('groups', limits.maxGroups)); + } + return ok(undefined); + } + + async canAddAttendees(ownerId: string, count = 1): Promise> { + if (!this.enforced || count <= 0) return ok(undefined); + const { readOnly, limits, usage } = await this.getEntitlements(ownerId); + if (readOnly) return err(planReadOnlyProblem()); + if (limits.maxAttendees !== null && usage.attendees + count > limits.maxAttendees) { + return err(planLimitReachedProblem('attendees', limits.maxAttendees)); + } + return ok(undefined); + } + + async requireFeature(ownerId: string, feature: PlanFeature): Promise> { + return (await this.hasFeature(ownerId, feature)) + ? ok(undefined) + : err(planFeatureRequiredProblem(feature)); + } + + async hasFeature(ownerId: string, feature: PlanFeature): Promise { + if (!this.enforced) return true; + const { limits } = await this.getEntitlements(ownerId); + return limits[feature]; + } +} diff --git a/apps/backend/src/modules/billing/lib/helpers.ts b/apps/backend/src/modules/billing/lib/helpers.ts new file mode 100644 index 0000000..e9baf89 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/helpers.ts @@ -0,0 +1,27 @@ +import type { BillingCharge, BillingSubscription } from '@generated/prisma/client'; +import type { BillingChargeDto, BillingReturnTo, CountryCode } from '@gruperly/shared'; +import { countryCodeSchema, DEFAULT_COUNTRY } from '@gruperly/shared'; + +export function toBillingChargeDto(charge: BillingCharge): BillingChargeDto { + return { + id: charge.id, + amount: Number(charge.amount.toString()), + currency: charge.currency, + status: charge.status, + paidAt: charge.paidAt?.toISOString() ?? null, + createdAt: charge.createdAt.toISOString(), + }; +} + +/** The professor's country as stored on the user; Argentina until they pick one. */ +export function countryOf(user: { country: string | null } | null): CountryCode { + const parsed = countryCodeSchema.safeParse(user?.country); + return parsed.success ? parsed.data : DEFAULT_COUNTRY; +} + +/** Where the billing provider sends the professor after authorizing (or abandoning). */ +export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string { + return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`; +} + +export type SubscriptionRecord = BillingSubscription; diff --git a/apps/backend/src/modules/billing/lib/index.ts b/apps/backend/src/modules/billing/lib/index.ts new file mode 100644 index 0000000..59f697a --- /dev/null +++ b/apps/backend/src/modules/billing/lib/index.ts @@ -0,0 +1,13 @@ +export { getGraceDays, isBillingEnforced } from './config'; +export { + type Entitlements, + exceedsLimits, + PlanGuard, + type PlanResolution, + type PlanUsage, + proSubscriptionWhere, + resolvePlan, + type SubscriptionSnapshot, +} from './entitlements'; +export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers'; +export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync'; diff --git a/apps/backend/src/modules/billing/lib/read-only-middleware.ts b/apps/backend/src/modules/billing/lib/read-only-middleware.ts new file mode 100644 index 0000000..ddb84c0 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/read-only-middleware.ts @@ -0,0 +1,29 @@ +import type { MiddlewareHandler } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { problemJson } from '@/http/problem-details'; +import { PlanGuard } from './entitlements'; + +const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); + +/** + * Blocks writes while the professor's account is read-only (Free with more + * usage than its limits). DELETE stays open: removing attendees is how they get + * back under the limits without paying. + * + * It checks the signed-in user. The create paths (groups, attendees) check the + * group **owner** on their own, so an ADMIN cannot add to a read-only owner's group. + */ +export function planReadOnlyMiddleware(guard: PlanGuard = new PlanGuard()): MiddlewareHandler { + return async (c, next) => { + const user = c.get('user'); + if (!user || SAFE_METHODS.has(c.req.method) || c.req.method === 'DELETE') { + await next(); + return; + } + + const writable = await guard.requireWritable(user.id); + if (!writable.ok) return problemJson(c, writable.error); + + await next(); + }; +} diff --git a/apps/backend/src/modules/billing/lib/sync.ts b/apps/backend/src/modules/billing/lib/sync.ts new file mode 100644 index 0000000..c4242c3 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/sync.ts @@ -0,0 +1,164 @@ +import type { BillingSubscription, PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; +import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + type BillingProviderResolver, + getBillingProvider, + type ProviderCharge, + type ProviderSubscription, + type SubscriptionRef, + toBillingProblem, +} from '../providers'; + +export type SyncSubscriptionDeps = { + db?: Pick; + providers?: BillingProviderResolver; + now?: () => Date; +}; + +export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null }; + +export function subscriptionRefOf( + row: Pick, +): SubscriptionRef { + return { country: row.country as CountryCode, externalId: row.externalId, checkoutRef: row.checkoutRef }; +} + +/** + * Brings one subscription row in line with its provider. Shared by the + * webhooks, the reconciliation job and the status endpoint (on read, while + * PENDING). It talks to `row.provider`, never to the country's current one. + * + * Never trusts what a notification says: it asks the provider for the + * subscription and its invoices, checks that the subscription is ours (it + * carries our user id) and only then writes. Re-running it is harmless; every + * write is an upsert or a monotonic `paidThrough`. + */ +export class SyncSubscription { + constructor(private readonly deps: SyncSubscriptionDeps = {}) {} + + async execute(subscriptionId: string): Promise> { + const db = this.deps.db ?? prisma; + const subscription = await db.billingSubscription.findUnique({ where: { id: subscriptionId } }); + if (!subscription || (!subscription.externalId && !subscription.checkoutRef)) { + return ok({ synced: false, status: subscription?.status ?? null }); + } + + const provider = (this.deps.providers ?? getBillingProvider)(subscription.provider); + const ref = subscriptionRefOf(subscription); + + let remote: ProviderSubscription | null; + try { + remote = await provider.fetch(ref); + } catch (error) { + return err(toBillingProblem(error)); + } + // Stripe: the checkout was not completed yet, there is nothing to sync. + if (!remote) return ok({ synced: false, status: subscription.status }); + + if (remote.ownerUserId !== subscription.userId) { + logger.warn({ subscriptionId }, 'Provider subscription does not belong to this subscription'); + return ok({ synced: false, status: subscription.status }); + } + + // The status is what grants Pro (an authorized subscription is Pro during + // the grace days), so failing to list the charges must not leave it + // PENDING: write the status and leave `lastSyncedAt` alone, so the charges + // are retried on the next sync. + let charges: ProviderCharge[] = []; + let chargesSynced = true; + try { + charges = await provider.listCharges({ ...ref, externalId: remote.externalId }); + } catch (error) { + chargesSynced = false; + logger.warn({ subscriptionId, err: error }, 'Could not list the subscription charges; syncing the status only'); + } + + const now = this.deps.now?.() ?? new Date(); + let paidThrough = subscription.paidThrough; + + for (const charge of charges) { + await db.billingCharge.upsert({ + where: { externalId: charge.externalId }, + create: { + subscriptionId: subscription.id, + externalId: charge.externalId, + amount: charge.amount, + currency: charge.currency || subscription.currency, + status: charge.status, + paidAt: charge.paidAt, + }, + update: { status: charge.status, paidAt: charge.paidAt }, + }); + + if (charge.coveredUntil && (!paidThrough || charge.coveredUntil > paidThrough)) { + paidThrough = charge.coveredUntil; + } + } + + const status = remote.status ?? subscription.status; + await db.billingSubscription.update({ + where: { id: subscription.id }, + data: { + // Stripe only creates the subscription when the checkout completes. + externalId: subscription.externalId ? undefined : remote.externalId, + status, + authorizedAt: status === 'AUTHORIZED' && !subscription.authorizedAt ? now : undefined, + nextPaymentDate: remote.nextPaymentDate, + paidThrough, + payerEmail: remote.payerEmail ?? undefined, + lastSyncedAt: chargesSynced ? now : undefined, + }, + }); + + return ok({ synced: true, status }); + } + + /** + * Same as `execute`, starting from the provider's subscription id (webhooks). + * A notification can beat our own write of `externalId` (Mercado Pago: the + * professor authorizes faster than our request returns; Stripe: the checkout + * completes before anyone reads the session), so an unknown id falls back to + * the user id the provider holds, once the provider confirms it. + */ + async byExternalId( + providerId: BillingProviderId, + externalId: string, + country: CountryCode | null, + ): Promise> { + const db = this.deps.db ?? prisma; + const known = await db.billingSubscription.findUnique({ where: { externalId } }); + if (known) return this.execute(known.id); + + let remote: ProviderSubscription | null; + try { + remote = await (this.deps.providers ?? getBillingProvider)(providerId).fetch({ + country, + externalId, + checkoutRef: null, + }); + } catch (error) { + return err(toBillingProblem(error)); + } + // A cancelled one is a previous attempt being replaced, never the new one. + if (!remote?.ownerUserId || remote.status === 'CANCELLED') { + return ok({ synced: false, status: null }); + } + + const claimed = await db.billingSubscription.updateMany({ + where: { + userId: remote.ownerUserId, + provider: providerId, + externalId: null, + ...(country ? { country } : {}), + }, + data: { externalId }, + }); + if (claimed.count === 0) return ok({ synced: false, status: null }); + + const row = await db.billingSubscription.findUnique({ where: { externalId } }); + return row ? this.execute(row.id) : ok({ synced: false, status: null }); + } +} diff --git a/apps/backend/src/modules/billing/providers/billing-provider.ts b/apps/backend/src/modules/billing/providers/billing-provider.ts new file mode 100644 index 0000000..3b4eb39 --- /dev/null +++ b/apps/backend/src/modules/billing/providers/billing-provider.ts @@ -0,0 +1,124 @@ +import type { SubscriptionStatus } from '@generated/prisma/client'; +import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared'; +import { billingNotAvailableProblem, billingProviderErrorProblem } from '@/http/problem-builders'; + +/** + * The port every Pro billing provider implements. The domain (subscribing, + * cancelling, syncing, the webhook and the reconciliation job) only talks to + * this interface; everything that knows about Mercado Pago or Stripe lives in + * `providers//`. Same idea as WhatsApp's `MessagingProvider`. + * + * Calls that reach the provider throw on failure: `BillingProviderNotConfigured` + * when Gruperly has no credentials for it, anything else when the provider + * refused or could not be reached. `toBillingProblem` turns either into the + * Problem Details the use-cases answer with. + */ + +export type { BillingProviderId }; + +/** What identifies one subscription at its provider. */ +export type SubscriptionRef = { + /** Mercado Pago picks Gruperly's account by country; Stripe ignores it. */ + country: CountryCode | null; + /** The provider's subscription id, once it exists. */ + externalId: string | null; + /** A checkout started but not completed yet (Stripe Checkout Session). */ + checkoutRef: string | null; +}; + +export type StartSubscriptionInput = { + /** Our user id: the only thing that ties the subscription back to a professor. */ + userId: string; + country: CountryCode; + amount: number; + currency: string; + /** Mandatory when `requiresPayerEmail`; otherwise only a pre-fill. */ + payerEmail: string | null; + /** Where the provider sends the professor back, completed or not. */ + backUrl: string; + /** First charge date; omitted means right after the professor authorizes. */ + startDate?: Date; +}; + +export type StartedSubscription = { + /** Where the browser goes to authorize the subscription. */ + checkoutUrl: string; + externalId: string | null; + checkoutRef: string | null; +}; + +export type ProviderSubscription = { + externalId: string; + /** Our user id as the provider holds it; checked before trusting anything. */ + ownerUserId: string | null; + /** `null` for a provider status we do not know: the row keeps its own. */ + status: SubscriptionStatus | null; + nextPaymentDate: Date | null; + /** The email the professor actually paid with, when the provider asks for it. */ + payerEmail: string | null; +}; + +export type ChargeStatus = 'approved' | 'pending' | 'rejected'; + +/** One monthly invoice of a subscription. */ +export type ProviderCharge = { + externalId: string; + amount: number; + currency: string | null; + status: ChargeStatus; + paidAt: Date | null; + /** Last day this charge pays for; null unless approved. */ + coveredUntil: Date | null; +}; + +export type BillingWebhookRequest = { + /** The `:country` of `/webhooks/mp/:country`; null for Stripe. */ + routeParam: string | null; + rawBody: string; + headers: Headers; + query: URLSearchParams; +}; + +export type BillingWebhookFailure = + | 'unknown_country' + | 'not_configured' + | 'invalid_signature' + | 'sync_failed'; + +/** What a verified notification points at. The body is never trusted for a status. */ +export type BillingWebhookHint = { + /** The sending account, for deduplication: `mp:` or `stripe`. */ + source: string; + dedupeKey: string | null; + country: CountryCode | null; + /** The subscription to sync; null for events that do not concern one. */ + externalId: string | null; +}; + +export interface BillingProvider { + readonly id: BillingProviderId; + /** Mercado Pago makes the payer log in with the email given up front. */ + readonly requiresPayerEmail: boolean; + /** Gruperly has credentials to collect Pro in that country. */ + isAvailable(country: CountryCode): boolean; + start(input: StartSubscriptionInput): Promise; + /** `null` while the professor has not completed the checkout. */ + fetch(ref: SubscriptionRef): Promise; + listCharges(ref: SubscriptionRef & { externalId: string }): Promise; + /** Stops the monthly charge, or voids a checkout never completed. */ + cancel(ref: SubscriptionRef): Promise; + parseWebhook(request: BillingWebhookRequest): Promise>; +} + +export class BillingProviderNotConfigured extends Error { + constructor(provider: BillingProviderId) { + super(`Billing provider ${provider} is not configured`); + this.name = 'BillingProviderNotConfigured'; + } +} + +export function toBillingProblem(error: unknown): ProblemDetails { + return error instanceof BillingProviderNotConfigured + ? billingNotAvailableProblem() + : billingProviderErrorProblem(); +} diff --git a/apps/backend/src/modules/billing/providers/index.ts b/apps/backend/src/modules/billing/providers/index.ts new file mode 100644 index 0000000..5557e35 --- /dev/null +++ b/apps/backend/src/modules/billing/providers/index.ts @@ -0,0 +1,32 @@ +import type { BillingProviderId } from '@gruperly/shared'; +import type { BillingProvider } from './billing-provider'; +import { MercadoPagoBillingProvider } from './mercado-pago'; +import { StripeBillingProvider } from './stripe'; + +export type * from './billing-provider'; +export { BillingProviderNotConfigured, toBillingProblem } from './billing-provider'; +export { MercadoPagoBillingProvider } from './mercado-pago'; +export { StripeBillingProvider } from './stripe'; + +/** How the domain gets a provider; use-cases take one in `deps` for tests. */ +export type BillingProviderResolver = (id: BillingProviderId) => BillingProvider; + +/** + * The one place that maps a provider id to its adapter. Which provider a new + * subscription uses comes from `billingProviderForCountry` (shared); an + * existing row always keeps its own `provider`. Adding a provider means + * a new `providers//` implementing `BillingProvider`, a case here and an + * entry in `BILLING_PROVIDER_BY_COUNTRY` (shared). + * + * Construction never fails: missing credentials surface as `isAvailable` false + * or as `BillingProviderNotConfigured` (503) when a call needs them. + */ +export const getBillingProvider: BillingProviderResolver = (id) => { + switch (id) { + case 'MERCADO_PAGO': + return new MercadoPagoBillingProvider(); + case 'STRIPE': + return new StripeBillingProvider(); + } +}; + diff --git a/apps/backend/src/modules/billing/providers/mercado-pago/config.ts b/apps/backend/src/modules/billing/providers/mercado-pago/config.ts new file mode 100644 index 0000000..aeb9ea7 --- /dev/null +++ b/apps/backend/src/modules/billing/providers/mercado-pago/config.ts @@ -0,0 +1,26 @@ +import type { CountryCode } from '@gruperly/shared'; + +export type PlatformCredentials = { + /** Access token of Gruperly's own Mercado Pago account in that country. */ + accessToken: string; + /** Secret of the webhook configured in that account's panel. */ + webhookSecret: string; +}; + +/** + * Gruperly's Mercado Pago credentials for one country. Mercado Pago does not + * charge across countries, so each country has its own account; a country + * without both variables cannot subscribe to Pro through Mercado Pago (503, not + * a deployment crash: rolling out country by country is expected). + * + * These are platform credentials, never the professor's OAuth token. + */ +export function getPlatformCredentials( + country: CountryCode, + env: Record = process.env, +): PlatformCredentials | null { + const accessToken = env[`MP_PLATFORM_ACCESS_TOKEN_${country}`]?.trim(); + const webhookSecret = env[`MP_PLATFORM_WEBHOOK_SECRET_${country}`]?.trim(); + if (!accessToken || !webhookSecret) return null; + return { accessToken, webhookSecret }; +} diff --git a/apps/backend/src/modules/billing/providers/mercado-pago/index.ts b/apps/backend/src/modules/billing/providers/mercado-pago/index.ts new file mode 100644 index 0000000..abe05ae --- /dev/null +++ b/apps/backend/src/modules/billing/providers/mercado-pago/index.ts @@ -0,0 +1,199 @@ +import type { SubscriptionStatus } from '@generated/prisma/client'; +import type { CountryCode, Result } from '@gruperly/shared'; +import { countryCodeSchema, err, ok } from '@gruperly/shared'; +import { + type BillingProvider, + BillingProviderNotConfigured, + type BillingWebhookFailure, + type BillingWebhookHint, + type BillingWebhookRequest, + type ChargeStatus, + type ProviderCharge, + type ProviderSubscription, + type StartedSubscription, + type StartSubscriptionInput, + type SubscriptionRef, +} from '../billing-provider'; +import { getPlatformCredentials, type PlatformCredentials } from './config'; +import { type MpAuthorizedPayment, mpPreapprovalClient, type PreapprovalClient } from './preapproval'; +import { verifyMpSignature } from './webhook-signature'; + +export { getPlatformCredentials, type PlatformCredentials } from './config'; +export { + type MpAuthorizedPayment, + type MpPreapproval, + mpPreapprovalClient, + type PreapprovalClient, +} from './preapproval'; +export { verifyMpSignature } from './webhook-signature'; + +const SUBSCRIPTION_REASON = 'Gruperly Pro'; + +const MP_STATUS: Record = { + pending: 'PENDING', + authorized: 'AUTHORIZED', + paused: 'PAUSED', + cancelled: 'CANCELLED', +}; + +const REJECTED_PAYMENT = new Set(['rejected', 'cancelled', 'refunded', 'charged_back']); + +/** One approved monthly charge covers one month from the day it was debited. */ +export function coveredUntil(paidAt: Date): Date { + const until = new Date(paidAt); + until.setUTCMonth(until.getUTCMonth() + 1); + return until; +} + +export function toChargeStatus(invoice: Pick): ChargeStatus { + if (invoice.paymentStatus === 'approved') return 'approved'; + if (invoice.paymentStatus && REJECTED_PAYMENT.has(invoice.paymentStatus)) return 'rejected'; + return invoice.status === 'cancelled' ? 'rejected' : 'pending'; +} + +type MercadoPagoBillingDeps = { + client?: PreapprovalClient; + credentials?: (country: CountryCode) => PlatformCredentials | null; +}; + +/** + * Pro through Mercado Pago Subscriptions (preapproval), collected by + * Gruperly's own account in the professor's country. The preapproval exists as + * soon as it is created, so `externalId` is known from the start and there is + * no `checkoutRef`. + */ +export class MercadoPagoBillingProvider implements BillingProvider { + readonly id = 'MERCADO_PAGO' as const; + readonly requiresPayerEmail = true; + + constructor(private readonly deps: MercadoPagoBillingDeps = {}) {} + + private get client(): PreapprovalClient { + return this.deps.client ?? mpPreapprovalClient; + } + + private credentialsFor(country: CountryCode | null): PlatformCredentials | null { + return country ? (this.deps.credentials ?? getPlatformCredentials)(country) : null; + } + + private tokenFor(country: CountryCode | null): string { + const credentials = this.credentialsFor(country); + if (!credentials) throw new BillingProviderNotConfigured(this.id); + return credentials.accessToken; + } + + isAvailable(country: CountryCode): boolean { + return this.credentialsFor(country) !== null; + } + + async start(input: StartSubscriptionInput): Promise { + if (!input.payerEmail) throw new Error('Mercado Pago needs the payer email'); + const preapproval = await this.client.createPreapproval(this.tokenFor(input.country), { + reason: SUBSCRIPTION_REASON, + externalReference: input.userId, + payerEmail: input.payerEmail, + amount: input.amount, + currencyId: input.currency, + backUrl: input.backUrl, + startDate: input.startDate, + }); + if (!preapproval.initPoint) throw new Error('Mercado Pago preapproval came back without init_point'); + return { checkoutUrl: preapproval.initPoint, externalId: preapproval.id, checkoutRef: null }; + } + + async fetch(ref: SubscriptionRef): Promise { + if (!ref.externalId) return null; + const preapproval = await this.client.getPreapproval(this.tokenFor(ref.country), ref.externalId); + return { + externalId: preapproval.id, + ownerUserId: preapproval.externalReference, + status: MP_STATUS[preapproval.status] ?? null, + nextPaymentDate: preapproval.nextPaymentDate ? new Date(preapproval.nextPaymentDate) : null, + payerEmail: null, + }; + } + + async listCharges(ref: SubscriptionRef & { externalId: string }): Promise { + const invoices = await this.client.searchAuthorizedPayments(this.tokenFor(ref.country), ref.externalId); + return invoices + .filter((invoice) => invoice.preapprovalId === ref.externalId) + .map((invoice) => { + const status = toChargeStatus(invoice); + const debitedAt = invoice.debitDate ?? invoice.createdAt; + const paidAt = status === 'approved' && debitedAt ? new Date(debitedAt) : null; + return { + externalId: invoice.id, + amount: invoice.amount, + currency: invoice.currencyId || null, + status, + paidAt, + coveredUntil: paidAt ? coveredUntil(paidAt) : null, + }; + }); + } + + async cancel(ref: SubscriptionRef): Promise { + if (!ref.externalId) return; + await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId); + } + + /** + * One URL per country, because each country is a different Gruperly account + * with its own secret. Mercado Pago signs a manifest of the notified id, the + * `x-request-id` and a timestamp (`x-signature`), not the body. + */ + async parseWebhook( + request: BillingWebhookRequest, + ): Promise> { + const parsedCountry = countryCodeSchema.safeParse(request.routeParam?.toUpperCase()); + if (!parsedCountry.success) return err('unknown_country'); + const country = parsedCountry.data; + + const credentials = this.credentialsFor(country); + if (!credentials) return err('not_configured'); + + const body = parseBody(request.rawBody); + const dataId = request.query.get('data.id') ?? request.query.get('id') ?? body.dataId; + const type = request.query.get('type') ?? request.query.get('topic') ?? body.type; + const requestId = request.headers.get('x-request-id'); + + const valid = verifyMpSignature({ + signature: request.headers.get('x-signature'), + requestId, + dataId, + secret: credentials.webhookSecret, + }); + if (!valid) return err('invalid_signature'); + + const hint: BillingWebhookHint = { source: `mp:${country}`, dedupeKey: requestId, country, externalId: null }; + if (!dataId || !isSubscriptionTopic(type)) return ok(hint); + + if (type === 'subscription_preapproval') return ok({ ...hint, externalId: dataId }); + + // An invoice notification: the subscription is its preapproval. + try { + const invoice = await this.client.getAuthorizedPayment(credentials.accessToken, dataId); + return ok({ ...hint, externalId: invoice.preapprovalId }); + } catch { + return err('sync_failed'); + } + } +} + +function isSubscriptionTopic( + type: string | null, +): type is 'subscription_preapproval' | 'subscription_authorized_payment' { + return type === 'subscription_preapproval' || type === 'subscription_authorized_payment'; +} + +function parseBody(rawBody: string): { dataId: string | null; type: string | null } { + try { + const payload = JSON.parse(rawBody) as { type?: unknown; data?: { id?: unknown } } | null; + return { + dataId: payload?.data?.id == null ? null : String(payload.data.id), + type: typeof payload?.type === 'string' ? payload.type : null, + }; + } catch { + return { dataId: null, type: null }; + } +} diff --git a/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts b/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts new file mode 100644 index 0000000..af0b49b --- /dev/null +++ b/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts @@ -0,0 +1,194 @@ +import { logger } from '@/logger'; +import { MP_API_URL, MpApiError } from '@/modules/mp/lib'; + +// Mercado Pago Subscriptions (preapproval), called with Gruperly's own +// platform token of the professor's country. Plain `fetch`, like `mp-http.ts`. + +export type MpPreapprovalStatus = 'pending' | 'authorized' | 'paused' | 'cancelled'; + +export type CreatePreapprovalInput = { + reason: string; + /** Our user id: the only thing that ties the subscription back to a professor. */ + externalReference: string; + /** Mercado Pago requires the payer to log in with this exact email. */ + payerEmail: string; + amount: number; + currencyId: string; + backUrl: string; + /** First charge date; omitted means right after the professor authorizes. */ + startDate?: Date; +}; + +export type MpPreapproval = { + id: string; + status: MpPreapprovalStatus | string; + externalReference: string | null; + initPoint: string | null; + nextPaymentDate: string | null; +}; + +export type MpAuthorizedPayment = { + id: string; + preapprovalId: string; + /** Status of the invoice itself: scheduled, processed, recycling, cancelled. */ + status: string; + /** Status of the payment Mercado Pago attempted for it, e.g. approved/rejected. */ + paymentStatus: string | null; + amount: number; + currencyId: string; + /** When the charge was debited (or attempted), ISO. */ + debitDate: string | null; + createdAt: string | null; +}; + +async function request( + accessToken: string, + path: string, + init: { method?: string; body?: unknown } = {}, +): Promise> { + let response: Response; + try { + response = await fetch(`${MP_API_URL}${path}`, { + method: init.method ?? 'GET', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + Authorization: `Bearer ${accessToken}`, + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }); + } catch (error) { + logger.error({ err: error, path: path.split('?')[0] }, 'Mercado Pago subscriptions unreachable'); + throw new MpApiError(0, null); + } + + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as Record | null; + const reason = typeof payload?.message === 'string' ? payload.message : null; + // The path carries ids, never tokens or emails; the body is not logged. + logger.error( + { status: response.status, reason, path: path.split('?')[0] }, + 'Mercado Pago subscriptions request failed', + ); + throw new MpApiError(response.status, reason); + } + + return (await response.json()) as Record; +} + +function toPreapproval(payload: Record): MpPreapproval { + return { + id: String(payload.id), + status: String(payload.status), + externalReference: + typeof payload.external_reference === 'string' ? payload.external_reference : null, + initPoint: typeof payload.init_point === 'string' ? payload.init_point : null, + nextPaymentDate: + typeof payload.next_payment_date === 'string' ? payload.next_payment_date : null, + }; +} + +/** + * Creates a monthly subscription waiting for the professor's authorization. + * Nothing is charged until they log in to Mercado Pago through `initPoint`. + */ +export async function createPreapproval( + accessToken: string, + input: CreatePreapprovalInput, +): Promise { + const payload = await request(accessToken, '/preapproval', { + method: 'POST', + body: { + reason: input.reason, + external_reference: input.externalReference, + payer_email: input.payerEmail, + back_url: input.backUrl, + status: 'pending', + auto_recurring: { + frequency: 1, + frequency_type: 'months', + transaction_amount: input.amount, + currency_id: input.currencyId, + ...(input.startDate ? { start_date: input.startDate.toISOString() } : {}), + }, + }, + }); + return toPreapproval(payload); +} + +export async function getPreapproval(accessToken: string, id: string): Promise { + return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`)); +} + +export async function cancelPreapproval(accessToken: string, id: string): Promise { + return toPreapproval( + await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, { + method: 'PUT', + body: { status: 'cancelled' }, + }), + ); +} + +function toAuthorizedPayment(payload: Record): MpAuthorizedPayment { + const payment = (payload.payment ?? null) as Record | null; + return { + id: String(payload.id), + preapprovalId: String(payload.preapproval_id), + status: String(payload.status), + paymentStatus: typeof payment?.status === 'string' ? payment.status : null, + amount: Number(payload.transaction_amount ?? 0), + currencyId: String(payload.currency_id ?? ''), + debitDate: typeof payload.debit_date === 'string' ? payload.debit_date : null, + createdAt: typeof payload.date_created === 'string' ? payload.date_created : null, + }; +} + +export async function getAuthorizedPayment( + accessToken: string, + id: string, +): Promise { + return toAuthorizedPayment( + await request(accessToken, `/authorized_payments/${encodeURIComponent(id)}`), + ); +} + +/** Safety net for the paging loop: one invoice a month, this is decades. */ +const MAX_INVOICE_PAGES = 20; + +/** + * The invoices of one subscription, newest first as Mercado Pago returns them. + * No `limit`: Mercado Pago answers 400 "Invalid value for limit" to values it + * accepts elsewhere, so it pages with its own default and we follow `offset`. + */ +export async function searchAuthorizedPayments( + accessToken: string, + preapprovalId: string, +): Promise { + const invoices: MpAuthorizedPayment[] = []; + for (let page = 0; page < MAX_INVOICE_PAGES; page++) { + const query = new URLSearchParams({ preapproval_id: preapprovalId, offset: String(invoices.length) }); + const payload = await request(accessToken, `/authorized_payments/search?${query}`); + const results = Array.isArray(payload.results) ? (payload.results as Record[]) : []; + invoices.push(...results.map(toAuthorizedPayment)); + + const total = Number((payload.paging as Record | undefined)?.total); + if (results.length === 0 || !Number.isFinite(total) || invoices.length >= total) break; + } + return invoices; +} + +export type PreapprovalClient = { + createPreapproval: typeof createPreapproval; + getPreapproval: typeof getPreapproval; + cancelPreapproval: typeof cancelPreapproval; + getAuthorizedPayment: typeof getAuthorizedPayment; + searchAuthorizedPayments: typeof searchAuthorizedPayments; +}; + +export const mpPreapprovalClient: PreapprovalClient = { + createPreapproval, + getPreapproval, + cancelPreapproval, + getAuthorizedPayment, + searchAuthorizedPayments, +}; diff --git a/apps/backend/src/modules/billing/providers/mercado-pago/webhook-signature.ts b/apps/backend/src/modules/billing/providers/mercado-pago/webhook-signature.ts new file mode 100644 index 0000000..289a803 --- /dev/null +++ b/apps/backend/src/modules/billing/providers/mercado-pago/webhook-signature.ts @@ -0,0 +1,40 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +/** + * Checks Mercado Pago's `x-signature` header (`ts=,v1=`). + * + * Mercado Pago does not sign the body: it signs a manifest built from the + * notified resource id (the `data.id` query parameter, lower-cased when it is + * alphanumeric), the `x-request-id` header and the timestamp. Parts that did + * not come in the request are left out of the manifest. + */ +export function verifyMpSignature(params: { + signature: string | null; + requestId: string | null; + dataId: string | null; + secret: string; +}): boolean { + if (!params.signature) return false; + + let ts: string | null = null; + let v1: string | null = null; + for (const part of params.signature.split(',')) { + const [key, value] = part.split('=', 2).map((piece) => piece.trim()); + if (key === 'ts') ts = value ?? null; + if (key === 'v1') v1 = value ?? null; + } + if (!ts || !v1) return false; + + const dataId = params.dataId && /^[a-z0-9]+$/i.test(params.dataId) + ? params.dataId.toLowerCase() + : params.dataId; + + let manifest = ''; + if (dataId) manifest += `id:${dataId};`; + if (params.requestId) manifest += `request-id:${params.requestId};`; + manifest += `ts:${ts};`; + + const expected = Buffer.from(createHmac('sha256', params.secret).update(manifest).digest('hex')); + const received = Buffer.from(v1); + return received.length === expected.length && timingSafeEqual(received, expected); +} diff --git a/apps/backend/src/modules/billing/providers/stripe/config.ts b/apps/backend/src/modules/billing/providers/stripe/config.ts new file mode 100644 index 0000000..f3b57ab --- /dev/null +++ b/apps/backend/src/modules/billing/providers/stripe/config.ts @@ -0,0 +1,18 @@ +export type StripeConfig = { + /** Secret key of Gruperly's single Stripe account (`sk_live_…` / `sk_test_…`). */ + secretKey: string; + /** Signing secret of the webhook endpoint (`whsec_…`). */ + webhookSecret: string; +}; + +/** + * One Stripe account collects Pro in every country that is not on Mercado Pago, + * each in its own currency. Without both variables those countries see Pro as + * "no disponible" (503), the same as a Mercado Pago country without credentials. + */ +export function getStripeConfig(env: Record = process.env): StripeConfig | null { + const secretKey = env.STRIPE_SECRET_KEY?.trim(); + const webhookSecret = env.STRIPE_WEBHOOK_SECRET?.trim(); + if (!secretKey || !webhookSecret) return null; + return { secretKey, webhookSecret }; +} diff --git a/apps/backend/src/modules/billing/providers/stripe/index.ts b/apps/backend/src/modules/billing/providers/stripe/index.ts new file mode 100644 index 0000000..ef2bf0b --- /dev/null +++ b/apps/backend/src/modules/billing/providers/stripe/index.ts @@ -0,0 +1,300 @@ +import type { SubscriptionStatus } from '@generated/prisma/client'; +import type { CountryCode, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + type BillingProvider, + BillingProviderNotConfigured, + type BillingWebhookFailure, + type BillingWebhookHint, + type BillingWebhookRequest, + type ChargeStatus, + type ProviderCharge, + type ProviderSubscription, + type StartedSubscription, + type StartSubscriptionInput, + type SubscriptionRef, +} from '../billing-provider'; +import { getStripeConfig, type StripeConfig } from './config'; +import { createStripeRequest, type StripeObject, type StripeRequest } from './stripe-http'; +import { verifyStripeSignature } from './webhook-signature'; + +export { getStripeConfig, type StripeConfig } from './config'; +export { STRIPE_API_VERSION, StripeApiError, toForm } from './stripe-http'; +export { verifyStripeSignature } from './webhook-signature'; + +const PRODUCT_NAME = 'Gruperly Pro'; +/** Our user id on the Stripe subscription: what ties it back to a professor. */ +const USER_ID_METADATA = 'gruperly_user_id'; +/** Checkout only accepts a `trial_end` at least this far ahead. */ +const MIN_TRIAL_MS = 48 * 60 * 60 * 1000; + +// Stripe takes amounts in the currency's minor unit, except these. +const ZERO_DECIMAL_CURRENCIES = new Set([ + 'BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF', +]); + +export function toStripeUnitAmount(amount: number, currency: string): number { + return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? Math.round(amount) : Math.round(amount * 100); +} + +export function fromStripeUnitAmount(unitAmount: number, currency: string): number { + return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? unitAmount : unitAmount / 100; +} + +const STRIPE_STATUS: Record = { + incomplete: 'PENDING', + active: 'AUTHORIZED', + trialing: 'AUTHORIZED', + // Stripe is retrying the charge; Pro survives it on `paidThrough` + grace. + past_due: 'AUTHORIZED', + unpaid: 'PAUSED', + paused: 'PAUSED', + canceled: 'CANCELLED', + incomplete_expired: 'CANCELLED', +}; + +const INVOICE_STATUS: Record = { + paid: 'approved', + open: 'pending', + uncollectible: 'rejected', + void: 'rejected', +}; + +type StripeBillingDeps = { + config?: () => StripeConfig | null; + fetch?: typeof fetch; + now?: () => Date; +}; + +/** + * Pro through Stripe Billing: a Checkout Session in subscription mode, priced + * inline in the professor's currency (`PRO_PRICE_BY_COUNTRY`), so there are no + * Prices to keep in sync in the Dashboard. + * + * The Stripe subscription only exists once the professor completes the + * checkout: until then the row carries the session id (`checkoutRef`) and + * `fetch` resolves the subscription through it. + */ +export class StripeBillingProvider implements BillingProvider { + readonly id = 'STRIPE' as const; + readonly requiresPayerEmail = false; + + constructor(private readonly deps: StripeBillingDeps = {}) {} + + private get config(): StripeConfig | null { + return (this.deps.config ?? getStripeConfig)(); + } + + private get request(): StripeRequest { + const config = this.config; + if (!config) throw new BillingProviderNotConfigured(this.id); + return createStripeRequest(config.secretKey, this.deps.fetch); + } + + isAvailable(_country: CountryCode): boolean { + return this.config !== null; + } + + async start(input: StartSubscriptionInput): Promise { + const now = this.deps.now?.() ?? new Date(); + // Re-subscribing within a paid period: the first charge waits for its end. + // Closer than Checkout allows, it is charged now instead (a few days overlap). + const trialEnd = + input.startDate && input.startDate.getTime() - now.getTime() >= MIN_TRIAL_MS + ? Math.floor(input.startDate.getTime() / 1000) + : null; + + const session = await this.request('/checkout/sessions', { + method: 'POST', + form: { + mode: 'subscription', + client_reference_id: input.userId, + customer_email: input.payerEmail, + success_url: input.backUrl, + cancel_url: input.backUrl, + line_items: [ + { + quantity: 1, + price_data: { + currency: input.currency.toLowerCase(), + unit_amount: toStripeUnitAmount(input.amount, input.currency), + recurring: { interval: 'month' }, + product_data: { name: PRODUCT_NAME }, + }, + }, + ], + subscription_data: { + metadata: { [USER_ID_METADATA]: input.userId }, + trial_end: trialEnd, + }, + }, + }); + + const url = stringOf(session.url); + if (!url) throw new Error('Stripe checkout session came back without url'); + return { checkoutUrl: url, externalId: null, checkoutRef: String(session.id) }; + } + + async fetch(ref: SubscriptionRef): Promise { + const request = this.request; + let subscriptionId = ref.externalId; + let payerEmail: string | null = null; + + if (!subscriptionId) { + if (!ref.checkoutRef) return null; + const session = await request(`/checkout/sessions/${encodeURIComponent(ref.checkoutRef)}`); + subscriptionId = idOf(session.subscription); + payerEmail = stringOf(objectOf(session.customer_details)?.email); + if (!subscriptionId) return null; + } + + const subscription = await request(`/subscriptions/${encodeURIComponent(subscriptionId)}`, { + query: new URLSearchParams({ 'expand[]': 'customer' }), + }); + const status = STRIPE_STATUS[String(subscription.status)] ?? null; + + return { + externalId: String(subscription.id), + ownerUserId: stringOf(objectOf(subscription.metadata)?.[USER_ID_METADATA]), + status, + nextPaymentDate: status === 'CANCELLED' ? null : nextChargeOf(subscription), + payerEmail: payerEmail ?? stringOf(objectOf(subscription.customer)?.email), + }; + } + + async listCharges(ref: SubscriptionRef & { externalId: string }): Promise { + const page = await this.request('/invoices', { + query: new URLSearchParams({ subscription: ref.externalId, limit: '50' }), + }); + const invoices = Array.isArray(page.data) ? (page.data as StripeObject[]) : []; + + return invoices.flatMap((invoice) => { + const status = INVOICE_STATUS[String(invoice.status)]; + // Drafts are not charges yet, and a zero invoice (a trial) charges nothing. + if (!status || Number(invoice.total ?? 0) === 0) return []; + + const currency = String(invoice.currency ?? '').toUpperCase(); + const unitAmount = Number(status === 'approved' ? invoice.amount_paid : invoice.amount_due); + const paidAt = status === 'approved' ? dateOf(objectOf(invoice.status_transitions)?.paid_at) : null; + + return [ + { + externalId: String(invoice.id), + amount: fromStripeUnitAmount(unitAmount || 0, currency), + currency: currency || null, + status, + paidAt, + coveredUntil: paidAt ? (periodEndOf(invoice) ?? oneMonthAfter(paidAt)) : null, + }, + ]; + }); + } + + /** + * A live subscription is cancelled right away (Pro lasts on `paidThrough`). + * A checkout still open is expired, so it cannot be completed later; one that + * was completed meanwhile has a subscription, which is cancelled instead. + */ + async cancel(ref: SubscriptionRef): Promise { + const request = this.request; + let subscriptionId = ref.externalId; + + if (!subscriptionId && ref.checkoutRef) { + const path = `/checkout/sessions/${encodeURIComponent(ref.checkoutRef)}`; + const session = await request(path); + if (session.status === 'open') { + await request(`${path}/expire`, { method: 'POST' }); + return; + } + subscriptionId = idOf(session.subscription); + } + + if (subscriptionId) { + await request(`/subscriptions/${encodeURIComponent(subscriptionId)}`, { method: 'DELETE' }); + } + } + + /** A single endpoint for the whole account; the event id is the dedupe key. */ + async parseWebhook( + request: BillingWebhookRequest, + ): Promise> { + const config = this.config; + if (!config) return err('not_configured'); + + const valid = verifyStripeSignature({ + signature: request.headers.get('stripe-signature'), + rawBody: request.rawBody, + secret: config.webhookSecret, + now: this.deps.now?.(), + }); + if (!valid) return err('invalid_signature'); + + let event: StripeObject; + try { + event = JSON.parse(request.rawBody) as StripeObject; + } catch { + return err('invalid_signature'); + } + + return ok({ + source: 'stripe', + dedupeKey: stringOf(event.id), + country: null, + externalId: subscriptionOfEvent(String(event.type), objectOf(objectOf(event.data)?.object)), + }); + } +} + +/** The subscription an event is about, for the events that change Pro. */ +function subscriptionOfEvent(type: string, object: StripeObject | null): string | null { + if (!object) return null; + if (type === 'checkout.session.completed' || type === 'checkout.session.async_payment_succeeded') { + return object.mode === 'subscription' ? idOf(object.subscription) : null; + } + if (type.startsWith('customer.subscription.')) return idOf(object.id); + if (type.startsWith('invoice.')) { + const details = objectOf(objectOf(object.parent)?.subscription_details); + return idOf(details?.subscription) ?? idOf(object.subscription); + } + return null; +} + +/** Next charge: the end of the trial or of the current period. */ +function nextChargeOf(subscription: StripeObject): Date | null { + if (subscription.status === 'trialing') return dateOf(subscription.trial_end); + const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]); + return dateOf(item?.current_period_end ?? subscription.current_period_end); +} + +/** The last day the invoice's lines pay for. */ +function periodEndOf(invoice: StripeObject): Date | null { + const lines = (objectOf(invoice.lines)?.data as unknown[] | undefined) ?? []; + const ends = lines + .map((line) => dateOf(objectOf(objectOf(line)?.period)?.end)) + .filter((end): end is Date => end !== null); + return ends.length > 0 ? new Date(Math.max(...ends.map((end) => end.getTime()))) : null; +} + +function oneMonthAfter(date: Date): Date { + const until = new Date(date); + until.setUTCMonth(until.getUTCMonth() + 1); + return until; +} + +function objectOf(value: unknown): StripeObject | null { + return value && typeof value === 'object' && !Array.isArray(value) ? (value as StripeObject) : null; +} + +function stringOf(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + +/** An expandable field: the id, or the expanded object's id. */ +function idOf(value: unknown): string | null { + return stringOf(value) ?? stringOf(objectOf(value)?.id); +} + +/** Stripe timestamps are Unix seconds. */ +function dateOf(value: unknown): Date | null { + return typeof value === 'number' && value > 0 ? new Date(value * 1000) : null; +} diff --git a/apps/backend/src/modules/billing/providers/stripe/stripe-http.ts b/apps/backend/src/modules/billing/providers/stripe/stripe-http.ts new file mode 100644 index 0000000..ba3cfda --- /dev/null +++ b/apps/backend/src/modules/billing/providers/stripe/stripe-http.ts @@ -0,0 +1,82 @@ +import { logger } from '@/logger'; + +// Stripe's REST API with plain `fetch` (no SDK, like Mercado Pago and Kapso): +// form-encoded bodies, JSON answers, and a pinned API version so a change in +// the account's default version cannot reshape the payloads under us. + +export const STRIPE_API_URL = 'https://api.stripe.com/v1'; +export const STRIPE_API_VERSION = '2025-03-31.basil'; + +export type StripeObject = Record; + +export class StripeApiError extends Error { + constructor( + readonly status: number, + readonly code: string | null, + ) { + super(`Stripe request failed with status ${status}`); + this.name = 'StripeApiError'; + } +} + +type FormValue = string | number | boolean | null | undefined | FormValue[] | { [key: string]: FormValue }; + +/** + * Stripe's form encoding of nested params: `a[b][0][c]=1`. `null`/`undefined` + * are left out. + */ +export function toForm(params: Record): URLSearchParams { + const form = new URLSearchParams(); + const add = (key: string, value: FormValue) => { + if (value === null || value === undefined) return; + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) add(`${key}[${index}]`, item); + return; + } + if (typeof value === 'object') { + for (const [child, nested] of Object.entries(value)) add(`${key}[${child}]`, nested); + return; + } + form.append(key, String(value)); + }; + for (const [key, value] of Object.entries(params)) add(key, value); + return form; +} + +export type StripeRequest = ( + path: string, + init?: { method?: 'GET' | 'POST' | 'DELETE'; form?: Record; query?: URLSearchParams }, +) => Promise; + +export function createStripeRequest(secretKey: string, fetchImpl: typeof fetch = fetch): StripeRequest { + return async (path, init = {}) => { + const method = init.method ?? 'GET'; + const query = init.query?.toString(); + let response: Response; + try { + response = await fetchImpl(`${STRIPE_API_URL}${path}${query ? `?${query}` : ''}`, { + method, + headers: { + Authorization: `Bearer ${secretKey}`, + 'Stripe-Version': STRIPE_API_VERSION, + ...(init.form ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}), + }, + body: init.form ? toForm(init.form).toString() : undefined, + }); + } catch (error) { + logger.error({ err: error, path }, 'Stripe unreachable'); + throw new StripeApiError(0, null); + } + + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as { error?: StripeObject } | null; + const code = typeof payload?.error?.code === 'string' ? payload.error.code : null; + // Only the error code: Stripe's messages can echo what we sent (emails). + // The path carries ids, never keys or emails. + logger.error({ status: response.status, code, path }, 'Stripe request failed'); + throw new StripeApiError(response.status, code); + } + + return (await response.json()) as StripeObject; + }; +} diff --git a/apps/backend/src/modules/billing/providers/stripe/webhook-signature.ts b/apps/backend/src/modules/billing/providers/stripe/webhook-signature.ts new file mode 100644 index 0000000..90e6862 --- /dev/null +++ b/apps/backend/src/modules/billing/providers/stripe/webhook-signature.ts @@ -0,0 +1,41 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +/** Stripe's own default: older deliveries are treated as replays. */ +const DEFAULT_TOLERANCE_SECONDS = 5 * 60; + +/** + * Checks Stripe's `Stripe-Signature` header (`t=,v1=[,v1=…]`). + * + * Stripe signs `.` with the endpoint secret (HMAC-SHA256). There + * can be several `v1` while a secret is being rolled; any of them may match. + */ +export function verifyStripeSignature(params: { + signature: string | null; + rawBody: string; + secret: string; + now?: Date; + toleranceSeconds?: number; +}): boolean { + if (!params.signature) return false; + + let timestamp: string | null = null; + const candidates: string[] = []; + for (const part of params.signature.split(',')) { + const [key, value] = part.split('=', 2).map((piece) => piece.trim()); + if (key === 't') timestamp = value ?? null; + if (key === 'v1' && value) candidates.push(value); + } + if (!timestamp || !/^\d+$/.test(timestamp) || candidates.length === 0) return false; + + const nowSeconds = Math.floor((params.now ?? new Date()).getTime() / 1000); + const tolerance = params.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS; + if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) return false; + + const expected = Buffer.from( + createHmac('sha256', params.secret).update(`${timestamp}.${params.rawBody}`).digest('hex'), + ); + return candidates.some((candidate) => { + const received = Buffer.from(candidate); + return received.length === expected.length && timingSafeEqual(received, expected); + }); +} diff --git a/apps/backend/src/modules/billing/routes.ts b/apps/backend/src/modules/billing/routes.ts new file mode 100644 index 0000000..7d8b587 --- /dev/null +++ b/apps/backend/src/modules/billing/routes.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import cancelRoute from './features/cancel/route'; +import chargesRoute from './features/charges/route'; +import statusRoute from './features/status/route'; +import subscribeRoute from './features/subscribe/route'; +import webhookRoute from './features/webhook/route'; + +const routes = new Hono(); + +routes.route('/', statusRoute); +routes.route('/', subscribeRoute); +routes.route('/', cancelRoute); +routes.route('/', chargesRoute); +routes.route('/', webhookRoute); + +export default routes; diff --git a/apps/backend/src/modules/classes/features/mark-attendance/route.ts b/apps/backend/src/modules/classes/features/mark-attendance/route.ts new file mode 100644 index 0000000..b7ad569 --- /dev/null +++ b/apps/backend/src/modules/classes/features/mark-attendance/route.ts @@ -0,0 +1,24 @@ +import type { MarkAttendance } from '@gruperly/shared'; +import { MarkAttendanceSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { MarkSessionAttendance } from './use-case'; + +const route = new Hono(); + +route.post('/:sessionId/attendance', validate.json(MarkAttendanceSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const sessionId = c.req.param('sessionId'); + const payload = c.req.valid('json') as MarkAttendance; + const useCase = new MarkSessionAttendance(); + const result = await useCase.execute(sessionId, payload, user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/mark-attendance/use-case.ts b/apps/backend/src/modules/classes/features/mark-attendance/use-case.ts new file mode 100644 index 0000000..713a5ba --- /dev/null +++ b/apps/backend/src/modules/classes/features/mark-attendance/use-case.ts @@ -0,0 +1,105 @@ +import { AttendanceStatus } from '@generated/prisma/client'; +import type { + MarkAttendance, + MarkAttendanceResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { validationProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { type ClassesDb, ensureSessionAccess, sessionNotFound } from '../../lib'; + +type MarkSessionAttendanceDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; +}; + +export class MarkSessionAttendance { + constructor(private readonly deps: MarkSessionAttendanceDeps = {}) {} + + async execute( + sessionId: string, + payload: MarkAttendance, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + if (payload.classSessionId !== sessionId) { + return err( + validationProblem({ + detail: 'El identificador de la clase no coincide con la ruta.', + }), + ); + } + + const session = await db.classSession.findUnique({ + where: { id: sessionId }, + include: { + group: { include: { members: { where: { userId } } } }, + }, + }); + if (!session) { + return err(sessionNotFound(sessionId)); + } + + const access = ensureSessionAccess(session, userId); + if (!access.ok) { + return access; + } + + const uniqueRecords = [ + ...new Map(payload.records.map((record) => [record.attendeeId, record])).values(), + ]; + + const attendees = await db.attendee.findMany({ + where: { + groupId: session.groupId, + id: { in: uniqueRecords.map((record) => record.attendeeId) }, + }, + select: { id: true }, + }); + const attendeeIds = new Set(attendees.map((attendee) => attendee.id)); + const invalidRecord = uniqueRecords.find((record) => !attendeeIds.has(record.attendeeId)); + if (invalidRecord) { + return err( + validationProblem({ + detail: 'Uno o más alumnos no pertenecen al grupo de esta clase.', + errors: { attendeeId: [invalidRecord.attendeeId] }, + }), + ); + } + + const markedAt = new Date(); + return unitOfWork.executeResult(async (tx) => { + for (const record of uniqueRecords) { + await tx.attendance.upsert({ + where: { + attendeeId_classSessionId: { + attendeeId: record.attendeeId, + classSessionId: sessionId, + }, + }, + create: { + attendeeId: record.attendeeId, + classSessionId: sessionId, + status: + record.status === 'PRESENT' + ? AttendanceStatus.PRESENT + : AttendanceStatus.ABSENT, + markedAt, + }, + update: { + status: + record.status === 'PRESENT' + ? AttendanceStatus.PRESENT + : AttendanceStatus.ABSENT, + markedAt, + }, + }); + } + return ok({ classSessionId: sessionId, marked: uniqueRecords.length }); + }); + } +} diff --git a/apps/backend/src/modules/classes/features/notify-absence/route.ts b/apps/backend/src/modules/classes/features/notify-absence/route.ts new file mode 100644 index 0000000..1304c06 --- /dev/null +++ b/apps/backend/src/modules/classes/features/notify-absence/route.ts @@ -0,0 +1,24 @@ +import type { NotifyAbsence } from '@gruperly/shared'; +import { NotifyAbsenceSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { NotifySessionAbsence } from './use-case'; + +const route = new Hono(); + +route.post('/:sessionId/notify-absence', validate.json(NotifyAbsenceSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const sessionId = c.req.param('sessionId'); + const payload = c.req.valid('json') as NotifyAbsence; + const useCase = new NotifySessionAbsence(); + const result = await useCase.execute(sessionId, payload, user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/notify-absence/use-case.ts b/apps/backend/src/modules/classes/features/notify-absence/use-case.ts new file mode 100644 index 0000000..6e7835c --- /dev/null +++ b/apps/backend/src/modules/classes/features/notify-absence/use-case.ts @@ -0,0 +1,71 @@ +import type { + NotifyAbsence, + NotifyAbsenceResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err } from '@gruperly/shared'; +import { validationProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { + absenceReleaseHours, + type ClassesDb, + ensureSessionAccess, + registerAbsence, + sessionNotFound, +} from '../../lib'; + +type NotifySessionAbsenceDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + now?: Date; + releaseHours?: number; +}; + +export class NotifySessionAbsence { + constructor(private readonly deps: NotifySessionAbsenceDeps = {}) {} + + async execute( + sessionId: string, + payload: NotifyAbsence, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const now = this.deps.now ?? new Date(); + const releaseHours = this.deps.releaseHours ?? absenceReleaseHours(); + + if (payload.classSessionId !== sessionId) { + return err( + validationProblem({ + detail: 'El identificador de la clase no coincide con la ruta.', + }), + ); + } + + const session = await db.classSession.findUnique({ + where: { id: sessionId }, + include: { + group: { include: { members: { where: { userId } } } }, + }, + }); + if (!session) { + return err(sessionNotFound(sessionId)); + } + + const access = ensureSessionAccess(session, userId); + if (!access.ok) { + return access; + } + + return registerAbsence( + { db, unitOfWork }, + { + attendeeId: payload.attendeeId, + classSessionId: sessionId, + now, + releaseHours, + }, + ); + } +} diff --git a/apps/backend/src/modules/classes/features/public-details/route.ts b/apps/backend/src/modules/classes/features/public-details/route.ts new file mode 100644 index 0000000..55fbb05 --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-details/route.ts @@ -0,0 +1,19 @@ +import type { AbsenceQuery } from '@gruperly/shared'; +import { AbsenceQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetAbsenceDetails } from './use-case'; + +const route = new Hono(); + +// Public route (whitelisted in session-auth): the attendee gets in with their personal token. +route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => { + const query = c.req.valid('query') as AbsenceQuery; + const useCase = new GetAbsenceDetails(); + const result = await useCase.execute(query); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/public-details/use-case.ts b/apps/backend/src/modules/classes/features/public-details/use-case.ts new file mode 100644 index 0000000..0f31993 --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-details/use-case.ts @@ -0,0 +1,94 @@ +import type { AbsenceDetails, AbsenceQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler'; +import { + buildTodayCandidates, + type ClassesDb, + ensureTodaySessions, +} from '../../lib'; + +type GetAbsenceDetailsDeps = { + db?: Pick< + ClassesDb, + 'attendee' | 'group' | 'classSession' | 'attendance' | 'slotRelease' + >; + now?: Date; + timeZone?: string; +}; + +export class GetAbsenceDetails { + constructor(private readonly deps: GetAbsenceDetailsDeps = {}) {} + + async execute( + query: AbsenceQuery, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? DEFAULT_TIME_ZONE; + + const attendee = await db.attendee.findUnique({ + where: { notifyToken: query.token }, + include: { + group: { select: { id: true, name: true, days: true, time: true } }, + person: { select: { fullName: true } }, + }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', 'notify token')); + } + + const candidates = buildTodayCandidates( + [{ id: attendee.group.id, days: attendee.group.days, time: attendee.group.time }], + now, + timeZone, + ); + if (candidates.length === 0) { + return ok({ + attendeeId: attendee.id, + fullName: attendee.person.fullName, + groupName: attendee.group.name, + sessions: [], + }); + } + + const sessionIds = await ensureTodaySessions(db, candidates); + const [sessions, attendances, releases] = await Promise.all([ + db.classSession.findMany({ + where: { id: { in: sessionIds } }, + orderBy: { startsAt: 'asc' }, + }), + db.attendance.findMany({ + where: { classSessionId: { in: sessionIds }, attendeeId: attendee.id }, + select: { classSessionId: true, status: true }, + }), + db.slotRelease.findMany({ + where: { classSessionId: { in: sessionIds }, attendeeId: attendee.id }, + select: { classSessionId: true }, + }), + ]); + + const attendanceBySession = new Map( + attendances.map((attendance) => [attendance.classSessionId, attendance.status]), + ); + const releasedSessionIds = new Set(releases.map((release) => release.classSessionId)); + + return ok({ + attendeeId: attendee.id, + fullName: attendee.person.fullName, + groupName: attendee.group.name, + sessions: sessions.map((session) => { + const attendanceStatus = attendanceBySession.get(session.id) ?? null; + return { + sessionId: session.id, + groupName: attendee.group.name, + startsAt: session.startsAt.toISOString(), + notified: + attendanceStatus === 'EXCUSED' || releasedSessionIds.has(session.id), + attendanceStatus, + }; + }), + }); + } +} diff --git a/apps/backend/src/modules/classes/features/public-notify/route.ts b/apps/backend/src/modules/classes/features/public-notify/route.ts new file mode 100644 index 0000000..850b46c --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-notify/route.ts @@ -0,0 +1,19 @@ +import type { PublicNotifyAbsence } from '@gruperly/shared'; +import { PublicNotifyAbsenceSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { PublicNotifyAbsenceUseCase } from './use-case'; + +const route = new Hono(); + +// Public route (whitelisted in session-auth): the attendee reports an absence with a token. +route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => { + const payload = c.req.valid('json') as PublicNotifyAbsence; + const useCase = new PublicNotifyAbsenceUseCase(); + const result = await useCase.execute(payload); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/public-notify/use-case.ts b/apps/backend/src/modules/classes/features/public-notify/use-case.ts new file mode 100644 index 0000000..24be0d3 --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-notify/use-case.ts @@ -0,0 +1,48 @@ +import type { + NotifyAbsenceResult, + ProblemDetails, + PublicNotifyAbsence, + Result, +} from '@gruperly/shared'; +import { err } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { absenceReleaseHours, type ClassesDb, registerAbsence } from '../../lib'; + +type PublicNotifyAbsenceDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + now?: Date; + releaseHours?: number; +}; + +export class PublicNotifyAbsenceUseCase { + constructor(private readonly deps: PublicNotifyAbsenceDeps = {}) {} + + async execute( + payload: PublicNotifyAbsence, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const now = this.deps.now ?? new Date(); + const releaseHours = this.deps.releaseHours ?? absenceReleaseHours(); + + const attendee = await db.attendee.findUnique({ + where: { notifyToken: payload.token }, + select: { id: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', 'notify token')); + } + + return registerAbsence( + { db, unitOfWork }, + { + attendeeId: attendee.id, + classSessionId: payload.classSessionId, + now, + releaseHours, + }, + ); + } +} diff --git a/apps/backend/src/modules/classes/features/session-students/route.ts b/apps/backend/src/modules/classes/features/session-students/route.ts new file mode 100644 index 0000000..7cd4f4e --- /dev/null +++ b/apps/backend/src/modules/classes/features/session-students/route.ts @@ -0,0 +1,24 @@ +import type { TodayClassesQuery } from '@gruperly/shared'; +import { TodayClassesQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetSessionStudents } from './use-case'; + +const route = new Hono(); + +route.get('/:sessionId/students', validate.query(TodayClassesQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const sessionId = c.req.param('sessionId'); + const query = c.req.valid('query') as TodayClassesQuery; + const useCase = new GetSessionStudents(); + const result = await useCase.execute(sessionId, user.id, query); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/session-students/use-case.ts b/apps/backend/src/modules/classes/features/session-students/use-case.ts new file mode 100644 index 0000000..037b7a3 --- /dev/null +++ b/apps/backend/src/modules/classes/features/session-students/use-case.ts @@ -0,0 +1,114 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + SessionStudents, + TodayClassesQuery, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { flattenPerson } from '@/modules/attendees/lib/helpers'; +import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler'; +import { + type ClassesDb, + ensureSessionAccess, + resolvePaymentStatus, + sessionNotFound, +} from '../../lib'; + +type GetSessionStudentsDeps = { + db?: Pick< + ClassesDb, + 'classSession' | 'attendee' | 'payment' | 'attendance' | 'slotRelease' + > & + Pick; + now?: Date; + timeZone?: string; +}; + +export class GetSessionStudents { + constructor(private readonly deps: GetSessionStudentsDeps = {}) {} + + async execute( + sessionId: string, + userId: string, + query: TodayClassesQuery = {}, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE; + + const session = await db.classSession.findUnique({ + where: { id: sessionId }, + include: { + group: { + include: { members: { where: { userId } } }, + }, + }, + }); + + if (!session) { + return err(sessionNotFound(sessionId)); + } + + const access = ensureSessionAccess(session, userId); + if (!access.ok) { + return access; + } + + const startOfToday = startOfDayInTimeZone(now, timeZone); + + const [attendees, payments, attendances, releases] = await Promise.all([ + db.attendee.findMany({ + where: { groupId: session.groupId }, + orderBy: { person: { fullName: 'asc' } }, + include: { person: { select: { fullName: true } } }, + }).then((rows) => rows.map(flattenPerson)), + db.payment.findMany({ + where: { groupId: session.groupId }, + select: { attendeeId: true, status: true, dueDate: true }, + }), + db.attendance.findMany({ + where: { classSessionId: sessionId }, + select: { attendeeId: true, status: true }, + }), + db.slotRelease.findMany({ + where: { classSessionId: sessionId }, + select: { attendeeId: true }, + }), + ]); + + const paymentsByAttendee = new Map(); + for (const payment of payments) { + const list = paymentsByAttendee.get(payment.attendeeId) ?? []; + list.push(payment); + paymentsByAttendee.set(payment.attendeeId, list); + } + + const attendanceByAttendee = new Map( + attendances.map((attendance) => [attendance.attendeeId, attendance.status]), + ); + const releasedAttendeeIds = new Set(releases.map((release) => release.attendeeId)); + + return ok({ + sessionId: session.id, + groupId: session.groupId, + groupName: session.group.name, + startsAt: session.startsAt.toISOString(), + students: attendees.map((attendee) => { + const attendanceStatus = attendanceByAttendee.get(attendee.id) ?? null; + return { + attendeeId: attendee.id, + fullName: attendee.fullName, + paymentStatus: resolvePaymentStatus( + paymentsByAttendee.get(attendee.id) ?? [], + startOfToday, + ), + attendanceStatus, + notifiedAbsence: + attendanceStatus === 'EXCUSED' || releasedAttendeeIds.has(attendee.id), + }; + }), + }); + } +} diff --git a/apps/backend/src/modules/classes/features/today/route.ts b/apps/backend/src/modules/classes/features/today/route.ts new file mode 100644 index 0000000..ab79dbf --- /dev/null +++ b/apps/backend/src/modules/classes/features/today/route.ts @@ -0,0 +1,23 @@ +import type { TodayClassesQuery } from '@gruperly/shared'; +import { TodayClassesQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetTodayClasses } from './use-case'; + +const route = new Hono(); + +route.get('/today', validate.query(TodayClassesQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const query = c.req.valid('query') as TodayClassesQuery; + const useCase = new GetTodayClasses(); + const result = await useCase.execute(user.id, query); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/today/use-case.ts b/apps/backend/src/modules/classes/features/today/use-case.ts new file mode 100644 index 0000000..8a5bb0d --- /dev/null +++ b/apps/backend/src/modules/classes/features/today/use-case.ts @@ -0,0 +1,82 @@ +import type { ClassTodayList, ProblemDetails, Result, TodayClassesQuery } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib/helpers'; +import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler'; +import { + buildTodayCandidates, + type ClassesDb, + ensureTodaySessions, + toClassToday, +} from '../../lib'; + +type GetTodayClassesDeps = { + db?: Pick; + now?: Date; + timeZone?: string; +}; + +export class GetTodayClasses { + constructor(private readonly deps: GetTodayClassesDeps = {}) {} + + async execute( + userId: string, + query: TodayClassesQuery = {}, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE; + + const groups = await db.group.findMany({ + where: buildGroupWhereForUser(userId), + select: { + id: true, + name: true, + days: true, + time: true, + capacity: true, + _count: { + select: { attendees: { where: { status: 'ACTIVE' } } }, + }, + }, + }); + + const candidates = buildTodayCandidates(groups, now, timeZone); + if (candidates.length === 0) { + return ok({ data: [] }); + } + + const sessionIds = await ensureTodaySessions(db, candidates); + + const [sessions, markedAttendances] = await Promise.all([ + db.classSession.findMany({ + where: { id: { in: sessionIds } }, + include: { + group: { select: { id: true, name: true, capacity: true } }, + }, + orderBy: { startsAt: 'asc' }, + }), + db.attendance.findMany({ + where: { + classSessionId: { in: sessionIds }, + status: { in: ['PRESENT', 'ABSENT'] }, + }, + select: { classSessionId: true }, + }), + ]); + + const markedSessionIds = new Set(markedAttendances.map((a) => a.classSessionId)); + const enrolledByGroup = new Map(groups.map((group) => [group.id, group._count.attendees])); + + return ok({ + data: sessions.map((session) => + toClassToday( + session, + session.group, + enrolledByGroup.get(session.groupId) ?? 0, + markedSessionIds.has(session.id), + ), + ), + }); + } +} diff --git a/apps/backend/src/modules/classes/index.ts b/apps/backend/src/modules/classes/index.ts new file mode 100644 index 0000000..02b8841 --- /dev/null +++ b/apps/backend/src/modules/classes/index.ts @@ -0,0 +1 @@ +export { default as classesRoutes } from './routes'; diff --git a/apps/backend/src/modules/classes/lib/helpers.ts b/apps/backend/src/modules/classes/lib/helpers.ts new file mode 100644 index 0000000..706085b --- /dev/null +++ b/apps/backend/src/modules/classes/lib/helpers.ts @@ -0,0 +1,92 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + AttendeePaymentStatus, + ClassToday, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; + +export type ClassesDb = Pick< + PrismaClient, + 'group' | 'classSession' | 'attendee' | 'payment' | 'attendance' | 'slotRelease' +>; + +type PaymentLike = { + status: 'PENDING' | 'PAID' | 'OVERDUE' | 'CANCELLED'; + dueDate: Date; +}; + +// Payment status computed in real time (no denormalized column): +// PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed. +export function resolvePaymentStatus( + payments: PaymentLike[], + startOfToday: Date, +): AttendeePaymentStatus { + const hasUnpaid = payments.some( + (payment) => + payment.status === 'OVERDUE' + || (payment.status === 'PENDING' && payment.dueDate.getTime() < startOfToday.getTime()), + ); + return hasUnpaid ? 'PENDING' : 'UP_TO_DATE'; +} + +export function absenceReleaseHours(): number { + const raw = process.env.ABSENCE_RELEASE_HOURS; + if (raw == null || raw.trim() === '') { + return 12; + } + const parsed = Number(raw); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : 12; +} + +export type ClassSessionRecord = { + id: string; + groupId: string; + startsAt: Date; +}; + +type GroupWithAccess = { + createdById: string; + members: { userId: string }[]; +}; + +// Verifies the user is the owner or a member of the group that owns the session. +export function ensureSessionAccess( + session: ClassSessionRecord & { group: GroupWithAccess }, + userId: string, +): Result { + const isOwner = session.group.createdById === userId; + const isMember = session.group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + return { + ok: true, + value: { id: session.id, groupId: session.groupId, startsAt: session.startsAt }, + }; +} + +export function sessionNotFound(sessionId: string): ProblemDetails { + return notFoundResourceProblem('Class session', sessionId); +} + +export function toClassToday( + session: { id: string; startsAt: Date }, + group: { id: string; name: string; capacity: number | null }, + enrolledCount: number, + hasAttendance: boolean, +): ClassToday { + return { + sessionId: session.id, + groupId: group.id, + groupName: group.name, + startsAt: session.startsAt.toISOString(), + enrolledCount, + capacity: group.capacity, + availableSlots: + group.capacity == null ? null : Math.max(0, group.capacity - enrolledCount), + hasAttendance, + }; +} diff --git a/apps/backend/src/modules/classes/lib/index.ts b/apps/backend/src/modules/classes/lib/index.ts new file mode 100644 index 0000000..d1e2995 --- /dev/null +++ b/apps/backend/src/modules/classes/lib/index.ts @@ -0,0 +1,3 @@ +export * from './helpers'; +export * from './notify'; +export * from './sessions'; diff --git a/apps/backend/src/modules/classes/lib/notify.ts b/apps/backend/src/modules/classes/lib/notify.ts new file mode 100644 index 0000000..b0c6e1c --- /dev/null +++ b/apps/backend/src/modules/classes/lib/notify.ts @@ -0,0 +1,91 @@ +import { AttendanceStatus } from '@generated/prisma/client'; +import type { NotifyAbsenceResult, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem, validationProblem } from '@/http/problem-builders'; +import type { UnitOfWork } from '@/lib/prisma'; +import { type ClassesDb, sessionNotFound } from './helpers'; + +type RegisterAbsenceDeps = { + db: Pick; + unitOfWork: UnitOfWork; +}; + +type RegisterAbsenceInput = { + attendeeId: string; + classSessionId: string; + now: Date; + releaseHours: number; +}; + +// Shared core of the absence notice (authenticated teacher and attendee with a token): +// - Marks the attendance as EXCUSED (idempotent upsert). +// - If the notice comes early enough to meet `releaseHours`, creates/keeps a SlotRelease to free the spot. +export async function registerAbsence( + deps: RegisterAbsenceDeps, + input: RegisterAbsenceInput, +): Promise> { + const { db, unitOfWork } = deps; + const { attendeeId, classSessionId, now, releaseHours } = input; + + const session = await db.classSession.findUnique({ where: { id: classSessionId } }); + if (!session) { + return err(sessionNotFound(classSessionId)); + } + + const attendee = await db.attendee.findUnique({ where: { id: attendeeId } }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + if (attendee.groupId !== session.groupId) { + return err( + validationProblem({ detail: 'El alumno no pertenece al grupo de esta clase.' }), + ); + } + + const anticipationMs = session.startsAt.getTime() - now.getTime(); + const slotReleased = anticipationMs >= releaseHours * 60 * 60 * 1000; + + return unitOfWork.executeResult(async (tx) => { + await tx.attendance.upsert({ + where: { + attendeeId_classSessionId: { + attendeeId, + classSessionId, + }, + }, + create: { + attendeeId, + classSessionId, + status: AttendanceStatus.EXCUSED, + markedAt: now, + }, + update: { + status: AttendanceStatus.EXCUSED, + markedAt: now, + }, + }); + + if (slotReleased) { + await tx.slotRelease.upsert({ + where: { + attendeeId_classSessionId: { + attendeeId, + classSessionId, + }, + }, + create: { + attendeeId, + classSessionId, + isClaimed: false, + }, + update: {}, + }); + } + + return ok({ + classSessionId, + notified: true, + slotReleased, + }); + }); +} diff --git a/apps/backend/src/modules/classes/lib/sessions.ts b/apps/backend/src/modules/classes/lib/sessions.ts new file mode 100644 index 0000000..d5a5965 --- /dev/null +++ b/apps/backend/src/modules/classes/lib/sessions.ts @@ -0,0 +1,64 @@ +import type { WeekDay } from '@gruperly/shared'; +import { todayOccurrence } from '@/modules/home/lib/scheduler'; +import type { ClassesDb } from './helpers'; + +export type TodaySessionCandidate = { + groupId: string; + startsAt: Date; +}; + +type ScheduledGroup = { + id: string; + days: WeekDay[] | null; + time: string | null; +}; + +// Computes which groups have a class today (from days/time and the teacher's time zone). +export function buildTodayCandidates( + groups: ScheduledGroup[], + now: Date, + timeZone: string, +): TodaySessionCandidate[] { + const candidates: TodaySessionCandidate[] = []; + for (const group of groups) { + if (!group.days || group.days.length === 0 || !group.time) { + continue; + } + const startsAt = todayOccurrence({ + days: group.days, + time: group.time, + now, + timeZone, + }); + if (startsAt) { + candidates.push({ groupId: group.id, startsAt }); + } + } + return candidates; +} + +// Materializes (idempotent upsert) today's ClassSession rows and returns their ids. +export async function ensureTodaySessions( + db: Pick, + candidates: TodaySessionCandidate[], +): Promise { + const sessionIds: string[] = []; + for (const candidate of candidates) { + const session = await db.classSession.upsert({ + where: { + groupId_startsAt: { + groupId: candidate.groupId, + startsAt: candidate.startsAt, + }, + }, + create: { + groupId: candidate.groupId, + startsAt: candidate.startsAt, + }, + update: {}, + select: { id: true }, + }); + sessionIds.push(session.id); + } + return sessionIds; +} diff --git a/apps/backend/src/modules/classes/routes.ts b/apps/backend/src/modules/classes/routes.ts new file mode 100644 index 0000000..c19b606 --- /dev/null +++ b/apps/backend/src/modules/classes/routes.ts @@ -0,0 +1,18 @@ +import { Hono } from 'hono'; +import markAttendanceRoute from './features/mark-attendance/route'; +import notifyAbsenceRoute from './features/notify-absence/route'; +import publicDetailsRoute from './features/public-details/route'; +import publicNotifyRoute from './features/public-notify/route'; +import sessionStudentsRoute from './features/session-students/route'; +import todayRoute from './features/today/route'; + +const routes = new Hono(); + +routes.route('/', todayRoute); +routes.route('/', sessionStudentsRoute); +routes.route('/', markAttendanceRoute); +routes.route('/', notifyAbsenceRoute); +routes.route('/', publicDetailsRoute); +routes.route('/', publicNotifyRoute); + +export default routes; diff --git a/apps/backend/src/modules/group-preregistrations/features/approve/route.ts b/apps/backend/src/modules/group-preregistrations/features/approve/route.ts new file mode 100644 index 0000000..c4d5e74 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/approve/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { ApproveGroupPreRegistration } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/preregistrations/:entryId/approve', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const entryId = c.req.param('entryId'); + const useCase = new ApproveGroupPreRegistration(); + const result = await useCase.execute(groupId, entryId, user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts new file mode 100644 index 0000000..02762aa --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts @@ -0,0 +1,126 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ApproveGroupPreRegistrationResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { countsAsNewStudent } from '@/modules/people/lib/people'; +import { + findGroupOwnedByUser, + type GroupWaitlistEntryRecord, + toGroupWaitlistEntryDto, +} from '../../../group-waitlist/lib/helpers'; +import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote'; +import { type GroupPreRegistrationRecord } from '../../lib/helpers'; + +type ApproveGroupPreRegistrationDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + planGuard?: Pick; +}; + +export class ApproveGroupPreRegistration { + constructor(private readonly deps: ApproveGroupPreRegistrationDeps = {}) {} + + async execute( + groupId: string, + entryId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + const groupResult = await findGroupOwnedByUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + + const entry = await db.groupPreRegistration.findFirst({ + where: { id: entryId, groupId }, + }); + if (!entry) { + return err(notFoundResourceProblem('GroupPreRegistration', entryId)); + } + if (entry.status !== 'PENDING') { + return err( + conflictProblem({ + detail: 'Esta pre-inscripción ya fue revisada.', + code: 'pre_registration_already_reviewed', + }), + ); + } + + const isNewStudent = await countsAsNewStudent(db, userId, entry.phone); + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0); + if (!allowed.ok) { + return allowed; + } + + const record = entry as unknown as GroupPreRegistrationRecord; + + return unitOfWork.executeResult( + async (tx): Promise> => { + const promoteResult = await promoteWaitlistEntryRecord( + tx, + groupResult.value, + { + id: record.id, + groupId: record.groupId, + fullName: record.fullName, + phone: record.phone, + email: record.email, + notes: null, + status: 'PENDING', + createdAt: record.createdAt, + updatedAt: record.updatedAt, + }, + ); + + if (promoteResult.ok) { + await tx.groupPreRegistration.update({ + where: { id: record.id }, + data: { status: 'APPROVED', reviewedAt: new Date() }, + }); + return ok({ + outcome: 'added', + attendee: promoteResult.value, + waitlistEntry: null, + }); + } + + if (promoteResult.error.code !== 'group_capacity_reached') { + return promoteResult; + } + + const existingWaitlistEntry = await tx.groupWaitlistEntry.findFirst({ + where: { groupId: record.groupId, phone: record.phone }, + }); + const waitlistEntryRecord = existingWaitlistEntry + ? (existingWaitlistEntry as unknown as GroupWaitlistEntryRecord) + : ((await tx.groupWaitlistEntry.create({ + data: { + groupId: record.groupId, + fullName: record.fullName, + phone: record.phone, + email: record.email, + }, + })) as unknown as GroupWaitlistEntryRecord); + + await tx.groupPreRegistration.update({ + where: { id: record.id }, + data: { status: 'APPROVED', reviewedAt: new Date() }, + }); + + return ok({ + outcome: 'waitlisted', + attendee: null, + waitlistEntry: toGroupWaitlistEntryDto(waitlistEntryRecord), + }); + }, + ); + } +} diff --git a/apps/backend/src/modules/group-preregistrations/features/get-all/route.ts b/apps/backend/src/modules/group-preregistrations/features/get-all/route.ts new file mode 100644 index 0000000..18c84d6 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/get-all/route.ts @@ -0,0 +1,24 @@ +import { + type GroupPreRegistrationQuery, + GroupPreRegistrationQuerySchema, +} from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListGroupPreRegistrations } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/preregistrations', validate.query(GroupPreRegistrationQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const query = c.req.valid('query') as GroupPreRegistrationQuery; + const useCase = new ListGroupPreRegistrations(); + const result = await useCase.execute(groupId, user.id, query); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts new file mode 100644 index 0000000..3be4276 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts @@ -0,0 +1,54 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + GroupPreRegistrationList, + GroupPreRegistrationQuery, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '../../../group-waitlist/lib/helpers'; +import { + type GroupPreRegistrationRecord, + toGroupPreRegistrationDto, +} from '../../lib/helpers'; + +type ListGroupPreRegistrationsDeps = { + db?: Pick; +}; + +export class ListGroupPreRegistrations { + constructor(private readonly deps: ListGroupPreRegistrationsDeps = {}) {} + + async execute( + groupId: string, + userId: string, + query: GroupPreRegistrationQuery, + ): Promise> { + const db = this.deps.db ?? prisma; + + const groupResult = await findGroupForUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + + const where = { groupId, status: query.status ?? ('PENDING' as const) }; + const [records, total] = await Promise.all([ + db.groupPreRegistration.findMany({ + where, + skip: getPaginationOffset(query), + take: query.pageSize, + orderBy: { createdAt: 'asc' }, + }), + db.groupPreRegistration.count({ where }), + ]); + + return ok({ + data: records.map( + (record) => toGroupPreRegistrationDto(record as unknown as GroupPreRegistrationRecord), + ), + pagination: getPaginationMetadata(query, total), + }); + } +} diff --git a/apps/backend/src/modules/group-preregistrations/features/reject/route.ts b/apps/backend/src/modules/group-preregistrations/features/reject/route.ts new file mode 100644 index 0000000..472b03c --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/reject/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { RejectGroupPreRegistration } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/preregistrations/:entryId/reject', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const entryId = c.req.param('entryId'); + const useCase = new RejectGroupPreRegistration(); + const result = await useCase.execute(groupId, entryId, user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts new file mode 100644 index 0000000..368dff9 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts @@ -0,0 +1,56 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + RejectGroupPreRegistrationResult, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { findGroupOwnedByUser } from '../../../group-waitlist/lib/helpers'; +import { type GroupPreRegistrationRecord, toGroupPreRegistrationDto } from '../../lib/helpers'; + +type RejectGroupPreRegistrationDeps = { + db?: Pick; +}; + +export class RejectGroupPreRegistration { + constructor(private readonly deps: RejectGroupPreRegistrationDeps = {}) {} + + async execute( + groupId: string, + entryId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + + const groupResult = await findGroupOwnedByUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + + const entry = await db.groupPreRegistration.findFirst({ + where: { id: entryId, groupId }, + }); + if (!entry) { + return err(notFoundResourceProblem('GroupPreRegistration', entryId)); + } + if (entry.status !== 'PENDING') { + return err( + conflictProblem({ + detail: 'Esta pre-inscripción ya fue revisada.', + code: 'pre_registration_already_reviewed', + }), + ); + } + + const updated = await db.groupPreRegistration.update({ + where: { id: entry.id }, + data: { status: 'REJECTED', reviewedAt: new Date() }, + }); + + return ok({ + entry: toGroupPreRegistrationDto(updated as unknown as GroupPreRegistrationRecord), + }); + } +} diff --git a/apps/backend/src/modules/group-preregistrations/index.ts b/apps/backend/src/modules/group-preregistrations/index.ts new file mode 100644 index 0000000..f63b27a --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/index.ts @@ -0,0 +1 @@ +export { default as groupPreRegistrationRoutes } from './routes'; diff --git a/apps/backend/src/modules/group-preregistrations/lib/helpers.ts b/apps/backend/src/modules/group-preregistrations/lib/helpers.ts new file mode 100644 index 0000000..8a1c337 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/lib/helpers.ts @@ -0,0 +1,29 @@ +import type { GroupPreRegistrationDto } from '@gruperly/shared'; + +export type GroupPreRegistrationRecord = { + id: string; + groupId: string; + fullName: string; + phone: string; + email: string | null; + status: GroupPreRegistrationDto['status']; + reviewedAt: Date | null; + createdAt: Date; + updatedAt: Date; +}; + +export function toGroupPreRegistrationDto( + record: GroupPreRegistrationRecord, +): GroupPreRegistrationDto { + return { + id: record.id, + groupId: record.groupId, + fullName: record.fullName, + phone: record.phone, + email: record.email, + status: record.status, + reviewedAt: record.reviewedAt ? record.reviewedAt.toISOString() : null, + createdAt: record.createdAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + }; +} diff --git a/apps/backend/src/modules/group-preregistrations/routes.ts b/apps/backend/src/modules/group-preregistrations/routes.ts new file mode 100644 index 0000000..31f5a2c --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/routes.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import approveRoute from './features/approve/route'; +import getAllRoute from './features/get-all/route'; +import rejectRoute from './features/reject/route'; + +const routes = new Hono(); + +routes.route('/', getAllRoute); +routes.route('/', approveRoute); +routes.route('/', rejectRoute); + +export default routes; diff --git a/apps/backend/src/modules/group-waitlist/features/get-all/route.ts b/apps/backend/src/modules/group-waitlist/features/get-all/route.ts new file mode 100644 index 0000000..50e73df --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/features/get-all/route.ts @@ -0,0 +1,21 @@ +import { type GroupWaitlistQuery, GroupWaitlistQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListGroupWaitlistEntries } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/waitlist', validate.query(GroupWaitlistQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const query = c.req.valid('query') as GroupWaitlistQuery; + const useCase = new ListGroupWaitlistEntries(); + const result = await useCase.execute(groupId, user.id, query); + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/features/get-all/use-case.ts b/apps/backend/src/modules/group-waitlist/features/get-all/use-case.ts new file mode 100644 index 0000000..c9522e6 --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/features/get-all/use-case.ts @@ -0,0 +1,43 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { GroupWaitlistList, GroupWaitlistQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; +import { findGroupForUser, type GroupWaitlistEntryRecord, toGroupWaitlistEntryDto } from '../../lib/helpers'; + +type ListGroupWaitlistEntriesDeps = { + db?: Pick; +}; + +export class ListGroupWaitlistEntries { + constructor(private readonly deps: ListGroupWaitlistEntriesDeps = {}) {} + + async execute( + groupId: string, + userId: string, + query: GroupWaitlistQuery, + ): Promise> { + const db = this.deps.db ?? prisma; + + const groupResult = await findGroupForUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + + const where = { groupId, status: 'PENDING' as const }; + const [records, total] = await Promise.all([ + db.groupWaitlistEntry.findMany({ + where, + skip: getPaginationOffset(query), + take: query.pageSize, + orderBy: { createdAt: 'asc' }, + }), + db.groupWaitlistEntry.count({ where }), + ]); + + return ok({ + data: records.map((record) => toGroupWaitlistEntryDto(record as unknown as GroupWaitlistEntryRecord)), + pagination: getPaginationMetadata(query, total), + }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/features/promote/route.ts b/apps/backend/src/modules/group-waitlist/features/promote/route.ts new file mode 100644 index 0000000..1ca6df8 --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/features/promote/route.ts @@ -0,0 +1,26 @@ +import { type PromoteGroupWaitlistEntry as PromoteBody, PromoteGroupWaitlistEntrySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { PromoteGroupWaitlistEntry } from './use-case'; + +const route = new Hono(); + +route.post( + '/:groupId/waitlist/:entryId/promote', + validate.json(PromoteGroupWaitlistEntrySchema), + async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const entryId = c.req.param('entryId'); + const body = c.req.valid('json') as PromoteBody; + const useCase = new PromoteGroupWaitlistEntry(); + const result = await useCase.execute(groupId, entryId, user.id, body.targetGroupId); + return resultJson(c, result); + }, +); + +export default route; diff --git a/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts b/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts new file mode 100644 index 0000000..a0291f6 --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts @@ -0,0 +1,77 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, PromoteGroupWaitlistEntryResult, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { countsAsNewStudent } from '@/modules/people/lib/people'; +import { + findGroupOwnedByUser, + type GroupWaitlistEntryRecord, +} from '../../lib/helpers'; +import { promoteWaitlistEntryRecord } from '../../lib/promote'; + +type PromoteGroupWaitlistEntryDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + planGuard?: Pick; +}; + +export class PromoteGroupWaitlistEntry { + constructor(private readonly deps: PromoteGroupWaitlistEntryDeps = {}) {} + + async execute( + groupId: string, + entryId: string, + userId: string, + targetGroupId?: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + const groupResult = await findGroupOwnedByUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + + const entry = await db.groupWaitlistEntry.findFirst({ + where: { id: entryId, groupId }, + }); + if (!entry) { + return err(notFoundResourceProblem('GroupWaitlistEntry', entryId)); + } + + // The entry leaves the waitlist of its own group but can land in another + // group of the same teacher (capacity and duplicates are checked there). + let targetGroup = groupResult.value; + if (targetGroupId && targetGroupId !== groupId) { + const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId); + if (!targetResult.ok) { + return targetResult; + } + targetGroup = targetResult.value; + } + + const isNewStudent = await countsAsNewStudent(db, userId, entry.phone); + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0); + if (!allowed.ok) { + return allowed; + } + + return unitOfWork.executeResult( + async (tx: Prisma.TransactionClient) => { + const promoteResult = await promoteWaitlistEntryRecord( + tx, + targetGroup, + entry as unknown as GroupWaitlistEntryRecord, + ); + if (!promoteResult.ok) { + return promoteResult; + } + + await tx.groupWaitlistEntry.delete({ where: { id: entry.id } }); + return ok({ attendee: promoteResult.value }); + }, + ); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/features/remove/route.ts b/apps/backend/src/modules/group-waitlist/features/remove/route.ts new file mode 100644 index 0000000..a55c71b --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/features/remove/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { RemoveGroupWaitlistEntry } from './use-case'; + +const route = new Hono(); + +route.delete('/:groupId/waitlist/:entryId', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const entryId = c.req.param('entryId'); + const useCase = new RemoveGroupWaitlistEntry(); + const result = await useCase.execute(groupId, entryId, user.id); + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/features/remove/use-case.ts b/apps/backend/src/modules/group-waitlist/features/remove/use-case.ts new file mode 100644 index 0000000..11f25cd --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/features/remove/use-case.ts @@ -0,0 +1,37 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, RemoveGroupWaitlistEntryResult, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { findGroupOwnedByUser } from '../../lib/helpers'; + +type RemoveGroupWaitlistEntryDeps = { + db?: Pick; +}; + +export class RemoveGroupWaitlistEntry { + constructor(private readonly deps: RemoveGroupWaitlistEntryDeps = {}) {} + + async execute( + groupId: string, + entryId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + + const groupResult = await findGroupOwnedByUser(db, groupId, userId); + if (!groupResult.ok) { + return groupResult; + } + + const existing = await db.groupWaitlistEntry.findFirst({ + where: { id: entryId, groupId }, + }); + if (!existing) { + return err(notFoundResourceProblem('GroupWaitlistEntry', entryId)); + } + + await db.groupWaitlistEntry.delete({ where: { id: entryId } }); + return ok({ deleted: true }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/index.ts b/apps/backend/src/modules/group-waitlist/index.ts new file mode 100644 index 0000000..545f43d --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/index.ts @@ -0,0 +1 @@ +export { default as groupWaitlistRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/lib/helpers.ts b/apps/backend/src/modules/group-waitlist/lib/helpers.ts new file mode 100644 index 0000000..907311d --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/lib/helpers.ts @@ -0,0 +1,65 @@ +import type { Group, PrismaClient } from '@generated/prisma/client'; +import type { GroupWaitlistEntryDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; + +export type GroupWaitlistEntryRecord = { + id: string; + groupId: string; + fullName: string; + phone: string; + email: string | null; + notes: string | null; + status: GroupWaitlistEntryDto['status']; + createdAt: Date; + updatedAt: Date; +}; + +export function toGroupWaitlistEntryDto(record: GroupWaitlistEntryRecord): GroupWaitlistEntryDto { + return { + id: record.id, + groupId: record.groupId, + fullName: record.fullName, + phone: record.phone, + email: record.email, + notes: record.notes, + status: record.status, + createdAt: record.createdAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + }; +} + +export async function findGroupForUser( + db: Pick, + groupId: string, + userId: string, +): Promise> { + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { members: { where: { userId } } }, + }); + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + return ok(group); +} + +export async function findGroupOwnedByUser( + db: Pick, + groupId: string, + userId: string, +): Promise> { + const group = await db.group.findUnique({ where: { id: groupId } }); + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + if (group.createdById !== userId) { + return err(noGroupAccessProblem()); + } + return ok(group); +} \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/lib/promote.ts b/apps/backend/src/modules/group-waitlist/lib/promote.ts new file mode 100644 index 0000000..de10bb5 --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/lib/promote.ts @@ -0,0 +1,105 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { capacityReachedProblem } from '@/http/problem-builders'; +import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers'; +import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people'; +import { type GroupWaitlistEntryRecord } from './helpers'; + +export type PromoteDb = Pick; + +type PromoteGroup = { + id: string; + capacity: number | null; + createdById: string; +}; + +export async function findFirstPendingWaitlistEntry( + db: PromoteDb, + groupId: string, +): Promise { + const record = await db.groupWaitlistEntry.findFirst({ + where: { groupId, status: 'PENDING' }, + orderBy: { createdAt: 'asc' }, + }); + return record as GroupWaitlistEntryRecord | null; +} + +/* Whether someone can join `group`: free capacity (ACTIVE members) and the + person (when there already is one) not being a member there yet. Shared by + the waitlist promotion, the member move and "Agregar a otro grupo". */ +export async function checkCanJoinGroup( + db: Pick, + group: Pick, + personId: string | null, +): Promise> { + if (group.capacity !== null) { + const currentCount = await db.attendee.count({ + where: { groupId: group.id, status: 'ACTIVE' }, + }); + if (currentCount >= group.capacity) { + return err(capacityReachedProblem(group.capacity)); + } + } + + if (personId) { + const existing = await db.attendee.findFirst({ + where: { groupId: group.id, personId }, + select: { id: true }, + }); + if (existing) { + return err(alreadyInGroupProblem()); + } + } + + return ok(undefined); +} + +/* The entry has its own contact data; if its phone is already one of the + teacher's people, the new membership goes to that person. */ +export async function promoteWaitlistEntryRecord( + db: PromoteDb, + group: PromoteGroup, + entry: GroupWaitlistEntryRecord, +): Promise> { + const person = await findOrCreatePerson(db, group.createdById, { + fullName: entry.fullName, + phone: entry.phone, + email: entry.email, + notes: entry.notes, + }); + + const canJoin = await checkCanJoinGroup(db, group, person.created ? null : person.id); + if (!canJoin.ok) { + return canJoin; + } + + const attendee = await db.attendee.create({ + data: { groupId: group.id, personId: person.id }, + include: attendeeWithPerson, + }); + + return ok(toAttendeeDto(attendee)); +} + +export type PromoteFirstResult = { + attendee: AttendeeDto; + entry: GroupWaitlistEntryRecord; +}; + +export async function promoteFirstPendingWaitlistEntry( + db: PromoteDb, + group: PromoteGroup, +): Promise> { + const entry = await findFirstPendingWaitlistEntry(db, group.id); + if (!entry) { + return ok(null); + } + + const result = await promoteWaitlistEntryRecord(db, group, entry); + if (!result.ok) { + return result; + } + + return ok({ attendee: result.value, entry }); +} \ No newline at end of file diff --git a/apps/backend/src/modules/group-waitlist/routes.ts b/apps/backend/src/modules/group-waitlist/routes.ts new file mode 100644 index 0000000..41da6c1 --- /dev/null +++ b/apps/backend/src/modules/group-waitlist/routes.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import getAllRoute from './features/get-all/route'; +import promoteRoute from './features/promote/route'; +import removeRoute from './features/remove/route'; + +const routes = new Hono(); + +routes.route('/', getAllRoute); +routes.route('/', promoteRoute); +routes.route('/', removeRoute); + +export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/groups/features/create-from-organization/route.ts b/apps/backend/src/modules/groups/features/create-from-organization/route.ts deleted file mode 100644 index 5b7fc90..0000000 --- a/apps/backend/src/modules/groups/features/create-from-organization/route.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { CreateGroupFromOrganization } from '@gruperly/shared'; -import { CreateGroupFromOrganizationSchema } from '@gruperly/shared'; -import { Hono } from 'hono'; -import { problemJson, unauthorizedProblem } from '@/http/problem-details'; -import { validate } from '@/http/validate'; -import { CreateGroupFromOrganization as UseCase } from './use-case'; - -const route = new Hono(); - -route.post('/', validate.json(CreateGroupFromOrganizationSchema), async (c) => { - const user = c.get('user'); - if (!user) { - return problemJson(c, unauthorizedProblem(c.req.path)); - } - - const data = c.req.valid('json') as CreateGroupFromOrganization; - const useCase = new UseCase(); - const result = await useCase.execute(data, user.id); - - if (!result.ok) { - return problemJson(c, result.error); - } - - return c.json(result.value, result.value.alreadyExists ? 200 : 201); -}); - -export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/groups/features/create-from-organization/use-case.ts b/apps/backend/src/modules/groups/features/create-from-organization/use-case.ts deleted file mode 100644 index 7dfa383..0000000 --- a/apps/backend/src/modules/groups/features/create-from-organization/use-case.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type { Prisma } from '@generated/prisma/client'; -import { Role } from '@generated/prisma/client'; -import type { - CreateGroupFromOrganization as CreateGroupFromOrganizationInput, - CreateGroupFromOrganizationResult, - ProblemDetails, - Result, -} from '@gruperly/shared'; -import { err, ok } from '@gruperly/shared'; -import { - groupOwnerRequiredProblem, - organizationNotFoundProblem, -} from '@/http/problem-builders'; -import { default as prisma, UnitOfWork } from '@/lib/prisma'; -import { type GroupDb, toGroupDto } from '../../lib'; - -type CreateGroupFromOrganizationDeps = { - db?: Pick; - unitOfWork?: UnitOfWork; -}; - -type GroupRecord = { - id: string; - name: string; - description: string | null; - createdById: string; - createdAt: Date; - updatedAt: Date; -}; - -export class CreateGroupFromOrganization { - constructor(private readonly deps: CreateGroupFromOrganizationDeps = {}) {} - - async execute( - data: CreateGroupFromOrganizationInput, - userId: string, - ): Promise> { - const db = this.deps.db ?? prisma; - const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); - - const organization = await db.organization.findUnique({ - where: { id: data.organizationId }, - include: { members: true }, - }); - if (!organization) { - return err(organizationNotFoundProblem(data.organizationId)); - } - - const membership = organization.members.find((member: { userId: string; role: string }) => member.userId === userId); - if (membership?.role !== 'owner') { - return err(groupOwnerRequiredProblem()); - } - - const existing = await db.group.findFirst({ - where: { createdById: userId, name: organization.name }, - }); - if (existing) { - return ok({ group: toGroupDto(existing), alreadyExists: true }); - } - - const transaction = unitOfWork.executeResult( - async (tx: Prisma.TransactionClient) => { - const created = await tx.group.create({ - data: { - name: organization.name, - createdById: userId, - }, - }); - - await tx.groupMember.create({ - data: { - groupId: created.id, - userId, - role: Role.OWNER, - }, - }); - - return ok(created); - }, - ); - - const result = await transaction; - if (!result.ok) { - return result; - } - - return ok({ - group: toGroupDto(result.value as GroupRecord), - alreadyExists: false, - }); - } -} \ No newline at end of file diff --git a/apps/backend/src/modules/groups/features/create/route.ts b/apps/backend/src/modules/groups/features/create/route.ts new file mode 100644 index 0000000..39c8631 --- /dev/null +++ b/apps/backend/src/modules/groups/features/create/route.ts @@ -0,0 +1,22 @@ +import type { CreateFirstGroup } from '@gruperly/shared'; +import { CreateFirstGroupSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { CreateGroup as CreateGroupUseCase } from './use-case'; + +const route = new Hono(); + +route.post('/', validate.json(CreateFirstGroupSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const data = c.req.valid('json') as CreateFirstGroup; + const useCase = new CreateGroupUseCase(); + const result = await useCase.execute(data, user.id); + return resultJson(c, result, { status: 201 }); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/groups/features/create/use-case.ts b/apps/backend/src/modules/groups/features/create/use-case.ts new file mode 100644 index 0000000..4e1eb8d --- /dev/null +++ b/apps/backend/src/modules/groups/features/create/use-case.ts @@ -0,0 +1,67 @@ +import type { Prisma } from '@generated/prisma/client'; +import { Role } from '@generated/prisma/client'; +import type { + CreateFirstGroup as CreateGroupInput, + CreateGroupResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { type GroupRecord, toGroupDto } from '../../lib'; + +type CreateGroupDeps = { + unitOfWork?: UnitOfWork; + planGuard?: Pick; +}; + +export class CreateGroup { + constructor(private readonly deps: CreateGroupDeps = {}) {} + + async execute( + data: CreateGroupInput, + userId: string, + ): Promise> { + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); + if (!allowed.ok) { + return allowed; + } + + const transaction = unitOfWork.executeResult( + async (tx: Prisma.TransactionClient) => { + const created = await tx.group.create({ + data: { + name: data.name, + createdById: userId, + days: data.days, + time: data.time, + capacity: data.capacity, + price: data.price, + billingType: data.billingType, + dueDay: data.dueDay, + }, + }); + + await tx.groupMember.create({ + data: { + groupId: created.id, + userId, + role: Role.OWNER, + }, + }); + + return ok(created); + }, + ); + + const result = await transaction; + if (!result.ok) { + return result; + } + + return ok({ group: toGroupDto(result.value as GroupRecord) }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/groups/features/get-all/use-case.ts b/apps/backend/src/modules/groups/features/get-all/use-case.ts index 6fbcd53..4873461 100644 --- a/apps/backend/src/modules/groups/features/get-all/use-case.ts +++ b/apps/backend/src/modules/groups/features/get-all/use-case.ts @@ -8,20 +8,31 @@ import type { import { ok } from '@gruperly/shared'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import prisma from '@/lib/prisma'; -import { buildGroupWhereForUser, type GroupDb, toGroupDto } from '../../lib'; +import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler'; +import { + buildGroupWhereForUser, + type GroupDb, + type GroupListRecord, + toGroupListItemDto, +} from '../../lib'; type ListGroupsDeps = { db?: Pick; + now?: Date; }; -type GroupRecord = { - id: string; - name: string; - description: string | null; - createdById: string; - createdAt: Date; - updatedAt: Date; -}; +const LIST_COUNT_INCLUDE = { + _count: { + select: { + // Group members. No status filter, same as the detail page counts. + attendees: true, + // Waitlist: the ones still waiting for a spot (the reviewed ones drop out). + waitlist: { where: { status: 'PENDING' as const } }, + // Payments still to collect: the ones pending and the overdue ones. + payments: { where: { status: { in: ['PENDING' as const, 'OVERDUE' as const] } } }, + }, + }, +} satisfies Prisma.GroupInclude; export class ListGroups { constructor(private readonly deps: ListGroupsDeps = {}) {} @@ -31,21 +42,59 @@ export class ListGroups { userId: string, ): Promise> { const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput; - const [records, total] = await Promise.all([ - db.group.findMany({ - where, - skip: getPaginationOffset(query), - take: query.pageSize, - orderBy: { createdAt: 'desc' }, - }), - db.group.count({ where }), - ]); + // We fetch the user's groups with their counters and sort them here: the next + // class is derived from days + time, there is no column to sort on in the + // database. It's the same engine the home summary uses, with the person's + // time zone (or the server's if it doesn't come along). + const records: GroupListRecord[] = await db.group.findMany({ + where, + include: LIST_COUNT_INCLUDE, + }); + + const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE; + const withNextClass = records.map((record) => ({ + record, + nextAt: nextOccurrenceAt(record, now, timeZone), + })); + + /* A group with no schedule has no class to compare, so it goes last; + between groups with the same class (or with no schedule) the newest one + breaks the tie, which was the listing's previous criterion. */ + const ordered = withNextClass.sort((a, b) => { + if (a.nextAt !== null && b.nextAt !== null) { + return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime(); + } + if (a.nextAt !== null) { + return -1; + } + if (b.nextAt !== null) { + return 1; + } + return b.record.createdAt.getTime() - a.record.createdAt.getTime(); + }); + + const offset = getPaginationOffset(query); + const page = ordered.slice(offset, offset + query.pageSize); return ok({ - data: records.map((record: GroupRecord) => toGroupDto(record)), - pagination: getPaginationMetadata(query, total), + data: page.map(({ record }) => toGroupListItemDto(record)), + pagination: getPaginationMetadata(query, ordered.length), }); } -} \ No newline at end of file +} + +function nextOccurrenceAt(record: GroupListRecord, now: Date, timeZone: string): number | null { + if (!record.days?.length || !record.time) { + return null; + } + const occurrence = nextClassOccurrence({ + days: record.days, + time: record.time, + now, + timeZone, + }); + return occurrence ? occurrence.occurrenceAt.getTime() : null; +} diff --git a/apps/backend/src/modules/groups/features/get-by-id/route.ts b/apps/backend/src/modules/groups/features/get-by-id/route.ts new file mode 100644 index 0000000..2034dd8 --- /dev/null +++ b/apps/backend/src/modules/groups/features/get-by-id/route.ts @@ -0,0 +1,18 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetGroupById } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const useCase = new GetGroupById(); + const result = await useCase.execute(groupId, user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/groups/features/get-by-id/use-case.ts b/apps/backend/src/modules/groups/features/get-by-id/use-case.ts new file mode 100644 index 0000000..71fe8db --- /dev/null +++ b/apps/backend/src/modules/groups/features/get-by-id/use-case.ts @@ -0,0 +1,40 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { GroupDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { type GroupRecord, toGroupDto } from '../../lib'; + +type GetGroupByIdDeps = { + db?: Pick; +}; + +export class GetGroupById { + constructor(private readonly deps: GetGroupByIdDeps = {}) {} + + async execute( + groupId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { + members: { where: { userId } }, + }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + return ok(toGroupDto(group as unknown as GroupRecord)); + } +} diff --git a/apps/backend/src/modules/groups/features/invite-token/route.ts b/apps/backend/src/modules/groups/features/invite-token/route.ts new file mode 100644 index 0000000..67905cf --- /dev/null +++ b/apps/backend/src/modules/groups/features/invite-token/route.ts @@ -0,0 +1,30 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetOrCreateInviteToken } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/invite-token', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const useCase = new GetOrCreateInviteToken(); + const result = await useCase.execute(groupId, user.id); + return resultJson(c, result); +}); + +route.post('/:groupId/invite-token', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const groupId = c.req.param('groupId'); + const regenerate = c.req.query('regenerate') === 'true'; + const useCase = new GetOrCreateInviteToken(); + const result = await useCase.execute(groupId, user.id, { regenerate }); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/groups/features/invite-token/use-case.ts b/apps/backend/src/modules/groups/features/invite-token/use-case.ts new file mode 100644 index 0000000..b7d2dbb --- /dev/null +++ b/apps/backend/src/modules/groups/features/invite-token/use-case.ts @@ -0,0 +1,53 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { InviteTokenResult, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { nanoid } from 'nanoid'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; + +type InviteTokenDeps = { + db?: Pick; +}; + +export class GetOrCreateInviteToken { + constructor(private readonly deps: InviteTokenDeps = {}) {} + + async execute( + groupId: string, + userId: string, + options?: { regenerate?: boolean }, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { + members: { where: { userId } }, + }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + let token = group.inviteToken; + if (!token || options?.regenerate) { + token = nanoid(12); + await db.group.update({ + where: { id: groupId }, + data: { inviteToken: token }, + }); + } + + const baseUrl = process.env.WEB_URL ?? 'http://localhost:6173'; + const inviteUrl = `${baseUrl}/join/${token}`; + + return ok({ token, inviteUrl }); + } +} diff --git a/apps/backend/src/modules/groups/features/list-attendees/route.ts b/apps/backend/src/modules/groups/features/list-attendees/route.ts new file mode 100644 index 0000000..297873c --- /dev/null +++ b/apps/backend/src/modules/groups/features/list-attendees/route.ts @@ -0,0 +1,17 @@ +import { type AttendeeQuery, AttendeeQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListAttendees } from '@/modules/attendees/features/get-all/use-case'; + +const route = new Hono(); + +route.get('/:groupId/attendees', validate.query(AttendeeQuerySchema), async (c) => { + const groupId = c.req.param('groupId'); + const query = c.req.valid('query') as AttendeeQuery; + const useCase = new ListAttendees(); + const result = await useCase.execute({ ...query, groupId }); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/groups/lib/helpers.ts b/apps/backend/src/modules/groups/lib/helpers.ts index b136d99..c6f6dd8 100644 --- a/apps/backend/src/modules/groups/lib/helpers.ts +++ b/apps/backend/src/modules/groups/lib/helpers.ts @@ -1,15 +1,35 @@ import type { PrismaClient } from '@generated/prisma/client'; -import type { GroupDto } from '@gruperly/shared'; +import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared'; -export type GroupDb = Pick; +export type GroupDb = Pick; -type GroupRecord = { +type PriceLike = { toString(): string }; + +export type GroupRecord = { id: string; name: string; description: string | null; createdById: string; createdAt: Date; updatedAt: Date; + days: WeekDay[] | null; + time: string | null; + capacity: number | null; + price: PriceLike | number | null; + billingType: BillingType | null; + dueDay: number | null; + inviteToken?: string | null; + autoPaymentReminders?: boolean; + autoReengagement?: boolean; +}; + +/* The listing adds the occupancy counters to each group so the card can show + them without asking for one endpoint per group. They come from the `_count` of + the same query: all the members (same as the detail page counts) and only the + waitlist entries still waiting for a spot (PENDING), plus the payments still + to collect (PENDING and OVERDUE). */ +export type GroupListRecord = GroupRecord & { + _count?: { attendees: number; waitlist: number; payments?: number }; }; export function toGroupDto(record: GroupRecord): GroupDto { @@ -20,6 +40,24 @@ export function toGroupDto(record: GroupRecord): GroupDto { createdById: record.createdById, createdAt: record.createdAt.toISOString(), updatedAt: record.updatedAt.toISOString(), + days: record.days, + time: record.time, + capacity: record.capacity, + price: record.price == null ? null : Number(record.price.toString()), + billingType: record.billingType, + dueDay: record.dueDay, + inviteToken: record.inviteToken ?? null, + autoPaymentReminders: record.autoPaymentReminders ?? false, + autoReengagement: record.autoReengagement ?? false, + }; +} + +export function toGroupListItemDto(record: GroupListRecord): GroupListItem { + return { + ...toGroupDto(record), + attendeesCount: record._count?.attendees ?? 0, + waitlistCount: record._count?.waitlist ?? 0, + unpaidPaymentsCount: record._count?.payments ?? 0, }; } diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index fe41e00..b1848bf 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -1,10 +1,46 @@ import { Hono } from 'hono'; -import createFromOrganizationRoute from './features/create-from-organization/route'; +import analyticsRoutes from '../analytics/routes'; +import addAttendeeToGroupRoute from '../attendees/features/add-to-group/route'; +import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route'; +import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route'; +import createAttendeeRoute from '../attendees/features/create/route'; +import getAttendeeRoute from '../attendees/features/get-by-id/route'; +import getAttendeeStatsRoute from '../attendees/features/get-stats/route'; +import moveAttendeeRoute from '../attendees/features/move/route'; +import removeAttendeeRoute from '../attendees/features/remove/route'; +import updateAttendeeRoute from '../attendees/features/update/route'; +import groupPreRegistrationRoutes from '../group-preregistrations/routes'; +import groupWaitlistRoutes from '../group-waitlist/routes'; +import createPaymentsBatchRoute from '../payments/features/create-batch/route'; +import { studentAccessRoutes } from '../student-access'; +import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route'; +import createGroupRoute from './features/create/route'; import getAllRoute from './features/get-all/route'; +import getByIdRoute from './features/get-by-id/route'; +import inviteTokenRoute from './features/invite-token/route'; +import listAttendeesRoute from './features/list-attendees/route'; const routes = new Hono(); routes.route('/', getAllRoute); -routes.route('/from-organization', createFromOrganizationRoute); +routes.route('/', createGroupRoute); +routes.route('/', inviteTokenRoute); +routes.route('/', listAttendeesRoute); +routes.route('/', createAttendeeRoute); +routes.route('/', bulkCreateAttendeesRoute); +routes.route('/', getByIdRoute); +routes.route('/', createPaymentsBatchRoute); +routes.route('/', updateGroupAutomationsRoute); +routes.route('/', addToGroupWaitlistRoute); +routes.route('/', groupWaitlistRoutes); +routes.route('/', groupPreRegistrationRoutes); +routes.route('/', analyticsRoutes); +routes.route('/', getAttendeeRoute); +routes.route('/', updateAttendeeRoute); +routes.route('/', getAttendeeStatsRoute); +routes.route('/', removeAttendeeRoute); +routes.route('/', moveAttendeeRoute); +routes.route('/', addAttendeeToGroupRoute); +routes.route('/', studentAccessRoutes); -export default routes; \ No newline at end of file +export default routes; diff --git a/apps/backend/src/modules/home/features/get-summary/route.ts b/apps/backend/src/modules/home/features/get-summary/route.ts new file mode 100644 index 0000000..d5bd181 --- /dev/null +++ b/apps/backend/src/modules/home/features/get-summary/route.ts @@ -0,0 +1,23 @@ +import type { HomeQuery } from '@gruperly/shared'; +import { HomeQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetHomeSummary } from './use-case'; + +const route = new Hono(); + +route.get('/', validate.query(HomeQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const query = c.req.valid('query') as HomeQuery; + const useCase = new GetHomeSummary(); + const result = await useCase.execute(user.id, query); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/home/features/get-summary/use-case.ts b/apps/backend/src/modules/home/features/get-summary/use-case.ts new file mode 100644 index 0000000..bcf74ba --- /dev/null +++ b/apps/backend/src/modules/home/features/get-summary/use-case.ts @@ -0,0 +1,146 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + HomeQuery, + HomeSummary, + NextClass, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib/helpers'; +import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '../../lib/scheduler'; + +export const UPCOMING_PAYMENTS_LIMIT = 5; + +type HomeSummaryDeps = { + db?: Pick; + now?: Date; + timeZone?: string; +}; + +type GroupSummaryRecord = { + id: string; + name: string; + days: NextClass['days']; + time: string | null; + _count: { attendees: number; preRegistrations: number }; +}; + +export class GetHomeSummary { + constructor(private readonly deps: HomeSummaryDeps = {}) {} + + async execute(userId: string, query: HomeQuery = {}): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE; + + const groups = await db.group.findMany({ + where: buildGroupWhereForUser(userId), + select: { + id: true, + name: true, + days: true, + time: true, + // The pending pre-registrations ride on the same query: Home lists + // them under "Para atender" without one request per group. + _count: { + select: { attendees: true, preRegistrations: { where: { status: 'PENDING' } } }, + }, + }, + }); + + if (groups.length === 0) { + return ok({ + stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 }, + nextClass: null, + upcomingPayments: [], + pendingPreRegistrations: [], + }); + } + + const groupIds = groups.map((group) => group.id); + const attendees = groups.reduce((sum, group) => sum + group._count.attendees, 0); + + const [pendingAggregate, upcomingPayments] = await Promise.all([ + db.payment.aggregate({ + where: { groupId: { in: groupIds }, status: { in: ['PENDING', 'OVERDUE'] } }, + _count: true, + _sum: { amount: true }, + }), + db.payment.findMany({ + where: { groupId: { in: groupIds }, status: { in: ['PENDING', 'OVERDUE'] } }, + orderBy: [{ dueDate: 'asc' as const }], + take: UPCOMING_PAYMENTS_LIMIT, + include: { + group: { select: { name: true } }, + attendee: { select: { person: { select: { fullName: true } } } }, + }, + }), + ]); + + return ok({ + stats: { + groups: groups.length, + attendees, + pendingPayments: pendingAggregate._count, + pendingAmount: pendingAggregate._sum.amount + ? Number(pendingAggregate._sum.amount.toString()) + : 0, + }, + nextClass: this.findNextClass(groups, now, timeZone), + upcomingPayments: upcomingPayments.map((payment) => ({ + id: payment.id, + amount: Number(payment.amount.toString()), + currency: payment.currency, + dueDate: payment.dueDate.toISOString(), + status: payment.status, + groupName: payment.group.name, + attendeeName: payment.attendee.person.fullName, + })), + pendingPreRegistrations: groups + .filter((group) => group._count.preRegistrations > 0) + .map((group) => ({ + groupId: group.id, + groupName: group.name, + count: group._count.preRegistrations, + })), + }); + } + + private findNextClass( + groups: GroupSummaryRecord[], + now: Date, + timeZone: string, + ): NextClass | null { + let best: NextClass | null = null; + + for (const group of groups) { + if (!group.days || group.days.length === 0 || !group.time) { + continue; + } + const occurrence = nextClassOccurrence({ + days: group.days, + time: group.time, + now, + timeZone, + }); + if (!occurrence) { + continue; + } + if (best && occurrence.occurrenceAt.getTime() >= new Date(best.occurrenceAt).getTime()) { + continue; + } + best = { + groupId: group.id, + name: group.name, + days: group.days, + time: group.time, + occurrenceAt: occurrence.occurrenceAt.toISOString(), + isNow: occurrence.isNow, + }; + } + + return best; + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/home/index.ts b/apps/backend/src/modules/home/index.ts new file mode 100644 index 0000000..8d35a7f --- /dev/null +++ b/apps/backend/src/modules/home/index.ts @@ -0,0 +1 @@ +export { default as homeRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/home/lib/scheduler.ts b/apps/backend/src/modules/home/lib/scheduler.ts new file mode 100644 index 0000000..92979e6 --- /dev/null +++ b/apps/backend/src/modules/home/lib/scheduler.ts @@ -0,0 +1,234 @@ +import type { WeekDay } from '@gruperly/shared'; + +export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Argentina/Buenos_Aires'; + +// Window (in hours) during which an already started class shows as "in progress". +export const CLASS_WINDOW_HOURS = 2; +export const CLASS_WINDOW_MS = CLASS_WINDOW_HOURS * 60 * 60 * 1000; + +const WEEKDAY_TO_DOW: Record = { + SUNDAY: 0, + MONDAY: 1, + TUESDAY: 2, + WEDNESDAY: 3, + THURSDAY: 4, + FRIDAY: 5, + SATURDAY: 6, +}; + +export type NextClassOccurrence = { + occurrenceAt: Date; + isNow: boolean; +}; + +// Converts a "wall clock" time expressed in `timeZone` into the absolute instant. +export function zonedWallClockToUtc(wall: string, timeZone: string): Date { + const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall); + if (!match) { + throw new Error(`Invalid wall clock: ${wall}`); + } + const [, year, month, day, hour, minute] = match; + + const asUtc = new Date( + Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute)), + ); + + const parts = new Intl.DateTimeFormat('en-US', { + timeZone, + hourCycle: 'h23', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }) + .formatToParts(asUtc) + .reduce>((acc, part) => { + acc[part.type] = part.value; + return acc; + }, {}); + + const tzRepresentation = new Date( + Date.UTC( + Number(parts.year), + Number(parts.month) - 1, + Number(parts.day), + Number(parts.hour), + Number(parts.minute), + Number(parts.second), + ), + ); + + const offsetMs = asUtc.getTime() - tzRepresentation.getTime(); + return new Date(asUtc.getTime() + offsetMs); +} + +export function wallDateInTimeZone(now: Date, timeZone: string): { year: number; month: number; day: number } { + const wall = new Intl.DateTimeFormat('en-US', { + timeZone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + }) + .formatToParts(now) + .reduce>((acc, part) => { + acc[part.type] = part.value; + return acc; + }, {}); + + return { + year: Number(wall.year), + month: Number(wall.month), + day: Number(wall.day), + }; +} + +export function nextClassOccurrence(opt: { + days: WeekDay[]; + time: string; + now: Date; + timeZone: string; +}): NextClassOccurrence | null { + const { days, time, now, timeZone } = opt; + + if (days.length === 0 || !time) { + return null; + } + const [hour, minute] = time.split(':').map(Number); + if ( + Number.isNaN(hour) || + Number.isNaN(minute) || + hour < 0 || + hour > 23 || + minute < 0 || + minute > 59 + ) { + return null; + } + + const dowSet = new Set(days.map((day) => WEEKDAY_TO_DOW[day])); + const { year, month, day } = wallDateInTimeZone(now, timeZone); + + let best: NextClassOccurrence | null = null; + + for (let offset = 0; offset <= 7; offset++) { + const candidateDay = new Date(Date.UTC(year, month - 1, day + offset, 0, 0, 0)); + const dow = candidateDay.getUTCDay(); + if (!dowSet.has(dow)) { + continue; + } + + const wall = `${candidateDay.toISOString().slice(0, 10)}T${pad(hour)}:${pad(minute)}`; + const candidate = zonedWallClockToUtc(wall, timeZone); + + if (offset === 0) { + if (candidate.getTime() > now.getTime()) { + best = { occurrenceAt: candidate, isNow: false }; + break; + } + if (now.getTime() >= candidate.getTime() && now.getTime() - candidate.getTime() < CLASS_WINDOW_MS) { + return { occurrenceAt: candidate, isNow: true }; + } + continue; + } + + if (!best || candidate.getTime() < best.occurrenceAt.getTime()) { + best = { occurrenceAt: candidate, isNow: false }; + } + } + + return best; +} + +function pad(value: number): string { + return String(value).padStart(2, '0'); +} + +// Absolute instant of TODAY's class (even if the time has already passed), or null if the +// group has no class scheduled for `now`'s day in `timeZone`. +export function todayOccurrence(opt: { + days: WeekDay[]; + time: string; + now: Date; + timeZone: string; +}): Date | null { + const { days, time, now, timeZone } = opt; + + if (days.length === 0 || !time) { + return null; + } + const [hour, minute] = time.split(':').map(Number); + if ( + Number.isNaN(hour) || + Number.isNaN(minute) || + hour < 0 || + hour > 23 || + minute < 0 || + minute > 59 + ) { + return null; + } + + const { year, month, day } = wallDateInTimeZone(now, timeZone); + const dow = new Date(Date.UTC(year, month - 1, day)).getUTCDay(); + const dayMatches = days.some((d) => WEEKDAY_TO_DOW[d] === dow); + if (!dayMatches) { + return null; + } + + const wall = `${year}-${pad(month)}-${pad(day)}T${pad(hour)}:${pad(minute)}`; + return zonedWallClockToUtc(wall, timeZone); +} + +// First instant of `now`'s day in `timeZone` (local midnight). +export function startOfDayInTimeZone(now: Date, timeZone: string): Date { + const { year, month, day } = wallDateInTimeZone(now, timeZone); + return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone); +} +// Every class start of a group within [from, to), in `timeZone`. Empty when the +// group has no valid schedule. +export function occurrencesBetween(opt: { + days: WeekDay[]; + time: string | null; + from: Date; + to: Date; + timeZone: string; +}): Date[] { + const { days, time, from, to, timeZone } = opt; + if (days.length === 0 || !time) return []; + const [hour, minute] = time.split(':').map(Number); + if ( + Number.isNaN(hour) || + Number.isNaN(minute) || + hour < 0 || + hour > 23 || + minute < 0 || + minute > 59 + ) { + return []; + } + + const dowSet = new Set(days.map((day) => WEEKDAY_TO_DOW[day])); + const { year, month, day } = wallDateInTimeZone(from, timeZone); + const result: Date[] = []; + // One extra day on each side covers the time zone offset. + const spanDays = Math.ceil((to.getTime() - from.getTime()) / (24 * 60 * 60 * 1000)) + 1; + for (let offset = -1; offset <= spanDays; offset++) { + const candidateDay = new Date(Date.UTC(year, month - 1, day + offset)); + if (!dowSet.has(candidateDay.getUTCDay())) continue; + const wall = `${candidateDay.toISOString().slice(0, 10)}T${pad(hour)}:${pad(minute)}`; + const startsAt = zonedWallClockToUtc(wall, timeZone); + if (startsAt >= from && startsAt < to) result.push(startsAt); + } + return result; +} + +// Monday 00:00 of `now`'s week in `timeZone`. +export function startOfWeekInTimeZone(now: Date, timeZone: string): Date { + const { year, month, day } = wallDateInTimeZone(now, timeZone); + const date = new Date(Date.UTC(year, month - 1, day)); + const sinceMonday = (date.getUTCDay() + 6) % 7; + const monday = new Date(Date.UTC(year, month - 1, day - sinceMonday)); + return zonedWallClockToUtc(`${monday.toISOString().slice(0, 10)}T00:00`, timeZone); +} diff --git a/apps/backend/src/modules/home/routes.ts b/apps/backend/src/modules/home/routes.ts new file mode 100644 index 0000000..b2273f5 --- /dev/null +++ b/apps/backend/src/modules/home/routes.ts @@ -0,0 +1,8 @@ +import { Hono } from 'hono'; +import getSummaryRoute from './features/get-summary/route'; + +const routes = new Hono(); + +routes.route('/', getSummaryRoute); + +export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/invitations/features/get-invite-info/route.ts b/apps/backend/src/modules/invitations/features/get-invite-info/route.ts new file mode 100644 index 0000000..94f3efc --- /dev/null +++ b/apps/backend/src/modules/invitations/features/get-invite-info/route.ts @@ -0,0 +1,14 @@ +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { GetInviteInfo } from './use-case'; + +const route = new Hono(); + +route.get('/:token', async (c) => { + const token = c.req.param('token'); + const useCase = new GetInviteInfo(); + const result = await useCase.execute(token); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/invitations/features/get-invite-info/use-case.ts b/apps/backend/src/modules/invitations/features/get-invite-info/use-case.ts new file mode 100644 index 0000000..8a9ee81 --- /dev/null +++ b/apps/backend/src/modules/invitations/features/get-invite-info/use-case.ts @@ -0,0 +1,40 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { GroupInviteInfoDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; + +type GetInviteInfoDeps = { + db?: Pick; +}; + +export class GetInviteInfo { + constructor(private readonly deps: GetInviteInfoDeps = {}) {} + + async execute(token: string): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { inviteToken: token }, + include: { + owner: { select: { name: true } }, + }, + }); + + if (!group) { + return err(notFoundResourceProblem('Invitación', token)); + } + + return ok({ + id: group.id, + name: group.name, + description: group.description, + teacherName: group.owner.name, + days: group.days, + time: group.time, + capacity: group.capacity, + price: group.price == null ? null : Number(group.price.toString()), + billingType: group.billingType, + }); + } +} diff --git a/apps/backend/src/modules/invitations/features/join-via-invite/route.ts b/apps/backend/src/modules/invitations/features/join-via-invite/route.ts new file mode 100644 index 0000000..88bce35 --- /dev/null +++ b/apps/backend/src/modules/invitations/features/join-via-invite/route.ts @@ -0,0 +1,17 @@ +import { type JoinGroupViaInvite, JoinGroupViaInviteSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { JoinViaInvite } from './use-case'; + +const route = new Hono(); + +route.post('/:token/join', validate.json(JoinGroupViaInviteSchema), async (c) => { + const token = c.req.param('token'); + const body = c.req.valid('json') as JoinGroupViaInvite; + const useCase = new JoinViaInvite(); + const result = await useCase.execute(token, body); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts new file mode 100644 index 0000000..8e98107 --- /dev/null +++ b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts @@ -0,0 +1,110 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { normalizePhone } from '@/modules/attendees/lib/helpers'; +import { phoneVariants } from '@/modules/people/lib/people'; + +type JoinViaInviteDeps = { + db?: Pick; +}; + +export type JoinViaInviteResult = { + status: 'pre_registered'; + message: string; + attendee: null; +}; + +export class JoinViaInvite { + constructor(private readonly deps: JoinViaInviteDeps = {}) {} + + async execute( + token: string, + payload: JoinGroupViaInvite, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { inviteToken: token }, + }); + + if (!group) { + return err(notFoundResourceProblem('Invitación', token)); + } + + const phone = normalizePhone(payload.phone); + const existing = await db.attendee.findFirst({ + where: { + groupId: group.id, + person: { phone: { in: phoneVariants(payload.phone) } }, + }, + }); + + if (existing) { + return err( + conflictProblem({ + detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.', + code: 'attendee_already_registered', + }), + ); + } + + const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); + const email = payload.email?.trim() || null; + + const existingPreRegistration = await db.groupPreRegistration.findFirst({ + where: { + groupId: group.id, + phone: { in: phoneVariants(payload.phone) }, + }, + }); + + if (existingPreRegistration?.status === 'REJECTED') { + await db.groupPreRegistration.update({ + where: { id: existingPreRegistration.id }, + data: { status: 'PENDING', fullName, email, reviewedAt: null }, + }); + + return ok({ + status: 'pre_registered', + attendee: null, + message: + 'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.', + }); + } + + if (existingPreRegistration) { + const message = + existingPreRegistration.status === 'APPROVED' + ? 'Tu inscripción para este grupo ya fue aprobada.' + : 'Ya enviaste una solicitud de inscripción para este grupo. Está pendiente de revisión por el profesor.'; + + return err( + conflictProblem({ + detail: message, + code: + existingPreRegistration.status === 'APPROVED' + ? 'pre_registration_already_approved' + : 'pre_registration_already_pending', + }), + ); + } + + await db.groupPreRegistration.create({ + data: { + groupId: group.id, + fullName, + phone, + email, + }, + }); + + return ok({ + status: 'pre_registered', + attendee: null, + message: + 'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.', + }); + } +} diff --git a/apps/backend/src/modules/invitations/index.ts b/apps/backend/src/modules/invitations/index.ts new file mode 100644 index 0000000..b48736d --- /dev/null +++ b/apps/backend/src/modules/invitations/index.ts @@ -0,0 +1 @@ +export { default as invitationsRoutes } from './routes'; diff --git a/apps/backend/src/modules/invitations/routes.ts b/apps/backend/src/modules/invitations/routes.ts new file mode 100644 index 0000000..abfb58d --- /dev/null +++ b/apps/backend/src/modules/invitations/routes.ts @@ -0,0 +1,10 @@ +import { Hono } from 'hono'; +import getInviteInfoRoute from './features/get-invite-info/route'; +import joinViaInviteRoute from './features/join-via-invite/route'; + +const routes = new Hono(); + +routes.route('/', getInviteInfoRoute); +routes.route('/', joinViaInviteRoute); + +export default routes; diff --git a/apps/backend/src/modules/mp/access-token.ts b/apps/backend/src/modules/mp/access-token.ts new file mode 100644 index 0000000..4a50ac3 --- /dev/null +++ b/apps/backend/src/modules/mp/access-token.ts @@ -0,0 +1,58 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { mpNotConnectedProblem, mpRequiresReauthProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { RefreshMpAccount } from './jobs'; +import { openToken } from './lib'; + +export type MpTokenAccount = { + accountId: string; + accessToken: string; + expiresAt: Date; +}; + +/** + * Below this, the on-demand path refreshes. The daily job renews much earlier + * (30 days out), so hitting this only means the job did not run, which is exactly + * when a payment link cannot be allowed to fail. + */ +const NEAR_EXPIRY_MS = 5 * 60 * 1000; + +type GetMpAccessTokenDeps = { + db?: Pick; + refresh?: RefreshMpAccount; +}; + +/** + * A usable access token for a teacher's Mercado Pago account. + * + * This is the entry point for payment links and webhook verification, so it fails + * explicitly instead of returning something unusable: an unlinked account and an + * account that needs re-authorization are different problems and the caller has + * to be able to tell them apart. + */ +export async function getMpAccessToken( + ownerId: string, + deps: GetMpAccessTokenDeps = {}, +): Promise> { + const db = deps.db ?? prisma; + + const account = await db.mpAccount.findUnique({ where: { ownerId } }); + if (!account) return err(mpNotConnectedProblem()); + if (account.status !== 'ACTIVE') return err(mpRequiresReauthProblem()); + + if (account.expiresAt.getTime() - Date.now() > NEAR_EXPIRY_MS) { + return ok({ + accountId: account.id, + accessToken: openToken(account.accessTokenEnc), + expiresAt: account.expiresAt, + }); + } + + const refresh = deps.refresh ?? new RefreshMpAccount(); + const refreshed = await refresh.execute(account.id); + if (!refreshed.ok) return refreshed; + + return ok(refreshed.value); +} diff --git a/apps/backend/src/modules/mp/features/callback/route.ts b/apps/backend/src/modules/mp/features/callback/route.ts new file mode 100644 index 0000000..2ac60bd --- /dev/null +++ b/apps/backend/src/modules/mp/features/callback/route.ts @@ -0,0 +1,50 @@ +import type { MpCallbackQuery, MpCallbackReason, ProblemDetails } from '@gruperly/shared'; +import { MpCallbackQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { validate } from '@/http/validate'; +import { logger } from '@/logger'; +import { buildMpReturnUrl, getWebOrigin } from '../../lib'; +import { CompleteMpAuthorization, type MpCallbackResult } from './use-case'; + +/** + * The browser arrives here from Mercado Pago, so this route always answers with + * a redirect back to the app and never renders or returns a problem body: there + * is nothing on the other side to render a failure into. + */ +const route = new Hono(); + +route.get('/', validate.query(MpCallbackQuerySchema), async (c) => { + const { code, state, error } = c.req.valid('query') as MpCallbackQuery; + + const user = c.get('user'); + if (!user) { + // Without a session there is nobody to credit the tokens to. The state was + // issued to whoever was signed in when the flow started, so guessing would + // be a way to attach somebody else's Mercado Pago account to this account. + logger.warn('Mercado Pago callback arrived without a session'); + return c.redirect(new URL('/login', getWebOrigin()).toString()); + } + + const useCase = new CompleteMpAuthorization(); + const result = await useCase.execute({ code, state, error }); + + if (!result.ok) { + logger.warn( + { code: result.error.code, status: result.error.status }, + 'Mercado Pago callback failed', + ); + } + + const outcome = result.ok ? result.value.outcome : problemToOutcome(result.error); + const returnTo = result.ok ? result.value.returnTo : 'settings'; + + return c.redirect(buildMpReturnUrl(getWebOrigin(), returnTo, outcome)); +}); + +/** Reduces an internal problem to a reason code that is safe in a URL. */ +function problemToOutcome(problem: ProblemDetails): MpCallbackResult['outcome'] { + const reason: MpCallbackReason = problem.code === 'mp_account_in_use' ? 'mp_account_in_use' : 'mp_error'; + return { kind: 'error', reason }; +} + +export default route; diff --git a/apps/backend/src/modules/mp/features/callback/use-case.ts b/apps/backend/src/modules/mp/features/callback/use-case.ts new file mode 100644 index 0000000..6114478 --- /dev/null +++ b/apps/backend/src/modules/mp/features/callback/use-case.ts @@ -0,0 +1,145 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { MpCallbackReason, MpReturnTo, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + mpAccountInUseProblem, + mpNotConfiguredProblem, + mpProviderErrorProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + exchangeAuthorizationCode, + getMpOAuthConfig, + type MpTokenResponse, + sealToken, +} from '../../lib'; + +type CompleteMpAuthorizationDeps = { + db?: Pick; + /** Swapped in tests; defaults to the real Mercado Pago exchange. */ + exchange?: typeof exchangeAuthorizationCode; +}; + +export type MpCallbackResult = { + returnTo: MpReturnTo; + outcome: { kind: 'success' } | { kind: 'error'; reason: MpCallbackReason }; +}; + +/** Prisma's unique-constraint violation on `mp_accounts_mpUserId_key`. */ +const UNIQUE_VIOLATION = 'P2002'; + +/** Where we land if the state is gone and there is nothing to recover. */ +const DEFAULT_RETURN_TO: MpReturnTo = 'settings'; + +export class CompleteMpAuthorization { + constructor(private readonly deps: CompleteMpAuthorizationDeps = {}) {} + + async execute(input: { + code?: string; + state?: string; + error?: string; + }): Promise> { + let config: ReturnType; + try { + config = getMpOAuthConfig(); + } catch (configError) { + logger.error({ err: configError }, 'Mercado Pago is not configured'); + return err(mpNotConfiguredProblem()); + } + + const db = this.deps.db ?? prisma; + + // The teacher closed the consent screen. There is nothing to exchange, but + // the state is still burned so it cannot be replayed later. + if (input.error) { + if (input.state) { + await db.mpOAuthState.deleteMany({ where: { state: input.state } }); + } + return failure('mp_denied'); + } + + if (!input.code || !input.state) { + return failure('invalid_state'); + } + + const stored = await db.mpOAuthState.findUnique({ where: { state: input.state } }); + if (!stored || stored.expiresAt.getTime() <= Date.now()) { + return failure('invalid_state'); + } + + const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO; + + // Single use, and burned *before* we talk to Mercado Pago: a `count` of zero + // means someone replayed a state we already consumed. + const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } }); + if (consumed.count === 0) { + return failure('invalid_state', returnTo); + } + + const exchange = this.deps.exchange ?? exchangeAuthorizationCode; + let tokens: MpTokenResponse; + try { + tokens = await exchange({ + clientId: config.clientId, + clientSecret: config.clientSecret, + redirectUri: config.redirectUri, + code: input.code, + codeVerifier: stored.codeVerifier, + }); + } catch (exchangeError) { + // `MpApiError` already logged the status and MP's own error code. Nothing + // added here mentions the authorization code or the verifier. + logger.error({ err: exchangeError }, 'Mercado Pago authorization could not be completed'); + return err(mpProviderErrorProblem()); + } + + const claimed = await db.mpAccount.findUnique({ where: { mpUserId: tokens.mpUserId } }); + if (claimed && claimed.ownerId !== stored.ownerId) { + return err(mpAccountInUseProblem()); + } + + const encrypted = { + accessTokenEnc: sealToken(tokens.accessToken), + refreshTokenEnc: sealToken(tokens.refreshToken), + expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000), + scope: tokens.scope, + liveMode: tokens.liveMode, + status: 'ACTIVE' as const, + }; + + try { + await db.mpAccount.upsert({ + where: { ownerId: stored.ownerId }, + create: { ownerId: stored.ownerId, mpUserId: tokens.mpUserId, ...encrypted }, + // Re-linking renews the credentials and clears a `requires_reauth`. + update: { mpUserId: tokens.mpUserId, ...encrypted, connectedAt: new Date() }, + }); + } catch (writeError) { + // Two teachers linked the same Mercado Pago id at the same time: the + // unique index is the real arbiter, not the read above. + if (isUniqueViolation(writeError)) { + return err(mpAccountInUseProblem()); + } + throw writeError; + } + + return ok({ returnTo, outcome: { kind: 'success' } }); + } +} + +function failure( + reason: MpCallbackReason, + returnTo: MpReturnTo = DEFAULT_RETURN_TO, +): Result { + return ok({ returnTo, outcome: { kind: 'error', reason } }); +} + +function isUniqueViolation(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as { code?: unknown }).code === UNIQUE_VIOLATION + ); +} diff --git a/apps/backend/src/modules/mp/features/connect/route.ts b/apps/backend/src/modules/mp/features/connect/route.ts new file mode 100644 index 0000000..e60cd5a --- /dev/null +++ b/apps/backend/src/modules/mp/features/connect/route.ts @@ -0,0 +1,21 @@ +import type { MpConnectQuery, MpReturnTo } from '@gruperly/shared'; +import { MpConnectQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { StartMpAuthorization } from './use-case'; + +const route = new Hono(); + +route.get('/', validate.query(MpConnectQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const { returnTo } = c.req.valid('query') as MpConnectQuery; + + const useCase = new StartMpAuthorization(); + const result = await useCase.execute(user.id, returnTo as MpReturnTo); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/mp/features/connect/use-case.ts b/apps/backend/src/modules/mp/features/connect/use-case.ts new file mode 100644 index 0000000..7c7c485 --- /dev/null +++ b/apps/backend/src/modules/mp/features/connect/use-case.ts @@ -0,0 +1,71 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + MpAuthorizationUrlDto, + MpReturnTo, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { mpNotConfiguredProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + buildAuthorizationUrl, + codeChallengeFromVerifier, + getMpOAuthConfig, + newCodeVerifier, + newState, +} from '../../lib'; + +type StartMpAuthorizationDeps = { db?: Pick }; + +/** The teacher has ten minutes to finish at Mercado Pago before the state dies. */ +export const STATE_TTL_MS = 10 * 60 * 1000; + +export class StartMpAuthorization { + constructor(private readonly deps: StartMpAuthorizationDeps = {}) {} + + async execute( + ownerId: string, + returnTo: MpReturnTo, + ): Promise> { + let config: ReturnType; + try { + config = getMpOAuthConfig(); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago is not configured'); + return err(mpNotConfiguredProblem()); + } + + const db = this.deps.db ?? prisma; + const now = new Date(); + + // Two jobs in one sweep: drop anything expired, and drop this teacher's + // previous attempt so a teacher clicking twice cannot leave rows behind. + await db.mpOAuthState.deleteMany({ + where: { OR: [{ expiresAt: { lt: now } }, { ownerId }] }, + }); + + const state = newState(); + const codeVerifier = newCodeVerifier(); + + await db.mpOAuthState.create({ + data: { + state, + ownerId, + codeVerifier, + returnTo, + expiresAt: new Date(now.getTime() + STATE_TTL_MS), + }, + }); + + return ok({ + authorizationUrl: buildAuthorizationUrl({ + clientId: config.clientId, + redirectUri: config.redirectUri, + state, + codeChallenge: codeChallengeFromVerifier(codeVerifier), + }), + }); + } +} diff --git a/apps/backend/src/modules/mp/features/disconnect/route.ts b/apps/backend/src/modules/mp/features/disconnect/route.ts new file mode 100644 index 0000000..3f481f2 --- /dev/null +++ b/apps/backend/src/modules/mp/features/disconnect/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { DisconnectMp } from './use-case'; + +const route = new Hono(); + +route.delete('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new DisconnectMp(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/mp/features/disconnect/use-case.ts b/apps/backend/src/modules/mp/features/disconnect/use-case.ts new file mode 100644 index 0000000..5bd5fba --- /dev/null +++ b/apps/backend/src/modules/mp/features/disconnect/use-case.ts @@ -0,0 +1,39 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { MpDisconnectResultDto, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; + +type DisconnectMpDeps = { db?: Pick }; + +/** + * Mercado Pago has no seller-side token revocation endpoint for these grants, so + * the tokens are dropped here and the row is kept as `REVOKED`. It is not + * deleted on purpose: the Mercado Pago id stays reserved for the same teacher, + * which stops someone else from claiming their account later. + */ +export class DisconnectMp { + constructor(private readonly deps: DisconnectMpDeps = {}) {} + + async execute(ownerId: string): Promise> { + const db = this.deps.db ?? prisma; + + const account = await db.mpAccount.findUnique({ where: { ownerId } }); + if (!account) { + return ok({ disconnected: false }); + } + + await db.mpAccount.update({ + where: { ownerId }, + data: { + status: 'REVOKED', + // The columns are NOT NULL, so the values are blanked rather than nulled. + // Nothing reads them: every consumer filters on `status` first. + accessTokenEnc: '', + refreshTokenEnc: '', + expiresAt: new Date(0), + }, + }); + + return ok({ disconnected: true }); + } +} diff --git a/apps/backend/src/modules/mp/features/status/route.ts b/apps/backend/src/modules/mp/features/status/route.ts new file mode 100644 index 0000000..0461dda --- /dev/null +++ b/apps/backend/src/modules/mp/features/status/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetMpStatus } from './use-case'; + +const route = new Hono(); + +route.get('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new GetMpStatus(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/mp/features/status/use-case.ts b/apps/backend/src/modules/mp/features/status/use-case.ts new file mode 100644 index 0000000..a635053 --- /dev/null +++ b/apps/backend/src/modules/mp/features/status/use-case.ts @@ -0,0 +1,52 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { MpAccountStatus, MpStatusDto, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; + +type GetMpStatusDeps = { db?: Pick }; + +/** How many trailing digits of the Mercado Pago id we show, to confirm the account. */ +const SUFFIX_LENGTH = 4; + +const NOT_LINKED: MpStatusDto = { + status: 'none', + liveMode: false, + expiresAt: null, + connectedAt: null, + mpUserIdSuffix: null, +}; + +/** + * An account the teacher unlinked stays in the table (so the Mercado Pago id + * stays reserved for them), but from the outside it is simply "not linked". + */ +function toVisibleStatus(status: 'ACTIVE' | 'REQUIRES_REAUTH' | 'REVOKED'): MpAccountStatus { + switch (status) { + case 'ACTIVE': + return 'active'; + case 'REQUIRES_REAUTH': + return 'requires_reauth'; + case 'REVOKED': + return 'none'; + } +} + +export class GetMpStatus { + constructor(private readonly deps: GetMpStatusDeps = {}) {} + + async execute(ownerId: string): Promise> { + const db = this.deps.db ?? prisma; + + const account = await db.mpAccount.findUnique({ where: { ownerId } }); + if (!account) return ok(NOT_LINKED); + + // Deliberately no tokens and no scope in the response. + return ok({ + status: toVisibleStatus(account.status), + liveMode: account.liveMode, + expiresAt: account.expiresAt.toISOString(), + connectedAt: account.connectedAt.toISOString(), + mpUserIdSuffix: account.mpUserId.slice(-SUFFIX_LENGTH), + }); + } +} diff --git a/apps/backend/src/modules/mp/index.ts b/apps/backend/src/modules/mp/index.ts new file mode 100644 index 0000000..5bc3d3a --- /dev/null +++ b/apps/backend/src/modules/mp/index.ts @@ -0,0 +1,3 @@ +export { getMpAccessToken, type MpTokenAccount } from './access-token'; +export { startMpJobs } from './jobs'; +export { default as mpRoutes } from './routes'; diff --git a/apps/backend/src/modules/mp/jobs/index.ts b/apps/backend/src/modules/mp/jobs/index.ts new file mode 100644 index 0000000..e653d80 --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/index.ts @@ -0,0 +1,7 @@ +export { + RENEWAL_WINDOW_DAYS, + RefreshExpiringMpTokens, + type RefreshExpiringMpTokensResult, +} from './refresh-expiring-mp-tokens'; +export { type MpAccountStore, RefreshMpAccount } from './refresh-mp-account'; +export { startMpJobs } from './schedule'; diff --git a/apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts b/apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts new file mode 100644 index 0000000..dbc38f7 --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts @@ -0,0 +1,85 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { refreshMpTokens } from '../lib'; +import { RefreshMpAccount } from './refresh-mp-account'; + +/** + * Mercado Pago hands out access tokens valid for about six months. Renewing at + * 30 days leaves room for the job to fail a few times before a token is at risk. + */ +const RENEWAL_WINDOW_DAYS = 30; +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * Keeps a bounded batch: the query below holds row locks for the life of the + * transaction, which means it holds them across the calls to Mercado Pago. + */ +const BATCH_LIMIT = 20; +const TRANSACTION_TIMEOUT_MS = 120_000; + +export type RefreshExpiringMpTokensResult = { + refreshed: number; + requiresReauth: number; + failed: number; +}; + +type RefreshExpiringMpTokensDeps = { + db?: PrismaClient; + /** Swapped in tests; defaults to the real Mercado Pago renewal. */ + refresh?: typeof refreshMpTokens; +}; + +type LockedAccountRow = { id: string }; + +export class RefreshExpiringMpTokens { + constructor(private readonly deps: RefreshExpiringMpTokensDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const now = new Date(); + const totals: RefreshExpiringMpTokensResult = { refreshed: 0, requiresReauth: 0, failed: 0 }; + + await db.$transaction( + async (tx) => { + const horizon = new Date(now.getTime() + RENEWAL_WINDOW_DAYS * DAY_MS); + + // FOR UPDATE SKIP LOCKED: two instances of the API never renew the same + // account, and a row already claimed by another instance is skipped + // instead of blocking the batch. The trade-off is that the lock stays + // held across the HTTP calls below; if MP's latency ever became a + // problem, this becomes an atomic `updateMany` claim on a + // `refresh_claimed_at` column and the rows are released immediately. + const rows = await tx.$queryRaw` + SELECT "id" + FROM "mp_accounts" + WHERE "status" = 'ACTIVE' AND "expires_at" < ${horizon} + ORDER BY "expires_at" ASC + LIMIT ${BATCH_LIMIT} + FOR UPDATE SKIP LOCKED + `; + + for (const row of rows) { + // Built per row with the transaction client, so the writes join the + // transaction holding the lock. With the shared client the lock would + // protect nothing. + const result = await new RefreshMpAccount({ db: tx, refresh: this.deps.refresh }).execute( + row.id, + ); + + if (result.ok) { + totals.refreshed += 1; + } else if (result.error.code === 'mp_requires_reauth') { + totals.requiresReauth += 1; + } else { + totals.failed += 1; + } + } + }, + { timeout: TRANSACTION_TIMEOUT_MS }, + ); + + return totals; + } +} + +export { RENEWAL_WINDOW_DAYS }; diff --git a/apps/backend/src/modules/mp/jobs/refresh-mp-account.ts b/apps/backend/src/modules/mp/jobs/refresh-mp-account.ts new file mode 100644 index 0000000..9ca9b06 --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/refresh-mp-account.ts @@ -0,0 +1,86 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { mpProviderErrorProblem, mpRequiresReauthProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import type { MpTokenAccount } from '../access-token'; +import { + getMpOAuthConfig, + isGrantRejected, + type MpTokenResponse, + openToken, + refreshMpTokens, + sealToken, +} from '../lib'; + +/** Either the client or a transaction client: the job runs this inside a transaction. */ +export type MpAccountStore = { mpAccount: PrismaClient['mpAccount'] }; + +export type RefreshMpAccountDeps = { + db?: MpAccountStore; + refresh?: typeof refreshMpTokens; +}; + +/** + * Renews one account's access token. + * + * Shared by the daily job and by the on-demand path in `getMpAccessToken`. + * + * Mercado Pago rotates the refresh token on every renewal, so the new one is + * always stored: keeping the old one would make the next renewal fail. + * + * Only `invalid_grant` marks the account as `REQUIRES_REAUTH`. A 5xx or a network + * failure means no decision was taken about the grant, and locking a teacher out + * over a bad afternoon at Mercado Pago would be worse than retrying tomorrow. + */ +export class RefreshMpAccount { + constructor(private readonly deps: RefreshMpAccountDeps = {}) {} + + async execute(accountId: string): Promise> { + const db = this.deps.db ?? prisma; + const refresh = this.deps.refresh ?? refreshMpTokens; + + const account = await db.mpAccount.findUnique({ where: { id: accountId } }); + if (!account) { + logger.warn({ accountId }, 'Mercado Pago account vanished mid-renewal'); + return err(mpRequiresReauthProblem()); + } + + let tokens: MpTokenResponse; + try { + const config = getMpOAuthConfig(); + tokens = await refresh({ + ...config, + refreshToken: openToken(account.refreshTokenEnc), + }); + } catch (error) { + if (isGrantRejected(error)) { + logger.warn({ accountId }, 'Mercado Pago refresh token is no longer valid'); + await db.mpAccount.update({ + where: { id: accountId }, + data: { status: 'REQUIRES_REAUTH' }, + }); + return err(mpRequiresReauthProblem()); + } + + logger.error({ accountId, err: error }, 'Mercado Pago token renewal failed'); + return err(mpProviderErrorProblem()); + } + + const expiresAt = new Date(Date.now() + tokens.expiresInSeconds * 1000); + + await db.mpAccount.update({ + where: { id: accountId }, + data: { + accessTokenEnc: sealToken(tokens.accessToken), + refreshTokenEnc: sealToken(tokens.refreshToken), + expiresAt, + scope: tokens.scope ?? account.scope, + status: 'ACTIVE', + }, + }); + + return ok({ accountId, accessToken: tokens.accessToken, expiresAt }); + } +} diff --git a/apps/backend/src/modules/mp/jobs/schedule.ts b/apps/backend/src/modules/mp/jobs/schedule.ts new file mode 100644 index 0000000..b3b490a --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/schedule.ts @@ -0,0 +1,33 @@ +import { logger } from '@/logger'; +import { RefreshExpiringMpTokens } from './refresh-expiring-mp-tokens'; + +/** + * 03:17 UTC. Not on the hour: every instance of the API fires this job at the + * same time, and the lock is only there to make the overlap harmless. + */ +const REFRESH_CRON = '17 3 * * *'; + +/** + * Registers the background jobs. Called once from `server.ts`. + * + * Two things are not obvious here: + * + * - `try/catch` is mandatory. Bun's in-process cron follows `setTimeout` error + * semantics: a rejected promise becomes an `unhandledRejection`, and without a + * listener the process exits with code 1. + * - `unref()` so the job does not keep the process alive on its own. + */ +export function startMpJobs(): void { + Bun.cron( + REFRESH_CRON, + async () => { + try { + const totals = await new RefreshExpiringMpTokens().execute(); + logger.info(totals, 'Mercado Pago token renewal finished'); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago token renewal failed'); + } + }, + { tz: 'UTC' }, + ).unref(); +} diff --git a/apps/backend/src/modules/mp/lib/config.ts b/apps/backend/src/modules/mp/lib/config.ts new file mode 100644 index 0000000..fb39260 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/config.ts @@ -0,0 +1,51 @@ +export type MpOAuthConfig = { + clientId: string; + clientSecret: string; + /** Registered as the app's "Redirect URL". Mercado Pago matches it exactly. */ + redirectUri: string; + /** Frontend origin, used to land the teacher back in the app after the callback. */ + webUrl: string; +}; + +const DEFAULT_WEB_URL = 'http://localhost:6173'; + +export function getWebOrigin(): string { + return process.env.WEB_URL?.trim() || DEFAULT_WEB_URL; +} + +/** + * Reads the Mercado Pago credentials from the environment. + * + * Throws instead of returning a `Result`: these are deployment mistakes, not + * something the teacher did wrong, so they surface as a 500 with a named + * variable in the logs rather than as a problem the UI has to explain. The + * names of the missing variables are safe to log; their values never are. + */ +export function getMpOAuthConfig(): MpOAuthConfig { + const missing: string[] = []; + const read = (name: string): string => { + const value = process.env[name]?.trim(); + if (!value) { + missing.push(name); + return ''; + } + return value; + }; + + const clientId = read('MP_CLIENT_ID'); + const clientSecret = read('MP_CLIENT_SECRET'); + const redirectUri = read('MP_REDIRECT_URI'); + + if (missing.length > 0) { + throw new Error( + `Missing Mercado Pago environment variables: ${missing.join(', ')}. See .env.example.`, + ); + } + + return { + clientId, + clientSecret, + redirectUri, + webUrl: getWebOrigin(), + }; +} diff --git a/apps/backend/src/modules/mp/lib/crypto.ts b/apps/backend/src/modules/mp/lib/crypto.ts new file mode 100644 index 0000000..83289f7 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/crypto.ts @@ -0,0 +1,79 @@ +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'; +import { nanoid } from 'nanoid'; + +/** + * Tokens are encrypted at rest with AES-256-GCM. The payload carries a version + * prefix so the scheme can be rotated later without a data migration: an unknown + * version fails loudly instead of being decrypted with the wrong assumptions. + * + * Layout: `v1:::`, each part base64url. GCM authenticates + * the ciphertext, so a tampered payload throws on `openToken` rather than + * yielding garbage that would later be sent to Mercado Pago as a token. + */ +const PAYLOAD_VERSION = 'v1'; +const KEY_BYTES = 32; +const IV_BYTES = 12; + +function getKey(): Buffer { + const raw = process.env.TOKEN_ENCRYPTION_KEY; + if (!raw) { + throw new Error('TOKEN_ENCRYPTION_KEY environment variable is required'); + } + + const key = Buffer.from(raw, 'base64'); + if (key.length !== KEY_BYTES) { + // Length only, never the value. + throw new Error( + `TOKEN_ENCRYPTION_KEY must decode to ${KEY_BYTES} bytes in base64, got ${key.length}`, + ); + } + + return key; +} + +export function sealToken(plaintext: string): string { + const iv = randomBytes(IV_BYTES); + const cipher = createCipheriv('aes-256-gcm', getKey(), iv); + const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); + + return [ + PAYLOAD_VERSION, + iv.toString('base64url'), + cipher.getAuthTag().toString('base64url'), + ciphertext.toString('base64url'), + ].join(':'); +} + +export function openToken(payload: string): string { + const [version, ivPart, tagPart, ciphertextPart] = payload.split(':'); + + if (version !== PAYLOAD_VERSION || !ivPart || !tagPart || ciphertextPart === undefined) { + throw new Error('Unsupported token payload'); + } + + const decipher = createDecipheriv('aes-256-gcm', getKey(), Buffer.from(ivPart, 'base64url')); + decipher.setAuthTag(Buffer.from(tagPart, 'base64url')); + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertextPart, 'base64url')), + decipher.final(), + ]).toString('utf8'); +} + +/** CSRF token echoed back by Mercado Pago. 32 chars of entropy. */ +export function newState(): string { + return nanoid(32); +} + +/** + * PKCE verifier. Mercado Pago requires 43 to 128 characters, so 32 random bytes + * in base64url (43 chars) is the smallest value that fits. + */ +export function newCodeVerifier(): string { + return randomBytes(32).toString('base64url'); +} + +/** PKCE S256 challenge: base64url(SHA256(verifier)) — RFC 7636 section 4.2. */ +export function codeChallengeFromVerifier(codeVerifier: string): string { + return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url'); +} diff --git a/apps/backend/src/modules/mp/lib/index.ts b/apps/backend/src/modules/mp/lib/index.ts new file mode 100644 index 0000000..76d252d --- /dev/null +++ b/apps/backend/src/modules/mp/lib/index.ts @@ -0,0 +1,29 @@ +export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config'; +export { + codeChallengeFromVerifier, + newCodeVerifier, + newState, + openToken, + sealToken, +} from './crypto'; +export { + createCheckoutPreference, + MP_API_URL, + type MpCreatePreferenceInput, + type MpPreference, + type MpSearchedPayment, + searchMpPaymentByExternalReference, +} from './mp-http'; +export { + buildAuthorizationUrl, + exchangeAuthorizationCode, + isGrantRejected, + MP_AUTHORIZE_URL, + MP_SCOPES, + MP_TOKEN_URL, + MpApiError, + type MpAuthorizationUrlInput, + type MpTokenResponse, + refreshMpTokens, +} from './mp-oauth'; +export { buildMpReturnUrl, type MpCallbackOutcome } from './return-url'; diff --git a/apps/backend/src/modules/mp/lib/mp-http.ts b/apps/backend/src/modules/mp/lib/mp-http.ts new file mode 100644 index 0000000..680c6ec --- /dev/null +++ b/apps/backend/src/modules/mp/lib/mp-http.ts @@ -0,0 +1,138 @@ +import { logger } from '@/logger'; +import { MpApiError } from './mp-oauth'; + +export const MP_API_URL = 'https://api.mercadopago.com'; + +// Mercado Pago runs the seller's money straight into the professor's own +// account: no platform_id of ours and no fee split. + +export type MpCreatePreferenceInput = { + title: string; + unitPrice: number; + currencyId: string; + externalReference: string; + /** Where the buyer lands after paying (pending/success/failure). */ + backUrl: string; +}; + +export type MpPreference = { + id: string; + initPoint: string; + sandboxInitPoint: string | null; +}; + +/** + * Creates a Checkout Pro preference in the seller's account. This is a payment + * *link*: nothing is charged, and creating it again after a lost connection is + * safe (same external_reference would be a new link for the same payment). + */ +export async function createCheckoutPreference( + accessToken: string, + input: MpCreatePreferenceInput, +): Promise { + let response: Response; + + try { + response = await fetch(`${MP_API_URL}/checkout/preferences`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + Authorization: `Bearer ${accessToken}`, + }, + body: JSON.stringify({ + items: [ + { + title: input.title, + currency_id: input.currencyId, + quantity: 1, + unit_price: input.unitPrice, + }, + ], + external_reference: input.externalReference, + auto_return: 'approved', + back_urls: { + success: input.backUrl, + pending: input.backUrl, + failure: input.backUrl, + }, + }), + }); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago preferences endpoint unreachable'); + throw new MpApiError(0, null); + } + + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as Record | null; + const reason = typeof payload?.error === 'string' ? payload.error : null; + logger.error( + { status: response.status, reason }, + 'Mercado Pago preferences request failed', + ); + throw new MpApiError(response.status, reason); + } + + const payload = (await response.json()) as Record; + return { + id: String(payload.id), + initPoint: String(payload.init_point), + sandboxInitPoint: payload.sandbox_init_point == null ? null : String(payload.sandbox_init_point), + }; +} + +export type MpSearchedPayment = { + id: string; + status: string; + externalReference: string; + liveMode: boolean; + dateApproved: string | null; +}; + +/** + * Finds a payment created for one of our payment rows. + * + * This is the reconciliation path: instead of trusting a webhook, the job asks + * the seller's account for payments whose `external_reference` is our payment + * id. Only an approved payment whose reference matches ours is a PAID row. + */ +export async function searchMpPaymentByExternalReference( + accessToken: string, + externalReference: string, +): Promise { + const url = new URL(`${MP_API_URL}/v1/payments/search`); + url.searchParams.set('external_reference', externalReference); + + let response: Response; + try { + response = await fetch(url, { + headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}` }, + }); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago payments search unreachable'); + throw new MpApiError(0, null); + } + + if (!response.ok) { + logger.error({ status: response.status }, 'Mercado Pago payments search failed'); + throw new MpApiError(response.status, null); + } + + const payload = (await response.json()) as { results?: Record[] } | null; + const results = payload?.results ?? []; + const match = results.find( + (payment) => payment.external_reference === externalReference, + ); + if (!match) { + return null; + } + + return { + id: String(match.id), + status: String(match.status), + externalReference: String(match.external_reference), + liveMode: Boolean(match.live_mode), + dateApproved: + typeof match.date_approved === 'string' ? match.date_approved : null, + }; +} \ No newline at end of file diff --git a/apps/backend/src/modules/mp/lib/mp-oauth.ts b/apps/backend/src/modules/mp/lib/mp-oauth.ts new file mode 100644 index 0000000..8ebb495 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/mp-oauth.ts @@ -0,0 +1,170 @@ +import { logger } from '@/logger'; + +export const MP_AUTHORIZE_URL = 'https://auth.mercadopago.com/authorization'; +export const MP_TOKEN_URL = 'https://api.mercadopago.com/oauth/token'; + +/** + * `offline_access` is what makes Mercado Pago return a refresh token. Without + * it the daily renewal job has nothing to work with. + */ +export const MP_SCOPES = 'offline_access read write'; + +export type MpTokenResponse = { + accessToken: string; + refreshToken: string; + expiresInSeconds: number; + scope: string | null; + mpUserId: string; + liveMode: boolean; +}; + +export type MpAuthorizationUrlInput = { + clientId: string; + redirectUri: string; + state: string; + codeChallenge: string; +}; + +/** + * A failure from Mercado Pago's token endpoint. + * + * `reason` is the safe subset of what MP returned. `error_description` is + * deliberately dropped: it echoes back request content, and the request is the + * authorization code. + */ +export class MpApiError extends Error { + constructor( + readonly status: number, + readonly reason: string | null, + ) { + super(`Mercado Pago token request failed with status ${status}`); + this.name = 'MpApiError'; + } +} + +/** Permanent rejection of the grant: the refresh token is dead. */ +export function isGrantRejected(error: unknown): boolean { + return error instanceof MpApiError && error.reason === 'invalid_grant'; +} + +export function buildAuthorizationUrl({ + clientId, + redirectUri, + state, + codeChallenge, +}: MpAuthorizationUrlInput): string { + const url = new URL(MP_AUTHORIZE_URL); + url.searchParams.set('client_id', clientId); + url.searchParams.set('response_type', 'code'); + // Declares this as a direct (non-marketplace) integration: the money lands in + // the seller's own account, so no platform_id of ours and no fee split. + url.searchParams.set('platform_id', 'mp'); + url.searchParams.set('redirect_uri', redirectUri); + url.searchParams.set('state', state); + url.searchParams.set('code_challenge', codeChallenge); + url.searchParams.set('code_challenge_method', 'S256'); + url.searchParams.set('scope', MP_SCOPES); + return url.toString(); +} + +type TokenRequestInput = { + clientId: string; + clientSecret: string; + redirectUri: string; +}; + +export function exchangeAuthorizationCode( + input: TokenRequestInput & { code: string; codeVerifier: string }, +): Promise { + return requestToken({ + grant_type: 'authorization_code', + client_id: input.clientId, + client_secret: input.clientSecret, + code: input.code, + redirect_uri: input.redirectUri, + code_verifier: input.codeVerifier, + }); +} + +export function refreshMpTokens( + input: TokenRequestInput & { refreshToken: string }, +): Promise { + return requestToken({ + grant_type: 'refresh_token', + client_id: input.clientId, + client_secret: input.clientSecret, + refresh_token: input.refreshToken, + }); +} + +async function requestToken(body: Record): Promise { + let response: Response; + + try { + response = await fetch(MP_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(body), + }); + } catch (error) { + // Network level: no grant decision has been made, so callers must treat the + // account as still fine. + logger.error({ err: error }, 'Mercado Pago token endpoint unreachable'); + throw new MpApiError(0, null); + } + + const payload = (await response.json().catch(() => null)) as Record | null; + + if (!response.ok) { + const reason = typeof payload?.error === 'string' ? payload.error : null; + // Only the status and MP's own error code. The body may echo the `code` or + // the `code_verifier` back, and neither may reach the logs. + logger.error({ status: response.status, reason }, 'Mercado Pago rejected the token request'); + throw new MpApiError(response.status, reason); + } + + return parseTokenResponse(payload); +} + +function parseTokenResponse(payload: Record | null): MpTokenResponse { + const accessToken = pickString(payload, 'access_token'); + const refreshToken = pickString(payload, 'refresh_token'); + const mpUserId = pickString(payload, 'user_id'); + const expiresInSeconds = pickNumber(payload, 'expires_in'); + + if (!accessToken || !refreshToken || !mpUserId || expiresInSeconds === null) { + logger.error( + { received: payload ? Object.keys(payload) : null }, + 'Mercado Pago token response is missing required fields', + ); + throw new MpApiError(200, 'malformed_token_response'); + } + + return { + accessToken, + refreshToken, + expiresInSeconds, + // The response omits `scope` when it matches what was requested. + scope: pickString(payload, 'scope') ?? null, + mpUserId, + liveMode: payload?.live_mode === true, + }; +} + +function pickString(payload: Record | null, key: string): string | null { + const value = payload?.[key]; + if (typeof value === 'string' && value.length > 0) return value; + // Mercado Pago sends `user_id` as a number. + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return null; +} + +function pickNumber(payload: Record | null, key: string): number | null { + const value = payload?.[key]; + if (typeof value === 'number' && Number.isFinite(value)) return value; + if (typeof value === 'string') { + const parsed = Number(value); + if (Number.isFinite(parsed)) return parsed; + } + return null; +} diff --git a/apps/backend/src/modules/mp/lib/return-url.ts b/apps/backend/src/modules/mp/lib/return-url.ts new file mode 100644 index 0000000..c1eec79 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/return-url.ts @@ -0,0 +1,25 @@ +import type { MpCallbackReason, MpReturnTo } from '@gruperly/shared'; + +export type MpCallbackOutcome = + | { kind: 'success' } + | { kind: 'error'; reason: MpCallbackReason }; + +/** + * Where the OAuth callback sends the teacher back to. + * + * Only `mp` and a reason code ever go in the URL: the authorization code and the + * PKCE verifier stay on the server. `returnTo` comes from a stored enum, never + * from the request, so this cannot be turned into an open redirect. + */ +export function buildMpReturnUrl( + webUrl: string, + returnTo: MpReturnTo, + outcome: MpCallbackOutcome, +): string { + const url = new URL(`/${returnTo}`, webUrl); + url.searchParams.set('mp', outcome.kind); + if (outcome.kind === 'error') { + url.searchParams.set('reason', outcome.reason); + } + return url.toString(); +} diff --git a/apps/backend/src/modules/mp/routes.ts b/apps/backend/src/modules/mp/routes.ts new file mode 100644 index 0000000..6ef40a8 --- /dev/null +++ b/apps/backend/src/modules/mp/routes.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import callbackRoute from './features/callback/route'; +import connectRoute from './features/connect/route'; +import disconnectRoute from './features/disconnect/route'; +import statusRoute from './features/status/route'; + +const routes = new Hono(); + +// `disconnectRoute` only declares `DELETE /`, so mounting it at the same path as +// `connectRoute` gives the unlink endpoint its RESTful `DELETE /mp/connect`. +routes.route('/connect', connectRoute); +routes.route('/connect', disconnectRoute); +routes.route('/callback', callbackRoute); +routes.route('/status', statusRoute); + +export default routes; diff --git a/apps/backend/src/modules/onboarding/features/first-group/route.ts b/apps/backend/src/modules/onboarding/features/first-group/route.ts new file mode 100644 index 0000000..662a3ae --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/first-group/route.ts @@ -0,0 +1,20 @@ +import type { CreateFirstGroup } from '@gruperly/shared'; +import { CreateFirstGroupSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { CreateFirstGroup as CreateFirstGroupUseCase } from './use-case'; + +const route = new Hono(); + +route.post('/', validate.json(CreateFirstGroupSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const data = c.req.valid('json') as CreateFirstGroup; + const useCase = new CreateFirstGroupUseCase(); + const result = await useCase.execute(data, user.id); + return resultJson(c, result, { status: 201 }); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts new file mode 100644 index 0000000..1714e08 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts @@ -0,0 +1,91 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import { Role } from '@generated/prisma/client'; +import type { + CreateFirstGroup as CreateFirstGroupInput, + CreateFirstGroupResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { onboardingAlreadyCompletedProblem, planNotSelectedProblem } from '@/http/problem-builders'; +import { problemDetails } from '@/http/problem-details'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { toOnboardingGroupDto } from '../../lib'; + +type CreateFirstGroupDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + planGuard?: Pick; +}; + +export class CreateFirstGroup { + constructor(private readonly deps: CreateFirstGroupDeps = {}) {} + + async execute( + data: CreateFirstGroupInput, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) { + return err(problemDetails({ title: 'Not Found', status: 404, code: 'user_not_found', detail: 'Usuario no encontrado.' })); + } + if (user.onboardingCompleted) { + return err(onboardingAlreadyCompletedProblem()); + } + // The "Plan" step is mandatory; this is its server-side half. + if (!user.planSelectedAt) { + return err(planNotSelectedProblem()); + } + + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); + if (!allowed.ok) { + return allowed; + } + + const transaction = unitOfWork.executeResult( + async (tx: Prisma.TransactionClient) => { + const created = await tx.group.create({ + data: { + name: data.name, + createdById: userId, + days: data.days, + time: data.time, + capacity: data.capacity, + price: data.price, + billingType: data.billingType, + dueDay: data.dueDay, + }, + }); + + await tx.groupMember.create({ + data: { + groupId: created.id, + userId, + role: Role.OWNER, + }, + }); + + await tx.user.update({ + where: { id: userId }, + data: { onboardingCompleted: true, country: data.country }, + }); + + return ok(created); + }, + ); + + const result = await transaction; + if (!result.ok) { + return result; + } + + return ok({ + group: toOnboardingGroupDto(result.value), + onboardingCompleted: true, + }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/features/select-plan/route.ts b/apps/backend/src/modules/onboarding/features/select-plan/route.ts new file mode 100644 index 0000000..ebf2288 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/select-plan/route.ts @@ -0,0 +1,19 @@ +import type { SelectPlanInput } from '@gruperly/shared'; +import { SelectPlanInputSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { SelectPlan } from './use-case'; + +const route = new Hono(); + +route.post('/', validate.json(SelectPlanInputSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const input = c.req.valid('json') as SelectPlanInput; + const result = await new SelectPlan().execute(user.id, input); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts b/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts new file mode 100644 index 0000000..b6dac10 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts @@ -0,0 +1,78 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, SelectPlanInput, SelectPlanResultDto } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + notFoundResourceProblem, + onboardingAlreadyCompletedProblem, + subscriptionAlreadyActiveProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; +import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; + +type SelectPlanDeps = { + db?: Pick; + subscribe?: Pick; + cancel?: Pick; + now?: () => Date; +}; + +/** + * The mandatory "Plan" step of the onboarding. + * + * It stores the country first: until now it was only saved with the first + * group, and Pro needs it to pick the price and Gruperly's Mercado Pago account. + * Free is immediate; Pro starts the subscription and returns where the browser + * goes to authorize it, coming back to `/onboarding?sub=return`. + */ +export class SelectPlan { + constructor(private readonly deps: SelectPlanDeps = {}) {} + + async execute( + userId: string, + input: SelectPlanInput, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now?.() ?? new Date(); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) return err(notFoundResourceProblem('User', userId)); + if (user.onboardingCompleted) return err(onboardingAlreadyCompletedProblem()); + + await db.user.update({ where: { id: userId }, data: { country: input.country } }); + const subscription = await db.billingSubscription.findUnique({ where: { userId } }); + + if (input.plan === 'FREE') { + // A paid subscription is never dropped from here; that is "Cancelar" in /billing. + if (subscription?.status === 'AUTHORIZED') return err(subscriptionAlreadyActiveProblem()); + + // Going back to Free after abandoning Mercado Pago: the attempt is void. + if (subscription && subscription.status !== 'CANCELLED') { + const cancelled = await (this.deps.cancel ?? new CancelSubscription()).execute(userId); + if (!cancelled.ok) { + await db.billingSubscription.update({ + where: { id: subscription.id }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + } + } + + await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); + return ok({ plan: 'FREE', checkoutUrl: null }); + } + + if (subscription?.status === 'AUTHORIZED') { + await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); + return ok({ plan: 'PRO', checkoutUrl: null }); + } + + const started = await (this.deps.subscribe ?? new Subscribe()).execute(userId, { + payerEmail: input.payerEmail, + returnTo: 'onboarding', + }); + if (!started.ok) return started; + + await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); + return ok({ plan: 'PRO', checkoutUrl: started.value.checkoutUrl }); + } +} diff --git a/apps/backend/src/modules/onboarding/features/status/route.ts b/apps/backend/src/modules/onboarding/features/status/route.ts new file mode 100644 index 0000000..0d66649 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/status/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetOnboardingStatus } from './use-case'; + +const route = new Hono(); + +route.get('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new GetOnboardingStatus(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/features/status/use-case.ts b/apps/backend/src/modules/onboarding/features/status/use-case.ts new file mode 100644 index 0000000..68bfc77 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/status/use-case.ts @@ -0,0 +1,74 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { OnboardingStatusDto, Plan, ProblemDetails, Result } from '@gruperly/shared'; +import { countryCodeSchema, err, ok } from '@gruperly/shared'; +import { problemDetails } from '@/http/problem-details'; +import prisma from '@/lib/prisma'; +import { isWhatsappAccountUsable } from '@/modules/whatsapp/lib/account'; + +type GetOnboardingStatusDeps = { + db?: Pick; +}; + +export class GetOnboardingStatus { + constructor(private readonly deps: GetOnboardingStatusDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) { + return err( + problemDetails({ + title: 'Not Found', + status: 404, + code: 'user_not_found', + detail: 'Usuario no encontrado.', + }), + ); + } + + const whatsappAccount = await db.whatsappAccount.findUnique({ where: { ownerId: userId } }); + const whatsappConnected = isWhatsappAccountUsable(whatsappAccount); + + // The "Plan" step: PRO as soon as the professor chose it (a subscription + // that is not cancelled, even if Mercado Pago has not authorized it yet). + const subscription = await db.billingSubscription.findUnique({ where: { userId } }); + const planSelected = user.planSelectedAt != null; + const selectedPlan: Plan | null = planSelected + ? subscription && subscription.status !== 'CANCELLED' ? 'PRO' : 'FREE' + : null; + const country = countryCodeSchema.safeParse(user.country); + const plan = { + planSelected, + selectedPlan, + subscriptionStatus: subscription?.status ?? null, + country: country.success ? country.data : null, + }; + + if (user.onboardingCompleted) { + return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true, ...plan }); + } + + // Linking Mercado Pago is optional, so `paymentConnected` here only resumes + // the flow where the teacher left off: with a usable account, they do not + // need to see the "Cobros" step again. A `revoked` row is not usable. + const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } }); + if (mpAccount && mpAccount.status === 'ACTIVE') { + return ok({ + step: 'PAYMENT_CONNECTED', + paymentConnected: true, + whatsappConnected, + completed: false, + ...plan, + }); + } + + return ok({ + step: 'NOT_STARTED', + paymentConnected: false, + whatsappConnected, + completed: false, + ...plan, + }); + } +} diff --git a/apps/backend/src/modules/onboarding/index.ts b/apps/backend/src/modules/onboarding/index.ts new file mode 100644 index 0000000..6c628e3 --- /dev/null +++ b/apps/backend/src/modules/onboarding/index.ts @@ -0,0 +1 @@ +export { default as onboardingRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/lib/helpers.ts b/apps/backend/src/modules/onboarding/lib/helpers.ts new file mode 100644 index 0000000..72a2ffb --- /dev/null +++ b/apps/backend/src/modules/onboarding/lib/helpers.ts @@ -0,0 +1,39 @@ +import type { BillingType, OnboardingGroupDto, WeekDay } from '@gruperly/shared'; + +type PriceLike = { toString(): string }; + +export type OnboardingGroupRecord = { + id: string; + name: string; + description: string | null; + createdById: string; + createdAt: Date; + updatedAt: Date; + days: WeekDay[] | null; + time: string | null; + capacity: number | null; + price: PriceLike | number | null; + billingType: BillingType | null; + dueDay: number | null; + autoPaymentReminders?: boolean; + autoReengagement?: boolean; +}; + +export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto { + return { + id: record.id, + name: record.name, + description: record.description, + createdById: record.createdById, + createdAt: record.createdAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + days: record.days, + time: record.time, + capacity: record.capacity, + price: record.price == null ? null : Number(record.price.toString()), + billingType: record.billingType, + dueDay: record.dueDay, + autoPaymentReminders: record.autoPaymentReminders ?? false, + autoReengagement: record.autoReengagement ?? false, + }; +} \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/lib/index.ts b/apps/backend/src/modules/onboarding/lib/index.ts new file mode 100644 index 0000000..c7c7ce0 --- /dev/null +++ b/apps/backend/src/modules/onboarding/lib/index.ts @@ -0,0 +1 @@ +export { type OnboardingGroupRecord, toOnboardingGroupDto } from './helpers'; \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/routes.ts b/apps/backend/src/modules/onboarding/routes.ts new file mode 100644 index 0000000..5b79eca --- /dev/null +++ b/apps/backend/src/modules/onboarding/routes.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import firstGroupRoute from './features/first-group/route'; +import selectPlanRoute from './features/select-plan/route'; +import statusRoute from './features/status/route'; + +const routes = new Hono(); + +routes.route('/status', statusRoute); +routes.route('/first-group', firstGroupRoute); +routes.route('/plan', selectPlanRoute); + +export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/create-batch/route.ts b/apps/backend/src/modules/payments/features/create-batch/route.ts new file mode 100644 index 0000000..dba42a8 --- /dev/null +++ b/apps/backend/src/modules/payments/features/create-batch/route.ts @@ -0,0 +1,27 @@ +import type { CreatePaymentsBatch } from '@gruperly/shared'; +import { CreatePaymentsBatchSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { CreatePaymentBatch } from './use-case'; + +const route = new Hono(); + +route.post( + '/:groupId/payments/batch', + validate.json(CreatePaymentsBatchSchema), + async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const groupId = c.req.param('groupId'); + const body = c.req.valid('json') as CreatePaymentsBatch; + const result = await new CreatePaymentBatch().execute(groupId, user.id, body); + + return resultJson(c, result, { status: 201 }); + }, +); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/create-batch/use-case.ts b/apps/backend/src/modules/payments/features/create-batch/use-case.ts new file mode 100644 index 0000000..9a57861 --- /dev/null +++ b/apps/backend/src/modules/payments/features/create-batch/use-case.ts @@ -0,0 +1,171 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + CountryCode, + CreatePaymentsBatch, + CreatePaymentsBatchResult, + PaymentBatchItem, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { currencyForCountry, err, ok } from '@gruperly/shared'; +import { + groupWithoutPriceProblem, + noAttendeesToBillProblem, + noGroupAccessProblem, + notFoundResourceProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { getMpAccessToken } from '@/modules/mp'; +import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib'; +import { CHECKOUT_BACK_PATH } from '../../lib'; + +type BatchDeps = { + db?: Pick; + createPreference?: typeof createCheckoutPreference; + getToken?: typeof getMpAccessToken; + webOrigin?: string; + planGuard?: Pick; +}; + +/** + * Creates one Checkout Pro payment link per active attendee of a group. + * + * The rows are created first (they are the single source of truth); a preference + * that fails leaves its row PENDING without a link, and the professor retries + * that one with `POST /payments/:id/renew` from the Cobros screen. A duplicate + * batch call for the same period is up to the professor: each run creates new + * links and creating a link never charges anyone. + */ +export class CreatePaymentBatch { + constructor(private readonly deps: BatchDeps = {}) {} + + async execute( + groupId: string, + userId: string, + input: CreatePaymentsBatch, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { members: { where: { userId } } }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( + group.createdById, + 'mpCharges', + ); + if (!allowed.ok) { + return allowed; + } + + if (group.price == null) { + return err(groupWithoutPriceProblem()); + } + + const attendees = await db.attendee.findMany({ + where: { + groupId, + status: 'ACTIVE', + ...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}), + }, + include: { person: { select: { fullName: true } } }, + }); + if (attendees.length === 0) { + return err(noAttendeesToBillProblem()); + } + + const owner = await db.user.findUnique({ where: { id: group.createdById } }); + const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null); + const unitPrice = Number(group.price.toString()); + + const getToken = this.deps.getToken ?? getMpAccessToken; + const token = await getToken(group.createdById); + if (!token.ok) { + return token; + } + + const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`; + const dueDate = new Date(input.dueDate); + const title = input.description?.trim() || group.name; + const createPreference = this.deps.createPreference ?? createCheckoutPreference; + + const items: PaymentBatchItem[] = []; + let failed = 0; + + for (const attendee of attendees) { + const payment = await db.payment.create({ + data: { + groupId, + attendeeId: attendee.id, + amount: group.price, + currency, + dueDate, + description: input.description?.trim() || null, + status: 'PENDING', + }, + }); + + let link: { initPoint: string; id: string } | null = null; + let reason: string | null = null; + + try { + const preference = await createPreference(token.value.accessToken, { + title, + unitPrice, + currencyId: currency, + externalReference: payment.id, + backUrl, + }); + link = preference; + } catch (error) { + failed += 1; + if (error instanceof MpApiError) { + reason = 'mp_provider_error'; + } else { + // Never swallow a real bug: log it, but keep the rest of the batch going. + reason = 'unknown_error'; + logger.error({ err: error }, 'Unexpected Mercado Pago preference failure'); + } + } + + if (link) { + await db.payment.update({ + where: { id: payment.id }, + data: { checkoutUrl: link.initPoint, mpPreferenceId: link.id }, + }); + } + + items.push({ + paymentId: payment.id, + attendeeId: attendee.id, + attendeeName: attendee.person.fullName, + amount: unitPrice, + currency, + checkoutUrl: link?.initPoint ?? null, + outcome: link ? 'LINKED' : 'FAILED', + reason, + }); + } + + return ok({ + groupId, + total: attendees.length, + linked: attendees.length - failed, + failed, + items, + }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/get-all/route.ts b/apps/backend/src/modules/payments/features/get-all/route.ts index 731c7d9..63abfb2 100644 --- a/apps/backend/src/modules/payments/features/get-all/route.ts +++ b/apps/backend/src/modules/payments/features/get-all/route.ts @@ -1,16 +1,20 @@ import type { PaymentQuery } from '@gruperly/shared'; import { PaymentQuerySchema } from '@gruperly/shared'; import { Hono } from 'hono'; -import { resultJson } from '@/http/problem-details'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; import { validate } from '@/http/validate'; import { ListPayments } from './use-case'; const route = new Hono(); route.get('/', validate.query(PaymentQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const query = c.req.valid('query') as PaymentQuery; - const useCase = new ListPayments(); - const result = await useCase.execute(query); + const result = await new ListPayments().execute(query, user.id); return resultJson(c, result); }); diff --git a/apps/backend/src/modules/payments/features/get-all/use-case.ts b/apps/backend/src/modules/payments/features/get-all/use-case.ts index d0bc158..8552e41 100644 --- a/apps/backend/src/modules/payments/features/get-all/use-case.ts +++ b/apps/backend/src/modules/payments/features/get-all/use-case.ts @@ -1,57 +1,52 @@ import type { PrismaClient } from '@generated/prisma/client'; -import type { PaymentDto, PaymentList, PaymentQuery, ProblemDetails, Result } from '@gruperly/shared'; +import type { PaymentList, PaymentQuery, ProblemDetails, Result } from '@gruperly/shared'; import { ok } from '@gruperly/shared'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { type PaymentRecord, toPaymentDto } from '../../lib'; type ListPaymentsDeps = { - db?: Pick; + db?: Pick; }; -type PaymentRecord = { - id: string; - groupId: string; - studentId: string; - amount: { toString(): string }; - currency: string; - status: PaymentDto['status']; - dueDate: Date; - paidAt: Date | null; - createdAt: Date; - updatedAt: Date; -}; - -function toPaymentDto(record: PaymentRecord): PaymentDto { - return { - id: record.id, - groupId: record.groupId, - studentId: record.studentId, - amount: Number(record.amount.toString()), - currency: record.currency, - status: record.status, - dueDate: record.dueDate.toISOString(), - paidAt: record.paidAt ? record.paidAt.toISOString() : null, - createdAt: record.createdAt.toISOString(), - updatedAt: record.updatedAt.toISOString(), - }; -} - export class ListPayments { constructor(private readonly deps: ListPaymentsDeps = {}) {} - async execute(query: PaymentQuery): Promise> { + async execute( + query: PaymentQuery, + userId: string, + ): Promise> { const db = this.deps.db ?? prisma; + + // Only the professor's own groups (owner or member) are visible. + const accessibleGroups = await db.group.findMany({ + where: buildGroupWhereForUser(userId), + select: { id: true }, + }); + const groupIds = accessibleGroups.map((group) => group.id); + const where = { + groupId: { in: groupIds }, + ...(query.groupId ? { groupId: query.groupId } : {}), + ...(query.status ? { status: query.status } : {}), + }; + const [records, total] = await Promise.all([ db.payment.findMany({ + where, + include: { + group: { select: { name: true, price: true } }, + attendee: { select: { person: { select: { fullName: true } } } }, + }, skip: getPaginationOffset(query), take: query.pageSize, orderBy: { createdAt: 'desc' }, }), - db.payment.count(), + db.payment.count({ where }), ]); return ok({ - data: records.map(toPaymentDto), + data: records.map((record) => toPaymentDto(record as unknown as PaymentRecord)), pagination: getPaginationMetadata(query, total), }); } diff --git a/apps/backend/src/modules/payments/features/renew/route.ts b/apps/backend/src/modules/payments/features/renew/route.ts new file mode 100644 index 0000000..0a359d7 --- /dev/null +++ b/apps/backend/src/modules/payments/features/renew/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { RenewPaymentLink } from './use-case'; + +const route = new Hono(); + +route.post('/:id/renew', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const paymentId = c.req.param('id'); + const result = await new RenewPaymentLink().execute(paymentId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/renew/use-case.ts b/apps/backend/src/modules/payments/features/renew/use-case.ts new file mode 100644 index 0000000..1766487 --- /dev/null +++ b/apps/backend/src/modules/payments/features/renew/use-case.ts @@ -0,0 +1,116 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CountryCode, PaymentDto, ProblemDetails, Result } from '@gruperly/shared'; +import { currencyForCountry, err, ok } from '@gruperly/shared'; +import { + groupWithoutPriceProblem, + mpProviderErrorProblem, + noGroupAccessProblem, + notFoundResourceProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import { getMpAccessToken } from '@/modules/mp'; +import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib'; +import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib'; + +type RenewDeps = { + db?: Pick; + createPreference?: typeof createCheckoutPreference; + getToken?: typeof getMpAccessToken; + webOrigin?: string; + planGuard?: Pick; +}; + +/** + * Re-creates the Checkout Pro link of a payment that lost it (a failed batch + * item). Idempotent: a payment that already has a link keeps it. + */ +export class RenewPaymentLink { + constructor(private readonly deps: RenewDeps = {}) {} + + async execute(paymentId: string, userId: string): Promise> { + const db = this.deps.db ?? prisma; + + const payment = await db.payment.findUnique({ + where: { id: paymentId }, + include: { + attendee: { select: { person: { select: { fullName: true } } } }, + group: { + select: { + name: true, + price: true, + createdById: true, + members: { where: { userId } }, + }, + }, + }, + }); + + if (!payment) { + return err(notFoundResourceProblem('Payment', paymentId)); + } + + const isOwner = payment.group.createdById === userId; + const isMember = payment.group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + if (payment.checkoutUrl) { + return ok(toPaymentDto(payment as unknown as PaymentRecord)); + } + + const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( + payment.group.createdById, + 'mpCharges', + ); + if (!allowed.ok) { + return allowed; + } + + if (payment.group.price == null) { + return err(groupWithoutPriceProblem()); + } + + const owner = await db.user.findUnique({ where: { id: payment.group.createdById } }); + const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null); + const unitPrice = Number(payment.amount.toString()); + + const getToken = this.deps.getToken ?? getMpAccessToken; + const token = await getToken(payment.group.createdById); + if (!token.ok) { + return token; + } + + const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`; + const createPreference = this.deps.createPreference ?? createCheckoutPreference; + + let preference: { initPoint: string; id: string }; + try { + preference = await createPreference(token.value.accessToken, { + title: payment.description ?? payment.group.name, + unitPrice, + currencyId: currency, + externalReference: payment.id, + backUrl, + }); + } catch (error) { + if (error instanceof Error) { + logger.error({ err: error }, 'Mercado Pago preference renew failed'); + } + return err(mpProviderErrorProblem()); + } + + const updated = await db.payment.update({ + where: { id: payment.id }, + data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id }, + include: { + attendee: { select: { person: { select: { fullName: true } } } }, + group: { select: { name: true, price: true } }, + }, + }); + + return ok(toPaymentDto(updated as unknown as PaymentRecord)); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/reported/route.ts b/apps/backend/src/modules/payments/features/reported/route.ts new file mode 100644 index 0000000..feb134d --- /dev/null +++ b/apps/backend/src/modules/payments/features/reported/route.ts @@ -0,0 +1,40 @@ +import { type RejectReportedPayment, RejectReportedPaymentSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ReportedPayments } from './use-case'; + +const route = new Hono(); + +route.get('/reported', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + return resultJson(c, await new ReportedPayments().list(user.id)); +}); + +route.get('/reported/:reportId/receipt', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + return resultJson(c, await new ReportedPayments().receiptUrl(user.id, c.req.param('reportId'))); +}); + +route.post('/reported/:reportId/confirm', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + return resultJson(c, await new ReportedPayments().confirm(user.id, c.req.param('reportId'))); +}); + +route.post('/reported/:reportId/reject', validate.json(RejectReportedPaymentSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + const { reason } = c.req.valid('json') as RejectReportedPayment; + return resultJson(c, await new ReportedPayments().reject(user.id, c.req.param('reportId'), reason ?? null)); +}); + +route.post('/reported/:reportId/undo', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + return resultJson(c, await new ReportedPayments().undo(user.id, c.req.param('reportId'))); +}); + +export default route; diff --git a/apps/backend/src/modules/payments/features/reported/use-case.ts b/apps/backend/src/modules/payments/features/reported/use-case.ts new file mode 100644 index 0000000..10da111 --- /dev/null +++ b/apps/backend/src/modules/payments/features/reported/use-case.ts @@ -0,0 +1,228 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, ReceiptUrlDto, ReportedPaymentDto, ReportedPaymentList, Result } from '@gruperly/shared'; +import { err, ok, REVIEW_UNDO_MINUTES } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { type FileStorage, getFileStorage } from '@/lib/storage'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems'; +import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments'; +import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications'; + +export const RECEIPT_URL_TTL_SECONDS = 5 * 60; +const PREVIEWABLE = new Set(['image/jpeg', 'image/png', 'image/webp']); + +type ReportedDeps = { + db?: Pick; + unitOfWork?: Pick; + storage?: FileStorage | null; + notify?: ReviewNotifier; + now?: Date; +}; + +const reportSelect = { + id: true, + status: true, + createdAt: true, + totalAmount: true, + currency: true, + note: true, + receiptKey: true, + receiptMime: true, + receiptName: true, + receiptSize: true, + attendee: { select: { id: true, person: { select: { fullName: true } } } }, + group: { select: { id: true, name: true } }, + items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } }, +} satisfies Prisma.ReportedPaymentSelect; + +type ReportRow = Prisma.ReportedPaymentGetPayload<{ select: typeof reportSelect }>; + +const STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const; + +function accessible(userId: string): Prisma.ReportedPaymentWhereInput { + return { group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput }; +} + +/* Cobros → "Pagos para verificar": reports waiting for the teacher, across + their groups, oldest first. */ +export class ReportedPayments { + constructor(private readonly deps: ReportedDeps = {}) {} + + private get db() { + return this.deps.db ?? prisma; + } + + private get storage(): FileStorage | null { + return this.deps.storage === undefined ? getFileStorage() : this.deps.storage; + } + + private get now(): Date { + return this.deps.now ?? new Date(); + } + + async list(userId: string): Promise> { + const rows = await this.db.reportedPayment.findMany({ + where: { ...accessible(userId), status: 'REPORTED' }, + orderBy: { createdAt: 'asc' }, + select: reportSelect, + }); + return ok({ data: rows.map((row) => this.toDto(row)) }); + } + + async receiptUrl(userId: string, reportId: string): Promise> { + const row = await this.db.reportedPayment.findFirst({ + where: { id: reportId, ...accessible(userId) }, + select: { receiptKey: true, receiptMime: true, receiptName: true }, + }); + if (!row?.receiptKey) return err(notFoundResourceProblem('Receipt', reportId)); + const storage = this.storage; + if (!storage) return err(storageNotAvailableProblem()); + return ok({ + url: storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS), + mime: row.receiptMime, + name: row.receiptName, + expiresAt: new Date(this.now.getTime() + RECEIPT_URL_TTL_SECONDS * 1000).toISOString(), + }); + } + + /* Confirm: the report and its fees become paid, in one transaction. A fee + already PAID (e.g. through Mercado Pago meanwhile) is left as it is. */ + async confirm(userId: string, reportId: string): Promise> { + return this.review(userId, reportId, 'CONFIRMED', null); + } + + /* Reject: the fees stay as they were, and they come back to the overdue alert. */ + async reject(userId: string, reportId: string, reason: string | null): Promise> { + return this.review(userId, reportId, 'REJECTED', reason); + } + + /* "Deshacer", for a few minutes after the review: back to REPORTED. A confirm + is reverted only on the fees it paid (paid_at equal to the review and no MP + payment), which go back to PENDING or OVERDUE by the overdue job's rule. */ + async undo(userId: string, reportId: string): Promise> { + const now = this.now; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + const undone = await unitOfWork.executeResult(async (tx) => { + const report = await tx.reportedPayment.findFirst({ + where: { + id: reportId, + ...accessible(userId), + status: { in: ['CONFIRMED', 'REJECTED'] }, + reviewedAt: { gt: new Date(now.getTime() - REVIEW_UNDO_MINUTES * 60 * 1000) }, + }, + select: { status: true, reviewedAt: true, items: { select: { paymentId: true } } }, + }); + if (!report?.reviewedAt) { + return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' })); + } + const claimed = await tx.reportedPayment.updateMany({ + where: { id: reportId, status: report.status, reviewedAt: report.reviewedAt }, + data: { status: 'REPORTED', reviewedAt: null, reviewedById: null, rejectionReason: null }, + }); + if (claimed.count !== 1) { + return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' })); + } + if (report.status === 'CONFIRMED') { + const paidByReview = { + id: { in: report.items.map((item) => item.paymentId) }, + status: 'PAID' as const, + paidAt: report.reviewedAt, + mpPaymentId: null, + }; + const overdueBefore = new Date(now.getTime() - OVERDUE_GRACE_MS); + await tx.payment.updateMany({ + where: { ...paidByReview, dueDate: { lt: overdueBefore } }, + data: { status: 'OVERDUE', paidAt: null }, + }); + await tx.payment.updateMany({ + where: { ...paidByReview, dueDate: { gte: overdueBefore } }, + data: { status: 'PENDING', paidAt: null }, + }); + } + return ok(null); + }); + if (!undone.ok) return undone; + return this.load(reportId); + } + + private async review( + userId: string, + reportId: string, + status: 'CONFIRMED' | 'REJECTED', + reason: string | null, + ): Promise> { + const now = this.now; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + + const reviewed = await unitOfWork.executeResult(async (tx) => { + const claimed = await tx.reportedPayment.updateMany({ + where: { id: reportId, ...accessible(userId), status: 'REPORTED' }, + data: { + status, + reviewedById: userId, + reviewedAt: now, + rejectionReason: status === 'REJECTED' ? reason || null : null, + }, + }); + if (claimed.count !== 1) { + const exists = await tx.reportedPayment.findFirst({ where: { id: reportId, ...accessible(userId) }, select: { id: true } }); + return err( + exists + ? conflictProblem({ detail: 'Este pago ya fue revisado.', code: 'payment_report_already_reviewed' }) + : notFoundResourceProblem('ReportedPayment', reportId), + ); + } + if (status === 'CONFIRMED') { + const items = await tx.reportedPaymentItem.findMany({ where: { reportedPaymentId: reportId }, select: { paymentId: true } }); + await tx.payment.updateMany({ + where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } }, + data: { status: 'PAID', paidAt: now }, + }); + } + return ok(null); + }); + if (!reviewed.ok) return reviewed; + + (this.deps.notify ?? scheduleReviewNotification)(reportId, now); + return this.load(reportId); + } + + private async load(reportId: string): Promise> { + const row = await this.db.reportedPayment.findUniqueOrThrow({ where: { id: reportId }, select: reportSelect }); + return ok(this.toDto(row)); + } + + private toDto(row: ReportRow): ReportedPaymentDto { + const storage = this.storage; + const thumbnailUrl = + row.receiptKey && storage && PREVIEWABLE.has(row.receiptMime) + ? storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS) + : null; + return { + id: row.id, + status: STATUS[row.status], + attendee: { id: row.attendee.id, fullName: row.attendee.person.fullName }, + group: row.group, + createdAt: row.createdAt.toISOString(), + totalAmount: row.totalAmount.toNumber(), + currency: row.currency, + note: row.note, + fees: row.items + .map(({ payment }) => ({ + id: payment.id, + description: payment.description, + dueDate: payment.dueDate.toISOString(), + amount: payment.amount.toNumber(), + })) + .sort((a, b) => a.dueDate.localeCompare(b.dueDate)), + receipt: { + mime: row.receiptMime, + name: row.receiptName, + size: row.receiptSize, + thumbnailUrl, + available: row.receiptKey !== null, + }, + }; + } +} diff --git a/apps/backend/src/modules/payments/features/transfer-details/route.ts b/apps/backend/src/modules/payments/features/transfer-details/route.ts new file mode 100644 index 0000000..64385b6 --- /dev/null +++ b/apps/backend/src/modules/payments/features/transfer-details/route.ts @@ -0,0 +1,32 @@ +import { type UpdateTransferDetails, UpdateTransferDetailsSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import prisma from '@/lib/prisma'; + +/* Bank transfer details (Ajustes) that students see when reporting a payment. */ +const route = new Hono(); + +route.get('/transfer-details', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + const row = await prisma.user.findUniqueOrThrow({ + where: { id: user.id }, + select: { transferAlias: true, transferHolder: true }, + }); + return c.json({ alias: row.transferAlias, holder: row.transferHolder }); +}); + +route.put('/transfer-details', validate.json(UpdateTransferDetailsSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + const { alias, holder } = c.req.valid('json') as UpdateTransferDetails; + const row = await prisma.user.update({ + where: { id: user.id }, + data: { transferAlias: alias || null, transferHolder: holder || null }, + select: { transferAlias: true, transferHolder: true }, + }); + return c.json({ alias: row.transferAlias, holder: row.transferHolder }); +}); + +export default route; diff --git a/apps/backend/src/modules/payments/index.ts b/apps/backend/src/modules/payments/index.ts index 1796d33..495ea68 100644 --- a/apps/backend/src/modules/payments/index.ts +++ b/apps/backend/src/modules/payments/index.ts @@ -1 +1,2 @@ +export { startPaymentJobs } from './jobs'; export { default as paymentsRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/jobs/index.ts b/apps/backend/src/modules/payments/jobs/index.ts new file mode 100644 index 0000000..5794244 --- /dev/null +++ b/apps/backend/src/modules/payments/jobs/index.ts @@ -0,0 +1,9 @@ +export { + MarkOverduePayments, + type MarkOverduePaymentsResult, +} from './mark-overdue-payments'; +export { + ReconcilePayments, + type ReconcilePaymentsResult, +} from './reconcile-payments'; +export { startPaymentJobs } from './schedule'; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/jobs/mark-overdue-payments.ts b/apps/backend/src/modules/payments/jobs/mark-overdue-payments.ts new file mode 100644 index 0000000..c2b33d7 --- /dev/null +++ b/apps/backend/src/modules/payments/jobs/mark-overdue-payments.ts @@ -0,0 +1,35 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; + +/** + * Marks overdue rows. A payment whose due date (plus a day of grace) passed and + * is still PENDING becomes OVERDUE; it stays billable, so the professor can + * renew its link from Cobros. + */ +export const OVERDUE_GRACE_MS = 24 * 60 * 60 * 1000; + +export type MarkOverduePaymentsResult = { + marked: number; +}; + +type MarkOverduePaymentsDeps = { + db?: PrismaClient; + now?: Date; +}; + +export class MarkOverduePayments { + constructor(private readonly deps: MarkOverduePaymentsDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const horizon = new Date(now.getTime() - OVERDUE_GRACE_MS); + + const updated = await db.payment.updateMany({ + where: { status: 'PENDING', dueDate: { lt: horizon } }, + data: { status: 'OVERDUE' }, + }); + + return { marked: updated.count }; + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/payments/jobs/reconcile-payments.ts b/apps/backend/src/modules/payments/jobs/reconcile-payments.ts new file mode 100644 index 0000000..bc2048c --- /dev/null +++ b/apps/backend/src/modules/payments/jobs/reconcile-payments.ts @@ -0,0 +1,87 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { getMpAccessToken } from '@/modules/mp'; +import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib'; + +/** + * Pulls payments from Mercado Pago instead of trusting a webhook. A payment + * link is just a preference until someone pays it; this job asks the seller's + * account for our `external_reference` and marks approved payments as PAID. + * + * This is the stopgap and the source of truth: if a webhook is ever added it + * gives you the confirmation, but this job is what keeps the Cobros screen + * correct even when a notification is lost. + */ +const RECONCILE_AFTER_MS = 5 * 60 * 1000; +const BATCH_LIMIT = 50; + +export type ReconcilePaymentsResult = { + paid: number; + skipped: number; + failed: number; +}; + +type ReconcilePaymentsDeps = { + db?: PrismaClient; + getToken?: typeof getMpAccessToken; + search?: typeof searchMpPaymentByExternalReference; + now?: Date; +}; + +export class ReconcilePayments { + constructor(private readonly deps: ReconcilePaymentsDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const getToken = this.deps.getToken ?? getMpAccessToken; + const search = this.deps.search ?? searchMpPaymentByExternalReference; + + const awaiting = await db.payment.findMany({ + where: { + status: 'PENDING', + checkoutUrl: { not: null }, + createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) }, + }, + include: { group: { select: { createdById: true } } }, + take: BATCH_LIMIT, + }); + + const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 }; + + for (const payment of awaiting) { + const token = await getToken(payment.group.createdById); + if (!token.ok) { + // No usable token (not linked, or needs re-auth). Not a payment problem: + // the row stays PENDING and the account notice tells the professor what to do. + totals.skipped += 1; + continue; + } + + try { + const found = await search(token.value.accessToken, payment.id); + if (found && found.status === 'approved' && found.externalReference === payment.id) { + await db.payment.update({ + where: { id: payment.id }, + data: { + status: 'PAID', + mpPaymentId: found.id, + paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(), + }, + }); + totals.paid += 1; + } + } catch (error) { + if (error instanceof MpApiError) { + totals.failed += 1; + } else { + logger.error({ err: error }, 'Unexpected payment reconciliation failure'); + totals.failed += 1; + } + } + } + + return totals; + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/payments/jobs/schedule.ts b/apps/backend/src/modules/payments/jobs/schedule.ts new file mode 100644 index 0000000..1c5c896 --- /dev/null +++ b/apps/backend/src/modules/payments/jobs/schedule.ts @@ -0,0 +1,40 @@ +import { logger } from '@/logger'; +import { MarkOverduePayments } from './mark-overdue-payments'; +import { ReconcilePayments } from './reconcile-payments'; + +const RECONCILE_CRON = '*/15 * * * *'; +const OVERDUE_CRON = '4 4 * * *'; + +/** + * Registers the payment background jobs. Called once from `server.ts`, following + * the same guards as `startMpJobs`: Bun's in-process cron treats a rejected + * promise as an unhandledRejection (which would crash the process), and `unref` + * keeps the jobs from holding the process alive on their own. + */ +export function startPaymentJobs(): void { + Bun.cron( + RECONCILE_CRON, + async () => { + try { + const totals = await new ReconcilePayments().execute(); + logger.info(totals, 'Mercado Pago payments reconciliation finished'); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago payments reconciliation failed'); + } + }, + { tz: 'UTC' }, + ).unref(); + + Bun.cron( + OVERDUE_CRON, + async () => { + try { + const totals = await new MarkOverduePayments().execute(); + logger.info(totals, 'Overdue payments marked'); + } catch (error) { + logger.error({ err: error }, 'Marking overdue payments failed'); + } + }, + { tz: 'UTC' }, + ).unref(); +} \ No newline at end of file diff --git a/apps/backend/src/modules/payments/lib/helpers.ts b/apps/backend/src/modules/payments/lib/helpers.ts new file mode 100644 index 0000000..3da80bd --- /dev/null +++ b/apps/backend/src/modules/payments/lib/helpers.ts @@ -0,0 +1,41 @@ +import type { PaymentDto } from '@gruperly/shared'; + +/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app + (without a student session it falls through to /access). */ +export const CHECKOUT_BACK_PATH = '/student/payments'; + +export type PaymentRecord = { + id: string; + groupId: string; + attendeeId: string; + amount: { toString(): string } | number; + currency: string; + status: PaymentDto['status']; + description: string | null; + checkoutUrl: string | null; + dueDate: Date; + paidAt: Date | null; + createdAt: Date; + updatedAt: Date; + group: { name: string; price: unknown }; + attendee: { person: { fullName: string } }; +}; + +export function toPaymentDto(record: PaymentRecord): PaymentDto { + return { + id: record.id, + groupId: record.groupId, + groupName: record.group.name, + attendeeId: record.attendeeId, + attendeeName: record.attendee.person.fullName, + amount: Number(record.amount.toString()), + currency: record.currency, + status: record.status, + description: record.description, + checkoutUrl: record.checkoutUrl, + dueDate: record.dueDate.toISOString(), + paidAt: record.paidAt ? record.paidAt.toISOString() : null, + createdAt: record.createdAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + }; +} \ No newline at end of file diff --git a/apps/backend/src/modules/payments/lib/index.ts b/apps/backend/src/modules/payments/lib/index.ts new file mode 100644 index 0000000..e75766d --- /dev/null +++ b/apps/backend/src/modules/payments/lib/index.ts @@ -0,0 +1 @@ +export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers'; diff --git a/apps/backend/src/modules/payments/lib/review-notifications.ts b/apps/backend/src/modules/payments/lib/review-notifications.ts new file mode 100644 index 0000000..081d28e --- /dev/null +++ b/apps/backend/src/modules/payments/lib/review-notifications.ts @@ -0,0 +1,56 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CountryCode } from '@gruperly/shared'; +import { type EmailProvider, emailProvider } from '@/lib/email'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { formatAmount } from '@/modules/whatsapp/lib/format'; + +// Long enough to cover the "Deshacer" on the card: an undone review emails nothing. +const NOTIFY_DELAY_MS = 60 * 1000; + +export type ReviewNotifier = (reportId: string, reviewedAt: Date) => void; + +/* Tells the student by email (only if they confirmed a recovery email) once + the review settles. The in-app banner is the main channel; this is a + courtesy, so an in-process timer lost on a restart is acceptable. */ +export const scheduleReviewNotification: ReviewNotifier = (reportId, reviewedAt) => { + const timer = setTimeout(() => { + void sendReviewNotification(reportId, reviewedAt).catch((error) => + logger.error({ error, reportId }, 'Payment review notification failed'), + ); + }, NOTIFY_DELAY_MS); + timer.unref?.(); +}; + +export async function sendReviewNotification( + reportId: string, + reviewedAt: Date, + deps: { db?: Pick; email?: Pick } = {}, +): Promise { + const db = deps.db ?? prisma; + const report = await db.reportedPayment.findUnique({ + where: { id: reportId }, + select: { + status: true, + reviewedAt: true, + rejectionReason: true, + totalAmount: true, + currency: true, + group: { select: { owner: { select: { country: true } } } }, + account: { select: { name: true, recoveryEmail: true, recoveryEmailVerifiedAt: true } }, + }, + }); + // Undone or reviewed again since: this notification is stale. + if (!report || report.status === 'REPORTED' || report.reviewedAt?.getTime() !== reviewedAt.getTime()) return false; + const account = report.account; + if (!account?.recoveryEmail || !account.recoveryEmailVerifiedAt) return false; + + await (deps.email ?? emailProvider).sendStudentPaymentReviewed({ + email: account.recoveryEmail, + name: account.name, + confirmed: report.status === 'CONFIRMED', + amount: formatAmount(report.totalAmount.toNumber(), report.currency, report.group.owner.country as CountryCode | null), + reason: report.rejectionReason, + }); + return true; +} diff --git a/apps/backend/src/modules/payments/routes.ts b/apps/backend/src/modules/payments/routes.ts index 7be42fc..8d5676c 100644 --- a/apps/backend/src/modules/payments/routes.ts +++ b/apps/backend/src/modules/payments/routes.ts @@ -1,8 +1,14 @@ import { Hono } from 'hono'; import getAllRoute from './features/get-all/route'; +import renewRoute from './features/renew/route'; +import reportedRoute from './features/reported/route'; +import transferDetailsRoute from './features/transfer-details/route'; const routes = new Hono(); routes.route('/', getAllRoute); +routes.route('/', reportedRoute); +routes.route('/', transferDetailsRoute); +routes.route('/', renewRoute); export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/people/features/lookup/route.ts b/apps/backend/src/modules/people/features/lookup/route.ts new file mode 100644 index 0000000..cc2e17a --- /dev/null +++ b/apps/backend/src/modules/people/features/lookup/route.ts @@ -0,0 +1,18 @@ +import type { PersonLookupQuery } from '@gruperly/shared'; +import { PersonLookupQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { LookupPerson } from './use-case'; + +const route = new Hono(); + +route.get('/lookup', validate.query(PersonLookupQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const result = await new LookupPerson().execute(c.req.valid('query') as PersonLookupQuery, user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/people/features/lookup/use-case.ts b/apps/backend/src/modules/people/features/lookup/use-case.ts new file mode 100644 index 0000000..3d381c8 --- /dev/null +++ b/apps/backend/src/modules/people/features/lookup/use-case.ts @@ -0,0 +1,24 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { PersonLookupQuery, PersonSummary, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; +import { findPersonSummaryByPhone } from '../../lib/people'; + +type LookupPersonDeps = { + db?: Pick; +}; + +/* While the teacher types a phone in the add form: is it someone they already + have? `null` when not. */ +export class LookupPerson { + constructor(private readonly deps: LookupPersonDeps = {}) {} + + async execute(query: PersonLookupQuery, userId: string): Promise> { + const db = this.deps.db ?? prisma; + const access = await findGroupForUser(db, query.groupId, userId); + if (!access.ok) return access; + + return ok(await findPersonSummaryByPhone(db, access.value.createdById, query.phone)); + } +} diff --git a/apps/backend/src/modules/people/index.ts b/apps/backend/src/modules/people/index.ts new file mode 100644 index 0000000..73592d8 --- /dev/null +++ b/apps/backend/src/modules/people/index.ts @@ -0,0 +1 @@ +export { default as peopleRoutes } from './routes'; diff --git a/apps/backend/src/modules/people/lib/people.ts b/apps/backend/src/modules/people/lib/people.ts new file mode 100644 index 0000000..1baa790 --- /dev/null +++ b/apps/backend/src/modules/people/lib/people.ts @@ -0,0 +1,142 @@ +import { Prisma, type PrismaClient } from '@generated/prisma/client'; +import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared'; +import { conflictProblem } from '@/http/problem-builders'; +import { normalizePhone } from '@/modules/attendees/lib/helpers'; + +/* A person is the teacher's contact (student, or a guardian's child); their + `attendees` are the memberships in each group. The phone is unique per + teacher (partial index `people_owner_phone_key`), so it is how a new row is + recognized as someone the teacher already has. */ + +export type PeopleDb = Pick; + +/* Phones are stored normalized, but older rows may keep what was typed. */ +export function phoneVariants(rawPhone: string): string[] { + const normalized = normalizePhone(rawPhone); + const trimmed = rawPhone.trim(); + return normalized === trimmed ? [normalized] : [normalized, trimmed]; +} + +export const personMembershipsSelect = { + attendees: { + orderBy: { createdAt: 'asc' }, + select: { id: true, groupId: true, status: true, group: { select: { name: true } } }, + }, +} as const; + +type MembershipRow = { + id: string; + groupId: string; + status: PersonMembership['status']; + group: { name: string }; +}; + +export function toMemberships(rows: MembershipRow[]): PersonMembership[] { + return rows.map((row) => ({ + attendeeId: row.id, + groupId: row.groupId, + groupName: row.group.name, + status: row.status, + })); +} + +export async function findPersonByPhone(db: PeopleDb, ownerId: string, rawPhone: string) { + return db.person.findFirst({ + where: { createdById: ownerId, phone: { in: phoneVariants(rawPhone) } }, + select: { + id: true, + fullName: true, + email: true, + phone: true, + ...personMembershipsSelect, + }, + }); +} + +export async function findPersonSummaryByPhone( + db: PeopleDb, + ownerId: string, + rawPhone: string, +): Promise { + const person = await findPersonByPhone(db, ownerId, rawPhone); + if (!person) return null; + return { + id: person.id, + fullName: person.fullName, + email: person.email, + phone: person.phone, + groups: toMemberships(person.attendees), + }; +} + +export type NewPersonData = { + fullName: string; + phone: string | null; + email?: string | null; + notes?: string | null; +}; + +/* Waitlist promotion, pre-registration approval and bulk import: the row has + its own contact data, and if that phone is already one of the teacher's + people the membership goes to that person (their data wins). */ +export async function findOrCreatePerson( + db: PeopleDb, + ownerId: string, + data: NewPersonData, +): Promise<{ id: string; created: boolean }> { + if (data.phone) { + const existing = await findPersonByPhone(db, ownerId, data.phone); + if (existing) return { id: existing.id, created: false }; + } + const person = await db.person.create({ + data: { + createdById: ownerId, + fullName: data.fullName, + phone: data.phone, + email: data.email ?? null, + notes: data.notes ?? null, + }, + select: { id: true }, + }); + return { id: person.id, created: true }; +} + +/* Whether adding someone with this phone takes a new student slot of the plan: + no when they are already an active member of another group. */ +export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone: string | null): Promise { + if (!rawPhone) return true; + const person = await findPersonByPhone(db, ownerId, rawPhone); + return !person?.attendees.some((membership) => membership.status === 'ACTIVE'); +} + +/* The number the teacher reaches the person on: theirs, or the guardian's. */ +export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null { + return person.phone ?? person.guardianPhone; +} + +export function isUniqueViolation(error: unknown): boolean { + return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002'; +} + +export function alreadyInGroupProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Esta persona ya es miembro de este grupo.', + code: 'attendee_already_registered', + }); +} + +/* The phone belongs to someone the teacher already has: the web offers to add + that person (`personId`) instead of creating a duplicate. */ +export function personExistsProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Ya tenés registrada a una persona con este número de teléfono.', + code: 'person_exists', + }); +} + +export function personPhoneTakenProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Otra persona que tenés registrada ya usa este número de teléfono.', + code: 'person_phone_taken', + }); +} diff --git a/apps/backend/src/modules/people/routes.ts b/apps/backend/src/modules/people/routes.ts new file mode 100644 index 0000000..a673c5e --- /dev/null +++ b/apps/backend/src/modules/people/routes.ts @@ -0,0 +1,8 @@ +import { Hono } from 'hono'; +import lookupRoute from './features/lookup/route'; + +const routes = new Hono(); + +routes.route('/', lookupRoute); + +export default routes; diff --git a/apps/backend/src/modules/student-access/features/get-status/route.ts b/apps/backend/src/modules/student-access/features/get-status/route.ts new file mode 100644 index 0000000..6a01f74 --- /dev/null +++ b/apps/backend/src/modules/student-access/features/get-status/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetStudentAccess } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/attendees/:attendeeId/student-access', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const result = await new GetStudentAccess().execute( + c.req.param('groupId'), + c.req.param('attendeeId'), + user.id, + ); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/student-access/features/get-status/use-case.ts b/apps/backend/src/modules/student-access/features/get-status/use-case.ts new file mode 100644 index 0000000..1a0f8ee --- /dev/null +++ b/apps/backend/src/modules/student-access/features/get-status/use-case.ts @@ -0,0 +1,31 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, StudentAccessDto } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; +import { computeStudentAccess } from '../../lib/status'; + +type GetStudentAccessDeps = { + db?: Pick; + now?: Date; +}; + +export class GetStudentAccess { + constructor(private readonly deps: GetStudentAccessDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) return access; + + const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } }); + if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + + return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date())); + } +} diff --git a/apps/backend/src/modules/student-access/features/invite/route.ts b/apps/backend/src/modules/student-access/features/invite/route.ts new file mode 100644 index 0000000..74f897c --- /dev/null +++ b/apps/backend/src/modules/student-access/features/invite/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { InviteStudent } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/attendees/:attendeeId/student-access/invite', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + const result = await new InviteStudent().execute( + c.req.param('groupId'), + c.req.param('attendeeId'), + user.id, + ); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/student-access/features/invite/use-case.ts b/apps/backend/src/modules/student-access/features/invite/use-case.ts new file mode 100644 index 0000000..b85b99d --- /dev/null +++ b/apps/backend/src/modules/student-access/features/invite/use-case.ts @@ -0,0 +1,106 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared'; +import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; +import { contactPhone } from '@/modules/people/lib/people'; +import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib'; +import { computeStudentAccess } from '../../lib/status'; + +type InviteStudentDeps = { + db?: Pick; + unitOfWork?: Pick; + now?: Date; +}; + +/* "Invitar" / "Reinvitar": reinviting restarts the access. It revokes every + pending link and every session and removes the passkeys (a lost phone must not + keep a way in), then issues a fresh 72 h single-use link. The welcome screen + shows again on the next sign-in so the student can add a passkey back. The + raw token only leaves here, inside the URL: the database keeps its hash. */ +export class InviteStudent { + constructor(private readonly deps: InviteStudentDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) return access; + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { + id: true, + personId: true, + person: { select: { fullName: true, phone: true, guardianPhone: true } }, + group: { select: { owner: { select: { country: true } } } }, + }, + }); + if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + + const token = generateAccessToken(); + const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000); + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + + const issued = await unitOfWork.executeResult(async (tx) => { + // One account per person: inviting from any of their groups reuses it. + const link = await tx.studentAccountPerson.findFirst({ + where: { personId: attendee.personId }, + orderBy: { createdAt: 'asc' }, + select: { accountId: true }, + }); + const accountId = + link?.accountId + ?? ( + await tx.studentAccount.create({ + data: { + name: attendee.person.fullName, + createdById: userId, + people: { create: { personId: attendee.personId } }, + }, + select: { id: true }, + }) + ).id; + + await tx.studentAccessToken.updateMany({ + where: { accountId, usedAt: null, revokedAt: null }, + data: { revokedAt: now }, + }); + await tx.studentSession.updateMany({ + where: { accountId, revokedAt: null }, + data: { revokedAt: now }, + }); + await tx.studentPasskey.deleteMany({ where: { accountId } }); + await tx.studentAccount.update({ where: { id: accountId }, data: { welcomedAt: null } }); + await tx.studentAccessToken.create({ + data: { + accountId, + kind: 'INVITATION', + tokenHash: hashToken(token), + expiresAt, + createdById: userId, + createdAt: now, + }, + }); + return ok(accountId); + }); + if (!issued.ok) return issued; + + return ok({ + url: studentLinkUrl(token), + expiresAt: expiresAt.toISOString(), + whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country), + access: await computeStudentAccess(db, attendee.personId, now), + }); + } +} + +function toWhatsappPhone(phone: string | null, country: string | null): string | null { + return phone ? toWhatsappE164(phone, country as CountryCode | null) : null; +} diff --git a/apps/backend/src/modules/student-access/features/list-absence-notices/route.ts b/apps/backend/src/modules/student-access/features/list-absence-notices/route.ts new file mode 100644 index 0000000..c29ee8a --- /dev/null +++ b/apps/backend/src/modules/student-access/features/list-absence-notices/route.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { ListGroupAbsenceNotices } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/absence-notices', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + return resultJson(c, await new ListGroupAbsenceNotices().execute(c.req.param('groupId'), user.id)); +}); + +export default route; diff --git a/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts b/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts new file mode 100644 index 0000000..dc1be9d --- /dev/null +++ b/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts @@ -0,0 +1,58 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, TeacherAbsenceNoticeList } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; +import { startOfWeekInTimeZone } from '@/modules/home/lib/scheduler'; +import { teacherTimeZone } from '@/modules/student-portal/lib/schedule'; + +const REASON = { HEALTH: 'health', TRAVEL: 'travel', WORK_STUDY: 'work_study', OTHER: 'other' } as const; +const DAY_MS = 24 * 60 * 60 * 1000; + +type ListAbsenceNoticesDeps = { + db?: Pick; + now?: Date; +}; + +/* "Faltas avisadas · esta semana" on the group card: active notices for this + week's classes (Monday to Sunday on the teacher's clock). */ +export class ListGroupAbsenceNotices { + constructor(private readonly deps: ListAbsenceNoticesDeps = {}) {} + + async execute(groupId: string, userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) return access; + + const owner = await db.user.findUnique({ where: { id: access.value.createdById }, select: { country: true } }); + const timeZone = teacherTimeZone(owner?.country); + const from = startOfWeekInTimeZone(now, timeZone); + const to = startOfWeekInTimeZone(new Date(from.getTime() + 8 * DAY_MS), timeZone); + + const notices = await db.absenceNotice.findMany({ + where: { cancelledAt: null, classSession: { groupId, startsAt: { gte: from, lt: to } } }, + orderBy: [{ classSession: { startsAt: 'asc' } }, { createdAt: 'asc' }], + select: { + id: true, + reason: true, + message: true, + createdAt: true, + attendee: { select: { id: true, person: { select: { fullName: true } } } }, + classSession: { select: { startsAt: true } }, + }, + }); + + return ok({ + data: notices.map((notice) => ({ + id: notice.id, + attendee: { id: notice.attendee.id, fullName: notice.attendee.person.fullName }, + startsAt: notice.classSession.startsAt.toISOString(), + reason: notice.reason ? REASON[notice.reason] : null, + message: notice.message, + createdAt: notice.createdAt.toISOString(), + })), + }); + } +} diff --git a/apps/backend/src/modules/student-access/index.ts b/apps/backend/src/modules/student-access/index.ts new file mode 100644 index 0000000..19b7305 --- /dev/null +++ b/apps/backend/src/modules/student-access/index.ts @@ -0,0 +1,2 @@ +export { startStudentAccessJobs } from './jobs/cleanup'; +export { default as studentAccessRoutes } from './routes'; diff --git a/apps/backend/src/modules/student-access/jobs/cleanup.ts b/apps/backend/src/modules/student-access/jobs/cleanup.ts new file mode 100644 index 0000000..8dbcf2e --- /dev/null +++ b/apps/backend/src/modules/student-access/jobs/cleanup.ts @@ -0,0 +1,95 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { type FileStorage, getFileStorage } from '@/lib/storage'; +import { logger } from '@/logger'; + +const DAY_MS = 24 * 60 * 60 * 1000; +const BATCH = 100; + +type CleanupDeps = { + db?: Pick; + storage?: FileStorage | null; + now?: Date; + /** Days a receipt is kept after the teacher reviewed it; 0 keeps it forever. */ + retentionDays?: number; +}; + +export function receiptRetentionDays(): number { + const parsed = Number(process.env.RECEIPT_RETENTION_DAYS ?? 0); + return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0; +} + +/* Daily housekeeping of the student access: + - Receipt retention: deletes the files of reports reviewed more than + RECEIPT_RETENTION_DAYS ago (the row stays, without `receipt_key`). Reports + still waiting for the teacher are never touched. + - Drops dead tokens, challenges, rate limit hits and sessions after a grace + period (they only matter for the audit while they are recent). */ +export class StudentAccessCleanup { + constructor(private readonly deps: CleanupDeps = {}) {} + + async execute() { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage; + const retentionDays = this.deps.retentionDays ?? receiptRetentionDays(); + + let receiptsDeleted = 0; + if (retentionDays > 0 && storage) { + const before = new Date(now.getTime() - retentionDays * DAY_MS); + for (;;) { + const rows = await db.reportedPayment.findMany({ + where: { status: { in: ['CONFIRMED', 'REJECTED'] }, reviewedAt: { lt: before }, receiptKey: { not: null } }, + select: { id: true, receiptKey: true }, + take: BATCH, + }); + if (rows.length === 0) break; + for (const row of rows) { + try { + await storage.remove(row.receiptKey as string); + await db.reportedPayment.update({ where: { id: row.id }, data: { receiptKey: null } }); + receiptsDeleted++; + } catch (error) { + logger.warn({ error, reportId: row.id }, 'Receipt retention: file could not be removed'); + } + } + if (rows.length < BATCH) break; + } + } + + const monthAgo = new Date(now.getTime() - 30 * DAY_MS); + const [tokens, challenges, hits, sessions] = await Promise.all([ + db.studentAccessToken.deleteMany({ where: { expiresAt: { lt: monthAgo } } }), + db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: now } } }), + db.rateLimitEvent.deleteMany({ where: { createdAt: { lt: new Date(now.getTime() - DAY_MS) } } }), + db.studentSession.deleteMany({ + where: { OR: [{ expiresAt: { lt: monthAgo } }, { revokedAt: { lt: monthAgo } }] }, + }), + ]); + + return { + receiptsDeleted, + tokensDeleted: tokens.count, + challengesDeleted: challenges.count, + rateLimitHitsDeleted: hits.count, + sessionsDeleted: sessions.count, + }; + } +} + +const CLEANUP_CRON = '23 5 * * *'; + +/** Registered from server.ts, with the same guards as the other jobs. */ +export function startStudentAccessJobs(): void { + Bun.cron( + CLEANUP_CRON, + async () => { + try { + logger.info(await new StudentAccessCleanup().execute(), 'Student access cleanup finished'); + } catch (error) { + logger.error({ err: error }, 'Student access cleanup failed'); + } + }, + { tz: 'UTC' }, + ).unref(); +} diff --git a/apps/backend/src/modules/student-access/lib/status.ts b/apps/backend/src/modules/student-access/lib/status.ts new file mode 100644 index 0000000..1392343 --- /dev/null +++ b/apps/backend/src/modules/student-access/lib/status.ts @@ -0,0 +1,71 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { StudentAccessDto } from '@gruperly/shared'; + +export type StudentAccessStatusDb = Pick; + +/* Passive state for the attendee's card: active (a live session) > invited + (a pending invitation) > expired (invited before, nothing alive) > not invited. + It is the person's access, so every group of theirs shows the same state. */ +export async function computeStudentAccess( + db: StudentAccessStatusDb, + personId: string, + now: Date, +): Promise { + const link = await db.studentAccountPerson.findFirst({ + where: { personId }, + orderBy: { createdAt: 'asc' }, + select: { + account: { + select: { + _count: { select: { passkeys: true } }, + sessions: { + where: { revokedAt: null, expiresAt: { gt: now } }, + orderBy: { lastUsedAt: 'desc' }, + select: { device: true, createdAt: true, lastUsedAt: true }, + }, + tokens: { + where: { kind: 'INVITATION' }, + orderBy: { createdAt: 'desc' }, + take: 1, + select: { usedAt: true, revokedAt: true, expiresAt: true }, + }, + }, + }, + }, + }); + + if (!link) { + return { status: 'not_invited', invitationExpiresAt: null, devices: [], hasPasskey: false }; + } + + const { account } = link; + const devices = account.sessions.map((session) => ({ + device: session.device, + createdAt: session.createdAt.toISOString(), + lastUsedAt: session.lastUsedAt.toISOString(), + })); + const hasPasskey = account._count.passkeys > 0; + const lastInvitation = account.tokens[0] ?? null; + const pending = + lastInvitation && !lastInvitation.usedAt && !lastInvitation.revokedAt && lastInvitation.expiresAt > now + ? lastInvitation + : null; + + if (devices.length > 0) { + return { status: 'active', invitationExpiresAt: null, devices, hasPasskey }; + } + if (pending) { + return { + status: 'invited', + invitationExpiresAt: pending.expiresAt.toISOString(), + devices, + hasPasskey, + }; + } + return { + status: lastInvitation ? 'expired' : 'not_invited', + invitationExpiresAt: null, + devices, + hasPasskey, + }; +} diff --git a/apps/backend/src/modules/student-access/routes.ts b/apps/backend/src/modules/student-access/routes.ts new file mode 100644 index 0000000..05287db --- /dev/null +++ b/apps/backend/src/modules/student-access/routes.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import getStatusRoute from './features/get-status/route'; +import inviteRoute from './features/invite/route'; +import listAbsenceNoticesRoute from './features/list-absence-notices/route'; + +// Teacher side of the student access. Hooked into modules/groups/routes.ts: +// it hangs from /groups/:groupId (absence notices) and +// /groups/:groupId/attendees/:attendeeId (access). +const routes = new Hono(); + +routes.route('/', getStatusRoute); +routes.route('/', inviteRoute); +routes.route('/', listAbsenceNoticesRoute); + +export default routes; diff --git a/apps/backend/src/modules/student-portal/features/absences/use-case.ts b/apps/backend/src/modules/student-portal/features/absences/use-case.ts new file mode 100644 index 0000000..d74391d --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/absences/use-case.ts @@ -0,0 +1,148 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + CreateAbsenceNotices, + CreateAbsenceNoticesResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { validationProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { absenceReleaseHours, registerAbsence } from '@/modules/classes/lib'; +import { occurrencesBetween } from '@/modules/home/lib/scheduler'; +import { + classAlreadyStartedProblem, + findLinkedAttendee, + studentAttendeeNotFoundProblem, + teacherTimeZone, +} from '../../lib'; +import { ABSENCE_REASON_TO_DB, horizonEnd } from '../classes/use-case'; + +type AbsenceDb = Pick< + PrismaClient, + 'attendee' | 'classSession' | 'absenceNotice' | 'attendance' | 'slotRelease' +>; + +type AbsenceDeps = { + db?: AbsenceDb; + unitOfWork?: UnitOfWork; + now?: Date; + releaseHours?: number; +}; + +/* "No voy a ir": only before the class starts, only for real classes of the + attendee's group. Each class goes through the same `registerAbsence` the + teacher and the old absence link use (EXCUSED + spot release), so an excused + absence doesn't count for the attendance risk rules. Classes already + notified are skipped (idempotent). */ +export class NotifyStudentAbsences { + constructor(private readonly deps: AbsenceDeps = {}) {} + + async execute( + accountId: string, + input: CreateAbsenceNotices, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + const now = this.deps.now ?? new Date(); + + const attendee = await findLinkedAttendee(db, accountId, input.attendeeId); + if (!attendee) return err(studentAttendeeNotFoundProblem()); + + const timeZone = teacherTimeZone(attendee.group.owner.country); + const valid = new Set( + occurrencesBetween({ + days: attendee.group.days, + time: attendee.group.time, + from: now, + to: horizonEnd(now), + timeZone, + }).map((date) => date.getTime()), + ); + + const requested = [...new Set(input.startsAt.map((value) => new Date(value).getTime()))]; + for (const time of requested) { + if (time <= now.getTime()) return err(classAlreadyStartedProblem()); + if (!valid.has(time)) { + return err(validationProblem({ detail: 'Una de las clases elegidas no es del grupo.' })); + } + } + + const notified: CreateAbsenceNoticesResult['notified'] = []; + for (const time of requested.sort((a, b) => a - b)) { + const startsAt = new Date(time); + const session = await db.classSession.upsert({ + where: { groupId_startsAt: { groupId: attendee.groupId, startsAt } }, + create: { groupId: attendee.groupId, startsAt }, + update: {}, + select: { id: true }, + }); + + const existing = await db.absenceNotice.findFirst({ + where: { attendeeId: attendee.id, classSessionId: session.id, cancelledAt: null }, + select: { id: true }, + }); + if (existing) continue; + + const registered = await registerAbsence( + { db, unitOfWork }, + { + attendeeId: attendee.id, + classSessionId: session.id, + now, + releaseHours: this.deps.releaseHours ?? absenceReleaseHours(), + }, + ); + if (!registered.ok) return registered; + + const notice = await db.absenceNotice.create({ + data: { + attendeeId: attendee.id, + classSessionId: session.id, + accountId, + reason: input.reason ? ABSENCE_REASON_TO_DB[input.reason] : null, + message: input.message || null, + createdAt: now, + }, + select: { id: true }, + }); + notified.push({ id: notice.id, startsAt: startsAt.toISOString() }); + } + + return ok({ notified }); + } +} + +/* "Deshacer": while the class hasn't started. Undoes what the notice did: the + EXCUSED mark and the released spot, if nobody claimed it. */ +export class CancelStudentAbsence { + constructor(private readonly deps: AbsenceDeps = {}) {} + + async execute(accountId: string, noticeId: string): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + const now = this.deps.now ?? new Date(); + + const notice = await db.absenceNotice.findFirst({ + where: { + id: noticeId, + cancelledAt: null, + attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } }, + }, + select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } }, + }); + if (!notice) return err(studentAttendeeNotFoundProblem()); + if (notice.classSession.startsAt <= now) return err(classAlreadyStartedProblem()); + + return unitOfWork.executeResult(async (tx) => { + await tx.absenceNotice.update({ where: { id: notice.id }, data: { cancelledAt: now } }); + await tx.attendance.deleteMany({ + where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, status: 'EXCUSED' }, + }); + await tx.slotRelease.deleteMany({ + where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, isClaimed: false }, + }); + return ok({ id: notice.id }); + }); + } +} diff --git a/apps/backend/src/modules/student-portal/features/classes/route.ts b/apps/backend/src/modules/student-portal/features/classes/route.ts new file mode 100644 index 0000000..d86fb7b --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/classes/route.ts @@ -0,0 +1,34 @@ +import { + type CreateAbsenceNotices, + CreateAbsenceNoticesSchema, + type StudentAttendeeQuery, + StudentAttendeeQuerySchema, +} from '@gruperly/shared'; +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { currentStudent, studentSession } from '../../middleware'; +import { CancelStudentAbsence, NotifyStudentAbsences } from '../absences/use-case'; +import { GetStudentClasses } from './use-case'; + +const route = new Hono(); + +route.get('/classes', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => { + const { accountId } = currentStudent(c); + const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery; + return resultJson(c, await new GetStudentClasses().execute(accountId, attendeeId)); +}); + +route.post('/absences', studentSession, validate.json(CreateAbsenceNoticesSchema), async (c) => { + const { accountId } = currentStudent(c); + const input = c.req.valid('json') as CreateAbsenceNotices; + return resultJson(c, await new NotifyStudentAbsences().execute(accountId, input), { status: 201 }); +}); + +route.delete('/absences/:noticeId', studentSession, async (c) => { + const { accountId } = currentStudent(c); + return resultJson(c, await new CancelStudentAbsence().execute(accountId, c.req.param('noticeId'))); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/classes/use-case.ts b/apps/backend/src/modules/student-portal/features/classes/use-case.ts new file mode 100644 index 0000000..2915f23 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/classes/use-case.ts @@ -0,0 +1,88 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AbsenceReasonValue, ProblemDetails, Result, StudentClassesDto } from '@gruperly/shared'; +import { ABSENCE_NOTICE_HORIZON_DAYS, err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler'; +import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib'; + +type GetStudentClassesDeps = { + db?: Pick; + now?: Date; +}; + +export const ABSENCE_REASON_TO_DB = { + health: 'HEALTH', + travel: 'TRAVEL', + work_study: 'WORK_STUDY', + other: 'OTHER', +} as const; + +const ABSENCE_REASON_FROM_DB: Record = { + HEALTH: 'health', + TRAVEL: 'travel', + WORK_STUDY: 'work_study', + OTHER: 'other', +}; + +export function horizonEnd(now: Date): Date { + return new Date(now.getTime() + ABSENCE_NOTICE_HORIZON_DAYS * 24 * 60 * 60 * 1000); +} + +/* Classes of this week (already started ones included, for "Esta semana") up + to the notice horizon, with the student's active notice on each. Only the + attendee's own data: never other members of the group. */ +export class GetStudentClasses { + constructor(private readonly deps: GetStudentClassesDeps = {}) {} + + async execute(accountId: string, attendeeId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const attendee = await findLinkedAttendee(db, accountId, attendeeId); + if (!attendee) return err(studentAttendeeNotFoundProblem()); + + const timeZone = teacherTimeZone(attendee.group.owner.country); + const from = startOfWeekInTimeZone(now, timeZone); + const to = horizonEnd(now); + const weekEndsAt = startOfWeekInTimeZone(new Date(from.getTime() + 8 * 24 * 60 * 60 * 1000), timeZone); + const starts = occurrencesBetween({ days: attendee.group.days, time: attendee.group.time, from, to, timeZone }); + + const notices = await db.absenceNotice.findMany({ + where: { + attendeeId, + cancelledAt: null, + classSession: { groupId: attendee.groupId, startsAt: { gte: from, lt: to } }, + }, + select: { + id: true, + reason: true, + message: true, + createdAt: true, + classSession: { select: { startsAt: true } }, + }, + }); + const noticeByStart = new Map(notices.map((notice) => [notice.classSession.startsAt.getTime(), notice])); + + return ok({ + attendeeId, + timeZone, + weekEndsAt: weekEndsAt.toISOString(), + classes: starts.map((startsAt) => { + const notice = noticeByStart.get(startsAt.getTime()); + return { + startsAt: startsAt.toISOString(), + groupName: attendee.group.name, + started: startsAt <= now, + notice: notice + ? { + id: notice.id, + reason: notice.reason ? ABSENCE_REASON_FROM_DB[notice.reason] ?? null : null, + message: notice.message, + createdAt: notice.createdAt.toISOString(), + } + : null, + }; + }), + }); + } +} diff --git a/apps/backend/src/modules/student-portal/features/consume-link/route.ts b/apps/backend/src/modules/student-portal/features/consume-link/route.ts new file mode 100644 index 0000000..99d93ff --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/consume-link/route.ts @@ -0,0 +1,21 @@ +import { Hono } from 'hono'; +import { problemJson } from '@/http/problem-details'; +import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib'; +import { ConsumeStudentLink } from './use-case'; + +const route = new Hono(); + +route.post('/links/:token/consume', async (c) => { + const result = await new ConsumeStudentLink().execute({ + token: c.req.param('token'), + ip: clientIp(c), + userAgent: userAgent(c), + currentSessionToken: readStudentSessionCookie(c), + }); + if (!result.ok) return problemJson(c, result.error); + + writeStudentSessionCookie(c, result.value.sessionToken); + return c.json({ firstLogin: result.value.firstLogin }); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/consume-link/use-case.ts b/apps/backend/src/modules/student-portal/features/consume-link/use-case.ts new file mode 100644 index 0000000..a1cf8eb --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/consume-link/use-case.ts @@ -0,0 +1,72 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { + createStudentSession, + hashToken, + revokeStudentSessionByToken, + studentLinkInvalidProblem, +} from '../../lib'; + +type ConsumeStudentLinkDeps = { + unitOfWork?: Pick; + now?: Date; +}; + +export type ConsumeStudentLinkInput = { + token: string; + ip: string | null; + userAgent: string | null; + /** Session cookie already on this device, if any: it is replaced. */ + currentSessionToken?: string; +}; + +export type ConsumeStudentLinkOutput = { sessionToken: string; firstLogin: boolean }; + +/* POST of the link. The conditional update is what makes it single use: under + concurrency Postgres re-checks `used_at IS NULL` after the first commit, so + exactly one request gets count === 1 and the rest see a dead link. */ +export class ConsumeStudentLink { + constructor(private readonly deps: ConsumeStudentLinkDeps = {}) {} + + async execute( + input: ConsumeStudentLinkInput, + ): Promise> { + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + const now = this.deps.now ?? new Date(); + const tokenHash = hashToken(input.token); + + return unitOfWork.executeResult(async (tx) => { + const claimed = await tx.studentAccessToken.updateMany({ + where: { + tokenHash, + kind: { in: ['INVITATION', 'RECOVERY'] }, + usedAt: null, + revokedAt: null, + expiresAt: { gt: now }, + }, + data: { usedAt: now, usedIp: input.ip, usedUserAgent: input.userAgent }, + }); + if (claimed.count !== 1) { + return err(studentLinkInvalidProblem()); + } + + const row = await tx.studentAccessToken.findUniqueOrThrow({ + where: { tokenHash }, + select: { accountId: true, account: { select: { welcomedAt: true } } }, + }); + + if (input.currentSessionToken) { + await revokeStudentSessionByToken(tx, input.currentSessionToken, now); + } + const sessionToken = await createStudentSession(tx, { + accountId: row.accountId, + userAgent: input.userAgent, + now, + }); + + return ok({ sessionToken, firstLogin: row.account.welcomedAt === null }); + }); + } +} diff --git a/apps/backend/src/modules/student-portal/features/fees/route.ts b/apps/backend/src/modules/student-portal/features/fees/route.ts new file mode 100644 index 0000000..d30d3b4 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/fees/route.ts @@ -0,0 +1,52 @@ +import { type StudentAttendeeQuery, StudentAttendeeQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { validationProblem } from '@/http/problem-builders'; +import { problemJson, resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { RECEIPT_MAX_BYTES } from '@/lib/file-type'; +import { currentStudent, studentSession } from '../../middleware'; +import { ReportStudentPayment } from '../payment-reports/use-case'; +import { GetStudentFees } from './use-case'; + +const route = new Hono(); + +route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => { + const { accountId } = currentStudent(c); + const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery; + return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId)); +}); + +// multipart/form-data: attendeeId, paymentIds (repeated), file and an optional note. +route.post('/payment-reports', studentSession, async (c) => { + const { accountId } = currentStudent(c); + // Reject oversized bodies before buffering them (10 MB + room for the fields). + const length = Number(c.req.header('Content-Length') ?? 0); + if (length > RECEIPT_MAX_BYTES + 64 * 1024) { + return problemJson(c, validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } })); + } + + let form: FormData; + try { + form = await c.req.formData(); + } catch { + return problemJson(c, validationProblem({ detail: 'Invalid form data' })); + } + const attendeeId = form.get('attendeeId'); + const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0); + const file = form.get('file'); + const note = form.get('note'); + if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) { + return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' })); + } + + const result = await new ReportStudentPayment().execute(accountId, { + attendeeId, + paymentIds, + note: typeof note === 'string' ? note : null, + file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) }, + }); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/fees/use-case.ts b/apps/backend/src/modules/student-portal/features/fees/use-case.ts new file mode 100644 index 0000000..677bc31 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/fees/use-case.ts @@ -0,0 +1,99 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, StudentFeeStatus, StudentFeesDto } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { startOfDayInTimeZone } from '@/modules/home/lib/scheduler'; +import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib'; + +type GetStudentFeesDeps = { + db?: Pick; + now?: Date; +}; + +const REPORTS_SHOWN = 10; + +const REPORT_STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const; + +/* Unpaid fees of the attendee and their latest reports. A fee inside a report + the teacher hasn't reviewed shows as "reported" (the Payment row itself is + not touched until the teacher confirms). */ +export class GetStudentFees { + constructor(private readonly deps: GetStudentFeesDeps = {}) {} + + async execute(accountId: string, attendeeId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const attendee = await findLinkedAttendee(db, accountId, attendeeId); + if (!attendee) return err(studentAttendeeNotFoundProblem()); + const startOfToday = startOfDayInTimeZone(now, teacherTimeZone(attendee.group.owner.country)); + + const [payments, reports] = await Promise.all([ + db.payment.findMany({ + where: { attendeeId, status: { in: ['PENDING', 'OVERDUE'] } }, + orderBy: { dueDate: 'asc' }, + select: { + id: true, + description: true, + amount: true, + currency: true, + dueDate: true, + status: true, + checkoutUrl: true, + reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } }, + }, + }), + db.reportedPayment.findMany({ + where: { attendeeId }, + orderBy: { createdAt: 'desc' }, + take: REPORTS_SHOWN, + select: { + id: true, + totalAmount: true, + currency: true, + status: true, + createdAt: true, + reviewedAt: true, + note: true, + rejectionReason: true, + items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } }, + }, + }), + ]); + + const { transferAlias, transferHolder } = attendee.group.owner; + return ok({ + attendeeId, + fees: payments.map((payment) => { + let status: StudentFeeStatus = 'pending'; + if (payment.reportedItems.length > 0) status = 'reported'; + else if (payment.status === 'OVERDUE' || payment.dueDate < startOfToday) status = 'overdue'; + return { + id: payment.id, + description: payment.description, + amount: payment.amount.toNumber(), + currency: payment.currency, + dueDate: payment.dueDate.toISOString(), + status, + checkoutUrl: payment.checkoutUrl, + }; + }), + transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null, + reports: reports.map((report) => ({ + id: report.id, + totalAmount: report.totalAmount.toNumber(), + currency: report.currency, + status: REPORT_STATUS[report.status], + createdAt: report.createdAt.toISOString(), + reviewedAt: report.reviewedAt?.toISOString() ?? null, + note: report.note, + rejectionReason: report.rejectionReason, + fees: report.items.map(({ payment }) => ({ + id: payment.id, + description: payment.description, + dueDate: payment.dueDate.toISOString(), + })), + })), + }); + } +} diff --git a/apps/backend/src/modules/student-portal/features/link-info/route.ts b/apps/backend/src/modules/student-portal/features/link-info/route.ts new file mode 100644 index 0000000..27b6f7f --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/link-info/route.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { GetStudentLinkInfo } from './use-case'; + +const route = new Hono(); + +route.get('/links/:token', async (c) => { + const result = await new GetStudentLinkInfo().execute(c.req.param('token')); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/link-info/use-case.ts b/apps/backend/src/modules/student-portal/features/link-info/use-case.ts new file mode 100644 index 0000000..62563a4 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/link-info/use-case.ts @@ -0,0 +1,74 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { hashToken } from '../../lib'; + +type GetStudentLinkInfoDeps = { + db?: Pick; + now?: Date; +}; + +const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/; + +/* GET of the link: only reads, never consumes (WhatsApp previews and link + scanners open it). Every unusable link answers the same `invalid`. */ +export class GetStudentLinkInfo { + constructor(private readonly deps: GetStudentLinkInfoDeps = {}) {} + + async execute(token: string): Promise> { + if (!TOKEN_PATTERN.test(token)) return ok({ status: 'invalid' }); + + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const row = await db.studentAccessToken.findUnique({ + where: { tokenHash: hashToken(token) }, + select: { + kind: true, + usedAt: true, + revokedAt: true, + expiresAt: true, + account: { + select: { + name: true, + people: { + orderBy: { createdAt: 'asc' }, + take: 1, + select: { + person: { + select: { + attendees: { + orderBy: { createdAt: 'asc' }, + take: 1, + select: { group: { select: { name: true, owner: { select: { name: true } } } } }, + }, + }, + }, + }, + }, + }, + }, + }, + }); + + if ( + !row + || row.kind === 'EMAIL_CONFIRMATION' + || row.usedAt + || row.revokedAt + || row.expiresAt <= now + ) { + return ok({ status: 'invalid' }); + } + + const group = row.account.people[0]?.person.attendees[0]?.group ?? null; + return ok({ + status: 'valid', + kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery', + name: row.account.name, + teacherName: group?.owner.name ?? null, + groupName: group?.name ?? null, + }); + } +} diff --git a/apps/backend/src/modules/student-portal/features/logout/route.ts b/apps/backend/src/modules/student-portal/features/logout/route.ts new file mode 100644 index 0000000..651b282 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/logout/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import prisma from '@/lib/prisma'; +import { clearStudentSessionCookie } from '../../lib'; +import { currentStudent, studentSession } from '../../middleware'; + +const route = new Hono(); + +// Closes this device only. Reinviting from the teacher's side closes all of them. +route.post('/logout', studentSession, async (c) => { + const student = currentStudent(c); + await prisma.studentSession.updateMany({ + where: { id: student.sessionId, revokedAt: null }, + data: { revokedAt: new Date() }, + }); + clearStudentSessionCookie(c); + return c.body(null, 204); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/me/route.ts b/apps/backend/src/modules/student-portal/features/me/route.ts new file mode 100644 index 0000000..39466cb --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/me/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { resultJson } from '@/http/problem-details'; +import { currentStudent, studentSession } from '../../middleware'; +import { GetStudentMe, MarkStudentWelcomed } from './use-case'; + +const route = new Hono(); + +route.get('/me', studentSession, async (c) => { + const student = currentStudent(c); + return resultJson(c, await new GetStudentMe().execute(student.accountId)); +}); + +route.post('/me/welcome', studentSession, async (c) => { + const student = currentStudent(c); + return resultJson(c, await new MarkStudentWelcomed().execute(student.accountId)); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/me/use-case.ts b/apps/backend/src/modules/student-portal/features/me/use-case.ts new file mode 100644 index 0000000..f2d1a27 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/me/use-case.ts @@ -0,0 +1,80 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { unauthorizedProblem } from '@/http/problem-details'; +import prisma from '@/lib/prisma'; + +type StudentMeDeps = { db?: Pick; now?: Date }; + +export class GetStudentMe { + constructor(private readonly deps: StudentMeDeps = {}) {} + + async execute(accountId: string): Promise> { + const db = this.deps.db ?? prisma; + const account = await db.studentAccount.findUnique({ + where: { id: accountId }, + select: { + id: true, + name: true, + recoveryEmail: true, + pendingRecoveryEmail: true, + welcomedAt: true, + _count: { select: { passkeys: true } }, + // Linked people, and every group each of them is in. + people: { + orderBy: { createdAt: 'asc' }, + select: { + person: { + select: { + fullName: true, + attendees: { + where: { status: { not: 'DROPPED' } }, + orderBy: { createdAt: 'asc' }, + select: { + id: true, + group: { select: { id: true, name: true, owner: { select: { name: true } } } }, + }, + }, + }, + }, + }, + }, + }, + }); + if (!account) return err(unauthorizedProblem('/student-portal/me')); + + return ok({ + account: { + id: account.id, + name: account.name, + recoveryEmail: account.recoveryEmail, + pendingRecoveryEmail: account.pendingRecoveryEmail, + hasPasskey: account._count.passkeys > 0, + welcomed: account.welcomedAt !== null, + }, + students: account.people.flatMap(({ person }) => + person.attendees.map((attendee) => ({ + attendeeId: attendee.id, + fullName: person.fullName, + groupId: attendee.group.id, + groupName: attendee.group.name, + teacherName: attendee.group.owner.name, + })), + ), + }); + } +} + +/* The welcome screen is shown until the student goes past it once. */ +export class MarkStudentWelcomed { + constructor(private readonly deps: StudentMeDeps = {}) {} + + async execute(accountId: string): Promise> { + const db = this.deps.db ?? prisma; + await db.studentAccount.updateMany({ + where: { id: accountId, welcomedAt: null }, + data: { welcomedAt: this.deps.now ?? new Date() }, + }); + return new GetStudentMe({ db }).execute(accountId); + } +} diff --git a/apps/backend/src/modules/student-portal/features/passkeys/route.ts b/apps/backend/src/modules/student-portal/features/passkeys/route.ts new file mode 100644 index 0000000..2042ee1 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/passkeys/route.ts @@ -0,0 +1,47 @@ +import { type PasskeyVerify, PasskeyVerifySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { problemJson, resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib'; +import { currentStudent, studentSession } from '../../middleware'; +import { GetStudentMe } from '../me/use-case'; +import { StudentPasskeys } from './use-case'; + +const route = new Hono(); + +route.post('/passkeys/register/options', studentSession, async (c) => { + const { accountId } = currentStudent(c); + return resultJson(c, await new StudentPasskeys().registrationOptions(accountId)); +}); + +route.post('/passkeys/register/verify', studentSession, validate.json(PasskeyVerifySchema), async (c) => { + const { accountId } = currentStudent(c); + const input = c.req.valid('json') as PasskeyVerify; + const result = await new StudentPasskeys().verifyRegistration(accountId, input, userAgent(c)); + if (!result.ok) return problemJson(c, result.error); + return resultJson(c, await new GetStudentMe().execute(accountId)); +}); + +route.delete('/passkeys', studentSession, async (c) => { + const { accountId } = currentStudent(c); + await new StudentPasskeys().removeAll(accountId); + return resultJson(c, await new GetStudentMe().execute(accountId)); +}); + +route.post('/passkeys/login/options', async (c) => { + return resultJson(c, await new StudentPasskeys().loginOptions(clientIp(c))); +}); + +route.post('/passkeys/login/verify', validate.json(PasskeyVerifySchema), async (c) => { + const input = c.req.valid('json') as PasskeyVerify; + const result = await new StudentPasskeys().verifyLogin(input, { + userAgent: userAgent(c), + currentSessionToken: readStudentSessionCookie(c), + }); + if (!result.ok) return problemJson(c, result.error); + writeStudentSessionCookie(c, result.value.sessionToken); + return c.json({ firstLogin: false }); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/passkeys/use-case.ts b/apps/backend/src/modules/student-portal/features/passkeys/use-case.ts new file mode 100644 index 0000000..1a22da2 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/passkeys/use-case.ts @@ -0,0 +1,246 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { PasskeyOptionsResult, PasskeyVerify, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + type AuthenticationResponseJSON, + type AuthenticatorTransportFuture, + generateAuthenticationOptions, + generateRegistrationOptions, + type RegistrationResponseJSON, + verifyAuthenticationResponse, + verifyRegistrationResponse, +} from '@simplewebauthn/server'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + consumeRateLimit, + createStudentSession, + describeDevice, + passkeyInvalidProblem, + revokeStudentSessionByToken, + tooManyRequestsProblem, + WEBAUTHN_CHALLENGE_TTL_MS, + webauthnConfig, +} from '../../lib'; + +type PasskeyDb = Pick< + PrismaClient, + 'studentAccount' | 'studentPasskey' | 'studentWebauthnChallenge' | 'studentSession' | 'rateLimitEvent' +>; + +/* The library is injectable so the tests don't need a real authenticator. */ +export type WebauthnLib = { + generateRegistrationOptions: typeof generateRegistrationOptions; + verifyRegistrationResponse: typeof verifyRegistrationResponse; + generateAuthenticationOptions: typeof generateAuthenticationOptions; + verifyAuthenticationResponse: typeof verifyAuthenticationResponse; +}; + +const defaultWebauthn: WebauthnLib = { + generateRegistrationOptions, + verifyRegistrationResponse, + generateAuthenticationOptions, + verifyAuthenticationResponse, +}; + +type PasskeyDeps = { + db?: PasskeyDb; + unitOfWork?: Pick; + webauthn?: WebauthnLib; + now?: Date; +}; + +const LOGIN_OPTIONS_PER_IP = 30; + +/* Optional passkeys ("Entrar con Face ID o huella"): registered from a signed-in + session; the login is discoverable (no account typed), so it works from the + "Ingresar" and "Link ya usado" pages without the teacher. */ +export class StudentPasskeys { + constructor(private readonly deps: PasskeyDeps = {}) {} + + private get db(): PasskeyDb { + return this.deps.db ?? prisma; + } + + private get webauthn(): WebauthnLib { + return this.deps.webauthn ?? defaultWebauthn; + } + + private get now(): Date { + return this.deps.now ?? new Date(); + } + + async registrationOptions(accountId: string): Promise> { + const { rpID, rpName } = webauthnConfig(); + const account = await this.db.studentAccount.findUniqueOrThrow({ + where: { id: accountId }, + select: { name: true, passkeys: { select: { credentialId: true, transports: true } } }, + }); + + const options = await this.webauthn.generateRegistrationOptions({ + rpName, + rpID, + userID: new TextEncoder().encode(accountId), + userName: account.name, + userDisplayName: account.name, + attestationType: 'none', + excludeCredentials: account.passkeys.map((passkey) => ({ + id: passkey.credentialId, + transports: passkey.transports as AuthenticatorTransportFuture[], + })), + authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' }, + }); + + const challengeId = await this.storeChallenge(options.challenge, 'REGISTER', accountId); + return ok({ challengeId, options: options as unknown as Record }); + } + + async verifyRegistration( + accountId: string, + input: PasskeyVerify, + userAgent: string | null, + ): Promise> { + const challenge = await this.takeChallenge(input.challengeId, 'REGISTER', accountId); + if (!challenge) return err(passkeyInvalidProblem()); + + const { rpID, origin } = webauthnConfig(); + let verification: Awaited>; + try { + verification = await this.webauthn.verifyRegistrationResponse({ + response: input.response as unknown as RegistrationResponseJSON, + expectedChallenge: challenge, + expectedOrigin: origin, + expectedRPID: rpID, + requireUserVerification: false, + }); + } catch (error) { + logger.warn({ error: (error as Error).message }, 'Student passkey registration rejected'); + return err(passkeyInvalidProblem()); + } + if (!verification.verified || !verification.registrationInfo) return err(passkeyInvalidProblem()); + + const { credential } = verification.registrationInfo; + await this.db.studentPasskey.upsert({ + where: { credentialId: credential.id }, + create: { + accountId, + credentialId: credential.id, + publicKey: Uint8Array.from(credential.publicKey), + counter: credential.counter, + transports: credential.transports ?? [], + device: describeDevice(userAgent), + createdAt: this.now, + }, + // Same authenticator again (excludeCredentials failed open): keep it, no takeover. + update: {}, + }); + return ok({ registered: true }); + } + + async loginOptions(ip: string | null): Promise> { + const allowed = await consumeRateLimit(this.db, `passkey-login:ip:${ip ?? 'unknown'}`, { + limit: LOGIN_OPTIONS_PER_IP, + windowMs: 15 * 60 * 1000, + now: this.now, + }); + if (!allowed) return err(tooManyRequestsProblem()); + + const { rpID } = webauthnConfig(); + const options = await this.webauthn.generateAuthenticationOptions({ + rpID, + userVerification: 'preferred', + }); + const challengeId = await this.storeChallenge(options.challenge, 'LOGIN', null); + return ok({ challengeId, options: options as unknown as Record }); + } + + async verifyLogin( + input: PasskeyVerify, + request: { userAgent: string | null; currentSessionToken?: string }, + ): Promise> { + const challenge = await this.takeChallenge(input.challengeId, 'LOGIN', null); + if (!challenge) return err(passkeyInvalidProblem()); + + const response = input.response as unknown as AuthenticationResponseJSON; + if (typeof response.id !== 'string') return err(passkeyInvalidProblem()); + const passkey = await this.db.studentPasskey.findUnique({ where: { credentialId: response.id } }); + if (!passkey) return err(passkeyInvalidProblem()); + + const { rpID, origin } = webauthnConfig(); + let verification: Awaited>; + try { + verification = await this.webauthn.verifyAuthenticationResponse({ + response, + expectedChallenge: challenge, + expectedOrigin: origin, + expectedRPID: rpID, + credential: { + id: passkey.credentialId, + publicKey: Uint8Array.from(passkey.publicKey), + counter: passkey.counter, + transports: passkey.transports as AuthenticatorTransportFuture[], + }, + requireUserVerification: false, + }); + } catch (error) { + logger.warn({ error: (error as Error).message }, 'Student passkey login rejected'); + return err(passkeyInvalidProblem()); + } + if (!verification.verified) return err(passkeyInvalidProblem()); + + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + return unitOfWork.executeResult(async (tx) => { + await tx.studentPasskey.update({ + where: { id: passkey.id }, + data: { counter: verification.authenticationInfo.newCounter, lastUsedAt: this.now }, + }); + if (request.currentSessionToken) { + await revokeStudentSessionByToken(tx, request.currentSessionToken, this.now); + } + const sessionToken = await createStudentSession(tx, { + accountId: passkey.accountId, + userAgent: request.userAgent, + now: this.now, + }); + return ok({ sessionToken }); + }); + } + + /* "Quitar Face ID": removes every passkey of the account. */ + async removeAll(accountId: string): Promise> { + await this.db.studentPasskey.deleteMany({ where: { accountId } }); + return ok(null); + } + + private async storeChallenge( + challenge: string, + purpose: 'REGISTER' | 'LOGIN', + accountId: string | null, + ): Promise { + await this.db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: this.now } } }); + const row = await this.db.studentWebauthnChallenge.create({ + data: { + challenge, + purpose, + accountId, + expiresAt: new Date(this.now.getTime() + WEBAUTHN_CHALLENGE_TTL_MS), + }, + select: { id: true }, + }); + return row.id; + } + + /* Single use: whoever deletes the row gets the challenge. */ + private async takeChallenge( + challengeId: string, + purpose: 'REGISTER' | 'LOGIN', + accountId: string | null, + ): Promise { + const row = await this.db.studentWebauthnChallenge.findUnique({ where: { id: challengeId } }); + if (!row || row.purpose !== purpose || row.accountId !== accountId || row.expiresAt <= this.now) { + return null; + } + const deleted = await this.db.studentWebauthnChallenge.deleteMany({ where: { id: challengeId } }); + return deleted.count === 1 ? row.challenge : null; + } +} diff --git a/apps/backend/src/modules/student-portal/features/payment-reports/use-case.ts b/apps/backend/src/modules/student-portal/features/payment-reports/use-case.ts new file mode 100644 index 0000000..c936369 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/payment-reports/use-case.ts @@ -0,0 +1,106 @@ +import { randomBytes } from 'node:crypto'; +import { Prisma, type PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok, REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared'; +import { conflictProblem, validationProblem } from '@/http/problem-builders'; +import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { type FileStorage, getFileStorage } from '@/lib/storage'; +import { logger } from '@/logger'; +import { findLinkedAttendee, storageNotAvailableProblem, studentAttendeeNotFoundProblem } from '../../lib'; + +type ReportPaymentDeps = { + db?: Pick; + unitOfWork?: Pick; + storage?: FileStorage | null; + now?: Date; +}; + +export type ReportPaymentInput = { + attendeeId: string; + paymentIds: string[]; + note?: string | null; + file: { name: string; bytes: Uint8Array }; +}; + +/* "Informar pago": the receipt goes to private storage and the report stays + REPORTED until the teacher reviews it; nothing about the fees changes here. + The fees are locked (FOR UPDATE) while checking that none of them is already + in another unreviewed report, so two concurrent reports can't overlap. */ +export class ReportStudentPayment { + constructor(private readonly deps: ReportPaymentDeps = {}) {} + + async execute(accountId: string, input: ReportPaymentInput): Promise> { + const db = this.deps.db ?? prisma; + const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage; + const now = this.deps.now ?? new Date(); + + const attendee = await findLinkedAttendee(db, accountId, input.attendeeId); + if (!attendee) return err(studentAttendeeNotFoundProblem()); + + const note = input.note?.trim() || null; + if (note && note.length > REPORTED_PAYMENT_NOTE_MAX) { + return err(validationProblem({ detail: `La nota puede tener hasta ${REPORTED_PAYMENT_NOTE_MAX} caracteres.`, errors: { note: ['too_long'] } })); + } + + if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) { + return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } })); + } + const mime = detectReceiptType(input.file.bytes); + if (!mime) { + return err(validationProblem({ detail: 'El comprobante tiene que ser JPG, PNG, WEBP, HEIC o PDF.', errors: { file: ['invalid_type'] } })); + } + if (!storage) return err(storageNotAvailableProblem()); + + const paymentIds = [...new Set(input.paymentIds)]; + const payments = await db.payment.findMany({ + where: { id: { in: paymentIds }, attendeeId: attendee.id, status: { in: ['PENDING', 'OVERDUE'] } }, + select: { id: true, amount: true, currency: true }, + }); + if (payments.length !== paymentIds.length) { + return err(validationProblem({ detail: 'Alguna de las cuotas elegidas ya no está pendiente.', errors: { paymentIds: ['invalid'] } })); + } + const currencies = new Set(payments.map((payment) => payment.currency)); + if (currencies.size !== 1) { + return err(validationProblem({ detail: 'Las cuotas tienen que ser de la misma moneda.' })); + } + const total = payments.reduce((sum, payment) => sum.add(payment.amount), new Prisma.Decimal(0)); + + const key = `receipts/${attendee.group.createdById}/${attendee.id}/${randomBytes(16).toString('hex')}.${RECEIPT_EXTENSIONS[mime]}`; + await storage.put(key, input.file.bytes, mime); + + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + const result = await unitOfWork.executeResult(async (tx) => { + await tx.$queryRaw`SELECT id FROM payments WHERE id IN (${Prisma.join(paymentIds)}) FOR UPDATE`; + const taken = await tx.reportedPaymentItem.count({ + where: { paymentId: { in: paymentIds }, reportedPayment: { status: 'REPORTED' } }, + }); + if (taken > 0) { + return err(conflictProblem({ detail: 'Ya informaste el pago de alguna de estas cuotas.', code: 'payment_already_reported' })); + } + const report = await tx.reportedPayment.create({ + data: { + attendeeId: attendee.id, + groupId: attendee.groupId, + accountId, + totalAmount: total, + currency: [...currencies][0] as string, + receiptKey: key, + receiptMime: mime, + receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`, + receiptSize: input.file.bytes.length, + note, + createdAt: now, + items: { create: paymentIds.map((paymentId) => ({ paymentId })) }, + }, + select: { id: true }, + }); + return ok({ id: report.id }); + }); + + if (!result.ok) { + await storage.remove(key).catch((error) => logger.warn({ error }, 'Orphan receipt could not be removed')); + } + return result; + } +} diff --git a/apps/backend/src/modules/student-portal/features/recovery-email/route.ts b/apps/backend/src/modules/student-portal/features/recovery-email/route.ts new file mode 100644 index 0000000..d14327c --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/recovery-email/route.ts @@ -0,0 +1,36 @@ +import { + type ConfirmRecoveryEmail as ConfirmRecoveryEmailInput, + ConfirmRecoveryEmailSchema, + type SetRecoveryEmail as SetRecoveryEmailInput, + SetRecoveryEmailSchema, +} from '@gruperly/shared'; +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { problemJson, resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { currentStudent, studentSession } from '../../middleware'; +import { GetStudentMe } from '../me/use-case'; +import { ConfirmRecoveryEmail, RemoveRecoveryEmail, SetRecoveryEmail } from './use-case'; + +const route = new Hono(); + +route.put('/me/recovery-email', studentSession, validate.json(SetRecoveryEmailSchema), async (c) => { + const { accountId } = currentStudent(c); + const { email } = c.req.valid('json') as SetRecoveryEmailInput; + const result = await new SetRecoveryEmail().execute(accountId, email); + if (!result.ok) return problemJson(c, result.error); + return resultJson(c, await new GetStudentMe().execute(accountId)); +}); + +route.delete('/me/recovery-email', studentSession, async (c) => { + const { accountId } = currentStudent(c); + await new RemoveRecoveryEmail().execute(accountId); + return resultJson(c, await new GetStudentMe().execute(accountId)); +}); + +route.post('/recovery-email/confirm', validate.json(ConfirmRecoveryEmailSchema), async (c) => { + const { token } = c.req.valid('json') as ConfirmRecoveryEmailInput; + return resultJson(c, await new ConfirmRecoveryEmail().execute(token)); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/recovery-email/use-case.ts b/apps/backend/src/modules/student-portal/features/recovery-email/use-case.ts new file mode 100644 index 0000000..4bd12d1 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/recovery-email/use-case.ts @@ -0,0 +1,143 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { EMAIL_CONFIRMATION_TTL_HOURS, err, ok } from '@gruperly/shared'; +import { type EmailProvider, emailProvider } from '@/lib/email'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + consumeRateLimit, + generateAccessToken, + hashToken, + studentLinkInvalidProblem, + tooManyRequestsProblem, + webUrl, +} from '../../lib'; + +type RecoveryEmailDeps = { + db?: Pick; + unitOfWork?: Pick; + email?: Pick; + now?: Date; +}; + +const CONFIRMATIONS_PER_HOUR = 5; + +/* The student loads an optional recovery email. It stays "pending" until they + open the confirmation link: an unconfirmed address is never used to recover. */ +export class SetRecoveryEmail { + constructor(private readonly deps: RecoveryEmailDeps = {}) {} + + async execute(accountId: string, email: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const account = await db.studentAccount.findUniqueOrThrow({ + where: { id: accountId }, + select: { name: true, recoveryEmail: true }, + }); + if (account.recoveryEmail === email) { + await db.studentAccount.update({ where: { id: accountId }, data: { pendingRecoveryEmail: null } }); + return ok({ pending: false }); + } + + const allowed = await consumeRateLimit(db, `confirm-email:account:${accountId}`, { + limit: CONFIRMATIONS_PER_HOUR, + windowMs: 60 * 60 * 1000, + now, + }); + if (!allowed) return err(tooManyRequestsProblem()); + + const token = generateAccessToken(); + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + await unitOfWork.executeResult(async (tx) => { + await tx.studentAccessToken.updateMany({ + where: { accountId, kind: 'EMAIL_CONFIRMATION', usedAt: null, revokedAt: null }, + data: { revokedAt: now }, + }); + await tx.studentAccessToken.create({ + data: { + accountId, + kind: 'EMAIL_CONFIRMATION', + email, + tokenHash: hashToken(token), + expiresAt: new Date(now.getTime() + EMAIL_CONFIRMATION_TTL_HOURS * 60 * 60 * 1000), + }, + }); + await tx.studentAccount.update({ + where: { id: accountId }, + data: { pendingRecoveryEmail: email }, + }); + return ok(null); + }); + + const sender = this.deps.email ?? emailProvider; + try { + await sender.sendStudentEmailConfirmation({ + email, + name: account.name, + url: `${webUrl()}/access/email/${token}`, + }); + } catch (error) { + logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent'); + } + return ok({ pending: true }); + } +} + +export class RemoveRecoveryEmail { + constructor(private readonly deps: Pick = {}) {} + + async execute(accountId: string): Promise> { + const db = this.deps.db ?? prisma; + await db.studentAccessToken.updateMany({ + where: { accountId, kind: { in: ['EMAIL_CONFIRMATION', 'RECOVERY'] }, usedAt: null, revokedAt: null }, + data: { revokedAt: this.deps.now ?? new Date() }, + }); + await db.studentAccount.update({ + where: { id: accountId }, + data: { recoveryEmail: null, recoveryEmailVerifiedAt: null, pendingRecoveryEmail: null }, + }); + return ok(null); + } +} + +/* Public: the link may open in the mail app's browser, without the session. */ +export class ConfirmRecoveryEmail { + constructor(private readonly deps: Pick = {}) {} + + async execute(token: string): Promise> { + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + const now = this.deps.now ?? new Date(); + const tokenHash = hashToken(token); + + return unitOfWork.executeResult(async (tx) => { + const claimed = await tx.studentAccessToken.updateMany({ + where: { + tokenHash, + kind: 'EMAIL_CONFIRMATION', + usedAt: null, + revokedAt: null, + expiresAt: { gt: now }, + }, + data: { usedAt: now }, + }); + if (claimed.count !== 1) return err(studentLinkInvalidProblem()); + + const row = await tx.studentAccessToken.findUniqueOrThrow({ + where: { tokenHash }, + select: { accountId: true, email: true, account: { select: { pendingRecoveryEmail: true } } }, + }); + if (!row.email) return err(studentLinkInvalidProblem()); + + await tx.studentAccount.update({ + where: { id: row.accountId }, + data: { + recoveryEmail: row.email, + recoveryEmailVerifiedAt: now, + ...(row.account.pendingRecoveryEmail === row.email ? { pendingRecoveryEmail: null } : {}), + }, + }); + return ok({ email: row.email }); + }); + } +} diff --git a/apps/backend/src/modules/student-portal/features/request-recovery/route.ts b/apps/backend/src/modules/student-portal/features/request-recovery/route.ts new file mode 100644 index 0000000..da25cdf --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/request-recovery/route.ts @@ -0,0 +1,20 @@ +import { type RequestRecoveryLink as RequestRecoveryLinkInput, RequestRecoveryLinkSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { clientIp } from '../../lib'; +import { RequestRecoveryLink } from './use-case'; + +const route = new Hono(); + +route.post('/recovery', validate.json(RequestRecoveryLinkSchema), async (c) => { + const { email } = c.req.valid('json') as RequestRecoveryLinkInput; + const result = await new RequestRecoveryLink().execute({ email, ip: clientIp(c) }); + if (!result.ok) { + c.header('Retry-After', '900'); + return problemJson(c, result.error); + } + return c.json({ accepted: true }, 202); +}); + +export default route; diff --git a/apps/backend/src/modules/student-portal/features/request-recovery/use-case.ts b/apps/backend/src/modules/student-portal/features/request-recovery/use-case.ts new file mode 100644 index 0000000..3810a32 --- /dev/null +++ b/apps/backend/src/modules/student-portal/features/request-recovery/use-case.ts @@ -0,0 +1,88 @@ +import { createHash } from 'node:crypto'; +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok, RECOVERY_TTL_MINUTES } from '@gruperly/shared'; +import { type EmailProvider, emailProvider } from '@/lib/email'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + consumeRateLimit, + generateAccessToken, + hashToken, + studentLinkUrl, + tooManyRequestsProblem, +} from '../../lib'; + +type RequestRecoveryLinkDeps = { + db?: Pick; + email?: Pick; + /** Runs the lookup + send after answering, so the response time doesn't + * tell whether the email exists. Tests run it inline. */ + defer?: (task: () => Promise) => void; + now?: Date; +}; + +export const RECOVERY_LIMIT_PER_EMAIL = 3; +export const RECOVERY_LIMIT_PER_IP = 10; +const WINDOW_MS = 15 * 60 * 1000; + +function runInBackground(task: () => Promise) { + void task().catch((error) => logger.error({ error }, 'Student recovery link could not be sent')); +} + +/* "Pedir un link a mi mail". The answer is identical whether the email exists + or not; only the rate limit (3 per email and 10 per IP every 15 minutes, + counted the same for unknown emails) can say no. */ +export class RequestRecoveryLink { + constructor(private readonly deps: RequestRecoveryLinkDeps = {}) {} + + async execute(input: { email: string; ip: string | null }): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const ipAllowed = await consumeRateLimit(db, `recovery:ip:${input.ip ?? 'unknown'}`, { + limit: RECOVERY_LIMIT_PER_IP, + windowMs: WINDOW_MS, + now, + }); + if (!ipAllowed) return err(tooManyRequestsProblem()); + + const emailKey = createHash('sha256').update(input.email).digest('hex'); + const emailAllowed = await consumeRateLimit(db, `recovery:email:${emailKey}`, { + limit: RECOVERY_LIMIT_PER_EMAIL, + windowMs: WINDOW_MS, + now, + }); + if (!emailAllowed) return err(tooManyRequestsProblem()); + + (this.deps.defer ?? runInBackground)(() => this.send(db, input.email, now)); + return ok({ accepted: true }); + } + + private async send( + db: NonNullable, + email: string, + now: Date, + ): Promise { + const accounts = await db.studentAccount.findMany({ + where: { recoveryEmail: email, recoveryEmailVerifiedAt: { not: null } }, + select: { id: true, name: true }, + }); + if (accounts.length === 0) return; + + const links: { name: string; url: string }[] = []; + for (const account of accounts) { + const token = generateAccessToken(); + await db.studentAccessToken.create({ + data: { + accountId: account.id, + kind: 'RECOVERY', + tokenHash: hashToken(token), + expiresAt: new Date(now.getTime() + RECOVERY_TTL_MINUTES * 60 * 1000), + }, + }); + links.push({ name: account.name, url: studentLinkUrl(token) }); + } + await (this.deps.email ?? emailProvider).sendStudentRecoveryLinks({ email, links }); + } +} diff --git a/apps/backend/src/modules/student-portal/index.ts b/apps/backend/src/modules/student-portal/index.ts new file mode 100644 index 0000000..2bb96e0 --- /dev/null +++ b/apps/backend/src/modules/student-portal/index.ts @@ -0,0 +1 @@ +export { default as studentPortalRoutes } from './routes'; diff --git a/apps/backend/src/modules/student-portal/lib/access.ts b/apps/backend/src/modules/student-portal/lib/access.ts new file mode 100644 index 0000000..436f2ef --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/access.ts @@ -0,0 +1,34 @@ +import type { Prisma } from '@generated/prisma/client'; + +export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate }; + +/* The authorization rule of every student endpoint: an attendee (membership) + of a person linked to the session's account, with what the student screens + need from the group. The account is linked to the person, so every group + they are in shows up. null for anything else (or DROPPED; PAUSED keeps + access): routes answer 404, the same as for an id that doesn't exist. */ +export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) { + return db.attendee.findFirst({ + where: { + id: attendeeId, + status: { not: 'DROPPED' }, + person: { studentAccounts: { some: { accountId } } }, + }, + select: { + id: true, + groupId: true, + group: { + select: { + id: true, + name: true, + days: true, + time: true, + createdById: true, + owner: { select: { name: true, country: true, transferAlias: true, transferHolder: true } }, + }, + }, + }, + }); +} + +export type LinkedAttendee = NonNullable>>; diff --git a/apps/backend/src/modules/student-portal/lib/device.ts b/apps/backend/src/modules/student-portal/lib/device.ts new file mode 100644 index 0000000..45b7366 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/device.ts @@ -0,0 +1,31 @@ +/* Human-readable device from the user agent ("iPhone · Safari"), shown to the + teacher in "Acceso a la app". Best effort: never used for security. */ +export function describeDevice(userAgent: string | null | undefined): string { + const ua = userAgent ?? ''; + const platform = detectPlatform(ua); + const browser = detectBrowser(ua); + if (platform && browser) return `${platform} · ${browser}`; + return platform ?? browser ?? 'Dispositivo desconocido'; +} + +function detectPlatform(ua: string): string | null { + if (/iPhone/i.test(ua)) return 'iPhone'; + if (/iPad/i.test(ua)) return 'iPad'; + if (/Android/i.test(ua)) return /Mobile/i.test(ua) ? 'Android' : 'Tablet Android'; + if (/CrOS/i.test(ua)) return 'Chromebook'; + if (/Macintosh|Mac OS X/i.test(ua)) return 'Mac'; + if (/Windows/i.test(ua)) return 'Windows'; + if (/Linux/i.test(ua)) return 'Linux'; + return null; +} + +function detectBrowser(ua: string): string | null { + // Order matters: Edge, Opera and Samsung also say "Chrome"; every iOS browser says "Safari". + if (/EdgiOS|Edg\//i.test(ua)) return 'Edge'; + if (/OPR\/|OPiOS/i.test(ua)) return 'Opera'; + if (/SamsungBrowser/i.test(ua)) return 'Samsung Internet'; + if (/FxiOS|Firefox\//i.test(ua)) return 'Firefox'; + if (/CriOS|Chrome\//i.test(ua)) return 'Chrome'; + if (/Safari\//i.test(ua)) return 'Safari'; + return null; +} diff --git a/apps/backend/src/modules/student-portal/lib/index.ts b/apps/backend/src/modules/student-portal/lib/index.ts new file mode 100644 index 0000000..a914578 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/index.ts @@ -0,0 +1,9 @@ +export * from './access'; +export * from './device'; +export * from './problems'; +export * from './rate-limit'; +export * from './request'; +export * from './schedule'; +export * from './session'; +export * from './tokens'; +export * from './webauthn'; diff --git a/apps/backend/src/modules/student-portal/lib/problems.ts b/apps/backend/src/modules/student-portal/lib/problems.ts new file mode 100644 index 0000000..1fbdaaa --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/problems.ts @@ -0,0 +1,72 @@ +import type { ProblemDetails } from '@gruperly/shared'; +import { problemDetails } from '@/http/problem-details'; +import { PROBLEM_DOMAIN } from '@/http/problem-domain'; + +export function studentLinkInvalidProblem(): ProblemDetails { + return problemDetails({ + type: `${PROBLEM_DOMAIN}/problems/student-link-invalid`, + title: 'Gone', + status: 410, + detail: 'Este link ya fue usado o venció.', + code: 'student_link_invalid', + }); +} + +export function passkeyInvalidProblem(): ProblemDetails { + return problemDetails({ + type: `${PROBLEM_DOMAIN}/problems/passkey-invalid`, + title: 'Bad Request', + status: 400, + detail: 'No pudimos verificar la llave de acceso.', + code: 'passkey_invalid', + }); +} + +export function tooManyRequestsProblem(): ProblemDetails { + return problemDetails({ + type: `${PROBLEM_DOMAIN}/problems/too-many-requests`, + title: 'Too Many Requests', + status: 429, + detail: 'Hiciste muchos pedidos seguidos. Probá de nuevo en unos minutos.', + code: 'too_many_requests', + }); +} + +export function crossOriginProblem(): ProblemDetails { + return problemDetails({ + type: `${PROBLEM_DOMAIN}/problems/forbidden`, + title: 'Forbidden', + status: 403, + detail: 'Origen no permitido.', + code: 'cross_origin_request', + }); +} + +export function studentAttendeeNotFoundProblem(): ProblemDetails { + return problemDetails({ + title: 'Not Found', + status: 404, + detail: 'The requested resource was not found.', + code: 'not_found', + }); +} + +export function classAlreadyStartedProblem(): ProblemDetails { + return problemDetails({ + type: `${PROBLEM_DOMAIN}/problems/conflict`, + title: 'Conflict', + status: 409, + detail: 'La clase ya empezó: el aviso solo se puede dar o deshacer antes.', + code: 'class_already_started', + }); +} + +export function storageNotAvailableProblem(): ProblemDetails { + return problemDetails({ + type: `${PROBLEM_DOMAIN}/problems/service-unavailable`, + title: 'Service Unavailable', + status: 503, + detail: 'Por ahora no se pueden adjuntar comprobantes.', + code: 'storage_not_available', + }); +} diff --git a/apps/backend/src/modules/student-portal/lib/rate-limit.ts b/apps/backend/src/modules/student-portal/lib/rate-limit.ts new file mode 100644 index 0000000..aed7025 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/rate-limit.ts @@ -0,0 +1,19 @@ +import type { Prisma } from '@generated/prisma/client'; + +export type RateLimitDb = { rateLimitEvent: Prisma.RateLimitEventDelegate }; + +/* Sliding window counted in `rate_limit_events`: returns false (and records + nothing) once `key` reached `limit` hits inside the window. Old hits of the + same key are swept on the way. */ +export async function consumeRateLimit( + db: RateLimitDb, + key: string, + options: { limit: number; windowMs: number; now: Date }, +): Promise { + const windowStart = new Date(options.now.getTime() - options.windowMs); + await db.rateLimitEvent.deleteMany({ where: { key, createdAt: { lt: windowStart } } }); + const hits = await db.rateLimitEvent.count({ where: { key, createdAt: { gte: windowStart } } }); + if (hits >= options.limit) return false; + await db.rateLimitEvent.create({ data: { key, createdAt: options.now } }); + return true; +} diff --git a/apps/backend/src/modules/student-portal/lib/request.ts b/apps/backend/src/modules/student-portal/lib/request.ts new file mode 100644 index 0000000..7e13658 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/request.ts @@ -0,0 +1,19 @@ +import type { Context } from 'hono'; + +/* Client IP for the rate limit and the token audit. Each proxy appends to + X-Forwarded-For, so the client is the entry `TRUSTED_PROXY_HOPS` from the end + (1 = only our nginx; 2 = Traefik + nginx). Entries further left can be forged + by the client and are ignored. */ +export function clientIp(c: Context): string | null { + const hops = Math.max(1, Number(process.env.TRUSTED_PROXY_HOPS ?? 1) || 1); + const chain = (c.req.header('X-Forwarded-For') ?? '') + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean); + if (chain.length >= hops) return chain[chain.length - hops] ?? null; + return c.req.header('X-Real-IP') ?? null; +} + +export function userAgent(c: Context): string | null { + return c.req.header('User-Agent')?.slice(0, 512) ?? null; +} diff --git a/apps/backend/src/modules/student-portal/lib/schedule.ts b/apps/backend/src/modules/student-portal/lib/schedule.ts new file mode 100644 index 0000000..b73aaf1 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/schedule.ts @@ -0,0 +1,7 @@ +import { COUNTRY_TIME_ZONES, type CountryCode } from '@gruperly/shared'; +import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler'; + +// The class schedule runs on the teacher's clock (their country). +export function teacherTimeZone(country: string | null | undefined): string { + return (country && COUNTRY_TIME_ZONES[country as CountryCode]) || DEFAULT_TIME_ZONE; +} diff --git a/apps/backend/src/modules/student-portal/lib/session.ts b/apps/backend/src/modules/student-portal/lib/session.ts new file mode 100644 index 0000000..3b98ae4 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/session.ts @@ -0,0 +1,99 @@ +import type { Prisma } from '@generated/prisma/client'; +import { STUDENT_SESSION_TTL_DAYS } from '@gruperly/shared'; +import type { Context } from 'hono'; +import { deleteCookie, getCookie, setCookie } from 'hono/cookie'; +import { describeDevice } from './device'; +import { generateAccessToken, hashToken, webUrl } from './tokens'; + +export type StudentSessionDb = { studentSession: Prisma.StudentSessionDelegate }; + +const COOKIE_NAME = 'gruperly_student'; +const SESSION_TTL_MS = STUDENT_SESSION_TTL_DAYS * 24 * 60 * 60 * 1000; +// Sliding renewal is written at most once per hour, not on every request. +const TOUCH_INTERVAL_MS = 60 * 60 * 1000; + +// Its own cookie, never Better Auth's: a student session can't reach the +// teacher's endpoints and a teacher session can't reach the student's. +// With HTTPS it carries the `__Host-` prefix (Secure, Path=/, no Domain). +function isSecure(): boolean { + return webUrl().startsWith('https://'); +} + +export function readStudentSessionCookie(c: Context): string | undefined { + return isSecure() ? getCookie(c, COOKIE_NAME, 'host') : getCookie(c, COOKIE_NAME); +} + +export function writeStudentSessionCookie(c: Context, token: string): void { + setCookie(c, COOKIE_NAME, token, { + httpOnly: true, + secure: isSecure(), + sameSite: 'Lax', + path: '/', + maxAge: SESSION_TTL_MS / 1000, + ...(isSecure() ? { prefix: 'host' as const } : {}), + }); +} + +export function clearStudentSessionCookie(c: Context): void { + deleteCookie(c, COOKIE_NAME, { + path: '/', + secure: isSecure(), + ...(isSecure() ? { prefix: 'host' as const } : {}), + }); +} + +/* A brand-new identifier on every sign-in (link or passkey): sessions are never + reused or upgraded. Returns the raw token for the cookie. */ +export async function createStudentSession( + db: StudentSessionDb, + input: { accountId: string; userAgent: string | null | undefined; now: Date }, +): Promise { + const token = generateAccessToken(); + await db.studentSession.create({ + data: { + accountId: input.accountId, + tokenHash: hashToken(token), + device: describeDevice(input.userAgent), + createdAt: input.now, + lastUsedAt: input.now, + expiresAt: new Date(input.now.getTime() + SESSION_TTL_MS), + }, + }); + return token; +} + +export type ResolvedStudentSession = { + sessionId: string; + accountId: string; + /** The expiry moved forward: the cookie has to be written again. */ + renewed: boolean; +}; + +export async function resolveStudentSession( + db: StudentSessionDb, + token: string, + now: Date, +): Promise { + const session = await db.studentSession.findUnique({ where: { tokenHash: hashToken(token) } }); + if (!session || session.revokedAt || session.expiresAt <= now) return null; + + const renewed = now.getTime() - session.lastUsedAt.getTime() >= TOUCH_INTERVAL_MS; + if (renewed) { + await db.studentSession.update({ + where: { id: session.id }, + data: { lastUsedAt: now, expiresAt: new Date(now.getTime() + SESSION_TTL_MS) }, + }); + } + return { sessionId: session.id, accountId: session.accountId, renewed }; +} + +export async function revokeStudentSessionByToken( + db: StudentSessionDb, + token: string, + now: Date, +): Promise { + await db.studentSession.updateMany({ + where: { tokenHash: hashToken(token), revokedAt: null }, + data: { revokedAt: now }, + }); +} diff --git a/apps/backend/src/modules/student-portal/lib/tokens.ts b/apps/backend/src/modules/student-portal/lib/tokens.ts new file mode 100644 index 0000000..0103d21 --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/tokens.ts @@ -0,0 +1,19 @@ +import { createHash, randomBytes } from 'node:crypto'; + +// 32 bytes from the CSPRNG, base64url: what travels in links and cookies. +export function generateAccessToken(): string { + return randomBytes(32).toString('base64url'); +} + +// Only this goes to the database. +export function hashToken(token: string): string { + return createHash('sha256').update(token).digest('hex'); +} + +export function webUrl(): string { + return (process.env.WEB_URL ?? 'http://localhost:6173').replace(/\/$/, ''); +} + +export function studentLinkUrl(token: string): string { + return `${webUrl()}/i/${token}`; +} diff --git a/apps/backend/src/modules/student-portal/lib/webauthn.ts b/apps/backend/src/modules/student-portal/lib/webauthn.ts new file mode 100644 index 0000000..339195c --- /dev/null +++ b/apps/backend/src/modules/student-portal/lib/webauthn.ts @@ -0,0 +1,14 @@ +import { webUrl } from './tokens'; + +// Relying party: the web's host. Override them when the web is served from +// another origin than WEB_URL (e.g. a tunnel to test on a phone). +export function webauthnConfig() { + const origin = process.env.WEBAUTHN_ORIGIN || webUrl(); + return { + rpName: 'Gruperly', + rpID: process.env.WEBAUTHN_RP_ID || new URL(origin).hostname, + origin, + }; +} + +export const WEBAUTHN_CHALLENGE_TTL_MS = 5 * 60 * 1000; diff --git a/apps/backend/src/modules/student-portal/middleware.ts b/apps/backend/src/modules/student-portal/middleware.ts new file mode 100644 index 0000000..02b31ec --- /dev/null +++ b/apps/backend/src/modules/student-portal/middleware.ts @@ -0,0 +1,57 @@ +import type { Context, MiddlewareHandler } from 'hono'; +import type { BackendEnv, StudentContext } from '@/http/env'; +import { problemJson, unauthorizedProblem } from '@/http/problem-details'; +import prisma from '@/lib/prisma'; +import { + crossOriginProblem, + readStudentSessionCookie, + resolveStudentSession, + type StudentSessionDb, + webUrl, + writeStudentSessionCookie, +} from './lib'; + +const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); + +/* CSRF: besides SameSite=Lax, every state-changing request must come from the + web's origin. Browsers always send `Origin` on POST/PATCH/DELETE, so a + missing header is rejected too. */ +export const studentOriginGuard: MiddlewareHandler = async (c, next) => { + if (SAFE_METHODS.has(c.req.method)) { + await next(); + return; + } + const allowed = new Set([webUrl(), process.env.WEBAUTHN_ORIGIN].filter(Boolean)); + const origin = c.req.header('Origin'); + if (!origin || !allowed.has(origin)) { + return problemJson(c, crossOriginProblem()); + } + await next(); +}; + +export function requireStudentSession( + deps: { db?: StudentSessionDb; now?: () => Date } = {}, +): MiddlewareHandler { + return async (c, next) => { + const token = readStudentSessionCookie(c); + const session = token + ? await resolveStudentSession(deps.db ?? prisma, token, (deps.now ?? (() => new Date()))()) + : null; + if (!token || !session) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + // Sliding session: the cookie's Max-Age moves with the stored expiry. + if (session.renewed) writeStudentSessionCookie(c, token); + c.set('student', { accountId: session.accountId, sessionId: session.sessionId }); + await next(); + }; +} + +export const studentSession = requireStudentSession(); + +/** The signed-in student, on a route behind `studentSession`. */ +export function currentStudent(c: Context): StudentContext { + const student = c.get('student'); + if (!student) throw new Error('currentStudent() used on a route without studentSession'); + return student; +} diff --git a/apps/backend/src/modules/student-portal/routes.ts b/apps/backend/src/modules/student-portal/routes.ts new file mode 100644 index 0000000..cc30809 --- /dev/null +++ b/apps/backend/src/modules/student-portal/routes.ts @@ -0,0 +1,31 @@ +import { Hono } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import classesRoute from './features/classes/route'; +import consumeLinkRoute from './features/consume-link/route'; +import feesRoute from './features/fees/route'; +import linkInfoRoute from './features/link-info/route'; +import logoutRoute from './features/logout/route'; +import meRoute from './features/me/route'; +import passkeysRoute from './features/passkeys/route'; +import recoveryEmailRoute from './features/recovery-email/route'; +import requestRecoveryRoute from './features/request-recovery/route'; +import { studentOriginGuard } from './middleware'; + +/* Student API. Outside the teacher's session middleware (public prefix): each + private route declares `studentSession`, which only accepts the student + cookie. Every state-changing request passes the Origin check (CSRF). */ +const routes = new Hono(); + +routes.use('*', studentOriginGuard); + +routes.route('/', linkInfoRoute); +routes.route('/', consumeLinkRoute); +routes.route('/', requestRecoveryRoute); +routes.route('/', meRoute); +routes.route('/', logoutRoute); +routes.route('/', recoveryEmailRoute); +routes.route('/', passkeysRoute); +routes.route('/', classesRoute); +routes.route('/', feesRoute); + +export default routes; diff --git a/apps/backend/src/modules/students/features/get-all/route.ts b/apps/backend/src/modules/students/features/get-all/route.ts deleted file mode 100644 index 1a7db3b..0000000 --- a/apps/backend/src/modules/students/features/get-all/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { StudentQuery } from '@gruperly/shared'; -import { StudentQuerySchema } from '@gruperly/shared'; -import { Hono } from 'hono'; -import { resultJson } from '@/http/problem-details'; -import { validate } from '@/http/validate'; -import { ListStudents } from './use-case'; - -const route = new Hono(); - -route.get('/', validate.query(StudentQuerySchema), async (c) => { - const query = c.req.valid('query') as StudentQuery; - const useCase = new ListStudents(); - const result: Awaited> = await useCase.execute(query); - - return resultJson(c, result); -}); - -export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/students/features/get-all/use-case.ts b/apps/backend/src/modules/students/features/get-all/use-case.ts deleted file mode 100644 index e3e9b69..0000000 --- a/apps/backend/src/modules/students/features/get-all/use-case.ts +++ /dev/null @@ -1,58 +0,0 @@ -import type { PrismaClient } from '@generated/prisma/client'; -import type { ProblemDetails, Result, StudentDto, StudentList, StudentQuery } from '@gruperly/shared'; -import { ok } from '@gruperly/shared'; -import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; -import prisma from '@/lib/prisma'; - -type ListStudentsDeps = { - db?: Pick; -}; - -type StudentRecord = { - id: string; - groupId: string; - fullName: string; - email: string | null; - phone: string | null; - guardianName: string | null; - guardianPhone: string | null; - notes: string | null; - createdAt: Date; - updatedAt: Date; -}; - -function toStudentDto(record: StudentRecord): StudentDto { - return { - id: record.id, - groupId: record.groupId, - fullName: record.fullName, - email: record.email, - phone: record.phone, - guardianName: record.guardianName, - guardianPhone: record.guardianPhone, - notes: record.notes, - createdAt: record.createdAt.toISOString(), - updatedAt: record.updatedAt.toISOString(), - }; -} - -export class ListStudents { - constructor(private readonly deps: ListStudentsDeps = {}) {} - - async execute(query: StudentQuery): Promise> { - const db = this.deps.db ?? prisma; - const [records, total] = await Promise.all([ - db.student.findMany({ - skip: getPaginationOffset(query), - take: query.pageSize, - orderBy: { createdAt: 'desc' }, - }), - db.student.count(), - ]); - - return ok({ - data: records.map(toStudentDto), - pagination: getPaginationMetadata(query, total), - }); - } -} \ No newline at end of file diff --git a/apps/backend/src/modules/students/index.ts b/apps/backend/src/modules/students/index.ts deleted file mode 100644 index 008c587..0000000 --- a/apps/backend/src/modules/students/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default as studentsRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/whatsapp/features/callback/route.ts b/apps/backend/src/modules/whatsapp/features/callback/route.ts new file mode 100644 index 0000000..419d9d4 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/callback/route.ts @@ -0,0 +1,33 @@ +import type { WhatsappCallbackQuery } from '@gruperly/shared'; +import { WhatsappCallbackQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { validate } from '@/http/validate'; +import { logger } from '@/logger'; +import { getWebOrigin } from '@/modules/mp/lib'; +import { buildWhatsappReturnUrl, CompleteWhatsappSetup } from './use-case'; + +/** + * The browser arrives here from the provider's hosted linking (Kapso), so this + * route always redirects back to the app and never returns a problem body. + */ +const route = new Hono(); + +route.get('/', validate.query(WhatsappCallbackQuerySchema), async (c) => { + const query = c.req.valid('query') as WhatsappCallbackQuery; + + const user = c.get('user'); + if (!user) { + // Without a session there is nobody to credit the number to. + logger.warn('WhatsApp setup callback arrived without a session'); + return c.redirect(new URL('/login', getWebOrigin()).toString()); + } + + const outcome = await new CompleteWhatsappSetup().execute(user.id, query); + if (outcome.kind === 'error') { + logger.warn({ reason: outcome.reason }, 'WhatsApp setup callback failed'); + } + + return c.redirect(buildWhatsappReturnUrl(getWebOrigin(), query.returnTo, outcome)); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/callback/use-case.ts b/apps/backend/src/modules/whatsapp/features/callback/use-case.ts new file mode 100644 index 0000000..6573fb6 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/callback/use-case.ts @@ -0,0 +1,70 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { WhatsappCallbackReason, WhatsappReturnTo } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { activateWhatsappAccount } from '../../lib/activate-account'; +import { getMessagingProvider } from '../../providers'; +import type { MessagingProvider } from '../../providers/messaging-provider'; + +type CompleteWhatsappSetupDeps = { + db?: Pick; + provider?: MessagingProvider; + now?: () => Date; +}; + +export type WhatsappCallbackOutcome = + | { kind: 'success' } + | { kind: 'error'; reason: WhatsappCallbackReason }; + +/** + * Finishes a redirect-based linking (Kapso's setup link). Never fails as a + * `Result`: whatever happens, the browser is sent back to the app with an + * outcome it can show. + */ +export class CompleteWhatsappSetup { + constructor(private readonly deps: CompleteWhatsappSetupDeps = {}) {} + + async execute( + ownerId: string, + query: Record, + ): Promise { + const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider(); + if (!providerResult.ok) return failure('provider_error'); + const provider = providerResult.value; + if (!provider.completeRedirect) return failure('invalid_setup'); + + const db = this.deps.db ?? prisma; + const account = await db.whatsappAccount.findUnique({ where: { ownerId } }); + if (!account || account.provider !== provider.id) return failure('invalid_setup'); + + const completed = await provider.completeRedirect(account, query); + if (!completed.ok) return failure(completed.error); + + const activated = await activateWhatsappAccount( + db, + provider, + account, + completed.value, + this.deps.now?.() ?? new Date(), + ); + return activated.ok ? { kind: 'success' } : failure('number_in_use'); + } +} + +function failure(reason: WhatsappCallbackReason): WhatsappCallbackOutcome { + return { kind: 'error', reason }; +} + +/** + * Where the callback sends the teacher back to. `returnTo` comes from the + * validated enum, so this cannot become an open redirect. + */ +export function buildWhatsappReturnUrl( + webUrl: string, + returnTo: WhatsappReturnTo, + outcome: WhatsappCallbackOutcome, +): string { + const url = new URL(`/${returnTo}`, webUrl); + url.searchParams.set('wa', outcome.kind); + if (outcome.kind === 'error') url.searchParams.set('reason', outcome.reason); + return url.toString(); +} diff --git a/apps/backend/src/modules/whatsapp/features/connect/route.ts b/apps/backend/src/modules/whatsapp/features/connect/route.ts new file mode 100644 index 0000000..d83693c --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/connect/route.ts @@ -0,0 +1,21 @@ +import type { WhatsappConnect } from '@gruperly/shared'; +import { WhatsappConnectSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { StartWhatsappConnection } from './use-case'; + +const route = new Hono(); + +route.post('/', validate.json(WhatsappConnectSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const { returnTo } = c.req.valid('json') as WhatsappConnect; + + const useCase = new StartWhatsappConnection(); + const result = await useCase.execute({ id: user.id, name: user.name }, returnTo); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/connect/use-case.ts b/apps/backend/src/modules/whatsapp/features/connect/use-case.ts new file mode 100644 index 0000000..fddece2 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/connect/use-case.ts @@ -0,0 +1,63 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + WhatsappConnectResultDto, + WhatsappReturnTo, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { getMessagingProvider } from '../../providers'; +import type { MessagingProvider } from '../../providers/messaging-provider'; + +type StartWhatsappConnectionDeps = { + db?: Pick; + provider?: MessagingProvider; +}; + +/** + * Starts linking the teacher's WhatsApp with the active provider. The answer + * tells the browser how to continue: show a QR code or navigate away. + * + * Linking again (another number, another provider) reuses the same row: the + * account goes back to PENDING until the provider confirms the new link. + */ +export class StartWhatsappConnection { + constructor(private readonly deps: StartWhatsappConnectionDeps = {}) {} + + async execute( + owner: { id: string; name: string }, + returnTo: WhatsappReturnTo, + ): Promise> { + const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider(); + if (!providerResult.ok) return providerResult; + const provider = providerResult.value; + + const db = this.deps.db ?? prisma; + const account = await db.whatsappAccount.findUnique({ where: { ownerId: owner.id } }); + + const started = await provider.startConnection({ + ownerId: owner.id, + ownerName: owner.name, + returnTo, + account, + }); + if (!started.ok) return err(started.error); + + const data = { + provider: provider.id, + status: 'PENDING' as const, + externalId: started.value.externalId, + displayPhoneNumber: null, + providerData: started.value.providerData ?? undefined, + connectedAt: null, + }; + await db.whatsappAccount.upsert({ + where: { ownerId: owner.id }, + create: { ownerId: owner.id, ...data }, + update: data, + }); + + return ok({ start: started.value.start }); + } +} diff --git a/apps/backend/src/modules/whatsapp/features/disconnect/route.ts b/apps/backend/src/modules/whatsapp/features/disconnect/route.ts new file mode 100644 index 0000000..760565a --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/disconnect/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { DisconnectWhatsapp } from './use-case'; + +const route = new Hono(); + +route.delete('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new DisconnectWhatsapp(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/disconnect/use-case.ts b/apps/backend/src/modules/whatsapp/features/disconnect/use-case.ts new file mode 100644 index 0000000..b161de4 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/disconnect/use-case.ts @@ -0,0 +1,53 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, WhatsappDisconnectResultDto } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { getMessagingProvider } from '../../providers'; +import type { MessagingProvider } from '../../providers/messaging-provider'; + +type DisconnectWhatsappDeps = { + db?: Pick; + /** The provider the account was linked with; defaults to building it from the env. */ + provider?: MessagingProvider; +}; + +/** + * Unlinks the teacher's WhatsApp. The provider side is best effort (OpenWA logs + * the device out of the phone; Kapso keeps the number at Meta); locally the row + * is kept as DISCONNECTED with no number, so it frees the number for a relink + * while keeping provider references (the Kapso customer) for next time. + */ +export class DisconnectWhatsapp { + constructor(private readonly deps: DisconnectWhatsappDeps = {}) {} + + async execute(ownerId: string): Promise> { + const db = this.deps.db ?? prisma; + + const account = await db.whatsappAccount.findUnique({ where: { ownerId } }); + if (!account || account.status === 'DISCONNECTED') { + return ok({ disconnected: false }); + } + + const provider = this.deps.provider ?? resolveProvider(account.provider); + if (provider) { + const result = await provider.disconnect(account); + if (!result.ok) { + logger.warn({ code: result.error.code }, 'WhatsApp provider-side disconnect failed'); + } + } + + await db.whatsappAccount.update({ + where: { id: account.id }, + data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null }, + }); + + return ok({ disconnected: true }); + } +} + +/** The adapter the row was linked with, if this deployment can still build it. */ +function resolveProvider(id: 'OPENWA' | 'KAPSO'): MessagingProvider | null { + const result = getMessagingProvider(id); + return result.ok ? result.value : null; +} diff --git a/apps/backend/src/modules/whatsapp/features/pairing-code/route.ts b/apps/backend/src/modules/whatsapp/features/pairing-code/route.ts new file mode 100644 index 0000000..69f1b01 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/pairing-code/route.ts @@ -0,0 +1,21 @@ +import type { WhatsappPairingCode } from '@gruperly/shared'; +import { WhatsappPairingCodeSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { RequestWhatsappPairingCode } from './use-case'; + +const route = new Hono(); + +route.post('/', validate.json(WhatsappPairingCodeSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const { phoneNumber } = c.req.valid('json') as WhatsappPairingCode; + + const useCase = new RequestWhatsappPairingCode(); + const result = await useCase.execute(user.id, phoneNumber); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/pairing-code/use-case.ts b/apps/backend/src/modules/whatsapp/features/pairing-code/use-case.ts new file mode 100644 index 0000000..47ddeb3 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/pairing-code/use-case.ts @@ -0,0 +1,63 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, WhatsappPairingCodeDto } from '@gruperly/shared'; +import { countryCodeSchema, err, ok, toWhatsappE164 } from '@gruperly/shared'; +import { + validationProblem, + whatsappLinkingNotStartedProblem, + whatsappPairingUnsupportedProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { getMessagingProvider } from '../../providers'; +import type { MessagingProvider } from '../../providers/messaging-provider'; + +type RequestWhatsappPairingCodeDeps = { + db?: Pick; + provider?: MessagingProvider; +}; + +/** + * Links the teacher's WhatsApp by phone number instead of QR: WhatsApp shows a + * prompt on that phone and the teacher types the code we return. It is what + * makes linking possible from the phone the app is running on. + * + * The linking must have been started with `POST /whatsapp/connect` (the account + * is PENDING with a live session); the code completes that same linking, so the + * status polling and the webhook finish it as with a QR. + */ +export class RequestWhatsappPairingCode { + constructor(private readonly deps: RequestWhatsappPairingCodeDeps = {}) {} + + async execute( + ownerId: string, + phoneNumber: string, + ): Promise> { + const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider(); + if (!providerResult.ok) return providerResult; + const provider = providerResult.value; + if (!provider.requestPairingCode) return err(whatsappPairingUnsupportedProblem()); + + const db = this.deps.db ?? prisma; + const account = await db.whatsappAccount.findUnique({ where: { ownerId } }); + if (!account || account.provider !== provider.id || account.status !== 'PENDING') { + return err(whatsappLinkingNotStartedProblem()); + } + + // Typed the way people write their own number (`11 2345-6789`): the + // teacher's country settles the calling code, as for the attendees. + const owner = await db.user.findUnique({ where: { id: ownerId }, select: { country: true } }); + const country = countryCodeSchema.safeParse(owner?.country); + const e164 = toWhatsappE164(phoneNumber, country.success ? country.data : null); + if (!e164) { + return err( + validationProblem({ + detail: 'Revisá el número: escribilo con el código de área.', + errors: { phoneNumber: ['Número inválido'] }, + }), + ); + } + + const code = await provider.requestPairingCode(account, e164.slice(1)); + if (!code.ok) return code; + return ok({ pairingCode: code.value }); + } +} diff --git a/apps/backend/src/modules/whatsapp/features/status/route.ts b/apps/backend/src/modules/whatsapp/features/status/route.ts new file mode 100644 index 0000000..f090857 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/status/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetWhatsappStatus } from './use-case'; + +const route = new Hono(); + +route.get('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new GetWhatsappStatus(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/status/use-case.ts b/apps/backend/src/modules/whatsapp/features/status/use-case.ts new file mode 100644 index 0000000..7d392e2 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/status/use-case.ts @@ -0,0 +1,105 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + WhatsappReadiness, + WhatsappStatusDto, +} from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { toVisibleWhatsappStatus } from '../../lib/account'; +import { activateWhatsappAccount } from '../../lib/activate-account'; +import { getMessagingProvider } from '../../providers'; +import type { MessagingProvider, WhatsappAccountRecord } from '../../providers/messaging-provider'; + +type GetWhatsappStatusDeps = { + db?: Pick; + provider?: MessagingProvider; + now?: () => Date; +}; + +const BLOCKED: WhatsappStatusDto['readiness'] = { + PAYMENT_REMINDER: 'blocked', + REENGAGEMENT: 'blocked', +}; + +/** + * The teacher's WhatsApp, for Settings, the onboarding step and the group + * automations card. + * + * While a linking is PENDING this also asks the provider how it is going, so a + * QR linking completes (and the QR refreshes) by polling this endpoint alone, + * even where the provider's webhook cannot reach us (local development). + */ +export class GetWhatsappStatus { + constructor(private readonly deps: GetWhatsappStatusDeps = {}) {} + + async execute(ownerId: string): Promise> { + const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider(); + if (!providerResult.ok) return providerResult; + const provider = providerResult.value; + + const db = this.deps.db ?? prisma; + let account: WhatsappAccountRecord | null = await db.whatsappAccount.findUnique({ + where: { ownerId }, + }); + + if (!account) { + return ok(dto(provider, null, null, BLOCKED)); + } + + let qrCode: string | null = null; + if (account.provider === provider.id && account.status === 'PENDING') { + const snapshot = await provider.refreshConnection(account); + if (snapshot.ok) { + const live = snapshot.value; + if (live.state === 'pending') { + qrCode = live.qrCode; + } else if (live.state === 'active') { + const activated = await activateWhatsappAccount( + db, + provider, + account, + { displayPhoneNumber: live.displayPhoneNumber }, + this.deps.now?.() ?? new Date(), + ); + if (activated.ok) account = activated.account; + } else { + account = await db.whatsappAccount.update({ + where: { id: account.id }, + data: { status: 'DISCONNECTED' }, + }); + } + } + // A failed lookup is not an answer: report what we have and let the next + // poll try again. + } + + const readiness = + toVisibleWhatsappStatus(account, provider.id) === 'active' + ? { + PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'), + REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'), + } + : BLOCKED; + + return ok(dto(provider, account, qrCode, readiness)); + } +} + +function dto( + provider: MessagingProvider, + account: WhatsappAccountRecord & { connectedAt?: Date | null } | null, + qrCode: string | null, + readiness: Record<'PAYMENT_REMINDER' | 'REENGAGEMENT', WhatsappReadiness>, +): WhatsappStatusDto { + const status = toVisibleWhatsappStatus(account, provider.id); + return { + status, + provider: provider.id, + displayPhoneNumber: status === 'active' ? (account?.displayPhoneNumber ?? null) : null, + connectedAt: status === 'active' ? (account?.connectedAt?.toISOString() ?? null) : null, + qrCode, + readiness, + }; +} diff --git a/apps/backend/src/modules/whatsapp/features/update-automations/route.ts b/apps/backend/src/modules/whatsapp/features/update-automations/route.ts new file mode 100644 index 0000000..e93c375 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/update-automations/route.ts @@ -0,0 +1,21 @@ +import type { UpdateGroupAutomations } from '@gruperly/shared'; +import { UpdateGroupAutomationsSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { UpdateGroupAutomationsUseCase } from './use-case'; + +/** Mounted from `modules/groups/routes.ts`: `PATCH /groups/:groupId/automations`. */ +const route = new Hono(); + +route.patch('/:groupId/automations', validate.json(UpdateGroupAutomationsSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const input = c.req.valid('json') as UpdateGroupAutomations; + const useCase = new UpdateGroupAutomationsUseCase(); + const result = await useCase.execute(c.req.param('groupId'), user.id, input); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts b/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts new file mode 100644 index 0000000..cf9ae38 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts @@ -0,0 +1,71 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + GroupAutomationsDto, + ProblemDetails, + Result, + UpdateGroupAutomations, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; + +type UpdateGroupAutomationsDeps = { + db?: Pick; + planGuard?: Pick; +}; + +/** + * Turns the group's weekly WhatsApp automations on or off. Only the owner can: + * the messages go out from their own WhatsApp. + * + * Turning one on does not require a linked WhatsApp. The weekly job skips + * groups whose owner has nothing usable, and the UI explains why. + */ +export class UpdateGroupAutomationsUseCase { + constructor(private readonly deps: UpdateGroupAutomationsDeps = {}) {} + + async execute( + groupId: string, + userId: string, + input: UpdateGroupAutomations, + ): Promise> { + const db = this.deps.db ?? prisma; + + const group = await db.group.findUnique({ + where: { id: groupId }, + select: { id: true, createdById: true }, + }); + if (!group) return err(notFoundResourceProblem('Group', groupId)); + if (group.createdById !== userId) { + return err( + forbiddenProblem({ + detail: 'Solo quien creó el grupo puede cambiar sus automatizaciones.', + code: 'group_owner_required', + }), + ); + } + + // Turning them off always works, so a Free professor can clean up. + if (input.autoPaymentReminders === true || input.autoReengagement === true) { + const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( + userId, + 'whatsappAutomations', + ); + if (!allowed.ok) return allowed; + } + + const updated = await db.group.update({ + where: { id: groupId }, + data: { + ...(input.autoPaymentReminders !== undefined + ? { autoPaymentReminders: input.autoPaymentReminders } + : {}), + ...(input.autoReengagement !== undefined ? { autoReengagement: input.autoReengagement } : {}), + }, + select: { autoPaymentReminders: true, autoReengagement: true }, + }); + + return ok(updated); + } +} diff --git a/apps/backend/src/modules/whatsapp/features/webhook/route.ts b/apps/backend/src/modules/whatsapp/features/webhook/route.ts new file mode 100644 index 0000000..de15643 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/webhook/route.ts @@ -0,0 +1,32 @@ +import { Hono } from 'hono'; +import { logger } from '@/logger'; +import type { MessagingProviderId } from '../../providers/messaging-provider'; +import { HandleWhatsappWebhook } from './use-case'; + +const PROVIDERS: Record = { openwa: 'OPENWA', kapso: 'KAPSO' }; + +/** + * Public endpoint (see `isPublicApiRequest`): the provider calls it, not the + * browser, so there is no session. Authenticity comes from the HMAC signature, + * checked over the raw body before anything is parsed. Answers fast: Kapso + * retries a delivery that is not acknowledged within 10 seconds. + */ +const route = new Hono(); + +route.post('/:provider', async (c) => { + const providerId = PROVIDERS[c.req.param('provider')]; + if (!providerId) return c.body(null, 404); + + const rawBody = await c.req.text(); + const result = await new HandleWhatsappWebhook().execute(providerId, rawBody, c.req.raw.headers); + + if (!result.ok) { + logger.warn({ provider: providerId, reason: result.error }, 'WhatsApp webhook rejected'); + const status = result.error === 'invalid_signature' ? 401 : result.error === 'not_configured' ? 503 : 400; + return c.body(null, status); + } + + return c.json({ received: true, duplicate: result.value.duplicate }); +}); + +export default route; diff --git a/apps/backend/src/modules/whatsapp/features/webhook/use-case.ts b/apps/backend/src/modules/whatsapp/features/webhook/use-case.ts new file mode 100644 index 0000000..b173a11 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/features/webhook/use-case.ts @@ -0,0 +1,138 @@ +import type { OutboundMessageStatus, PrismaClient } from '@generated/prisma/client'; +import type { Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { activateWhatsappAccount } from '../../lib/activate-account'; +import { getMessagingProvider } from '../../providers'; +import type { + MessageDeliveryStatus, + MessagingProvider, + MessagingProviderId, + NormalizedEvent, +} from '../../providers/messaging-provider'; + +type HandleWhatsappWebhookDeps = { + db?: Pick; + provider?: MessagingProvider; + now?: () => Date; +}; + +export type WebhookFailure = 'not_configured' | 'invalid_signature' | 'invalid_payload'; + +/** Prisma's unique-constraint violation: this delivery was already processed. */ +const UNIQUE_VIOLATION = 'P2002'; + +/** + * States a message may move to from each state. Receipts can arrive out of + * order (a `read` before its `delivered`), so a late one never moves it back. + */ +const ADVANCES_FROM: Record = { + SENT: ['QUEUED'], + DELIVERED: ['QUEUED', 'SENT'], + READ: ['QUEUED', 'SENT', 'DELIVERED'], + FAILED: ['QUEUED', 'SENT', 'DELIVERED'], +}; + +/** + * Applies one provider webhook delivery: verify, dedupe, then reduce to the two + * things we track (the account's link and each message's delivery status). + */ +export class HandleWhatsappWebhook { + constructor(private readonly deps: HandleWhatsappWebhookDeps = {}) {} + + async execute( + providerId: MessagingProviderId, + rawBody: string, + headers: Headers, + ): Promise> { + const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider(providerId); + if (!providerResult.ok) return err('not_configured'); + const provider = providerResult.value; + + const parsed = provider.parseWebhook(rawBody, headers); + if (!parsed.ok) return err(parsed.error); + + const db = this.deps.db ?? prisma; + const dedupe = { provider: provider.id, dedupeKey: parsed.value.dedupeKey }; + + try { + await db.whatsappWebhookEvent.create({ data: dedupe }); + } catch (error) { + if ((error as { code?: string }).code === UNIQUE_VIOLATION) { + return ok({ duplicate: true, applied: 0 }); + } + throw error; + } + + try { + let applied = 0; + for (const event of parsed.value.events) { + applied += (await this.apply(db, provider, event)) ? 1 : 0; + } + return ok({ duplicate: false, applied }); + } catch (error) { + // Un-burn the key so the provider's retry gets another chance. + await db.whatsappWebhookEvent + .delete({ where: { provider_dedupeKey: dedupe } }) + .catch(() => undefined); + throw error; + } + } + + private async apply( + db: NonNullable, + provider: MessagingProvider, + event: NormalizedEvent, + ): Promise { + if (event.type === 'message_status') { + const result = await db.outboundMessage.updateMany({ + where: { + provider: provider.id, + providerMessageId: event.providerMessageId, + status: { in: ADVANCES_FROM[event.status] }, + }, + data: { + status: event.status, + ...(event.status === 'FAILED' + ? { errorCode: event.errorCode ?? 'delivery_failed', errorMessage: event.errorMessage ?? null } + : {}), + }, + }); + return result.count > 0; + } + + const account = + (await db.whatsappAccount.findFirst({ + where: { provider: provider.id, externalId: event.externalId }, + })) ?? + (event.ownerId + ? await db.whatsappAccount.findFirst({ + where: { provider: provider.id, ownerId: event.ownerId, status: { not: 'DISCONNECTED' } }, + }) + : null); + if (!account) return false; + + if (event.status === 'disconnected') { + if (account.status === 'DISCONNECTED') return false; + await db.whatsappAccount.update({ where: { id: account.id }, data: { status: 'DISCONNECTED' } }); + return true; + } + + const activated = await activateWhatsappAccount( + db, + provider, + account, + { + externalId: event.externalId, + displayPhoneNumber: event.displayPhoneNumber, + providerData: event.providerData, + }, + this.deps.now?.() ?? new Date(), + ); + if (!activated.ok) { + logger.warn({ provider: provider.id }, 'WhatsApp number already linked to another teacher'); + } + return activated.ok; + } +} diff --git a/apps/backend/src/modules/whatsapp/index.ts b/apps/backend/src/modules/whatsapp/index.ts new file mode 100644 index 0000000..9218ac9 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/index.ts @@ -0,0 +1,2 @@ +export { startWhatsappJobs } from './jobs'; +export { default as whatsappRoutes } from './routes'; diff --git a/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts b/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts new file mode 100644 index 0000000..9d6467d --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts @@ -0,0 +1,63 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared'; +import { countryCodeSchema } from '@gruperly/shared'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; +import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider'; + +export type EligibleGroup = { id: string; name: string }; + +export type EligibleAccount = { + account: WhatsappAccountRecord; + country: CountryCode | null; + groups: EligibleGroup[]; +}; + +type AutomationFlag = 'autoPaymentReminders' | 'autoReengagement'; + +/** + * Groups with the automation on, bundled by owner, keeping only owners whose + * WhatsApp is linked with the active provider and ready to send this kind of + * message (for Kapso: the template is approved) and whose plan includes the + * automations (Pro). A Free owner keeps the flag on but nothing goes out. + */ +export async function findEligibleAccounts( + db: Pick, + provider: MessagingProvider, + flag: AutomationFlag, + kind: WhatsappMessageKind, + planGuard: Pick = new PlanGuard(), +): Promise { + const groups = await db.group.findMany({ + where: { + [flag]: true, + owner: { whatsappAccount: { is: { provider: provider.id, status: 'ACTIVE' } } }, + }, + select: { + id: true, + name: true, + createdById: true, + owner: { select: { country: true, whatsappAccount: true } }, + }, + orderBy: { createdAt: 'asc' }, + }); + + const byOwner = new Map(); + for (const group of groups) { + const account = group.owner.whatsappAccount; + if (!account) continue; + let entry = byOwner.get(group.createdById); + if (!entry) { + const country = countryCodeSchema.safeParse(group.owner.country); + entry = { account, country: country.success ? country.data : null, groups: [] }; + byOwner.set(group.createdById, entry); + } + entry.groups.push({ id: group.id, name: group.name }); + } + + const eligible: EligibleAccount[] = []; + for (const [ownerId, entry] of byOwner) { + if (!(await planGuard.hasFeature(ownerId, 'whatsappAutomations'))) continue; + if ((await provider.readiness(entry.account, kind)) === 'ready') eligible.push(entry); + } + return eligible; +} diff --git a/apps/backend/src/modules/whatsapp/jobs/index.ts b/apps/backend/src/modules/whatsapp/jobs/index.ts new file mode 100644 index 0000000..a85cdef --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/index.ts @@ -0,0 +1,4 @@ +export { startWhatsappJobs } from './schedule'; +export { SendPaymentReminders } from './send-payment-reminders'; +export { SendReengagementMessages } from './send-reengagement-messages'; +export { SyncKapsoTemplates } from './sync-kapso-templates'; diff --git a/apps/backend/src/modules/whatsapp/jobs/schedule.ts b/apps/backend/src/modules/whatsapp/jobs/schedule.ts new file mode 100644 index 0000000..d96f387 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/schedule.ts @@ -0,0 +1,63 @@ +import { logger } from '@/logger'; +import { getActiveProviderId } from '../providers'; +import { SendPaymentReminders } from './send-payment-reminders'; +import { SendReengagementMessages } from './send-reengagement-messages'; +import { SyncKapsoTemplates } from './sync-kapso-templates'; + +/** Mondays 13:00 UTC = 10:00 in Argentina (UTC-3, no DST). */ +export const WEEKLY_MESSAGES_CRON = '0 13 * * 1'; +const TEMPLATE_SYNC_CRON = '*/30 * * * *'; + +/** + * Registers the WhatsApp jobs. Called once from `server.ts`, with the same + * guards as `startMpJobs`: Bun's cron turns a rejected promise into an + * unhandledRejection (which exits the process), and `unref` keeps the jobs from + * holding the process alive. + * + * Reminders run before re-engagement: if the gateway rate limits the account + * halfway, the message about money is the one that already went out. + */ +export function startWhatsappJobs(): void { + Bun.cron( + WEEKLY_MESSAGES_CRON, + async () => { + try { + const reminders = await new SendPaymentReminders().execute(); + logger.info(reminders, 'WhatsApp payment reminders finished'); + } catch (error) { + logger.error({ err: error }, 'WhatsApp payment reminders failed'); + } + try { + const reengagement = await new SendReengagementMessages().execute(); + logger.info(reengagement, 'WhatsApp re-engagement messages finished'); + } catch (error) { + logger.error({ err: error }, 'WhatsApp re-engagement messages failed'); + } + }, + { tz: 'UTC' }, + ).unref(); + + if (activeProviderIs('KAPSO')) { + Bun.cron( + TEMPLATE_SYNC_CRON, + async () => { + try { + const totals = await new SyncKapsoTemplates().execute(); + if (totals.checked > 0) logger.info(totals, 'Kapso template sync finished'); + } catch (error) { + logger.error({ err: error }, 'Kapso template sync failed'); + } + }, + { tz: 'UTC' }, + ).unref(); + } +} + +function activeProviderIs(id: 'OPENWA' | 'KAPSO'): boolean { + try { + return getActiveProviderId() === id; + } catch (error) { + logger.error({ err: error }, 'Invalid WHATSAPP_PROVIDER'); + return false; + } +} diff --git a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts new file mode 100644 index 0000000..bcb61c5 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts @@ -0,0 +1,118 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { contactPhone } from '@/modules/people/lib/people'; +import { + addTotals, + type DispatchItem, + type DispatchTotals, + dispatchForAccount, + emptyTotals, + sendIntervalFromEnv, + sleep, +} from '../lib/dispatch'; +import { formatAmount, formatDueDate } from '../lib/format'; +import { getMessagingProvider } from '../providers'; +import type { MessagingProvider } from '../providers/messaging-provider'; +import { findEligibleAccounts } from './eligible-accounts'; + +/** Only charges that are due within the coming week (or already overdue). */ +const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000; + +type SendPaymentRemindersDeps = { + db?: Pick; + provider?: MessagingProvider; + now?: Date; + intervalMs?: number; + sleep?: (ms: number) => Promise; +}; + +/** + * Weekly reminder to members with a PENDING or OVERDUE charge that already has + * a Checkout Pro link, in groups whose owner turned the automation on. + * + * One reminder per member per week even with several open charges: the oldest + * one goes in the message (the rest are in the same Cobros screen anyway). + */ +export class SendPaymentReminders { + constructor(private readonly deps: SendPaymentRemindersDeps = {}) {} + + async execute(): Promise { + const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider(); + if (!providerResult.ok) { + logger.warn('WhatsApp is not configured; payment reminders skipped'); + return emptyTotals(); + } + const provider = providerResult.value; + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const totals = emptyTotals(); + + const accounts = await findEligibleAccounts(db, provider, 'autoPaymentReminders', 'PAYMENT_REMINDER'); + + for (const { account, country, groups } of accounts) { + const items: DispatchItem[] = []; + + for (const group of groups) { + const payments = await db.payment.findMany({ + where: { + groupId: group.id, + status: { in: ['PENDING', 'OVERDUE'] }, + checkoutUrl: { not: null }, + dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) }, + attendee: { status: 'ACTIVE' }, + // Already reported by the student: the teacher is reviewing it. + reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } }, + }, + select: { + id: true, + amount: true, + currency: true, + dueDate: true, + checkoutUrl: true, + attendee: { + select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } }, + }, + }, + orderBy: { dueDate: 'asc' }, + }); + + const seen = new Set(); + for (const payment of payments) { + if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue; + seen.add(payment.attendee.id); + items.push({ + groupId: group.id, + attendeeId: payment.attendee.id, + paymentId: payment.id, + rawPhone: contactPhone(payment.attendee.person), + message: { + kind: 'PAYMENT_REMINDER', + studentName: payment.attendee.person.fullName, + groupName: group.name, + amount: formatAmount(Number(payment.amount.toString()), payment.currency, country), + dueDate: formatDueDate(payment.dueDate, country), + paymentLink: payment.checkoutUrl, + }, + }); + } + } + + const result = await dispatchForAccount( + { + db, + provider, + now, + intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(), + sleep: this.deps.sleep ?? sleep, + }, + account, + country, + items, + ); + addTotals(totals, result); + } + + return totals; + } +} diff --git a/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts new file mode 100644 index 0000000..a02d7a1 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts @@ -0,0 +1,107 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + findStudentsAtRisk, + type StudentsAtRiskDb, +} from '@/modules/analytics/features/get-students-at-risk/use-case'; +import { contactPhone } from '@/modules/people/lib/people'; +import { + addTotals, + type DispatchItem, + type DispatchTotals, + dispatchForAccount, + emptyTotals, + sendIntervalFromEnv, + sleep, +} from '../lib/dispatch'; +import { getMessagingProvider } from '../providers'; +import type { MessagingProvider } from '../providers/messaging-provider'; +import { findEligibleAccounts } from './eligible-accounts'; + +/** A member who got a re-engagement message is left alone for two weeks. */ +export const REENGAGEMENT_COOLDOWN_MS = 14 * 24 * 60 * 60 * 1000; + +type SendReengagementMessagesDeps = { + db?: Pick & StudentsAtRiskDb; + provider?: MessagingProvider; + now?: Date; + intervalMs?: number; + sleep?: (ms: number) => Promise; +}; + +/** + * Weekly re-engagement message to the members the teacher sees in "Alumnos en + * riesgo" (same rule, `findStudentsAtRisk`), in groups with the automation on. + */ +export class SendReengagementMessages { + constructor(private readonly deps: SendReengagementMessagesDeps = {}) {} + + async execute(): Promise { + const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider(); + if (!providerResult.ok) { + logger.warn('WhatsApp is not configured; re-engagement messages skipped'); + return emptyTotals(); + } + const provider = providerResult.value; + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const totals = emptyTotals(); + + const accounts = await findEligibleAccounts(db, provider, 'autoReengagement', 'REENGAGEMENT'); + + for (const { account, country, groups } of accounts) { + const items: DispatchItem[] = []; + + for (const group of groups) { + const atRisk = await findStudentsAtRisk(db, group.id, now); + if (atRisk.length === 0) continue; + const ids = atRisk.map((student) => student.attendeeId); + + const [recent, contacts] = await Promise.all([ + db.outboundMessage.findMany({ + where: { + kind: 'REENGAGEMENT', + attendeeId: { in: ids }, + status: { in: ['SENT', 'DELIVERED', 'READ'] }, + createdAt: { gte: new Date(now.getTime() - REENGAGEMENT_COOLDOWN_MS) }, + }, + select: { attendeeId: true }, + }), + db.attendee.findMany({ + where: { id: { in: ids } }, + select: { id: true, person: { select: { phone: true, guardianPhone: true } } }, + }), + ]); + const coolingDown = new Set(recent.map((row) => row.attendeeId)); + const phones = new Map(contacts.map((row) => [row.id, contactPhone(row.person)])); + + for (const student of atRisk) { + if (coolingDown.has(student.attendeeId)) continue; + items.push({ + groupId: group.id, + attendeeId: student.attendeeId, + rawPhone: phones.get(student.attendeeId) ?? null, + message: { kind: 'REENGAGEMENT', studentName: student.fullName, groupName: group.name }, + }); + } + } + + const result = await dispatchForAccount( + { + db, + provider, + now, + intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(), + sleep: this.deps.sleep ?? sleep, + }, + account, + country, + items, + ); + addTotals(totals, result); + } + + return totals; + } +} diff --git a/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts b/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts new file mode 100644 index 0000000..a11d1f7 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts @@ -0,0 +1,52 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { KapsoProvider } from '../providers'; +import { getKapsoConfig } from '../providers/kapso/config'; + +type SyncKapsoTemplatesDeps = { + db?: Pick; + provider?: KapsoProvider; +}; + +export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number }; + +/** How many templates each account should have (one per message kind). */ +const EXPECTED_TEMPLATES = 2; + +/** + * Meta reviews templates on its own schedule (up to ~24h) and Kapso documents + * no webhook for the verdict, so this polls the accounts that are still waiting. + * Accounts missing a template (a submission that failed) get it resubmitted. + */ +export class SyncKapsoTemplates { + constructor(private readonly deps: SyncKapsoTemplatesDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const provider = this.deps.provider ?? new KapsoProvider(getKapsoConfig(), { db }); + const totals: SyncKapsoTemplatesResult = { checked: 0, updated: 0, failed: 0 }; + + const accounts = await db.whatsappAccount.findMany({ + where: { provider: 'KAPSO', status: 'ACTIVE' }, + include: { templates: { select: { status: true } } }, + }); + + for (const account of accounts) { + const missing = account.templates.length < EXPECTED_TEMPLATES; + const pending = account.templates.some((template) => template.status === 'PENDING'); + if (!missing && !pending) continue; + + totals.checked += 1; + try { + if (missing) await provider.onConnected(account); + totals.updated += await provider.syncTemplates(account); + } catch (error) { + totals.failed += 1; + logger.warn({ err: error }, 'Kapso template sync failed for an account'); + } + } + + return totals; + } +} diff --git a/apps/backend/src/modules/whatsapp/lib/account.ts b/apps/backend/src/modules/whatsapp/lib/account.ts new file mode 100644 index 0000000..ddc3ae0 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/account.ts @@ -0,0 +1,43 @@ +import type { WhatsappAccountStatus } from '@gruperly/shared'; +import { getActiveProviderId } from '../providers/active'; +import type { MessagingProviderId } from '../providers/messaging-provider'; + +type AccountLike = { provider: MessagingProviderId; status: 'PENDING' | 'ACTIVE' | 'DISCONNECTED' }; + +/** + * A row linked through another gateway is useless after `WHATSAPP_PROVIDER` + * changes: the session or phone number id means nothing to the new one. It is + * kept (so nothing is lost if the switch is rolled back) and shown as + * "requires reconnect". + */ +export function toVisibleWhatsappStatus( + account: AccountLike | null, + activeProvider: MessagingProviderId = getActiveProviderId(), +): WhatsappAccountStatus { + if (!account) return 'none'; + if (account.provider !== activeProvider) { + return account.status === 'DISCONNECTED' ? 'none' : 'requires_reconnect'; + } + switch (account.status) { + case 'PENDING': + return 'pending'; + case 'ACTIVE': + return 'active'; + case 'DISCONNECTED': + return 'disconnected'; + } +} + +/** Whether automated messages can go out from this account at all. */ +export function isWhatsappAccountUsable( + account: AccountLike | null, + activeProvider?: MessagingProviderId, +): boolean { + if (!account) return false; + try { + return toVisibleWhatsappStatus(account, activeProvider) === 'active'; + } catch { + // A bad WHATSAPP_PROVIDER must not break the screens that only ask "linked?". + return false; + } +} diff --git a/apps/backend/src/modules/whatsapp/lib/activate-account.ts b/apps/backend/src/modules/whatsapp/lib/activate-account.ts new file mode 100644 index 0000000..ec79222 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/activate-account.ts @@ -0,0 +1,74 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import { logger } from '@/logger'; +import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider'; + +export type WhatsappAccountDb = Pick; + +/** Prisma's unique-constraint violation (here: the number is someone else's). */ +const UNIQUE_VIOLATION = 'P2002'; + +export type ActivationInput = { + externalId?: string | null; + displayPhoneNumber?: string | null; + providerData?: Record | null; +}; + +/** + * Marks the teacher's account ACTIVE and runs the provider's `onConnected`. + * + * The same activation arrives through three doors (the status poll, the Kapso + * callback and the webhooks) and possibly more than once; an account that is + * already ACTIVE is left alone so `onConnected` does not run on every poll. + */ +export async function activateWhatsappAccount( + db: WhatsappAccountDb, + provider: MessagingProvider, + account: WhatsappAccountRecord, + input: ActivationInput, + now: Date, +): Promise<{ ok: true; account: WhatsappAccountRecord } | { ok: false; reason: 'number_in_use' }> { + if (account.status === 'ACTIVE' && account.provider === provider.id) { + return { ok: true, account }; + } + + let updated: WhatsappAccountRecord; + try { + updated = await db.whatsappAccount.update({ + where: { id: account.id }, + data: { + status: 'ACTIVE', + connectedAt: now, + ...(input.externalId ? { externalId: input.externalId } : {}), + ...(input.displayPhoneNumber !== undefined ? { displayPhoneNumber: input.displayPhoneNumber } : {}), + ...(input.providerData + ? { providerData: mergeProviderData(account.providerData, input.providerData) } + : {}), + }, + }); + } catch (error) { + if ((error as { code?: string }).code === UNIQUE_VIOLATION) { + return { ok: false, reason: 'number_in_use' }; + } + throw error; + } + + if (provider.onConnected) { + try { + await provider.onConnected(updated); + } catch (error) { + // The account is linked either way; templates and webhooks are retried + // the next time the teacher links, and the sync job reports their state. + logger.error({ err: error, provider: provider.id }, 'WhatsApp post-connection setup failed'); + } + } + + return { ok: true, account: updated }; +} + +export function mergeProviderData( + current: unknown, + next: Record | null | undefined, +): Prisma.InputJsonObject { + const base = current && typeof current === 'object' && !Array.isArray(current) ? current : {}; + return { ...(base as Record), ...(next ?? {}) }; +} diff --git a/apps/backend/src/modules/whatsapp/lib/dispatch.ts b/apps/backend/src/modules/whatsapp/lib/dispatch.ts new file mode 100644 index 0000000..541003e --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/dispatch.ts @@ -0,0 +1,171 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared'; +import { toWhatsappE164 } from '@gruperly/shared'; +import { logger } from '@/logger'; +import type { + MessagingProvider, + WhatsappAccountRecord, + WhatsappMessage, +} from '../providers/messaging-provider'; +import { isoWeekKey } from './period'; + +export type DispatchDb = Pick; + +/** One message the weekly job wants to send to one member. */ +export type DispatchItem = { + groupId: string; + attendeeId: string; + paymentId?: string | null; + /** The member's phone, or their guardian's, as stored. */ + rawPhone: string | null; + message: WhatsappMessage; +}; + +export type DispatchTotals = { sent: number; skipped: number; failed: number }; + +export type DispatcherDeps = { + db: DispatchDb; + provider: MessagingProvider; + now: Date; + /** Pause between two sends from the same account. */ + intervalMs: number; + sleep: (ms: number) => Promise; +}; + +/** Prisma's unique-constraint violation: already handled this week. */ +const UNIQUE_VIOLATION = 'P2002'; + +export const DEFAULT_SEND_INTERVAL_MS = 5_000; + +export function sendIntervalFromEnv(): number { + const value = Number(process.env.WHATSAPP_SEND_INTERVAL_MS); + return Number.isFinite(value) && value >= 0 ? value : DEFAULT_SEND_INTERVAL_MS; +} + +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +export function emptyTotals(): DispatchTotals { + return { sent: 0, skipped: 0, failed: 0 }; +} + +export function addTotals(into: DispatchTotals, from: DispatchTotals): DispatchTotals { + into.sent += from.sent; + into.skipped += from.skipped; + into.failed += from.failed; + return into; +} + +/** + * Sends one account's messages, one after the other. + * + * Every message is first written to `outbound_messages` (QUEUED) and only then + * handed to the provider: the unique (kind, attendee, week) makes a second run + * of the job skip it, and the row id doubles as the provider's idempotency key, + * so a retried HTTP call cannot deliver twice either. + * + * Sends are paced (`intervalMs`) and stop for the whole account when the + * provider says it is rate limited: hammering an unofficial gateway is how a + * number gets banned. What was not sent stays for next week. + */ +export async function dispatchForAccount( + deps: DispatcherDeps, + account: WhatsappAccountRecord, + country: CountryCode | null, + items: DispatchItem[], +): Promise { + const totals = emptyTotals(); + const periodKey = isoWeekKey(deps.now); + let sentBefore = false; + + for (const item of items) { + const base = { + ownerId: account.ownerId, + groupId: item.groupId, + attendeeId: item.attendeeId, + paymentId: item.paymentId ?? null, + kind: item.message.kind as WhatsappMessageKind, + provider: deps.provider.id, + periodKey, + }; + + const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null; + if (!e164) { + await record(deps.db, { ...base, toPhone: item.rawPhone ?? '', status: 'SKIPPED', errorCode: 'invalid_phone' }); + totals.skipped += 1; + continue; + } + + const recipient = await deps.provider.resolveRecipient(account, e164); + if (!recipient.ok) { + if (recipient.code === 'no_whatsapp') { + await record(deps.db, { ...base, toPhone: e164, status: 'SKIPPED', errorCode: 'no_whatsapp' }); + totals.skipped += 1; + } else { + // No row: the gateway could not tell, so next week tries again. + totals.failed += 1; + } + continue; + } + + const row = await record(deps.db, { ...base, toPhone: e164, status: 'QUEUED' }); + if (!row) { + totals.skipped += 1; + continue; + } + + if (sentBefore && deps.intervalMs > 0) await deps.sleep(deps.intervalMs); + sentBefore = true; + + const outcome = await deps.provider.send(account, recipient.to, item.message, row.id); + if (outcome.ok) { + await deps.db.outboundMessage.update({ + where: { id: row.id }, + data: { status: 'SENT', providerMessageId: outcome.providerMessageId, sentAt: new Date() }, + }); + totals.sent += 1; + continue; + } + + if (outcome.rateLimitedForMs !== undefined) { + // Never sent: drop the row so this member is not marked as handled. + await deps.db.outboundMessage.delete({ where: { id: row.id } }); + totals.skipped += 1; + logger.warn( + { provider: deps.provider.id, retryInMs: outcome.rateLimitedForMs }, + 'WhatsApp account rate limited; stopping its sends for this run', + ); + break; + } + + await deps.db.outboundMessage.update({ + where: { id: row.id }, + data: { status: 'FAILED', errorCode: outcome.code, errorMessage: outcome.message.slice(0, 500) }, + }); + totals.failed += 1; + } + + return totals; +} + +type RecordInput = { + ownerId: string; + groupId: string; + attendeeId: string; + paymentId: string | null; + kind: WhatsappMessageKind; + provider: MessagingProvider['id']; + periodKey: string; + toPhone: string; + status: 'QUEUED' | 'SKIPPED'; + errorCode?: string; +}; + +/** Creates the log row, or returns null when this member was already handled this week. */ +async function record(db: DispatchDb, data: RecordInput): Promise<{ id: string } | null> { + try { + return await db.outboundMessage.create({ data, select: { id: true } }); + } catch (error) { + if ((error as { code?: string }).code === UNIQUE_VIOLATION) return null; + throw error; + } +} diff --git a/apps/backend/src/modules/whatsapp/lib/format.ts b/apps/backend/src/modules/whatsapp/lib/format.ts new file mode 100644 index 0000000..1e1defe --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/format.ts @@ -0,0 +1,42 @@ +import type { CountryCode } from '@gruperly/shared'; +import { COUNTRY_TIME_ZONES, DEFAULT_COUNTRY } from '@gruperly/shared'; + +/* Amounts and dates go inside a WhatsApp message, so they are formatted the way + people in the teacher's country write them (the student is there too). */ + +const LOCALES: Record = { + AR: 'es-AR', + BR: 'pt-BR', + CL: 'es-CL', + CO: 'es-CO', + MX: 'es-MX', + PE: 'es-PE', + UY: 'es-UY', +}; + +const TIME_ZONES = COUNTRY_TIME_ZONES; + +/** `25000` ARS → `$ 25.000`; cents only when there are any. */ +export function formatAmount( + amount: number, + currency: string, + country: CountryCode | null | undefined, +): string { + const hasCents = !Number.isInteger(amount); + return new Intl.NumberFormat(LOCALES[country ?? DEFAULT_COUNTRY], { + style: 'currency', + currency, + minimumFractionDigits: hasCents ? 2 : 0, + maximumFractionDigits: 2, + }).format(amount); +} + +/** Due date as day/month in the teacher's country, e.g. `10/11`. */ +export function formatDueDate(date: Date, country: CountryCode | null | undefined): string { + const resolved = country ?? DEFAULT_COUNTRY; + return new Intl.DateTimeFormat(LOCALES[resolved], { + day: '2-digit', + month: '2-digit', + timeZone: TIME_ZONES[resolved], + }).format(date); +} diff --git a/apps/backend/src/modules/whatsapp/lib/hmac.ts b/apps/backend/src/modules/whatsapp/lib/hmac.ts new file mode 100644 index 0000000..38d0e9a --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/hmac.ts @@ -0,0 +1,24 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +/** + * Constant-time check of an HMAC-SHA256 hex signature computed over the raw + * request body. It has to be the raw text: re-serializing the parsed JSON can + * reorder keys or change whitespace and the signature would never match. + * + * `prefix` covers providers that send `sha256=` (OpenWA) instead of the + * bare hex (Kapso). + */ +export function verifyHmacSha256( + rawBody: string, + signature: string | null | undefined, + secret: string, + prefix = '', +): boolean { + if (typeof signature !== 'string' || !signature) return false; + + const expected = prefix + createHmac('sha256', secret).update(rawBody).digest('hex'); + const received = Buffer.from(signature.trim()); + const wanted = Buffer.from(expected); + // `timingSafeEqual` throws on a length mismatch, so a forged short header fails first. + return received.length === wanted.length && timingSafeEqual(received, wanted); +} diff --git a/apps/backend/src/modules/whatsapp/lib/period.ts b/apps/backend/src/modules/whatsapp/lib/period.ts new file mode 100644 index 0000000..0c14d74 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/period.ts @@ -0,0 +1,16 @@ +/** + * ISO-8601 week of a date in UTC, e.g. `2026-W43`. + * + * It is the `periodKey` of an automated message: one message of each kind per + * member per week, enforced by a unique index, so a job that runs twice (two + * API instances, a manual re-run) cannot write to the same person twice. + */ +export function isoWeekKey(date: Date): string { + const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())); + // Thursday of the same week decides the ISO year. + const weekday = day.getUTCDay() || 7; + day.setUTCDate(day.getUTCDate() + 4 - weekday); + const yearStart = new Date(Date.UTC(day.getUTCFullYear(), 0, 1)); + const week = Math.ceil(((day.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7); + return `${day.getUTCFullYear()}-W${String(week).padStart(2, '0')}`; +} diff --git a/apps/backend/src/modules/whatsapp/lib/render-message.ts b/apps/backend/src/modules/whatsapp/lib/render-message.ts new file mode 100644 index 0000000..7494565 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/lib/render-message.ts @@ -0,0 +1,33 @@ +import type { WhatsappMessage } from '../providers/messaging-provider'; + +/** + * The Spanish copy of the automated messages, as free text. + * + * OpenWA sends exactly this. Kapso cannot (Meta only allows approved templates + * outside the 24h window), but its template bodies in `providers/kapso/templates.ts` + * are written from these same sentences: if one changes, change the other and + * submit a new template version. + */ +export function renderMessage(message: WhatsappMessage): string { + const firstName = firstNameOf(message.studentName); + + switch (message.kind) { + case 'PAYMENT_REMINDER': + return ( + `¡Hola ${firstName}! Te recordamos el pago de ${message.groupName} ` + + `por ${message.amount}, con vencimiento el ${message.dueDate}. ` + + `Podés pagarlo desde este link: ${message.paymentLink}` + ); + case 'REENGAGEMENT': + // Same copy the teacher sends by hand from "Alumnos en riesgo". + return ( + `¡Hola ${firstName}! 👋 Te extrañamos en ${message.groupName}. ` + + 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' + + 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.' + ); + } +} + +export function firstNameOf(fullName: string): string { + return fullName.trim().split(/\s+/)[0] ?? fullName; +} diff --git a/apps/backend/src/modules/whatsapp/providers/active.ts b/apps/backend/src/modules/whatsapp/providers/active.ts new file mode 100644 index 0000000..9f5d6f3 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/active.ts @@ -0,0 +1,19 @@ +import type { MessagingProviderId } from './messaging-provider'; + +const PROVIDERS: Record = { + openwa: 'OPENWA', + kapso: 'KAPSO', +}; + +/** + * The gateway this deployment sends through (`WHATSAPP_PROVIDER`, default + * `openwa`). An unknown value is a deployment mistake and fails loudly. + */ +export function getActiveProviderId(): MessagingProviderId { + const raw = process.env.WHATSAPP_PROVIDER?.trim().toLowerCase() || 'openwa'; + const id = PROVIDERS[raw]; + if (!id) { + throw new Error(`Unknown WHATSAPP_PROVIDER "${raw}". Use one of: ${Object.keys(PROVIDERS).join(', ')}.`); + } + return id; +} diff --git a/apps/backend/src/modules/whatsapp/providers/index.ts b/apps/backend/src/modules/whatsapp/providers/index.ts new file mode 100644 index 0000000..b71da22 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/index.ts @@ -0,0 +1,40 @@ +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { whatsappNotConfiguredProblem } from '@/http/problem-builders'; +import { logger } from '@/logger'; +import { getActiveProviderId } from './active'; +import { KapsoProvider } from './kapso'; +import { getKapsoConfig } from './kapso/config'; +import type { MessagingProvider, MessagingProviderId } from './messaging-provider'; +import { OpenWaProvider } from './openwa'; +import { getOpenWaConfig } from './openwa/config'; + +export { getActiveProviderId } from './active'; +export { KapsoProvider } from './kapso'; +export type * from './messaging-provider'; +export { OpenWaProvider } from './openwa'; + +/** + * The one place that maps a provider id to its adapter. Swapping gateways means + * changing `WHATSAPP_PROVIDER`; adding one means a new `providers//` that + * implements `MessagingProvider` plus a case here. + * + * A missing variable is answered as `whatsapp_not_configured` (503) instead of + * crashing, so the rest of the app (and the skippable onboarding step) keeps + * working on a deployment without WhatsApp. + */ +export function getMessagingProvider( + id?: MessagingProviderId, +): Result { + try { + switch (id ?? getActiveProviderId()) { + case 'OPENWA': + return ok(new OpenWaProvider(getOpenWaConfig())); + case 'KAPSO': + return ok(new KapsoProvider(getKapsoConfig())); + } + } catch (error) { + logger.error({ err: error }, 'WhatsApp messaging is not configured'); + return err(whatsappNotConfiguredProblem()); + } +} diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/config.ts b/apps/backend/src/modules/whatsapp/providers/kapso/config.ts new file mode 100644 index 0000000..cee671a --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/kapso/config.ts @@ -0,0 +1,47 @@ +export type KapsoConfig = { + /** `https://api.kapso.ai` unless overridden. */ + apiUrl: string; + /** Project API key, sent as `X-API-Key`. */ + apiKey: string; + /** Public URL of `/api/v1/whatsapp/callback` (setup link redirects). */ + callbackUrl: string; + /** Public URL of `/api/v1/whatsapp/webhooks/kapso`. */ + webhookUrl: string; + /** HMAC secret for the project webhook and every per-number webhook. */ + webhookSecret: string; +}; + +const DEFAULT_API_URL = 'https://api.kapso.ai'; + +/** + * Reads the Kapso settings. Throws on a deployment mistake, naming the missing + * variables (never their values), like `getMpOAuthConfig()`. + */ +export function getKapsoConfig(): KapsoConfig { + const missing: string[] = []; + const read = (name: string): string => { + const value = process.env[name]?.trim(); + if (!value) { + missing.push(name); + return ''; + } + return value; + }; + + const apiKey = read('KAPSO_API_KEY'); + const callbackUrl = read('KAPSO_CALLBACK_URL'); + const webhookUrl = read('KAPSO_WEBHOOK_URL'); + const webhookSecret = read('KAPSO_WEBHOOK_SECRET'); + + if (missing.length > 0) { + throw new Error(`Missing Kapso environment variables: ${missing.join(', ')}. See .env.example.`); + } + + return { + apiUrl: (process.env.KAPSO_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, ''), + apiKey, + callbackUrl, + webhookUrl, + webhookSecret, + }; +} diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/http.ts b/apps/backend/src/modules/whatsapp/providers/kapso/http.ts new file mode 100644 index 0000000..87bb430 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/kapso/http.ts @@ -0,0 +1,210 @@ +import type { KapsoConfig } from './config'; + +/** + * Thin client for Kapso: the Platform API (customers, setup links, phone + * numbers, webhooks) and the Meta proxy (templates, messages). Plain `fetch` + * on purpose: `@kapso/whatsapp-cloud-api` brings its own Zod, and this repo + * pins zod 3.24 (see AGENTS.md). + */ + +export const META_GRAPH_VERSION = 'v24.0'; + +export class KapsoApiError extends Error { + constructor( + readonly status: number, + /** Meta error code (e.g. `131047`) or Kapso's error string when there is one. */ + readonly code: string | null, + ) { + super(`Kapso request failed with ${status}${code ? ` (${code})` : ''}`); + this.name = 'KapsoApiError'; + } +} + +export type KapsoFetch = (input: string, init?: RequestInit) => Promise; + +export type KapsoPhoneNumber = { + phone_number_id: string; + business_account_id: string | null; + display_phone_number: string | null; + customer_id: string | null; + status?: string | null; +}; + +export type MetaTemplate = { + id: string; + name: string; + language?: string; + status: string; + category?: string; + rejected_reason?: string | null; +}; + +export type MetaTemplateComponent = { + type: 'BODY'; + text: string; + example?: { body_text_named_params: { param_name: string; example: string }[] }; +}; + +export type MetaTemplateDefinition = { + name: string; + language: string; + category: 'UTILITY' | 'MARKETING'; + parameter_format: 'NAMED'; + components: MetaTemplateComponent[]; +}; + +const REQUEST_TIMEOUT_MS = 30_000; + +export class KapsoClient { + constructor( + private readonly config: KapsoConfig, + private readonly fetchFn: KapsoFetch = (input, init) => fetch(input, init), + ) {} + + async createCustomer(input: { name: string; externalId: string }): Promise<{ id: string }> { + const response = await this.request<{ data: { id: string } }>('POST', '/platform/v1/customers', { + customer: { name: input.name, external_customer_id: input.externalId }, + }); + return response.data; + } + + async createSetupLink( + customerId: string, + input: { successRedirectUrl: string; failureRedirectUrl: string }, + ): Promise<{ id: string; url: string }> { + const response = await this.request<{ data: { id: string; url: string } }>( + 'POST', + `/platform/v1/customers/${encodeURIComponent(customerId)}/setup_links`, + { + setup_link: { + success_redirect_url: input.successRedirectUrl, + failure_redirect_url: input.failureRedirectUrl, + allowed_connection_types: ['coexistence', 'dedicated'], + // The teacher pays Meta from their own Business account. Fixed at + // creation: Kapso cannot change it on an existing link. + meta_billing_mode: 'customer_managed', + language: 'es', + }, + }, + ); + return response.data; + } + + async getPhoneNumber(phoneNumberId: string): Promise { + const response = await this.request<{ data: KapsoPhoneNumber }>( + 'GET', + `/platform/v1/whatsapp/phone_numbers/${encodeURIComponent(phoneNumberId)}`, + ); + return response.data; + } + + async createPhoneWebhook( + phoneNumberId: string, + input: { url: string; secret: string; events: string[] }, + ): Promise<{ id: string }> { + const response = await this.request<{ data: { id: string } }>( + 'POST', + `/platform/v1/whatsapp/phone_numbers/${encodeURIComponent(phoneNumberId)}/webhooks`, + { + whatsapp_webhook: { + url: input.url, + secret_key: input.secret, + events: input.events, + kind: 'kapso', + active: true, + }, + }, + ); + return response.data; + } + + createTemplate( + businessAccountId: string, + template: MetaTemplateDefinition, + ): Promise<{ id: string; status: string; category?: string }> { + return this.request( + 'POST', + `/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(businessAccountId)}/message_templates`, + template, + ); + } + + async listTemplates(businessAccountId: string, name?: string): Promise { + const query = name ? `?name=${encodeURIComponent(name)}` : ''; + const response = await this.request<{ data?: MetaTemplate[] }>( + 'GET', + `/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(businessAccountId)}/message_templates${query}`, + ); + return response.data ?? []; + } + + async sendTemplate( + phoneNumberId: string, + input: { + to: string; + name: string; + language: string; + parameters: { name: string; text: string }[]; + }, + ): Promise<{ messageId: string }> { + const response = await this.request<{ messages?: { id: string }[] }>( + 'POST', + `/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(phoneNumberId)}/messages`, + { + messaging_product: 'whatsapp', + to: input.to, + type: 'template', + template: { + name: input.name, + language: { code: input.language }, + components: [ + { + type: 'body', + parameters: input.parameters.map((parameter) => ({ + type: 'text', + parameter_name: parameter.name, + text: parameter.text, + })), + }, + ], + }, + }, + ); + const messageId = response.messages?.[0]?.id; + if (!messageId) throw new KapsoApiError(502, 'missing_message_id'); + return { messageId }; + } + + private async request(method: string, path: string, body?: unknown): Promise { + const response = await this.fetchFn(`${this.config.apiUrl}${path}`, { + method, + headers: { + 'X-API-Key': this.config.apiKey, + Accept: 'application/json', + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as { + error?: { code?: unknown; error_subcode?: unknown } | string; + code?: unknown; + } | null; + throw new KapsoApiError(response.status, errorCode(payload)); + } + + if (response.status === 204) return undefined as T; + return (await response.json()) as T; + } +} + +function errorCode( + payload: { error?: { code?: unknown } | string; code?: unknown } | null, +): string | null { + if (!payload) return null; + if (typeof payload.error === 'string') return payload.error; + const code = payload.error?.code ?? payload.code; + return code === undefined || code === null ? null : String(code); +} diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/index.ts b/apps/backend/src/modules/whatsapp/providers/kapso/index.ts new file mode 100644 index 0000000..6f408ad --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/kapso/index.ts @@ -0,0 +1,436 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + WhatsappCallbackReason, + WhatsappMessageKind, + WhatsappReadiness, +} from '@gruperly/shared'; +import { err, ok, whatsappMessageKindSchema } from '@gruperly/shared'; +import { whatsappProviderErrorProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { verifyHmacSha256 } from '../../lib/hmac'; +import type { + CompletedConnection, + ConnectionSnapshot, + MessageDeliveryStatus, + MessagingProvider, + NormalizedEvent, + ParsedWebhook, + RecipientResolution, + SendOutcome, + StartConnectionContext, + StartConnectionResult, + WebhookParseError, + WhatsappAccountRecord, + WhatsappMessage, +} from '../messaging-provider'; +import type { KapsoConfig } from './config'; +import { KapsoApiError, KapsoClient, type KapsoFetch } from './http'; +import { KAPSO_TEMPLATES, TEMPLATE_LANGUAGE, toTemplateStatus } from './templates'; + +/** Message events each connected number reports to our webhook. */ +export const KAPSO_MESSAGE_EVENTS = [ + 'whatsapp.message.sent', + 'whatsapp.message.delivered', + 'whatsapp.message.read', + 'whatsapp.message.failed', +]; + +/** + * Errors where repeating the same send cannot help: 402 out of credits (only + * with partner billing), 131047 outside the 24h window (templates avoid it), + * the student opting out of marketing, or a number/account mismatch. + */ +const PERMANENT_SEND_ERRORS = new Set([ + '131047', + '131050', + 'marketing_preference_stopped', + 'messaging_account_mismatch', + 'insufficient_credits', +]); + +export type KapsoProviderData = { + customerId?: string; + setupLinkId?: string; + businessAccountId?: string; + webhookId?: string; +}; + +type KapsoProviderDeps = { + db?: Pick; + fetch?: KapsoFetch; +}; + +/** + * Kapso, on top of Meta's official WhatsApp Cloud API. + * + * Linking is a hosted flow: we create a Kapso customer for the teacher, send + * them to a setup link (Facebook login + number verification at Meta) and + * Kapso redirects back to our callback. Messages outside a conversation must + * be approved templates, which Meta reviews per WhatsApp Business Account, so + * a freshly linked account sends nothing until its templates are APPROVED. + */ +export class KapsoProvider implements MessagingProvider { + readonly id = 'KAPSO' as const; + private readonly client: KapsoClient; + + constructor( + private readonly config: KapsoConfig, + private readonly deps: KapsoProviderDeps = {}, + ) { + this.client = new KapsoClient(config, deps.fetch); + } + + private get db() { + return this.deps.db ?? prisma; + } + + async startConnection( + context: StartConnectionContext, + ): Promise> { + const previous = context.account?.provider === 'KAPSO' ? readData(context.account.providerData) : {}; + + try { + // One Kapso customer per teacher, reused when they link again. + const customerId = + previous.customerId ?? + (await this.client.createCustomer({ name: context.ownerName, externalId: context.ownerId })).id; + + const returnUrl = `${this.config.callbackUrl}?returnTo=${context.returnTo}`; + const link = await this.client.createSetupLink(customerId, { + successRedirectUrl: returnUrl, + failureRedirectUrl: returnUrl, + }); + + return ok({ + start: { type: 'redirect', url: link.url }, + externalId: null, + providerData: { customerId, setupLinkId: link.id }, + }); + } catch (error) { + logger.error({ err: describe(error) }, 'Kapso could not create a setup link'); + return err(whatsappProviderErrorProblem()); + } + } + + async refreshConnection( + account: WhatsappAccountRecord, + ): Promise> { + // A Kapso linking happens at Meta; there is no QR to refresh. Until the + // callback (or the `phone_number.created` webhook) lands it is just pending. + if (account.status === 'ACTIVE') { + return ok({ state: 'active', displayPhoneNumber: account.displayPhoneNumber }); + } + return ok({ state: 'pending', qrCode: null }); + } + + async completeRedirect( + account: WhatsappAccountRecord, + query: Record, + ): Promise> { + const data = readData(account.providerData); + + // Nothing in this query is trusted: anyone can type a URL. The setup link + // has to be the one we created for this teacher, and Kapso itself has to + // confirm that the number belongs to this teacher's customer. + if (!query.setup_link_id || query.setup_link_id !== data.setupLinkId || !data.customerId) { + return err('invalid_setup'); + } + if (query.error_code || (query.status && query.status !== 'completed')) { + return err('setup_failed'); + } + if (!query.phone_number_id) return err('invalid_setup'); + + try { + const phone = await this.client.getPhoneNumber(query.phone_number_id); + if (phone.customer_id !== data.customerId) return err('invalid_setup'); + + return ok({ + externalId: phone.phone_number_id, + displayPhoneNumber: formatPhone(phone.display_phone_number), + providerData: { + ...compact(data), + ...(phone.business_account_id ? { businessAccountId: phone.business_account_id } : {}), + }, + }); + } catch (error) { + logger.error({ err: describe(error) }, 'Kapso phone number lookup failed'); + return err('provider_error'); + } + } + + async disconnect(): Promise> { + // The number stays connected to the teacher's WhatsApp Business Account at + // Meta (they manage it there); unlinking here only stops Gruperly from + // sending through it. The Kapso customer is kept for a later relink. + return ok(undefined); + } + + /** + * Subscribes our webhook to the number and submits the templates. Safe to run + * again: what already exists is skipped. + */ + async onConnected(account: WhatsappAccountRecord): Promise { + if (!account.externalId) return; + const data = readData(account.providerData); + + if (!data.businessAccountId) { + const phone = await this.client.getPhoneNumber(account.externalId); + if (phone.business_account_id) data.businessAccountId = phone.business_account_id; + } + + if (!data.webhookId) { + try { + const webhook = await this.client.createPhoneWebhook(account.externalId, { + url: this.config.webhookUrl, + secret: this.config.webhookSecret, + events: KAPSO_MESSAGE_EVENTS, + }); + data.webhookId = webhook.id; + } catch (error) { + // Only delivery receipts depend on it; sending still works. + logger.warn({ err: describe(error) }, 'Kapso per-number webhook registration failed'); + } + } + + await this.db.whatsappAccount.update({ + where: { id: account.id }, + data: { providerData: compact(data) }, + }); + + if (data.businessAccountId) { + await this.submitTemplates(account.id, data.businessAccountId); + } + } + + async readiness( + account: WhatsappAccountRecord, + kind: WhatsappMessageKind, + ): Promise { + if (account.status !== 'ACTIVE') return 'blocked'; + const template = await this.db.whatsappTemplate.findUnique({ + where: { accountId_kind: { accountId: account.id, kind } }, + }); + if (!template || template.status === 'PENDING') return 'pending'; + return template.status === 'APPROVED' ? 'ready' : 'blocked'; + } + + async resolveRecipient(_account: WhatsappAccountRecord, e164: string): Promise { + // The Cloud API takes the E.164 digits; it reports unknown numbers on send. + return { ok: true, to: e164.replace(/\D/g, '') }; + } + + async send( + account: WhatsappAccountRecord, + to: string, + message: WhatsappMessage, + ): Promise { + if (!account.externalId) { + return { ok: false, retryable: false, code: 'no_phone_number', message: 'Account has no number' }; + } + const spec = KAPSO_TEMPLATES[message.kind]; + + try { + const response = await this.client.sendTemplate(account.externalId, { + to, + name: spec.definition.name, + language: TEMPLATE_LANGUAGE, + parameters: spec.parameters(message), + }); + return { ok: true, providerMessageId: response.messageId }; + } catch (error) { + if (error instanceof KapsoApiError) { + const permanent = + error.status === 402 || + (error.code !== null && PERMANENT_SEND_ERRORS.has(error.code)) || + (error.status >= 400 && error.status < 500 && error.status !== 409 && error.status !== 429); + return { + ok: false, + retryable: !permanent, + ...(error.status === 429 ? { rateLimitedForMs: 60_000 } : {}), + code: error.code ?? `http_${error.status}`, + message: error.message, + }; + } + return { ok: false, retryable: true, code: 'network_error', message: describe(error).message }; + } + } + + parseWebhook(rawBody: string, headers: Headers): Result { + if (!verifyHmacSha256(rawBody, headers.get('X-Webhook-Signature'), this.config.webhookSecret)) { + return err('invalid_signature'); + } + + let payload: unknown; + try { + payload = JSON.parse(rawBody); + } catch { + return err('invalid_payload'); + } + + const dedupeKey = headers.get('X-Idempotency-Key'); + if (!dedupeKey) return err('invalid_payload'); + + // Batched deliveries (`X-Webhook-Batch`) carry the events in `data[]`. + const headerEvent = headers.get('X-Webhook-Event'); + const items = isRecord(payload) && Array.isArray(payload.data) ? payload.data : [payload]; + const events = items.flatMap((item) => (isRecord(item) ? toEvents(item, headerEvent) : [])); + + return ok({ dedupeKey, events }); + } + + /** Pulls Meta's verdict for the account's pending templates. */ + async syncTemplates(account: WhatsappAccountRecord): Promise { + const data = readData(account.providerData); + if (!data.businessAccountId) return 0; + + const pending = await this.db.whatsappTemplate.findMany({ + where: { accountId: account.id, status: 'PENDING' }, + }); + let updated = 0; + for (const template of pending) { + const [remote] = await this.client.listTemplates(data.businessAccountId, template.name); + if (!remote) continue; + const status = toTemplateStatus(remote.status); + if (status === template.status) continue; + await this.db.whatsappTemplate.update({ + where: { id: template.id }, + data: { status, metaTemplateId: remote.id, rejectedReason: remote.rejected_reason ?? null }, + }); + updated += 1; + } + return updated; + } + + private async submitTemplates(accountId: string, businessAccountId: string): Promise { + for (const kind of whatsappMessageKindSchema.options) { + const existing = await this.db.whatsappTemplate.findUnique({ + where: { accountId_kind: { accountId, kind } }, + }); + if (existing) continue; + + const { definition } = KAPSO_TEMPLATES[kind]; + let remote: { id: string; status: string } | null = null; + try { + remote = await this.client.createTemplate(businessAccountId, definition); + } catch (error) { + // Relinking the same Business Account: the template is already there. + const [found] = await this.client.listTemplates(businessAccountId, definition.name).catch(() => []); + if (!found) { + logger.error({ err: describe(error), kind }, 'Kapso template submission failed'); + continue; + } + remote = found; + } + + await this.db.whatsappTemplate.create({ + data: { + accountId, + kind, + name: definition.name, + language: definition.language, + metaTemplateId: remote.id, + status: toTemplateStatus(remote.status), + }, + }); + } + } +} + +const MESSAGE_STATUSES: Record = { + 'whatsapp.message.sent': 'SENT', + 'whatsapp.message.delivered': 'DELIVERED', + 'whatsapp.message.read': 'READ', + 'whatsapp.message.failed': 'FAILED', +}; + +function toEvents(item: Record, headerEvent: string | null): NormalizedEvent[] { + const event = headerEvent ?? (typeof item.event === 'string' ? item.event : null); + if (!event) return []; + + const phoneNumberId = stringAt(item, 'phone_number_id') ?? stringAt(item, 'phone_number', 'phone_number_id'); + + if (event === 'whatsapp.phone_number.created') { + if (!phoneNumberId) return []; + const businessAccountId = stringAt(item, 'business_account_id'); + return [ + { + type: 'connection', + externalId: phoneNumberId, + ownerId: stringAt(item, 'customer', 'external_id') ?? undefined, + status: 'active', + displayPhoneNumber: formatPhone(stringAt(item, 'display_phone_number')), + providerData: businessAccountId ? { businessAccountId } : null, + }, + ]; + } + + if ( + event === 'whatsapp.phone_number.deleted' || + event === 'whatsapp.phone_number.disconnected' || + event === 'whatsapp.phone_number.offboarded' + ) { + return phoneNumberId ? [{ type: 'connection', externalId: phoneNumberId, status: 'disconnected' }] : []; + } + + const status = MESSAGE_STATUSES[event]; + const messageId = stringAt(item, 'message', 'id'); + if (!status || !messageId) return []; + + const errors = (isRecord(item.message) && isRecord(item.message.kapso) && Array.isArray(item.message.kapso.statuses) + ? item.message.kapso.statuses + : [] + ).flatMap((entry) => (isRecord(entry) && Array.isArray(entry.errors) ? entry.errors : [])); + const firstError = errors.find(isRecord); + + return [ + { + type: 'message_status', + providerMessageId: messageId, + status, + errorCode: status === 'FAILED' ? (firstError?.code != null ? String(firstError.code) : 'delivery_failed') : null, + errorMessage: + status === 'FAILED' && typeof firstError?.title === 'string' ? firstError.title : null, + }, + ]; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function stringAt(value: Record, ...path: string[]): string | null { + let current: unknown = value; + for (const key of path) { + if (!isRecord(current)) return null; + current = current[key]; + } + return typeof current === 'string' && current ? current : null; +} + +function readData(value: unknown): KapsoProviderData { + return isRecord(value) ? { ...(value as KapsoProviderData) } : {}; +} + +function compact(data: KapsoProviderData): Record { + return Object.fromEntries( + Object.entries(data).filter((entry): entry is [string, string] => typeof entry[1] === 'string'), + ); +} + +function formatPhone(phone: string | null | undefined): string | null { + if (!phone) return null; + const digits = phone.replace(/\D/g, ''); + return digits ? `+${digits}` : null; +} + +function describe(error: unknown): { name: string; message: string; status?: number } { + if (error instanceof KapsoApiError) { + return { name: error.name, message: error.message, status: error.status }; + } + return error instanceof Error + ? { name: error.name, message: error.message } + : { name: 'Unknown', message: String(error) }; +} diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts b/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts new file mode 100644 index 0000000..30e1b15 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts @@ -0,0 +1,104 @@ +import type { WhatsappMessageKind } from '@gruperly/shared'; +import { firstNameOf } from '../../lib/render-message'; +import type { WhatsappMessage } from '../messaging-provider'; +import type { MetaTemplateDefinition } from './http'; + +/** + * The message templates submitted to Meta for each teacher's WhatsApp Business + * Account. Their bodies follow `lib/render-message.ts` (the OpenWA copy). + * + * Rules Meta enforces and that are easy to break: + * - A submitted template cannot be edited. Changing the copy means a new name + * (`gruperly_payment_reminder_v2`) and a new approval round. + * - The payment reminder stays UTILITY only while it has no promotional + * content; anything that sells turns it into MARKETING (and Meta may + * re-categorize it on its own). + * - The body cannot start or end with a variable. + */ +export const TEMPLATE_LANGUAGE = 'es_AR'; + +type TemplateSpec = { + definition: MetaTemplateDefinition; + parameters: (message: WhatsappMessage) => { name: string; text: string }[]; +}; + +export const KAPSO_TEMPLATES: Record = { + PAYMENT_REMINDER: { + definition: { + name: 'gruperly_payment_reminder', + language: TEMPLATE_LANGUAGE, + category: 'UTILITY', + parameter_format: 'NAMED', + components: [ + { + type: 'BODY', + text: + '¡Hola {{student_name}}! Te recordamos el pago de {{group_name}} por {{amount}}, ' + + 'con vencimiento el {{due_date}}. Podés pagarlo desde este link: {{payment_link}} ¡Gracias!', + example: { + body_text_named_params: [ + { param_name: 'student_name', example: 'Ana' }, + { param_name: 'group_name', example: 'Yoga Martes y Jueves' }, + { param_name: 'amount', example: '$ 25.000' }, + { param_name: 'due_date', example: '10/11' }, + { param_name: 'payment_link', example: 'https://mpago.la/2xYz123' }, + ], + }, + }, + ], + }, + parameters: (message) => + message.kind === 'PAYMENT_REMINDER' + ? [ + { name: 'student_name', text: firstNameOf(message.studentName) }, + { name: 'group_name', text: message.groupName }, + { name: 'amount', text: message.amount }, + { name: 'due_date', text: message.dueDate }, + { name: 'payment_link', text: message.paymentLink }, + ] + : [], + }, + REENGAGEMENT: { + definition: { + name: 'gruperly_reengagement', + language: TEMPLATE_LANGUAGE, + category: 'MARKETING', + parameter_format: 'NAMED', + components: [ + { + type: 'BODY', + text: + '¡Hola {{student_name}}! 👋 Te extrañamos en {{group_name}}. ' + + 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' + + 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.', + example: { + body_text_named_params: [ + { param_name: 'student_name', example: 'Ana' }, + { param_name: 'group_name', example: 'Yoga Martes y Jueves' }, + ], + }, + }, + ], + }, + parameters: (message) => [ + { name: 'student_name', text: firstNameOf(message.studentName) }, + { name: 'group_name', text: message.groupName }, + ], + }, +}; + +/** Meta's template status, mapped to ours. Unknown values stay PENDING. */ +export function toTemplateStatus(status: string): 'PENDING' | 'APPROVED' | 'REJECTED' | 'DISABLED' { + switch (status.toUpperCase()) { + case 'APPROVED': + return 'APPROVED'; + case 'REJECTED': + return 'REJECTED'; + case 'DISABLED': + case 'PAUSED': + case 'ARCHIVED': + return 'DISABLED'; + default: + return 'PENDING'; + } +} diff --git a/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts new file mode 100644 index 0000000..235cebc --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts @@ -0,0 +1,176 @@ +import type { WhatsappAccount } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + WhatsappCallbackReason, + WhatsappConnectionStart, + WhatsappMessageKind, + WhatsappReadiness, + WhatsappReturnTo, +} from '@gruperly/shared'; + +/** + * The port every WhatsApp gateway implements. The domain (linking, the weekly + * jobs, the webhook) only talks to this interface; everything that knows about + * OpenWA or Kapso lives in `providers//`. Switching gateways is a matter of + * `WHATSAPP_PROVIDER` plus an adapter, never of touching the jobs or the UI. + */ + +export type MessagingProviderId = 'OPENWA' | 'KAPSO'; + +export type WhatsappAccountRecord = Pick< + WhatsappAccount, + 'id' | 'ownerId' | 'provider' | 'status' | 'externalId' | 'displayPhoneNumber' | 'providerData' +>; + +/** + * What the teacher receives, in domain terms. Each provider turns it into its + * own wire format: free text (OpenWA) or a template with parameters (Kapso). + */ +export type WhatsappMessage = + | { + kind: 'PAYMENT_REMINDER'; + studentName: string; + groupName: string; + amount: string; + dueDate: string; + paymentLink: string; + } + | { + kind: 'REENGAGEMENT'; + studentName: string; + groupName: string; + }; + +export type StartConnectionContext = { + ownerId: string; + ownerName: string; + returnTo: WhatsappReturnTo; + /** The teacher's existing row, if any, to reuse provider-side resources. */ + account: WhatsappAccountRecord | null; +}; + +export type StartConnectionResult = { + start: WhatsappConnectionStart; + /** OpenWA: the session id. Kapso: null until the setup finishes. */ + externalId: string | null; + providerData?: Record | null; +}; + +/** The live state of a linking, as the provider reports it. */ +export type ConnectionSnapshot = + | { state: 'pending'; qrCode: string | null } + | { state: 'active'; displayPhoneNumber: string | null } + | { state: 'disconnected'; reason: string | null }; + +/** The provider-side result of finishing a redirect-based linking (Kapso). */ +export type CompletedConnection = { + externalId: string; + displayPhoneNumber: string | null; + providerData?: Record | null; +}; + +export type RecipientResolution = + | { ok: true; to: string } + | { ok: false; code: 'no_whatsapp' | 'provider_error' }; + +export type SendOutcome = + | { ok: true; providerMessageId: string } + | { + ok: false; + /** Worth trying again on the next run (5xx, network). */ + retryable: boolean; + /** The gateway asked us to stop sending from this account for a while. */ + rateLimitedForMs?: number; + code: string; + message: string; + }; + +export type MessageDeliveryStatus = 'SENT' | 'DELIVERED' | 'READ' | 'FAILED'; + +/** Webhook payloads reduced to the two things the domain cares about. */ +export type NormalizedEvent = + | { + type: 'connection'; + /** Session id (OpenWA) or phone_number_id (Kapso). */ + externalId: string; + /** When the provider carries our own reference (Kapso's external customer id). */ + ownerId?: string; + status: 'active' | 'disconnected'; + displayPhoneNumber?: string | null; + providerData?: Record | null; + } + | { + type: 'message_status'; + providerMessageId: string; + status: MessageDeliveryStatus; + errorCode?: string | null; + errorMessage?: string | null; + }; + +export type ParsedWebhook = { + /** The delivery's idempotency key; burned before the events are applied. */ + dedupeKey: string; + events: NormalizedEvent[]; +}; + +export type WebhookParseError = 'invalid_signature' | 'invalid_payload'; + +export interface MessagingProvider { + readonly id: MessagingProviderId; + + /** Starts (or restarts) linking the teacher's number. */ + startConnection( + context: StartConnectionContext, + ): Promise>; + + /** Asks the provider how the linking is going (fresh QR, linked, failed). */ + refreshConnection( + account: WhatsappAccountRecord, + ): Promise>; + + /** + * Asks for a code to link by phone number instead of scanning the QR, for a + * linking already started with `startConnection`. `phoneDigits` is the + * teacher's number in international format, digits only. Only providers that + * link a WhatsApp Web session (OpenWA) implement it. + */ + requestPairingCode?( + account: WhatsappAccountRecord, + phoneDigits: string, + ): Promise>; + + /** + * Finishes a redirect-based linking from the callback query. Only providers + * whose `startConnection` answers `redirect` implement it. + */ + completeRedirect?( + account: WhatsappAccountRecord, + query: Record, + ): Promise>; + + /** Unlinks the number on the provider side. Best effort. */ + disconnect(account: WhatsappAccountRecord): Promise>; + + /** Runs once the account becomes ACTIVE (Kapso: templates and webhooks). */ + onConnected?(account: WhatsappAccountRecord): Promise; + + /** Whether a message of this kind can be sent from the account right now. */ + readiness(account: WhatsappAccountRecord, kind: WhatsappMessageKind): Promise; + + /** Turns an E.164 number into the provider's recipient id, or says it has no WhatsApp. */ + resolveRecipient(account: WhatsappAccountRecord, e164: string): Promise; + + send( + account: WhatsappAccountRecord, + to: string, + message: WhatsappMessage, + idempotencyKey: string, + ): Promise; + + /** Verifies the signature over the raw body and normalizes the payload. */ + parseWebhook( + rawBody: string, + headers: Headers, + ): Result; +} diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/config.ts b/apps/backend/src/modules/whatsapp/providers/openwa/config.ts new file mode 100644 index 0000000..020c5e4 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/openwa/config.ts @@ -0,0 +1,51 @@ +export type OpenWaConfig = { + /** Base URL including `/api`, e.g. `https://openwa.example.com/api`. */ + apiUrl: string; + /** An OPERATOR key that is not scoped to specific sessions (it creates them). */ + apiKey: string; + /** + * Public URL of `/api/v1/whatsapp/webhooks/openwa`. Optional: without it the + * linking still works (the status endpoint polls OpenWA) but delivery and + * read receipts never reach `outbound_messages`. + */ + webhookUrl: string | null; + /** HMAC secret registered with each session webhook (16+ characters). */ + webhookSecret: string | null; +}; + +const MIN_SECRET_LENGTH = 16; + +/** + * Reads the OpenWA settings. Throws on a deployment mistake, naming the + * variables (never their values), like `getMpOAuthConfig()`. + */ +export function getOpenWaConfig(): OpenWaConfig { + const missing: string[] = []; + const read = (name: string, required: boolean): string | null => { + const value = process.env[name]?.trim(); + if (!value) { + if (required) missing.push(name); + return null; + } + return value; + }; + + const apiUrl = read('OPENWA_API_URL', true); + const apiKey = read('OPENWA_API_KEY', true); + const webhookUrl = read('OPENWA_WEBHOOK_URL', false); + const webhookSecret = read('OPENWA_WEBHOOK_SECRET', webhookUrl !== null); + + if (missing.length > 0) { + throw new Error(`Missing OpenWA environment variables: ${missing.join(', ')}. See .env.example.`); + } + if (webhookSecret !== null && webhookSecret.length < MIN_SECRET_LENGTH) { + throw new Error(`OPENWA_WEBHOOK_SECRET must be at least ${MIN_SECRET_LENGTH} characters long.`); + } + + return { + apiUrl: (apiUrl as string).replace(/\/+$/, ''), + apiKey: apiKey as string, + webhookUrl, + webhookSecret, + }; +} diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/http.ts b/apps/backend/src/modules/whatsapp/providers/openwa/http.ts new file mode 100644 index 0000000..ee1d8c4 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/openwa/http.ts @@ -0,0 +1,165 @@ +import type { OpenWaConfig } from './config'; + +/** + * Thin client for the OpenWA REST gateway (rmyndharis/OpenWA). Plain `fetch`: + * responses are the raw resource (no `{ data }` envelope) and errors use the + * NestJS shape `{ statusCode, message, error, code? }`. + */ + +export class OpenWaApiError extends Error { + constructor( + readonly status: number, + /** OpenWA's stable machine code when it sends one (e.g. `SEND_PACING_LIMITED`). */ + readonly code: string | null, + readonly retryAfterSeconds: number | null = null, + ) { + super(`OpenWA request failed with ${status}${code ? ` (${code})` : ''}`); + this.name = 'OpenWaApiError'; + } +} + +export type OpenWaSessionStatus = + | 'created' + | 'initializing' + | 'qr_ready' + | 'authenticating' + | 'ready' + | 'disconnected' + | 'action_required' + | 'failed'; + +export type OpenWaSession = { + id: string; + name: string; + status: OpenWaSessionStatus; + phone: string | null; + lastError: string | null; + engineLoaded: boolean; +}; + +export type OpenWaFetch = (input: string, init?: RequestInit) => Promise; + +const REQUEST_TIMEOUT_MS = 30_000; + +export class OpenWaClient { + constructor( + private readonly config: OpenWaConfig, + private readonly fetchFn: OpenWaFetch = (input, init) => fetch(input, init), + ) {} + + getSession(sessionId: string): Promise { + return this.request('GET', `/sessions/${encodeURIComponent(sessionId)}`); + } + + async findSessionByName(name: string): Promise { + const sessions = await this.request( + 'GET', + `/sessions?name=${encodeURIComponent(name)}`, + ); + return sessions[0] ?? null; + } + + createSession(name: string): Promise { + return this.request('POST', '/sessions', { name }); + } + + startSession(sessionId: string): Promise { + return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/start`); + } + + logoutSession(sessionId: string): Promise { + return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/logout`); + } + + async deleteSession(sessionId: string): Promise { + await this.request('DELETE', `/sessions/${encodeURIComponent(sessionId)}`); + } + + async getQrCode(sessionId: string): Promise { + const response = await this.request<{ qrCode?: string | null }>( + 'GET', + `/sessions/${encodeURIComponent(sessionId)}/qr`, + ); + return response.qrCode ?? null; + } + + requestPairingCode( + sessionId: string, + phoneNumber: string, + ): Promise<{ pairingCode: string; status?: string }> { + return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/pairing-code`, { + phoneNumber, + }); + } + + createWebhook( + sessionId: string, + body: { url: string; events: string[]; secret: string; retryCount: number }, + ): Promise<{ id: string }> { + return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/webhooks`, body); + } + + checkContact( + sessionId: string, + digits: string, + ): Promise<{ exists: boolean; whatsappId: string | null }> { + return this.request( + 'GET', + `/sessions/${encodeURIComponent(sessionId)}/contacts/check/${encodeURIComponent(digits)}`, + ); + } + + sendText( + sessionId: string, + body: { chatId: string; text: string }, + idempotencyKey: string, + ): Promise<{ messageId: string; timestamp?: number }> { + return this.request( + 'POST', + `/sessions/${encodeURIComponent(sessionId)}/messages/send-text`, + body, + { 'Idempotency-Key': idempotencyKey }, + ); + } + + private async request( + method: string, + path: string, + body?: unknown, + extraHeaders: Record = {}, + ): Promise { + const response = await this.fetchFn(`${this.config.apiUrl}${path}`, { + method, + headers: { + 'X-API-Key': this.config.apiKey, + Accept: 'application/json', + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + ...extraHeaders, + }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as { + code?: unknown; + retryAfterSeconds?: unknown; + } | null; + const retryAfterHeader = Number(response.headers.get('Retry-After')); + const retryAfterSeconds = + typeof payload?.retryAfterSeconds === 'number' + ? payload.retryAfterSeconds + : Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 + ? retryAfterHeader + : null; + throw new OpenWaApiError( + response.status, + typeof payload?.code === 'string' ? payload.code : null, + retryAfterSeconds, + ); + } + + if (response.status === 204) return undefined as T; + return (await response.json()) as T; + } +} diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/index.ts b/apps/backend/src/modules/whatsapp/providers/openwa/index.ts new file mode 100644 index 0000000..fe04dce --- /dev/null +++ b/apps/backend/src/modules/whatsapp/providers/openwa/index.ts @@ -0,0 +1,408 @@ +import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { whatsappPairingNotReadyProblem, whatsappProviderErrorProblem } from '@/http/problem-builders'; +import { logger } from '@/logger'; +import { sleep } from '../../lib/dispatch'; +import { verifyHmacSha256 } from '../../lib/hmac'; +import { renderMessage } from '../../lib/render-message'; +import type { + ConnectionSnapshot, + MessageDeliveryStatus, + MessagingProvider, + NormalizedEvent, + ParsedWebhook, + RecipientResolution, + SendOutcome, + StartConnectionContext, + StartConnectionResult, + WebhookParseError, + WhatsappAccountRecord, + WhatsappMessage, +} from '../messaging-provider'; +import type { OpenWaConfig } from './config'; +import { OpenWaApiError, OpenWaClient, type OpenWaFetch, type OpenWaSession } from './http'; + +/** Events each session webhook subscribes to. */ +export const OPENWA_WEBHOOK_EVENTS = [ + 'session.status', + 'session.authenticated', + 'session.disconnected', + 'message.ack', + 'message.failed', +]; + +const WEBHOOK_RETRY_COUNT = 3; +/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */ +const DEFAULT_RATE_LIMIT_MS = 60_000; + +/** + * Right after `start` the session is still `initializing` and OpenWA answers a + * pairing-code request with 409 until it reads `qr_ready` (on Baileys also for + * up to 30 s while a socket closes). Retried here so the teacher's click works. + */ +const PAIRING_ATTEMPTS = 6; +const PAIRING_RETRY_MS = 2_000; + +const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']); + +/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */ +export function openWaSessionName(ownerId: string): string { + return `gruperly-${ownerId.replace(/[^a-zA-Z0-9-]/g, '')}`.slice(0, 50); +} + +type OpenWaProviderDeps = { fetch?: OpenWaFetch; sleep?: (ms: number) => Promise }; + +/** + * OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP. + * + * The teacher links their own WhatsApp as a "linked device" by scanning a QR + * code shown inside Gruperly; messages are free text sent from that session. + * It is not Meta's official API: see `docs/whatsapp.md` for the ban risk and + * why sends are paced. + */ +export class OpenWaProvider implements MessagingProvider { + readonly id = 'OPENWA' as const; + private readonly client: OpenWaClient; + private readonly sleep: (ms: number) => Promise; + + constructor( + private readonly config: OpenWaConfig, + deps: OpenWaProviderDeps = {}, + ) { + this.client = new OpenWaClient(config, deps.fetch); + this.sleep = deps.sleep ?? sleep; + } + + async startConnection( + context: StartConnectionContext, + ): Promise> { + const previous = + context.account?.provider === 'OPENWA' ? context.account : null; + const previousData = readData(previous?.providerData); + + try { + let session = previous?.externalId ? await this.findSession(previous.externalId) : null; + let webhookId = session ? previousData.webhookId ?? null : null; + + if (!session) { + session = await this.createOrAdoptSession(openWaSessionName(context.ownerId)); + webhookId = null; + } + + if (!webhookId) { + webhookId = await this.registerWebhook(session.id); + } + + // Linking again from an already linked session (e.g. to change number): + // unlink first so WhatsApp hands out a fresh QR code. + if (session.status === 'ready' && session.engineLoaded) { + session = await this.client.logoutSession(session.id).catch(() => session as OpenWaSession); + } + + if (!session.engineLoaded || session.status === 'disconnected' || session.status === 'failed') { + session = await this.client.startSession(session.id).catch((error: unknown) => { + // 400 = already started / starting: fine, the QR is on its way. + if (error instanceof OpenWaApiError && error.status === 400) return session as OpenWaSession; + throw error; + }); + } + + return ok({ + start: { type: 'qr', qrCode: await this.tryQrCode(session.id) }, + externalId: session.id, + providerData: { + sessionName: session.name, + ...(webhookId ? { webhookId } : {}), + }, + }); + } catch (error) { + logger.error({ err: describe(error) }, 'OpenWA could not start a session'); + return err(whatsappProviderErrorProblem()); + } + } + + async refreshConnection( + account: WhatsappAccountRecord, + ): Promise> { + if (!account.externalId) return ok({ state: 'disconnected', reason: 'no_session' }); + + try { + const session = await this.findSession(account.externalId); + if (!session) return ok({ state: 'disconnected', reason: 'session_not_found' }); + + if (session.status === 'ready') { + return ok({ state: 'active', displayPhoneNumber: formatPhone(session.phone) }); + } + if (PENDING_STATUSES.has(session.status)) { + const qrCode = session.status === 'qr_ready' ? await this.tryQrCode(session.id) : null; + return ok({ state: 'pending', qrCode }); + } + // A `disconnected` session whose engine is still loaded is backing off + // before an automatic reconnect: not a failure yet. + if (session.status === 'disconnected' && session.engineLoaded) { + return ok({ state: 'pending', qrCode: null }); + } + return ok({ state: 'disconnected', reason: session.lastError ?? session.status }); + } catch (error) { + logger.warn({ err: describe(error) }, 'OpenWA session status lookup failed'); + return err(whatsappProviderErrorProblem()); + } + } + + async requestPairingCode( + account: WhatsappAccountRecord, + phoneDigits: string, + ): Promise> { + if (!account.externalId) return err(whatsappProviderErrorProblem()); + + for (let attempt = 1; ; attempt++) { + try { + const response = await this.client.requestPairingCode(account.externalId, phoneDigits); + return ok(response.pairingCode); + } catch (error) { + const notReady = error instanceof OpenWaApiError && error.status === 409; + if (notReady && attempt < PAIRING_ATTEMPTS) { + await this.sleep(PAIRING_RETRY_MS); + continue; + } + if (notReady) return err(whatsappPairingNotReadyProblem()); + logger.warn({ err: describe(error) }, 'OpenWA pairing code request failed'); + return err(whatsappProviderErrorProblem()); + } + } + } + + async disconnect(account: WhatsappAccountRecord): Promise> { + if (!account.externalId) return ok(undefined); + const sessionId = account.externalId; + + // `logout` unlinks the device from the teacher's phone; `delete` alone + // would leave it listed under "Linked devices". Both are best effort: the + // local row is unlinked either way. + try { + await this.client.logoutSession(sessionId); + } catch (error) { + logger.warn({ err: describe(error) }, 'OpenWA logout did not complete'); + } + try { + await this.client.deleteSession(sessionId); + } catch (error) { + if (!(error instanceof OpenWaApiError && error.status === 404)) { + logger.warn({ err: describe(error) }, 'OpenWA session delete did not complete'); + } + } + return ok(undefined); + } + + async readiness(account: WhatsappAccountRecord): Promise { + return account.status === 'ACTIVE' ? 'ready' : 'blocked'; + } + + async resolveRecipient( + account: WhatsappAccountRecord, + e164: string, + ): Promise { + if (!account.externalId) return { ok: false, code: 'provider_error' }; + try { + // The canonical id WhatsApp knows the number by. It also settles the + // Argentine "9" after the country code, which differs per account. + const contact = await this.client.checkContact(account.externalId, e164.replace(/\D/g, '')); + return contact.exists && contact.whatsappId + ? { ok: true, to: contact.whatsappId } + : { ok: false, code: 'no_whatsapp' }; + } catch (error) { + logger.warn({ err: describe(error) }, 'OpenWA contact check failed'); + return { ok: false, code: 'provider_error' }; + } + } + + async send( + account: WhatsappAccountRecord, + to: string, + message: WhatsappMessage, + idempotencyKey: string, + ): Promise { + if (!account.externalId) { + return { ok: false, retryable: false, code: 'no_session', message: 'Account has no session' }; + } + + try { + const response = await this.client.sendText( + account.externalId, + { chatId: to, text: renderMessage(message) }, + idempotencyKey, + ); + return { ok: true, providerMessageId: response.messageId }; + } catch (error) { + return toSendFailure(error); + } + } + + parseWebhook(rawBody: string, headers: Headers): Result { + const secret = this.config.webhookSecret; + if (!secret || !verifyHmacSha256(rawBody, headers.get('X-OpenWA-Signature'), secret, 'sha256=')) { + return err('invalid_signature'); + } + + let payload: OpenWaWebhookPayload; + try { + payload = JSON.parse(rawBody) as OpenWaWebhookPayload; + } catch { + return err('invalid_payload'); + } + + const dedupeKey = + headers.get('X-OpenWA-Idempotency-Key') ?? payload.idempotencyKey ?? payload.deliveryId; + if (!dedupeKey || typeof payload.event !== 'string') return err('invalid_payload'); + + return ok({ dedupeKey, events: toEvents(payload) }); + } + + private async findSession(sessionId: string): Promise { + try { + return await this.client.getSession(sessionId); + } catch (error) { + if (error instanceof OpenWaApiError && error.status === 404) return null; + throw error; + } + } + + /** Creates the teacher's session, or adopts it if one with that name survived. */ + private async createOrAdoptSession(name: string): Promise { + try { + return await this.client.createSession(name); + } catch (error) { + if (error instanceof OpenWaApiError && error.status === 409) { + const existing = await this.client.findSessionByName(name); + if (existing) return existing; + } + throw error; + } + } + + private async registerWebhook(sessionId: string): Promise { + if (!this.config.webhookUrl || !this.config.webhookSecret) return null; + try { + const webhook = await this.client.createWebhook(sessionId, { + url: this.config.webhookUrl, + events: OPENWA_WEBHOOK_EVENTS, + secret: this.config.webhookSecret, + retryCount: WEBHOOK_RETRY_COUNT, + }); + return webhook.id; + } catch (error) { + // Without the webhook the linking still works through polling; only the + // delivery receipts are lost. Not worth failing the teacher's click. + logger.warn({ err: describe(error) }, 'OpenWA webhook registration failed'); + return null; + } + } + + private async tryQrCode(sessionId: string): Promise { + try { + return await this.client.getQrCode(sessionId); + } catch { + // 400 while the engine is still starting: the next status poll brings it. + return null; + } + } +} + +type OpenWaWebhookPayload = { + event?: unknown; + sessionId?: string; + idempotencyKey?: string; + deliveryId?: string; + data?: Record; +}; + +const ACK_STATUSES: Record = { + sent: 'SENT', + delivered: 'DELIVERED', + read: 'READ', + played: 'READ', + failed: 'FAILED', +}; + +function toEvents(payload: OpenWaWebhookPayload): NormalizedEvent[] { + const data = payload.data ?? {}; + const sessionId = (typeof data.sessionId === 'string' ? data.sessionId : null) ?? payload.sessionId; + + switch (payload.event) { + case 'session.authenticated': + return sessionId + ? [ + { + type: 'connection', + externalId: sessionId, + status: 'active', + displayPhoneNumber: formatPhone(typeof data.phone === 'string' ? data.phone : null), + }, + ] + : []; + case 'session.status': + if (!sessionId) return []; + if (data.status === 'ready') return [{ type: 'connection', externalId: sessionId, status: 'active' }]; + if (data.status === 'failed') { + return [{ type: 'connection', externalId: sessionId, status: 'disconnected' }]; + } + return []; + case 'session.disconnected': + return sessionId ? [{ type: 'connection', externalId: sessionId, status: 'disconnected' }] : []; + case 'message.ack': + case 'message.failed': { + const status = ACK_STATUSES[String(data.status ?? (payload.event === 'message.failed' ? 'failed' : ''))]; + const messageId = typeof data.messageId === 'string' ? data.messageId : null; + if (!status || !messageId) return []; + return [ + { + type: 'message_status', + providerMessageId: messageId, + status, + errorCode: status === 'FAILED' ? 'delivery_failed' : null, + }, + ]; + } + default: + return []; + } +} + +function toSendFailure(error: unknown): SendOutcome { + if (error instanceof OpenWaApiError) { + if (error.status === 429) { + return { + ok: false, + retryable: true, + rateLimitedForMs: error.retryAfterSeconds ? error.retryAfterSeconds * 1000 : DEFAULT_RATE_LIMIT_MS, + code: error.code ?? 'rate_limited', + message: error.message, + }; + } + // 4xx: the session is not active, the body was refused, the key reused… + // none of them gets better by repeating the same request. + const retryable = error.status >= 500 || error.status === 409; + return { ok: false, retryable, code: error.code ?? `http_${error.status}`, message: error.message }; + } + return { ok: false, retryable: true, code: 'network_error', message: describe(error).message }; +} + +function readData(value: unknown): Record { + return value && typeof value === 'object' ? (value as Record) : {}; +} + +function formatPhone(phone: string | null | undefined): string | null { + if (!phone) return null; + const digits = phone.replace(/\D/g, ''); + return digits ? `+${digits}` : null; +} + +/** Errors are logged by name and status only: request bodies may hold phone numbers. */ +function describe(error: unknown): { name: string; message: string; status?: number } { + if (error instanceof OpenWaApiError) { + return { name: error.name, message: error.message, status: error.status }; + } + return error instanceof Error + ? { name: error.name, message: error.message } + : { name: 'Unknown', message: String(error) }; +} diff --git a/apps/backend/src/modules/whatsapp/routes.ts b/apps/backend/src/modules/whatsapp/routes.ts new file mode 100644 index 0000000..79fb1fb --- /dev/null +++ b/apps/backend/src/modules/whatsapp/routes.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import callbackRoute from './features/callback/route'; +import connectRoute from './features/connect/route'; +import disconnectRoute from './features/disconnect/route'; +import pairingCodeRoute from './features/pairing-code/route'; +import statusRoute from './features/status/route'; +import webhookRoute from './features/webhook/route'; + +const routes = new Hono(); + +// Same trick as `mp`: `disconnectRoute` only declares `DELETE /`, so mounting +// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`. +routes.route('/connect', connectRoute); +routes.route('/connect', disconnectRoute); +routes.route('/connect/pairing-code', pairingCodeRoute); +routes.route('/status', statusRoute); +routes.route('/callback', callbackRoute); +routes.route('/webhooks', webhookRoute); + +export default routes; diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts index a490a6c..53b2210 100644 --- a/apps/backend/src/server.ts +++ b/apps/backend/src/server.ts @@ -1,6 +1,11 @@ import app from '@/app'; import { getPrismaClient } from '@/lib/prisma'; import { logger } from '@/logger'; +import { startBillingJobs } from '@/modules/billing'; +import { startMpJobs } from '@/modules/mp'; +import { startPaymentJobs } from '@/modules/payments'; +import { startStudentAccessJobs } from '@/modules/student-access'; +import { startWhatsappJobs } from '@/modules/whatsapp'; const port = Number(process.env.PORT ?? 4000); @@ -11,6 +16,12 @@ const server = Bun.serve({ fetch: app.fetch, }); +startMpJobs(); +startPaymentJobs(); +startWhatsappJobs(); +startBillingJobs(); +startStudentAccessJobs(); + async function shutdown(): Promise { server.stop(true); await getPrismaClient().$disconnect(); diff --git a/apps/backend/test/admin.test.ts b/apps/backend/test/admin.test.ts new file mode 100644 index 0000000..ab27bd9 --- /dev/null +++ b/apps/backend/test/admin.test.ts @@ -0,0 +1,315 @@ +import { afterAll, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + user: { findMany: mock(), count: mock(), findUnique: mock() }, + group: { findMany: mock() }, + billingCharge: { findMany: mock() }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import { adminRoutes } from '@/modules/admin'; +import { GetAccount } from '@/modules/admin/features/get-account/use-case'; +import { ListAccounts } from '@/modules/admin/features/list-accounts/use-case'; +import { buildAccountWhere, isAdminEmail } from '@/modules/admin/lib'; + +const now = new Date('2026-10-22T12:00:00.000Z'); +const days = (n: number) => new Date(now.getTime() + n * 24 * 60 * 60 * 1000); +const context = { now, graceDays: 7 }; + +function subscription(overrides: Record = {}) { + return { + id: 'sub-1', + userId: 'u1', + country: 'AR', + currency: 'ARS', + amount: { toString: () => '15000' }, + payerEmail: 'pagos@ana.com', + mpPreapprovalId: 'pre-1', + status: 'AUTHORIZED', + requestedAt: days(-40), + authorizedAt: days(-40), + nextPaymentDate: days(20), + paidThrough: days(10), + lastSyncedAt: null, + createdAt: days(-40), + updatedAt: days(-1), + ...overrides, + }; +} + +function user(id: string, overrides: Record = {}) { + return { + id, + name: `Profe ${id}`, + email: `${id}@gruperly.test`, + country: 'AR', + createdAt: days(-60), + onboardingCompleted: true, + planSelectedAt: days(-60), + subscription: null, + ...overrides, + }; +} + +function makeApp(email: string | null) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', email ? ({ id: 'staff-1', email } as never) : null); + await next(); + }); + app.route('/admin', adminRoutes); + return app; +} + +const previousAdminEmails = process.env.ADMIN_EMAILS; + +beforeEach(() => { + process.env.ADMIN_EMAILS = 'staff@gruperly.com, Otra@Gruperly.com'; + db.user.findMany.mockReset(); + db.user.count.mockReset(); + db.user.findUnique.mockReset(); + db.group.findMany.mockReset(); + db.billingCharge.findMany.mockReset(); +}); + +afterAll(() => { + process.env.ADMIN_EMAILS = previousAdminEmails; +}); + +describe('admin access', () => { + it('matches the allowlist ignoring case and spaces', () => { + const env = { ADMIN_EMAILS: ' staff@gruperly.com ,Otra@Gruperly.com' }; + expect(isAdminEmail('STAFF@gruperly.com', env)).toBe(true); + expect(isAdminEmail('otra@gruperly.com', env)).toBe(true); + expect(isAdminEmail('profe@gmail.com', env)).toBe(false); + }); + + it('lets nobody in with an empty allowlist', () => { + expect(isAdminEmail('staff@gruperly.com', {})).toBe(false); + expect(isAdminEmail('', { ADMIN_EMAILS: ',' })).toBe(false); + }); + + it('tells any signed-in user whether they are an admin', async () => { + const admin = await makeApp('staff@gruperly.com').request('/admin/me'); + expect(await admin.json()).toEqual({ isAdmin: true }); + + const professor = await makeApp('profe@gmail.com').request('/admin/me'); + expect(professor.status).toBe(200); + expect(await professor.json()).toEqual({ isAdmin: false }); + }); + + it('forbids the accounts to anyone outside the allowlist', async () => { + const list = await makeApp('profe@gmail.com').request('/admin/accounts'); + expect(list.status).toBe(403); + expect(await list.json()).toMatchObject({ code: 'admin_required' }); + + const detail = await makeApp('profe@gmail.com').request('/admin/accounts/u1'); + expect(detail.status).toBe(403); + expect(db.user.findUnique).not.toHaveBeenCalled(); + }); + + it('asks for a session without a user', async () => { + const response = await makeApp(null).request('/admin/accounts'); + expect(response.status).toBe(401); + }); + + it('serves the list to an admin', async () => { + db.user.findMany.mockResolvedValue([]); + db.user.count.mockResolvedValue(0); + + const response = await makeApp('staff@gruperly.com').request('/admin/accounts?plan=PRO'); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ data: [], pagination: { total: 0 } }); + }); + + it('rejects an unknown filter', async () => { + const response = await makeApp('staff@gruperly.com').request('/admin/accounts?plan=GOLD'); + expect(response.status).toBe(400); + }); +}); + +describe('ListAccounts', () => { + it('adds up groups and ACTIVE attendees per owner and resolves the plan', async () => { + db.user.findMany.mockResolvedValue([ + user('pro', { subscription: subscription() }), + user('grace', { subscription: subscription({ paidThrough: days(-2), status: 'CANCELLED' }) }), + user('free'), + user('new', { planSelectedAt: null, country: null, onboardingCompleted: false }), + ]); + db.user.count.mockResolvedValue(4); + db.group.findMany.mockResolvedValue([ + { createdById: 'pro', _count: { attendees: 12 } }, + { createdById: 'pro', _count: { attendees: 8 } }, + { createdById: 'free', _count: { attendees: 5 } }, + ]); + + const result = await new ListAccounts({ db: db as never, graceDays: 7, now: () => now }).execute({ + page: 1, + pageSize: 20, + }); + + expect(result.ok).toBe(true); + if (!result.ok) return; + const [pro, grace, free, fresh] = result.value.data; + expect(pro).toMatchObject({ + plan: 'PRO', + groupsCount: 2, + attendeesCount: 20, + subscription: { status: 'AUTHORIZED', amount: 15000, currency: 'ARS' }, + }); + expect(grace).toMatchObject({ plan: 'PRO', subscription: { status: 'CANCELLED', nextPaymentDate: null } }); + expect(free).toMatchObject({ plan: 'FREE', subscription: null, groupsCount: 1, attendeesCount: 5 }); + expect(fresh).toMatchObject({ plan: null, country: null, groupsCount: 0, attendeesCount: 0 }); + expect(result.value.pagination).toEqual({ page: 1, pageSize: 20, total: 4, totalPages: 1 }); + + const groupQuery = db.group.findMany.mock.calls[0]?.[0]; + expect(groupQuery.where).toEqual({ createdById: { in: ['pro', 'grace', 'free', 'new'] } }); + }); + + it('skips the usage query on an empty page', async () => { + db.user.findMany.mockResolvedValue([]); + db.user.count.mockResolvedValue(0); + + await new ListAccounts({ db: db as never, graceDays: 7, now: () => now }).execute({ page: 3, pageSize: 20 }); + + expect(db.group.findMany).not.toHaveBeenCalled(); + expect(db.user.findMany.mock.calls[0]?.[0]).toMatchObject({ skip: 40, take: 20 }); + }); +}); + +describe('buildAccountWhere', () => { + const cutoff = days(-7); + const isPro = { + subscription: { + is: { + OR: [ + { paidThrough: { gt: cutoff } }, + { paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } }, + ], + }, + }, + }; + + it('is empty without filters', () => { + expect(buildAccountWhere({}, context)).toEqual({}); + }); + + it('searches name and email and filters by country', () => { + expect(buildAccountWhere({ search: 'ana', country: 'UY' }, context)).toEqual({ + AND: [ + { + OR: [ + { name: { contains: 'ana', mode: 'insensitive' } }, + { email: { contains: 'ana', mode: 'insensitive' } }, + ], + }, + { country: 'UY' }, + ], + }); + }); + + it('filters by subscription status, NONE meaning never subscribed', () => { + expect(buildAccountWhere({ subscriptionStatus: 'NONE' }, context)).toEqual({ + AND: [{ subscription: { is: null } }], + }); + expect(buildAccountWhere({ subscriptionStatus: 'PAUSED' }, context)).toEqual({ + AND: [{ subscription: { is: { status: 'PAUSED' } } }], + }); + }); + + it('writes the plan with the same grace period as resolvePlan', () => { + expect(buildAccountWhere({ plan: 'PRO' }, context)).toEqual({ AND: [isPro] }); + expect(buildAccountWhere({ plan: 'FREE' }, context)).toEqual({ + AND: [{ planSelectedAt: { not: null }, NOT: isPro }], + }); + expect(buildAccountWhere({ plan: 'NOT_SELECTED' }, context)).toEqual({ + AND: [{ planSelectedAt: null, NOT: isPro }], + }); + }); +}); + +describe('GetAccount', () => { + it('returns the account with its groups, links and charges', async () => { + db.user.findUnique.mockResolvedValue({ + ...user('u1', { subscription: subscription() }), + mpAccount: { status: 'ACTIVE' }, + whatsappAccount: null, + groupsOwner: [ + { id: 'g1', name: 'Yoga', createdAt: days(-30), _count: { attendees: 9 } }, + { id: 'g2', name: 'Pilates', createdAt: days(-50), _count: { attendees: 4 } }, + ], + }); + db.billingCharge.findMany.mockResolvedValue([ + { + id: 'c1', + subscriptionId: 'sub-1', + mpAuthorizedPaymentId: 'ap-1', + amount: { toString: () => '15000' }, + currency: 'ARS', + status: 'approved', + paidAt: days(-20), + createdAt: days(-20), + updatedAt: days(-20), + }, + ]); + + const result = await new GetAccount({ db: db as never, enforced: true, graceDays: 7, now: () => now }).execute( + 'u1', + ); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.value).toMatchObject({ + plan: 'PRO', + readOnly: false, + graceUntil: null, + groupsCount: 2, + attendeesCount: 13, + mpStatus: 'ACTIVE', + whatsappStatus: null, + subscription: { payerEmail: 'pagos@ana.com', status: 'AUTHORIZED' }, + groups: [{ id: 'g1', attendeesCount: 9 }, { id: 'g2', attendeesCount: 4 }], + charges: [{ id: 'c1', amount: 15000, status: 'approved' }], + }); + expect(db.billingCharge.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { subscription: { userId: 'u1' } } }); + }); + + it('flags a Free account over its limits as read-only when enforced', async () => { + db.user.findUnique.mockResolvedValue({ + ...user('u1'), + mpAccount: null, + whatsappAccount: null, + groupsOwner: [ + { id: 'g1', name: 'A', createdAt: days(-3), _count: { attendees: 1 } }, + { id: 'g2', name: 'B', createdAt: days(-2), _count: { attendees: 1 } }, + ], + }); + db.billingCharge.findMany.mockResolvedValue([]); + + const enforced = await new GetAccount({ db: db as never, enforced: true, graceDays: 7, now: () => now }).execute( + 'u1', + ); + expect(enforced.ok && enforced.value.readOnly).toBe(true); + + const notEnforced = await new GetAccount({ db: db as never, enforced: false, graceDays: 7, now: () => now }).execute( + 'u1', + ); + expect(notEnforced.ok && notEnforced.value.readOnly).toBe(false); + }); + + it('is 404 for an unknown account', async () => { + db.user.findUnique.mockResolvedValue(null); + + const result = await new GetAccount({ db: db as never }).execute('missing'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(404); + expect(db.billingCharge.findMany).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/analytics-groups-risk.test.ts b/apps/backend/test/analytics-groups-risk.test.ts new file mode 100644 index 0000000..99537d1 --- /dev/null +++ b/apps/backend/test/analytics-groups-risk.test.ts @@ -0,0 +1,430 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findMany: mock(), + }, + attendee: { + findMany: mock(), + }, + classSession: { + findMany: mock(), + }, + attendance: { + findMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import { groupsRiskOverviewRoute } from '@/modules/analytics'; + +const userId = 'user-1'; +const DAY_MS = 24 * 60 * 60 * 1000; +const now = Date.now(); +const at = (offsetDays: number) => new Date(now - offsetDays * DAY_MS); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups-risk', groupsRiskOverviewRoute); + return app; +} + +describe('GET /groups-risk/overview', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('devuelve items vacíos si el usuario no tiene grupos', async () => { + prismaFetchGroupFindMany([]); + prismaFetchAttendeeFindMany([]); + prismaFetchClassSessionFindMany([]); + prismaFetchAttendanceFindMany([]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ items: [] }); + }); + + it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => { + prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]); + prismaFetchAttendeeFindMany([attendee('a-1', 'group-1'), attendee('a-2', 'group-2')]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(2) }, + { id: 's3', groupId: 'group-1', startsAt: at(3) }, + { id: 's4', groupId: 'group-2', startsAt: at(1) }, + ]); + prismaFetchAttendanceFindMany([ + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's2', 'ABSENT', at(2)), + attendance('a-1', 's3', 'ABSENT', at(3)), + attendance('a-2', 's4', 'PRESENT', at(1)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + // `toMatchObject` because the item now also carries the per-level summary + // the card consumes; here we are testing the usual status light. + expect(await res.json()).toMatchObject({ + items: [ + { + groupId: 'group-1', + groupName: 'Funcional', + riskLevel: 'HIGH', + absenceStreakCount: 1, + lowAttendanceCount: 0, + }, + { + groupId: 'group-2', + groupName: 'Yoga', + riskLevel: 'NONE', + absenceStreakCount: 0, + lowAttendanceCount: 0, + }, + ], + }); + }); + + it('cuenta el motivo: faltas seguidas o faltas sueltas, sin repetir alumnos', async () => { + prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]); + prismaFetchAttendeeFindMany([ + attendee('a-1', 'group-1'), + attendee('a-2', 'group-1'), + attendee('a-3', 'group-1'), + attendee('b-1', 'group-2'), + ]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(2) }, + { id: 's3', groupId: 'group-1', startsAt: at(3) }, + { id: 's4', groupId: 'group-1', startsAt: at(4) }, + { id: 's7', groupId: 'group-1', startsAt: at(15) }, + { id: 's5', groupId: 'group-2', startsAt: at(1) }, + { id: 's6', groupId: 'group-2', startsAt: at(2) }, + ]); + prismaFetchAttendanceFindMany([ + // Two consecutive absences: counts toward the absence reason. + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's2', 'ABSENT', at(2)), + attendance('a-1', 's3', 'PRESENT', at(3)), + // No streak (they came to s2), but 4 of their last 5 classes missed: + // high risk through the window, not through the streak. + attendance('a-2', 's1', 'ABSENT', at(1)), + attendance('a-2', 's2', 'PRESENT', at(2)), + attendance('a-2', 's3', 'ABSENT', at(3)), + attendance('a-2', 's4', 'ABSENT', at(4)), + attendance('a-2', 's7', 'ABSENT', at(15)), + // Ok. + attendance('a-3', 's1', 'PRESENT', at(1)), + attendance('a-3', 's2', 'PRESENT', at(2)), + attendance('a-3', 's3', 'PRESENT', at(3)), + attendance('a-3', 's4', 'PRESENT', at(4)), + // Again via streak, in the other group. + attendance('b-1', 's5', 'ABSENT', at(1)), + attendance('b-1', 's6', 'ABSENT', at(2)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ + items: [ + { + groupId: 'group-1', + groupName: 'Funcional', + riskLevel: 'HIGH', + absenceStreakCount: 1, + lowAttendanceCount: 1, + }, + { + groupId: 'group-2', + groupName: 'Yoga', + riskLevel: 'MEDIUM', + absenceStreakCount: 1, + lowAttendanceCount: 0, + }, + ], + }); + }); +}); + +/* What the listing card consumes. The status light above already had its + tests; what was missing was pinning the new payload against the same + endpoint, because that is the contract the frontend reads. */ +it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => { + prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]); + prismaFetchAttendeeFindMany([ + attendee('a-1', 'group-1', 'Sofía Díaz'), + attendee('a-2', 'group-1', 'Diego Soto'), + attendee('a-3', 'group-1', 'Ana Ruiz'), + ]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(2) }, + { id: 's3', groupId: 'group-1', startsAt: at(3) }, + ]); + // The mock ignores `orderBy`, so the rows come most recent first, as Prisma + // would return them: the streak depends on that order. + // `at(n)` is n days back; the summary drops what has not happened yet, so + // the dates have to be in the past, not in the future. + prismaFetchAttendanceFindMany([ + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's2', 'ABSENT', at(2)), + attendance('a-1', 's3', 'ABSENT', at(3)), + attendance('a-2', 's1', 'ABSENT', at(1)), + attendance('a-2', 's2', 'ABSENT', at(2)), + attendance('a-2', 's3', 'PRESENT', at(3)), + attendance('a-3', 's1', 'PRESENT', at(1)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + const { items } = (await res.json()) as { items: Record[] }; + expect(items[0]).toMatchObject({ + riesgoAlto: 1, + atencion: 1, + ok: 1, + // Capacity is 5 and there are 3 members, not 2: free spots are computed + // against capacity, not as "the ones with no signal at all". + libres: 2, + enEspera: 2, + // Average of the already-rounded per-person rates: 0, 33 and 100 → 44. + asistencia: 44, + }); + expect(items[0].urgentes).toEqual([ + { + attendeeId: 'a-1', + fullName: 'Sofía Díaz', + level: 'riesgo_alto', + consecutiveAbsences: 3, + daysSinceLastAttendance: 1, + attendanceRate: 0, + }, + { + attendeeId: 'a-2', + fullName: 'Diego Soto', + level: 'atencion', + consecutiveAbsences: 2, + // Counted from their last class they attended, not from the group's + // most recent one: theirs was 3 days ago. + daysSinceLastAttendance: 3, + attendanceRate: 33, + }, + { + attendeeId: 'a-3', + fullName: 'Ana Ruiz', + level: 'ok', + consecutiveAbsences: 0, + daysSinceLastAttendance: 1, + attendanceRate: 100, + }, + ]); +}); + +it('un grupo sin capacidad declarada no inventa lugares libres', async () => { + prismaFetchGroupFindMany([group('group-1', 'Sin cupo', null)]); + prismaFetchAttendeeFindMany([]); + prismaFetchClassSessionFindMany([]); + prismaFetchAttendanceFindMany([]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ + items: [ + { + riskLevel: 'NONE', + riesgoAlto: 0, + atencion: 0, + ok: 0, + libres: 0, + enEspera: 0, + asistencia: null, + urgentes: [], + }, + ], + }); +}); + +it('una clase sin registro corta la racha: no son faltas seguidas', async () => { + prismaFetchGroupFindMany([group('group-1', 'Funcional')]); + prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(2) }, + { id: 's3', groupId: 'group-1', startsAt: at(3) }, + ]); + // Absence, unmarked class, absence. Reading only the `Attendance` rows this + // would look like a streak of 2; the middle class happened and has no + // record, so the real streak is 1. The level is still attention, but because + // of the short window (2 absences in the last marked classes), not the streak. + prismaFetchAttendanceFindMany([ + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's3', 'ABSENT', at(3)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + const { items } = (await res.json()) as { items: Record[] }; + expect(items[0].riesgoAlto).toBe(0); + expect(items[0].atencion).toBe(1); + expect(items[0].absenceStreakCount).toBe(0); + expect(items[0].urgentes).toEqual([ + { + attendeeId: 'a-1', + fullName: 'Sofía Díaz', + level: 'atencion', + consecutiveAbsences: 1, + daysSinceLastAttendance: 1, + // Both marked classes were absences; the middle one does not go into the average. + attendanceRate: 0, + }, + ]); +}); + +it('las faltas pegadas hasta la última clase sí cuentan como racha', async () => { + prismaFetchGroupFindMany([group('group-1', 'Funcional')]); + prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(2) }, + { id: 's3', groupId: 'group-1', startsAt: at(3) }, + ]); + // The streak is counted backwards from the most recent class, so they reach + // exactly the end: s1 and s2 back to back, and the one 3 days ago is + // unmarked, which falls before the streak and does not touch it. + prismaFetchAttendanceFindMany([ + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's2', 'ABSENT', at(2)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + const { items } = (await res.json()) as { items: Record[] }; + expect(items[0].atencion).toBe(1); + expect(items[0].urgentes).toEqual([ + { + attendeeId: 'a-1', + fullName: 'Sofía Díaz', + level: 'atencion', + consecutiveAbsences: 2, + daysSinceLastAttendance: 1, + attendanceRate: 0, + }, + ]); +}); + +it('una clase sin registrar después de las faltas las borra: la racha mira hasta la última clase', async () => { + prismaFetchGroupFindMany([group('group-1', 'Funcional')]); + prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(2) }, + { id: 's3', groupId: 'group-1', startsAt: at(3) }, + ]); + // The same two back-to-back absences as the previous case, but the most + // recent class (s1) is the one with no record. Since the streak is counted + // from the end and "no record" is not an absence, there is no streak: the + // asymmetry is there on purpose, because it is the same thing that already + // happens with an excused class. The two absences still fill the short + // window, so the level is attention without a streak. + prismaFetchAttendanceFindMany([ + attendance('a-1', 's2', 'ABSENT', at(2)), + attendance('a-1', 's3', 'ABSENT', at(3)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + const { items } = (await res.json()) as { items: Record[] }; + expect(items[0].atencion).toBe(1); + expect(items[0].riesgoAlto).toBe(0); + expect(items[0].absenceStreakCount).toBe(0); + expect(items[0].urgentes).toEqual([ + { + attendeeId: 'a-1', + fullName: 'Sofía Díaz', + level: 'atencion', + consecutiveAbsences: 0, + daysSinceLastAttendance: 1, + attendanceRate: 0, + }, + ]); +}); + +it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => { + prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]); + // The attendee was created today (offset 0), but has 3 absences in classes 7, 3 and 1 days ago. + prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(1) }, + { id: 's2', groupId: 'group-1', startsAt: at(3) }, + { id: 's3', groupId: 'group-1', startsAt: at(7) }, + ]); + prismaFetchAttendanceFindMany([ + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's2', 'ABSENT', at(3)), + attendance('a-1', 's3', 'ABSENT', at(7)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + const { items } = (await res.json()) as { items: Record[] }; + expect(items[0].riesgoAlto).toBe(1); + expect(items[0].riskLevel).toBe('HIGH'); + expect(items[0].absenceStreakCount).toBe(1); +}); + +/* The use-case asks for `capacity` and the waitlist count to compute the + free spots, and `fullName` + `createdAt` of every attendee for the per-level + summary. The fixtures provide them so the older tests don't have to know + about that. */ +function group(id: string, name: string, capacity: number | null = 10, waiting = 0) { + return { id, name, capacity, _count: { waitlist: waiting } }; +} + +function attendee(id: string, groupId: string, fullName = id) { + return { id, groupId, fullName, createdAt: at(90) }; +} + +function prismaFetchGroupFindMany(rows: unknown[]) { + db.group.findMany.mockResolvedValue(rows); +} + +function prismaFetchAttendeeFindMany(rows: unknown[]) { + db.attendee.findMany.mockResolvedValue(rows); +} + +function prismaFetchClassSessionFindMany(rows: unknown[]) { + db.classSession.findMany.mockResolvedValue(rows); +} + +function prismaFetchAttendanceFindMany(rows: unknown[]) { + db.attendance.findMany.mockResolvedValue(rows); +} + +/* The `classSessionId` matters: the summary is built by cross-referencing the + group's class sessions with the attendance rows, and without that join every + class would have no record for everyone. */ +function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) { + return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } }; +} \ No newline at end of file diff --git a/apps/backend/test/analytics-risk.test.ts b/apps/backend/test/analytics-risk.test.ts new file mode 100644 index 0000000..09119c4 --- /dev/null +++ b/apps/backend/test/analytics-risk.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'bun:test'; +import { lastAttendedAt, monthlyAttendanceRate } from '@/modules/analytics/lib/risk'; + +const day = 24 * 60 * 60 * 1000; +const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day); + +function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) { + return { status, occurredAt: at(offsetDays) }; +} +describe('lastAttendedAt', () => { + it('devuelve la clase PRESENT más reciente', () => { + const now = Date.now(); + const result = lastAttendedAt([ + { status: 'PRESENT', occurredAt: new Date(now) }, + entry('ABSENT', 7), + entry('ABSENT', 14), + ]); + expect(result).not.toBeNull(); + expect(result?.getTime()).toBe(now); + }); + + it('devuelve null si nunca asistió', () => { + expect(lastAttendedAt([entry('ABSENT', 0), entry('EXCUSED', 7)])).toBeNull(); + expect(lastAttendedAt([])).toBeNull(); + }); +}); + +describe('monthlyAttendanceRate', () => { + it('razón de PRESENT sobre el total de sesiones', () => { + expect(monthlyAttendanceRate([entry('PRESENT', 0), entry('PRESENT', 7), entry('ABSENT', 14)], 5)).toBe(40); + }); + + it('devuelve 0 sin sesiones o sin presentes', () => { + expect(monthlyAttendanceRate([], 3)).toBe(0); + expect(monthlyAttendanceRate([entry('ABSENT', 0)], 3)).toBe(0); + }); +}); diff --git a/apps/backend/test/analytics.test.ts b/apps/backend/test/analytics.test.ts new file mode 100644 index 0000000..e1228b5 --- /dev/null +++ b/apps/backend/test/analytics.test.ts @@ -0,0 +1,370 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + classSession: { + findMany: mock(), + }, + attendee: { + findMany: mock(), + findFirst: mock(), + findUnique: mock(), + update: mock(), + }, + attendance: { + findMany: mock(), + findFirst: mock(), + }, + slotRelease: { + count: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { analyticsRoutes, studentStatusRoutes } from '@/modules/analytics'; + +const userId = 'user-1'; +const DAY_MS = 24 * 60 * 60 * 1000; +const now = Date.now(); +const at = (offsetDays: number) => new Date(now - offsetDays * DAY_MS).toISOString(); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', analyticsRoutes); + app.route('/students', studentStatusRoutes); + return app; +} + +function makeGroup(overrides: Record = {}) { + return { + id: 'group-1', + name: 'Funcional', + createdById: userId, + members: [], + ...overrides, + }; +} + +describe('analytics routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('GET /groups/:groupId/analytics', () => { + it('calcula métricas de asistencia de los últimos 30 días', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue([{ id: 's-1' }, { id: 's-2' }]); + prisma.attendance.findMany.mockResolvedValue([ + { status: 'PRESENT' }, + { status: 'PRESENT' }, + { status: 'ABSENT' }, + { status: 'EXCUSED' }, + ]); + prisma.slotRelease.count.mockResolvedValue(2); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendanceRate: 50, + totalPresent: 2, + totalClasses: 2, + recoveredSlots: 2, + }); + }); + + it('devuelve 0 en todas las métricas sin clases en el período', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue([]); + prisma.attendance.findMany.mockResolvedValue([]); + prisma.slotRelease.count.mockResolvedValue(0); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendanceRate: 0, + totalPresent: 0, + totalClasses: 0, + recoveredSlots: 0, + }); + }); + + it('prohíbe el acceso a quien no es owner ni miembro', async () => { + prisma.group.findUnique.mockResolvedValue( + makeGroup({ createdById: 'someone-else' }), + ); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('devuelve 404 si el grupo no existe', async () => { + prisma.group.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/groups/group-1/analytics'); + + expect(res.status).toBe(401); + }); + }); + + describe('GET /groups/:groupId/students-at-risk', () => { + // Every 3 days: with weekly classes two absences already add up to 14 days + // without coming, and the inactivity rule would turn the MEDIUM case HIGH. + const sessions = [at(0), at(3), at(6), at(9)]; + const sessionRows = sessions.map((startsAt, index) => ({ id: `s${index}`, startsAt: new Date(startsAt) })); + const enrolled = new Date(at(60)); + // `offset` is the index in `sessions`: 0 is the most recent class. + const row = (attendeeId: string, status: string, offset: number) => ({ + attendeeId, + classSessionId: `s${offset}`, + status, + classSession: { startsAt: new Date(sessions[offset]) }, + }); + + it('clasifica HIGH y MEDIUM según el historial de asistencia', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue(sessionRows); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'a-1', fullName: 'Ana Pérez', phone: '+521111111111', createdAt: enrolled }, + { id: 'a-2', fullName: 'Bruno Díaz', phone: null, createdAt: enrolled }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + row('a-1', 'ABSENT', 0), + row('a-1', 'ABSENT', 1), + row('a-1', 'ABSENT', 2), + row('a-1', 'PRESENT', 3), + row('a-2', 'ABSENT', 0), + row('a-2', 'ABSENT', 1), + row('a-2', 'PRESENT', 2), + row('a-2', 'PRESENT', 3), + ]); + + const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + groupName: 'Funcional', + data: [ + { + attendeeId: 'a-1', + fullName: 'Ana Pérez', + phone: '+521111111111', + riskLevel: 'HIGH', + consecutiveAbsences: 3, + lastAttendedAt: sessions[3], + monthlyAttendanceRate: 25, + }, + { + attendeeId: 'a-2', + fullName: 'Bruno Díaz', + phone: null, + riskLevel: 'MEDIUM', + consecutiveAbsences: 2, + lastAttendedAt: sessions[2], + monthlyAttendanceRate: 50, + }, + ], + }); + }); + + it('devuelve lista vacía cuando nadie está en riesgo', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue(sessionRows); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'a-1', fullName: 'Ana Pérez', phone: null, createdAt: enrolled }, + ]); + prisma.attendance.findMany.mockResolvedValue([row('a-1', 'PRESENT', 0), row('a-1', 'PRESENT', 1)]); + + const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ groupName: 'Funcional', data: [] }); + }); + }); + + describe('GET /groups/:groupId/attendees/:attendeeId/history', () => { + it('devuelve el historial de presentismo con su porcentaje', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue({ + id: 'a-1', + fullName: 'Ana Pérez', + createdAt: new Date('2026-09-29T00:00:00.000Z'), + }); + prisma.classSession.findMany.mockResolvedValue([ + { id: 's-2', startsAt: new Date(at(7)) }, + { id: 's-1', startsAt: new Date(at(0)) }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + { classSessionId: 's-1', status: 'PRESENT' }, + { classSessionId: 's-2', status: 'ABSENT' }, + ]); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/a-1/history', + ); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendeeId: 'a-1', + fullName: 'Ana Pérez', + groupId: 'group-1', + groupName: 'Funcional', + attendanceRate: 50, + sessions: [ + { classSessionId: 's-1', startsAt: at(0), status: 'PRESENT' }, + { classSessionId: 's-2', startsAt: at(7), status: 'ABSENT' }, + ], + }); + expect(prisma.classSession.findMany).toHaveBeenCalledWith({ + where: { + groupId: 'group-1', + startsAt: { gte: new Date('2026-09-29T00:00:00.000Z') }, + }, + orderBy: { startsAt: 'desc' }, + take: 20, + select: { id: true, startsAt: true }, + }); + }); + + it('arranca en la primera clase registrada si es anterior al alta', async () => { + // Loaded on 1/10 with classes already marked since 20/9: the history + // starts at the first one, as the risk rule and the group list count it. + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue({ + id: 'a-1', + fullName: 'Ana Pérez', + createdAt: new Date('2026-10-01T00:00:00.000Z'), + }); + prisma.attendance.findFirst.mockResolvedValueOnce({ + classSession: { startsAt: new Date('2026-09-20T10:00:00.000Z') }, + }); + prisma.classSession.findMany.mockResolvedValue([]); + + await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1/history'); + + expect(prisma.classSession.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { groupId: 'group-1', startsAt: { gte: new Date('2026-09-20T10:00:00.000Z') } }, + }), + ); + }); + + it('devuelve 404 si el alumno no pertenece al grupo', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/nope/history', + ); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + }); + + describe('POST /students/:studentId/status', () => { + function makeAttendee(status: string, overrides: Record = {}) { + return { + id: 'a-1', + status, + group: { createdById: userId, members: [] }, + ...overrides, + }; + } + + it('cambia el estado del alumno', async () => { + prisma.attendee.findUnique.mockResolvedValue(makeAttendee('ACTIVE')); + prisma.attendee.update.mockResolvedValue({ id: 'a-1', status: 'DROPPED' }); + + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'DROPPED' }), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ attendeeId: 'a-1', status: 'DROPPED' }); + expect(prisma.attendee.update).toHaveBeenCalledWith({ + where: { id: 'a-1' }, + data: { status: 'DROPPED' }, + select: { id: true, status: true }, + }); + }); + + it('es idempotente si el estado no cambia', async () => { + prisma.attendee.findUnique.mockResolvedValue(makeAttendee('PAUSED')); + + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'PAUSED' }), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ attendeeId: 'a-1', status: 'PAUSED' }); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('prohíbe el acceso a quien no es owner ni miembro', async () => { + prisma.attendee.findUnique.mockResolvedValue( + makeAttendee('ACTIVE', { group: { createdById: 'someone-else', members: [] } }), + ); + + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'PAUSED' }), + }); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('rechaza estados fuera del contrato', async () => { + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'HOLD' }), + }); + + expect(res.status).toBe(400); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'ACTIVE' }), + }); + + expect(res.status).toBe(401); + }); + }); +}); diff --git a/apps/backend/test/attendance-risk.test.ts b/apps/backend/test/attendance-risk.test.ts new file mode 100644 index 0000000..efa2d52 --- /dev/null +++ b/apps/backend/test/attendance-risk.test.ts @@ -0,0 +1,287 @@ +import { describe, expect, it } from 'bun:test'; +import { + ATTENDANCE_RISK_RULES, + getGroupAttendanceSummary, + getMemberAttendanceRisk, + type MemberAttendance, + type MemberClassSession, + summarizeMemberAttendance, +} from '@gruperly/shared'; + +/* The risk rule is business logic, not a screen concern: these tests pin it so + that changing a threshold or refactoring the class filter doesn't quietly + move the status light of the group list. + + Two test-scaffold helpers: + + - `dense` puts the classes on consecutive days. + - `series` honors the offsets it is given, for the cases that do need gaps. + + All dates hang off a fixed `NOW`: the function takes the moment as an + argument precisely so it can be tested without a clock. */ + +const DAY_MS = 24 * 60 * 60 * 1000; +const NOW = new Date('2026-09-30T20:00:00.000Z'); + +/** Days back from `NOW`, in ISO. Negative = future class. */ +const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString(); + +type Status = MemberClassSession['status']; + +/** Classes on consecutive days, oldest first. */ +function dense(statuses: Status[]): MemberClassSession[] { + return statuses.map((status, index) => ({ + sessionId: `ses_${statuses.length - index}`, + startsAt: daysAgo(statuses.length - index), + status, + })); +} + +/** Classes with the offsets given, in any order. */ +function series(rows: [Status, number][]): MemberClassSession[] { + return rows.map(([status, offsetDays], index) => ({ + sessionId: `ses_${index}`, + startsAt: daysAgo(offsetDays), + status, + })); +} + +function member(sessions: MemberClassSession[], enrolledDaysAgo = 365): MemberAttendance { + return { + attendeeId: 'at_1', + fullName: 'Sofía Ramírez', + enrolledAt: daysAgo(enrolledDaysAgo), + sessions, + }; +} + +describe('getMemberAttendanceRisk', () => { + it('un alumno nuevo sin clases no genera ninguna alerta', () => { + expect(getMemberAttendanceRisk(member([]), NOW)).toBe('ok'); + }); + + it('no lo penaliza por clases anteriores a su alta en el grupo', () => { + const rejo = member(series([['ABSENT', 28], ['ABSENT', 21], ['ABSENT', 14]]), 2); + expect(getMemberAttendanceRisk(rejo, NOW)).toBe('ok'); + }); + + it('no cuenta clases que todavía no ocurrieron', () => { + // Attended the last three and is absent for the next three: nobody is drifting away. + const alumno = member(series([['PRESENT', 7], ['PRESENT', 14], ['PRESENT', 21], ['ABSENT', -7], ['ABSENT', -14]])); + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok'); + }); + + it('tres o más faltas consecutivas dan riesgo alto', () => { + const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT'])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.consecutiveAbsences).toBe(3); + // 4 days since last showing up: the level comes from the streak, not from the + // time since they last came. + expect(señales.daysSinceLastAttendance).toBe(4); + expect(señales.level).toBe('riesgo_alto'); + }); + + it('una racha larguísima sin ninguna clase con presencia igual es riesgo alto', () => { + // Never attended an eligible class: the reference for "how long since we saw + // them" is the last class, so it doesn't stay green forever. + const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT'])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.consecutiveAbsences).toBe(5); + expect(señales.daysSinceLastAttendance).toBe(1); + expect(señales.level).toBe('riesgo_alto'); + }); + + it('dos faltas consecutivas dan atención y una sola no da nada', () => { + expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])), NOW)).toBe('atencion'); + expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])), NOW)).toBe('ok'); + }); + + it('4 faltas en las últimas 6 clases dan riesgo alto aunque no haya racha', () => { + const { highWindowAbsences, highWindowSize } = ATTENDANCE_RISK_RULES; + const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT'])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.consecutiveAbsences).toBe(0); + expect(señales.highWindow).toEqual({ absences: highWindowAbsences, classes: highWindowSize }); + expect(señales.level).toBe('riesgo_alto'); + }); + + it('3 faltas en las últimas 6 sin racha son atención, no riesgo alto', () => { + const alumno = member(dense(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.highWindow.absences).toBe(3); + expect(señales.attentionWindow).toEqual({ absences: 2, classes: 4 }); + expect(señales.level).toBe('atencion'); + }); + + it('2 faltas en las últimas 4 clases dan atención', () => { + const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])); + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion'); + }); + + it('una sola falta reciente no alcanza', () => { + const alumno = member(dense(['ABSENT', 'ABSENT', 'PRESENT', 'PRESENT', 'ABSENT', 'PRESENT'])); + // The two old absences fall outside the short window (last 4). + expect(summarizeMemberAttendance(alumno, NOW).attentionWindow.absences).toBe(1); + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok'); + }); + + it('los días sin venir se informan pero no mueven el nivel', () => { + // The group stopped recording classes: 30 days since the last presence, + // but the attendee missed nothing. + const alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.daysSinceLastAttendance).toBe(30); + expect(señales.level).toBe('ok'); + }); + + it('tres faltas seguidas son riesgo alto con buena historia detrás', () => { + // 16 classes at 81%: the 3 trailing absences are what decides the level. + const alumno = member(dense([ + 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', + 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT', + ])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.consecutiveAbsences).toBe(3); + expect(señales.attendanceRate).toBe(81); + expect(señales.level).toBe('riesgo_alto'); + }); + + it('una clase sin registro corta la racha: sin dato no hay ausencia', () => { + // Absent, the middle one has no record, absent again. The real streak + // is one, not two; the two absences still fill the short window. + const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]])); + const señales = summarizeMemberAttendance(conHueco, NOW); + expect(señales.consecutiveAbsences).toBe(1); + expect(señales.markedClasses).toBe(2); + expect(señales.attendanceRate).toBe(0); + expect(señales.level).toBe('atencion'); + }); + + it('una clase justificada es la clase que no cuenta', () => { + // Absent, notified, absent again: the streak is one, and the average ignores + // the excused class instead of counting it as attendance or as an absence. + const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]])); + const señales = summarizeMemberAttendance(justificada, NOW); + expect(señales.consecutiveAbsences).toBe(1); + expect(señales.markedClasses).toBe(2); + expect(señales.attendanceRate).toBe(0); + expect(señales.attentionWindow).toEqual({ absences: 2, classes: 2 }); + }); + + it('avisar de la falta tampoco encadena las de alrededor', () => { + const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]])); + expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0); + // No streak, but the two absences are still recent: attention, not high. + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion'); + }); + + it('no le importa el orden en que llegan las clases', () => { + const desordenado = member(series([['ABSENT', 1], ['PRESENT', 4], ['ABSENT', 2], ['ABSENT', 3]])); + expect(summarizeMemberAttendance(desordenado, NOW).consecutiveAbsences).toBe(3); + expect(getMemberAttendanceRisk(desordenado, NOW)).toBe('riesgo_alto'); + }); +}); + +describe('getGroupAttendanceSummary', () => { + const conNivel = (attendeeId: string, level: 'riesgo_alto' | 'atencion' | 'ok') => ({ + attendeeId, + fullName: attendeeId, + enrolledAt: daysAgo(365), + sessions: + level === 'riesgo_alto' + ? dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']) + : level === 'atencion' + ? dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT']) + : dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT']), + }); + + it('cuenta por nivel y calcula los lugares libres', () => { + const resumen = getGroupAttendanceSummary({ + groupId: 'grp_1', + capacity: 10, + waitlistCount: 2, + members: [ + conNivel('a', 'riesgo_alto'), + conNivel('b', 'riesgo_alto'), + conNivel('c', 'atencion'), + conNivel('d', 'ok'), + conNivel('e', 'ok'), + ], + now: NOW, + }); + + expect(resumen).toMatchObject({ riesgoAlto: 2, atencion: 1, ok: 2, libres: 5, enEspera: 2 }); + expect(resumen.peorNivel).toBe('riesgo_alto'); + }); + + it('un grupo vacío no inventa niveles', () => { + const resumen = getGroupAttendanceSummary({ + groupId: 'grp_vacio', + capacity: 5, + waitlistCount: 0, + members: [], + now: NOW, + }); + + expect(resumen).toMatchObject({ riesgoAlto: 0, atencion: 0, ok: 0, libres: 5, enEspera: 0 }); + expect(resumen.peorNivel).toBeNull(); + expect(resumen.urgentes).toEqual([]); + expect(resumen.asistencia).toBeNull(); + }); + + it('más miembros que lugares da 0 libres, nunca negativos', () => { + const resumen = getGroupAttendanceSummary({ + groupId: 'grp_lleno', + capacity: 2, + waitlistCount: 3, + members: [conNivel('a', 'ok'), conNivel('b', 'ok'), conNivel('c', 'ok')], + now: NOW, + }); + + expect(resumen.libres).toBe(0); + expect(resumen.enEspera).toBe(3); + expect(resumen.ok).toBe(3); + }); + + it('sin cupo definido tampoco hay lugares libres que mostrar', () => { + const resumen = getGroupAttendanceSummary({ + groupId: 'grp_sin_cupo', + capacity: null, + waitlistCount: 0, + members: [conNivel('a', 'ok')], + now: NOW, + }); + + expect(resumen.libres).toBe(0); + }); + + it('ordena los urgentes de peor a mejor', () => { + const resumen = getGroupAttendanceSummary({ + groupId: 'grp_1', + capacity: 4, + waitlistCount: 0, + members: [conNivel('ok_1', 'ok'), conNivel('alto_1', 'riesgo_alto'), conNivel('aten_1', 'atencion'), conNivel('ok_2', 'ok')], + now: NOW, + }); + + expect(resumen.urgentes.map((urgente) => urgente.attendeeId)).toEqual(['alto_1', 'aten_1', 'ok_1', 'ok_2']); + }); + + it('la asistencia del grupo promedia solo a los que tienen clases con dato', () => { + const resumen = getGroupAttendanceSummary({ + groupId: 'grp_1', + capacity: 4, + waitlistCount: 0, + members: [ + conNivel('a', 'ok'), + { attendeeId: 'b', fullName: 'b', enrolledAt: daysAgo(365), sessions: series([['PRESENT', 1], ['ABSENT', 2]]) }, + // Just joined Chess: no marked classes, so they don't move the average. + { attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] }, + ], + now: NOW, + }); + + expect(resumen.asistencia).toBe(75); + expect(resumen.ok).toBe(3); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/attendee-add-to-group.test.ts b/apps/backend/test/attendee-add-to-group.test.ts new file mode 100644 index 0000000..aceea7c --- /dev/null +++ b/apps/backend/test/attendee-add-to-group.test.ts @@ -0,0 +1,175 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + count: mock(), + create: mock(), + update: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const group = (overrides: Record = {}) => ({ + id: 'group-1', + name: 'Taller de Pintura', + createdById: teacherId, + capacity: 20, + ...overrides, +}); +const targetGroup = (overrides: Record = {}) => + group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides }); + +const person = { + id: 'person-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + guardianName: null, + guardianPhone: null, + notes: null, +}; + +const membership = (overrides: Record = {}) => ({ + id: 'att-2', + groupId: 'group-2', + personId: 'person-1', + person, + notifyToken: 'notify-2', + status: 'ACTIVE', + createdAt: new Date('2026-11-02T10:00:00.000Z'), + updatedAt: new Date('2026-11-02T10:00:00.000Z'), + ...overrides, +}); + +function addRequest(targetGroupId: string, userId = teacherId) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', { id: userId } as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app.request('/groups/group-1/attendees/att-1/add-to-group', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ targetGroupId }), + }); +} + +describe('POST /groups/:groupId/attendees/:attendeeId/add-to-group', () => { + beforeEach(() => { + vi.clearAllMocks(); + prisma.group.findUnique.mockReset(); + prisma.attendee.findFirst.mockReset(); + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup() as never); + prisma.attendee.count.mockResolvedValue(3); + }); + + it('creates a membership of the same person in the target group', async () => { + prisma.attendee.findFirst + .mockResolvedValueOnce({ personId: 'person-1' } as never) + .mockResolvedValueOnce(null); + prisma.attendee.create.mockResolvedValue(membership() as never); + + const res = await addRequest('group-2'); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ + id: 'att-2', + groupId: 'group-2', + personId: 'person-1', + fullName: 'Martín Gómez', + }); + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { groupId: 'group-2', personId: 'person-1' }, + include: { person: { select: expect.any(Object) } }, + }); + // The source membership is not touched. + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('reactivates a former (DROPPED) membership in the target group', async () => { + prisma.attendee.findFirst + .mockResolvedValueOnce({ personId: 'person-1' } as never) + .mockResolvedValueOnce({ id: 'att-old', status: 'DROPPED' } as never); + prisma.attendee.update.mockResolvedValue(membership({ id: 'att-old' }) as never); + + const res = await addRequest('group-2'); + + expect(res.status).toBe(200); + expect(prisma.attendee.update).toHaveBeenCalledWith({ + where: { id: 'att-old' }, + data: { status: 'ACTIVE' }, + include: { person: { select: expect.any(Object) } }, + }); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the person is already in the target group', async () => { + prisma.attendee.findFirst + .mockResolvedValueOnce({ personId: 'person-1' } as never) + .mockResolvedValueOnce({ id: 'att-2', status: 'PAUSED' } as never); + + const res = await addRequest('group-2'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('attendee_already_registered'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the target group reached its capacity', async () => { + prisma.group.findUnique.mockReset(); + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup({ capacity: 3 }) as never); + prisma.attendee.findFirst + .mockResolvedValueOnce({ personId: 'person-1' } as never) + .mockResolvedValueOnce(null); + + const res = await addRequest('group-2'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('group_capacity_reached'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('rejects adding to the same group', async () => { + prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never); + + const res = await addRequest('group-1'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('attendee_same_group'); + }); + + it('rejects a target group owned by another teacher', async () => { + prisma.group.findUnique.mockReset(); + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never); + prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never); + + const res = await addRequest('group-2'); + + expect(res.status).toBe(403); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/attendee-get-by-id.test.ts b/apps/backend/test/attendee-get-by-id.test.ts new file mode 100644 index 0000000..0dd69af --- /dev/null +++ b/apps/backend/test/attendee-get-by-id.test.ts @@ -0,0 +1,135 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import getAttendeeRoute from '@/modules/attendees/features/get-by-id/route'; + +const userId = 'user-1'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', getAttendeeRoute); + return app; +} + +function makeGroup(overrides: Record = {}) { + return { id: 'group-1', name: 'Funcional', createdById: userId, members: [], ...overrides }; +} + +const attendee = { + id: 'a-1', + groupId: 'group-1', + personId: 'person-1', + person: { + id: 'person-1', + fullName: 'Ana Pérez', + email: 'ana@example.com', + phone: '5512345678', + guardianName: 'Luis Pérez', + guardianPhone: null, + notes: null, + // Every membership of the person: this one and another group. + attendees: [ + { id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } }, + { id: 'a-2', groupId: 'group-2', status: 'PAUSED', group: { name: 'Yoga' } }, + ], + }, + notifyToken: 'token-1', + createdAt: new Date('2026-08-01T10:00:00.000Z'), + updatedAt: new Date('2026-08-01T10:00:00.000Z'), + payments: [ + { status: 'PENDING', dueDate: new Date('2026-10-10T00:00:00.000Z') }, + ], +}; + +describe('GET /groups/:groupId/attendees/:attendeeId', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('devuelve el participante del grupo', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue(attendee); + + const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + id: 'a-1', + groupId: 'group-1', + personId: 'person-1', + fullName: 'Ana Pérez', + email: 'ana@example.com', + phone: '5512345678', + guardianName: 'Luis Pérez', + guardianPhone: null, + notes: null, + notifyToken: 'token-1', + createdAt: '2026-08-01T10:00:00.000Z', + updatedAt: '2026-08-01T10:00:00.000Z', + payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' }, + otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }], + }); + expect(prisma.attendee.findFirst).toHaveBeenCalledWith({ + where: { id: 'a-1', groupId: 'group-1' }, + include: { + person: { select: expect.objectContaining({ fullName: true, attendees: expect.any(Object) }) }, + payments: { + where: { + status: { not: 'CANCELLED' }, + dueDate: { gte: expect.any(Date), lt: expect.any(Date) }, + }, + orderBy: { dueDate: 'desc' }, + take: 1, + select: { status: true, dueDate: true }, + }, + }, + }); + }); + + it('devuelve 404 si el participante no pertenece al grupo', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/nope'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + + it('devuelve 403 si el usuario no tiene acceso al grupo', async () => { + prisma.group.findUnique.mockResolvedValue( + makeGroup({ createdById: 'otro-user', members: [] }), + ); + + const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1'); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('devuelve 401 si no hay sesión', async () => { + const res = await makeApp(undefined).request('/groups/group-1/attendees/a-1'); + + expect(res.status).toBe(401); + }); +}); diff --git a/apps/backend/test/attendee-move.test.ts b/apps/backend/test/attendee-move.test.ts new file mode 100644 index 0000000..2ed4247 --- /dev/null +++ b/apps/backend/test/attendee-move.test.ts @@ -0,0 +1,220 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + count: mock(), + update: mock(), + }, + absenceNotice: { + updateMany: mock(), + }, + attendance: { + deleteMany: mock(), + }, + slotRelease: { + deleteMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const group = (overrides: Record = {}) => ({ + id: 'group-1', + name: 'Taller de Pintura', + description: null, + createdById: teacherId, + inviteToken: null, + createdAt: new Date('2026-09-01T10:00:00.000Z'), + updatedAt: new Date('2026-09-01T10:00:00.000Z'), + days: ['MONDAY'], + time: '18:00', + capacity: 20, + price: 1500, + billingType: 'MONTHLY', + dueDay: 10, + ...overrides, +}); +const targetGroup = (overrides: Record = {}) => + group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides }); + +const attendee = (overrides: Record = {}) => ({ + id: 'att-1', + groupId: 'group-1', + personId: 'person-1', + person: { + id: 'person-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + guardianName: null, + guardianPhone: null, + notes: null, + }, + notifyToken: 'notify-1', + status: 'ACTIVE', + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + ...overrides, +}); + +function moveRequest(targetGroupId: string, userId = teacherId, attendeeId = 'att-1') { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', { id: userId } as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app.request(`/groups/group-1/attendees/${attendeeId}/move`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ targetGroupId }), + }); +} + +describe('POST /groups/:groupId/attendees/:attendeeId/move', () => { + beforeEach(() => { + vi.clearAllMocks(); + prisma.group.findUnique.mockReset(); + }); + + it('moves the member to the target group and undoes the old group future bookings', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup() as never); + prisma.attendee.findFirst.mockResolvedValueOnce(attendee() as never).mockResolvedValueOnce(null); + prisma.attendee.count.mockResolvedValue(3); + prisma.attendee.update.mockResolvedValue(attendee({ groupId: 'group-2' }) as never); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.groupId).toBe('group-2'); + expect(prisma.attendee.update).toHaveBeenCalledWith({ + where: { id: 'att-1' }, + data: { groupId: 'group-2' }, + include: { person: { select: expect.any(Object) } }, + }); + const futureOldClasses = { + classSession: { groupId: 'group-1', startsAt: { gt: expect.any(Date) } }, + }; + expect(prisma.absenceNotice.updateMany).toHaveBeenCalledWith({ + where: { attendeeId: 'att-1', cancelledAt: null, ...futureOldClasses }, + data: { cancelledAt: expect.any(Date) }, + }); + expect(prisma.attendance.deleteMany).toHaveBeenCalledWith({ + where: { attendeeId: 'att-1', ...futureOldClasses }, + }); + expect(prisma.slotRelease.deleteMany).toHaveBeenCalledWith({ + where: { attendeeId: 'att-1', isClaimed: false, ...futureOldClasses }, + }); + }); + + it('rejects moving to the same group', async () => { + prisma.group.findUnique.mockResolvedValue(group() as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await moveRequest('group-1'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('attendee_same_group'); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('rejects a target group owned by another teacher', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(403); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('returns 404 when the target group does not exist', async () => { + prisma.group.findUnique.mockResolvedValueOnce(group() as never).mockResolvedValueOnce(null); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await moveRequest('group-missing'); + + expect(res.status).toBe(404); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the target group reached its capacity', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup({ capacity: 5 }) as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + prisma.attendee.count.mockResolvedValue(5); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('group_capacity_reached'); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the person is already a member of the target group', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup() as never); + prisma.attendee.findFirst + .mockResolvedValueOnce(attendee() as never) + .mockResolvedValueOnce({ id: 'att-existing' } as never); + prisma.attendee.count.mockResolvedValue(3); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('attendee_already_registered'); + expect(prisma.attendee.findFirst).toHaveBeenLastCalledWith({ + where: { groupId: 'group-2', personId: 'person-1' }, + select: { id: true }, + }); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('returns 404 when the member is not in the group', async () => { + prisma.group.findUnique.mockResolvedValue(group() as never); + prisma.attendee.findFirst.mockResolvedValue(null); + + const res = await moveRequest('group-2', teacherId, 'att-missing'); + + expect(res.status).toBe(404); + }); + + it('rejects a non-owner user', async () => { + prisma.group.findUnique.mockResolvedValue(group() as never); + + const res = await moveRequest('group-2', 'other-user'); + + expect(res.status).toBe(403); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('returns 400 without a target group', async () => { + const res = await moveRequest(''); + + expect(res.status).toBe(400); + }); +}); diff --git a/apps/backend/test/attendee-stats.test.ts b/apps/backend/test/attendee-stats.test.ts new file mode 100644 index 0000000..74e1ba8 --- /dev/null +++ b/apps/backend/test/attendee-stats.test.ts @@ -0,0 +1,126 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + }, + attendance: { + groupBy: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import getAttendeeStatsRoute from '@/modules/attendees/features/get-stats/route'; + +const userId = 'user-1'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', getAttendeeStatsRoute); + return app; +} + +function makeGroup(overrides: Record = {}) { + return { id: 'group-1', name: 'Funcional', createdById: userId, members: [], ...overrides }; +} + +function countRow(status: string, count: number) { + return { status, _count: { _all: count } }; +} + +describe('GET /groups/:groupId/attendees/:attendeeId/stats', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('cuenta asistencias, ausencias y justificadas con su porcentaje', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1' }); + prisma.attendance.groupBy.mockResolvedValue([ + countRow('PRESENT', 17), + countRow('ABSENT', 2), + countRow('EXCUSED', 1), + ]); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/a-1/stats', + ); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendeeId: 'a-1', + groupId: 'group-1', + presentCount: 17, + absentCount: 2, + excusedCount: 1, + totalMarked: 20, + attendanceRate: 85, + }); + }); + + it('devuelve conteos en cero cuando el participante no tiene registros', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1' }); + prisma.attendance.groupBy.mockResolvedValue([]); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/a-1/stats', + ); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendeeId: 'a-1', + groupId: 'group-1', + presentCount: 0, + absentCount: 0, + excusedCount: 0, + totalMarked: 0, + attendanceRate: 0, + }); + }); + + it('devuelve 404 si el participante no pertenece al grupo', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/nope/stats', + ); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + + it('devuelve 403 si el usuario no tiene acceso al grupo', async () => { + prisma.group.findUnique.mockResolvedValue( + makeGroup({ createdById: 'otro-user', members: [] }), + ); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/a-1/stats', + ); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('devuelve 401 si no hay sesión', async () => { + const res = await makeApp(undefined).request('/groups/group-1/attendees/a-1/stats'); + + expect(res.status).toBe(401); + }); +}); diff --git a/apps/backend/test/attendee-update.test.ts b/apps/backend/test/attendee-update.test.ts new file mode 100644 index 0000000..41867b0 --- /dev/null +++ b/apps/backend/test/attendee-update.test.ts @@ -0,0 +1,140 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test' +import { Prisma } from '@generated/prisma/client' +import { Hono } from 'hono' + +const db = { + group: { findUnique: mock() }, + attendee: { findFirst: mock(), findUniqueOrThrow: mock() }, + person: { update: mock() }, +} + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})) + +import updateAttendeeRoute from '@/modules/attendees/features/update/route' + +const userId = 'user-1' +const person = { + id: 'person-1', + fullName: 'Ana Pérez', + email: null, + phone: null, + guardianName: null, + guardianPhone: null, + notes: 'Llega temprano', +} +const attendee = { + id: 'a-1', + groupId: 'group-1', + personId: 'person-1', + person, + notifyToken: 'token-1', + createdAt: new Date('2026-08-01T10:00:00.000Z'), + updatedAt: new Date('2026-10-01T12:00:00.000Z'), +} + +function makeApp() { + const app = new Hono() + app.use('*', async (context, next) => { + context.set('user', { id: userId } as never) + await next() + }) + app.route('/groups', updateAttendeeRoute) + return app +} + +describe('PATCH /groups/:groupId/attendees/:attendeeId', () => { + beforeEach(() => { + vi.clearAllMocks() + db.group.findUnique.mockResolvedValue({ + id: 'group-1', + name: 'Funcional', + createdById: userId, + members: [], + }) + db.attendee.findFirst.mockResolvedValue(attendee) + }) + + it('actualiza el contacto de la persona y conserva los campos vacíos como null', async () => { + db.attendee.findUniqueOrThrow.mockResolvedValue({ + ...attendee, + person: { ...person, email: 'ana@example.com' }, + }) + + const response = await makeApp().request('/groups/group-1/attendees/a-1', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: 'ana@example.com', phone: '' }), + }) + + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ id: 'a-1', personId: 'person-1', email: 'ana@example.com' }) + // The person's row: the change shows in every group they are in. + expect(db.person.update).toHaveBeenCalledWith({ + where: { id: 'person-1' }, + data: { email: 'ana@example.com', phone: null }, + }) + }) + + it('normaliza el teléfono como el alta', async () => { + db.attendee.findUniqueOrThrow.mockResolvedValue(attendee) + + await makeApp().request('/groups/group-1/attendees/a-1', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ phone: '11 2345-6789' }), + }) + + expect(db.person.update).toHaveBeenCalledWith({ + where: { id: 'person-1' }, + data: { phone: '1123456789' }, + }) + }) + + it('devuelve 409 si el teléfono ya es de otra persona del profe', async () => { + db.person.update.mockRejectedValueOnce( + new Prisma.PrismaClientKnownRequestError('Unique constraint failed', { + code: 'P2002', + clientVersion: 'test', + }), + ) + + const response = await makeApp().request('/groups/group-1/attendees/a-1', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ phone: '1123456789' }), + }) + + expect(response.status).toBe(409) + expect(await response.json()).toMatchObject({ code: 'person_phone_taken' }) + }) + + it('actualiza una única nota', async () => { + db.attendee.findUniqueOrThrow.mockResolvedValue({ ...attendee, person: { ...person, notes: 'Traer colchoneta' } }) + + await makeApp().request('/groups/group-1/attendees/a-1', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ notes: 'Traer colchoneta' }), + }) + + expect(db.person.update).toHaveBeenCalledWith({ + where: { id: 'person-1' }, + data: { notes: 'Traer colchoneta' }, + }) + }) + + it('rechaza un email inválido', async () => { + const response = await makeApp().request('/groups/group-1/attendees/a-1', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: 'sin-arroba' }), + }) + + expect(response.status).toBe(400) + expect(db.person.update).not.toHaveBeenCalled() + }) +}) diff --git a/apps/backend/test/attendees-incorporation.test.ts b/apps/backend/test/attendees-incorporation.test.ts new file mode 100644 index 0000000..daf6052 --- /dev/null +++ b/apps/backend/test/attendees-incorporation.test.ts @@ -0,0 +1,595 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + findFirst: mock(), + update: mock(), + count: mock(), + }, + attendee: { + findMany: mock(), + findFirst: mock(), + create: mock(), + count: mock(), + }, + person: { + findFirst: mock(), + findMany: mock(), + }, + groupWaitlistEntry: { + findMany: mock(), + findFirst: mock(), + create: mock(), + count: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const mockGroup = { + id: 'group-1', + name: 'Taller de Pintura', + description: 'Acuarelas para principiantes', + createdById: teacherId, + inviteToken: 'pintura-token-xyz', + createdAt: new Date('2026-09-01T10:00:00.000Z'), + updatedAt: new Date('2026-09-01T10:00:00.000Z'), + days: ['MONDAY'], + time: '18:00', + capacity: 20, + price: 1500, + billingType: 'MONTHLY', + dueDay: 10, + members: [], +}; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app; +} + +const personRow = (overrides: Record = {}) => ({ + id: 'person-1', + fullName: 'Martín Gómez', + email: 'martin@example.com', + phone: '+5491133445566', + guardianName: null, + guardianPhone: null, + notes: 'Viene con su hermano', + ...overrides, +}); + +const attendeeRow = (overrides: Record = {}) => ({ + id: 'att-1', + groupId: 'group-1', + personId: 'person-1', + person: personRow(), + notifyToken: null, + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + ...overrides, +}); + +describe('attendee incorporation & invite-token in groups', () => { + beforeEach(() => { + vi.clearAllMocks(); + // Nobody with that phone among the teacher's people, unless a test says so. + prisma.person.findFirst.mockResolvedValue(null); + prisma.person.findMany.mockResolvedValue([]); + }); + + describe('GET /groups/:groupId/invite-token', () => { + it('returns existing invite token and url', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/invite-token'); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.token).toBe('pintura-token-xyz'); + expect(data.inviteUrl).toContain('/join/pintura-token-xyz'); + }); + + it('generates a new token if group did not have one', async () => { + prisma.group.findUnique.mockResolvedValue({ + ...mockGroup, + inviteToken: null, + } as never); + prisma.group.update.mockResolvedValue({} as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/invite-token'); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.token).toBeDefined(); + expect(data.token.length).toBeGreaterThan(5); + expect(prisma.group.update).toHaveBeenCalled(); + }); + + it('rejects user without access to the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const app = makeApp({ id: 'other-user' }); + const res = await app.request('/groups/group-1/invite-token'); + + expect(res.status).toBe(403); + }); + }); + + describe('POST /groups/:groupId/attendees (individual quick add)', () => { + it('creates an attendee for the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.create.mockResolvedValue(attendeeRow() as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '+54 9 11 3344-5566', + email: 'martin@example.com', + notes: 'Viene con su hermano', + }), + }); + + expect(res.status).toBe(201); + const data = await res.json(); + expect(data.outcome).toBe('created'); + expect(data.attendee.fullName).toBe('Martín Gómez'); + expect(data.attendee.phone).toBe('+5491133445566'); + expect(data.attendee.personId).toBe('person-1'); + // A new person of the group owner, created with the membership. + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { + group: { connect: { id: 'group-1' } }, + person: { + create: { + createdById: teacherId, + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: 'martin@example.com', + notes: 'Viene con su hermano', + }, + }, + }, + include: { person: { select: expect.any(Object) } }, + }); + }); + + it('answers person_exists when the phone is already a person of another group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.person.findFirst.mockResolvedValue({ + ...personRow(), + attendees: [{ id: 'att-9', groupId: 'group-9', status: 'ACTIVE', group: { name: 'Yoga' } }], + } as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ firstName: 'Martín', lastName: 'Gómez', phone: '+54 9 11 3344-5566' }), + }); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('person_exists'); + expect(prisma.person.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: { createdById: teacherId, phone: { in: ['+5491133445566', '+54 9 11 3344-5566'] } }, + }), + ); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('adds an existing person (personId) to the group without a new plan slot', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.person.findFirst.mockResolvedValue({ id: 'person-1', fullName: 'Martín Gómez' } as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.count.mockResolvedValue(1); + prisma.attendee.create.mockResolvedValue(attendeeRow() as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-1' }), + }); + + expect(res.status).toBe(201); + expect(prisma.person.findFirst).toHaveBeenCalledWith({ + where: { id: 'person-1', createdById: teacherId }, + select: { id: true, fullName: true }, + }); + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } }, + include: { person: { select: expect.any(Object) } }, + }); + }); + + it('returns 404 for a personId of another teacher', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.person.findFirst.mockResolvedValue(null); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-other' }), + }); + + expect(res.status).toBe(404); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('rejects duplicate phone number in individual add', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.person.findFirst.mockResolvedValue({ + ...personRow(), + attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }], + } as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(409); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('rejects owner with 409 group_capacity_reached when the group is full', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.count.mockResolvedValue(20); // capacity full + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('group_capacity_reached'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled(); + }); + + it('allows the owner to add anyway when allowOverflow is set', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.count.mockResolvedValue(20); + prisma.attendee.create.mockResolvedValue(attendeeRow() as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees?allowOverflow=true', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(201); + const body = await res.json(); + expect(body.outcome).toBe('created'); + expect(body.attendee.fullName).toBe('Martín Gómez'); + expect(prisma.attendee.create).toHaveBeenCalled(); + }); + + it('adds to the waitlist when a non-owner member tries to add to a full group', async () => { + const memberGroup = { + ...mockGroup, + members: [{ id: 'gm-1', role: 'MEMBER' }], + }; + prisma.group.findUnique.mockResolvedValue(memberGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.count.mockResolvedValue(20); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + prisma.groupWaitlistEntry.create.mockResolvedValue({ + id: 'wl-1', + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + notes: null, + status: 'PENDING', + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + } as never); + + const app = makeApp({ id: 'member-1' }); + const res = await app.request('/groups/group-1/attendees', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(201); + const body = await res.json(); + expect(body.outcome).toBe('waitlisted'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({ + data: { + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '1133445566', + email: null, + notes: null, + }, + }); + }); + + it('still waitlists a non-owner member even when allowOverflow is set', async () => { + const memberGroup = { + ...mockGroup, + members: [{ id: 'gm-1', role: 'MEMBER' }], + }; + prisma.group.findUnique.mockResolvedValue(memberGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.count.mockResolvedValue(20); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + + const app = makeApp({ id: 'member-1' }); + const res = await app.request('/groups/group-1/attendees?allowOverflow=true', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(201); + const body = await res.json(); + expect(body.outcome).toBe('waitlisted'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupWaitlistEntry.create).toHaveBeenCalled(); + }); + }); + + describe('POST /groups/:groupId/waitlist (add to group waitlist)', () => { + it('creates a waitlist entry for the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + prisma.groupWaitlistEntry.create.mockResolvedValue({ + id: 'wl-1', + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: 'martin@example.com', + notes: 'Viene con su hermano', + status: 'PENDING', + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + } as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/waitlist', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '+54 9 11 3344-5566', + email: 'martin@example.com', + notes: 'Viene con su hermano', + }), + }); + + expect(res.status).toBe(201); + const body = await res.json(); + expect(body.fullName).toBe('Martín Gómez'); + expect(body.phone).toBe('+5491133445566'); + expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({ + data: { + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: 'martin@example.com', + notes: 'Viene con su hermano', + }, + }); + }); + + it('rejects when the phone number already belongs to an attendee', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/waitlist', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('attendee_already_registered'); + expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled(); + }); + + it('rejects when the phone number is already on the waitlist', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue({ id: 'wl-existing' } as never); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/waitlist', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('already_waitlisted'); + }); + + it('rejects user without access to the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const app = makeApp({ id: 'other-user' }); + const res = await app.request('/groups/group-1/waitlist', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Martín', + lastName: 'Gómez', + phone: '1133445566', + }), + }); + + expect(res.status).toBe(403); + }); + }); + + describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => { + it('imports multiple attendees, skipping duplicates and reporting counts', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + // The teacher's people: '11111111' is already in this group, '44444444' + // is in another group only (and active there). + prisma.person.findMany.mockResolvedValue([ + { id: 'person-in-group', phone: '11111111', attendees: [{ groupId: 'group-1', status: 'ACTIVE' }] }, + { id: 'person-elsewhere', phone: '44444444', attendees: [{ groupId: 'group-9', status: 'ACTIVE' }] }, + ] as never); + + prisma.attendee.create.mockImplementation(async ({ data }: { data: any }) => ({ + id: `att-${Math.random()}`, + groupId: 'group-1', + personId: data.personId ?? 'person-new', + notifyToken: null, + person: personRow({ fullName: data.person?.create?.fullName ?? 'Existente' }), + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + })); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees/bulk', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + attendees: [ + { firstName: 'Ana', lastName: 'García', phone: '22222222' }, + { firstName: 'Pedro', lastName: 'López', phone: '33333333' }, + { firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the group + { firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch + { firstName: 'Otra', lastName: 'Persona', phone: '44444444' }, // In another group: linked + ], + }), + }); + + expect(res.status).toBe(201); + const data = await res.json(); + expect(data.totalProcessed).toBe(5); + expect(data.createdCount).toBe(3); + expect(data.linkedCount).toBe(1); + expect(data.duplicatesCount).toBe(2); + expect(data.message).toBe( + '3 alumnos agregados con éxito (1 ya estaban en otros de tus grupos), 2 duplicados omitidos.', + ); + expect(prisma.attendee.create).toHaveBeenCalledTimes(3); + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { groupId: 'group-1', personId: 'person-elsewhere' }, + include: { person: { select: expect.any(Object) } }, + }); + }); + }); + + describe('GET /groups/:groupId/attendees', () => { + it('lists attendees filtered by groupId', async () => { + prisma.attendee.findMany.mockResolvedValue([ + { + id: 'att-1', + groupId: 'group-1', + personId: 'person-1', + person: personRow({ fullName: 'Ana García', phone: '22222222', email: null, notes: null }), + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + attendances: [], + payments: [], + }, + ] as never); + prisma.attendee.count.mockResolvedValue(1); + + const app = makeApp({ id: teacherId }); + const res = await app.request('/groups/group-1/attendees'); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.data.length).toBe(1); + expect(data.data[0].fullName).toBe('Ana García'); + expect(data.data[0].recentAttendance).toEqual([]); + expect(data.data[0].payment).toBeNull(); + expect(prisma.attendee.findMany).toHaveBeenCalledWith({ + where: { groupId: 'group-1' }, + skip: 0, + take: 10, + orderBy: { createdAt: 'desc' }, + // The row summary is requested in the same query: one request per + // member would be N+1 over a listing of up to 100. + include: { + person: { select: expect.any(Object) }, + attendances: { + orderBy: { classSession: { startsAt: 'desc' } }, + take: RECENT_ATTENDANCE_LIMIT, + select: { status: true }, + }, + payments: { + where: { status: { not: 'CANCELLED' } }, + orderBy: { dueDate: 'desc' }, + take: 3, + select: { status: true, dueDate: true }, + }, + }, + }); + }); + }); +}); diff --git a/apps/backend/test/attendees-list-item.test.ts b/apps/backend/test/attendees-list-item.test.ts new file mode 100644 index 0000000..13eefa9 --- /dev/null +++ b/apps/backend/test/attendees-list-item.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'bun:test'; +import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers'; +import { toAttendeeListItemDto } from '@/modules/attendees/lib/helpers'; + +/* The row summary is built in memory: which class counts as recent and + which payment is shown. Those are the two decisions the row reads. */ + +function record( + overrides: Partial = {}, +): AttendeeListItemRecord { + return { + id: 'att-1', + groupId: 'group-1', + personId: 'person-1', + person: { + id: 'person-1', + fullName: 'Ana Pérez', + email: null, + phone: null, + guardianName: null, + guardianPhone: null, + notes: null, + }, + notifyToken: null, + createdAt: new Date('2026-08-01T10:00:00.000Z'), + updatedAt: new Date('2026-08-01T10:00:00.000Z'), + attendances: [], + payments: [], + ...overrides, + }; +} + +const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`); + +describe('toAttendeeListItemDto', () => { + it('invierte la asistencia para que la clase más reciente quede a la derecha', () => { + const dto = toAttendeeListItemDto( + record({ + // It arrives from most recent to oldest. + attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }], + }), + ); + + expect(dto.recentAttendance).toEqual(['ABSENT', 'EXCUSED', 'PRESENT']); + }); + + it('deja la lista vacía cuando no hay ninguna clase registrada', () => { + expect(toAttendeeListItemDto(record()).recentAttendance).toEqual([]); + }); + + it('no inventa cobro cuando no hay pagos', () => { + expect(toAttendeeListItemDto(record()).payment).toBeNull(); + }); + + it('arranca en cero los pagos impagos y descarta los cancelados', () => { + const dto = toAttendeeListItemDto( + record({ + payments: [ + { status: 'CANCELLED', dueDate: day('2026-01-05') }, + { status: 'PAID', dueDate: day('2026-08-10') }, + { status: 'PENDING', dueDate: day('2026-09-10') }, + ], + }), + ); + + expect(dto.payment).toEqual({ status: 'PENDING', dueDate: '2026-09-10T00:00:00.000Z' }); + }); + + it('manda el impago más antiguo: los días de atraso son los que hay que ver', () => { + const dto = toAttendeeListItemDto( + record({ + payments: [ + { status: 'PENDING', dueDate: day('2026-09-10') }, + { status: 'OVERDUE', dueDate: day('2026-04-10') }, + ], + }), + ); + + expect(dto.payment).toEqual({ status: 'OVERDUE', dueDate: '2026-04-10T00:00:00.000Z' }); + }); + + it('cae al último pago cerrado cuando no queda nada impago', () => { + const dto = toAttendeeListItemDto( + record({ + payments: [ + { status: 'PAID', dueDate: day('2026-08-10') }, + { status: 'PAID', dueDate: day('2026-09-10') }, + ], + }), + ); + + expect(dto.payment).toEqual({ status: 'PAID', dueDate: '2026-09-10T00:00:00.000Z' }); + }); + + it('conserva los campos del DTO plano', () => { + const base = record(); + const dto = toAttendeeListItemDto(record({ person: { ...base.person, phone: '22222222' } })); + + expect(dto.fullName).toBe('Ana Pérez'); + expect(dto.phone).toBe('22222222'); + expect(dto.personId).toBe('person-1'); + expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z'); + }); +}); diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts new file mode 100644 index 0000000..428229b --- /dev/null +++ b/apps/backend/test/attendees.test.ts @@ -0,0 +1,132 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; +import { Hono } from 'hono'; + +mock.module('@/lib/prisma', () => ({ + default: { + attendee: { + findMany: mock(), + count: mock(), + }, + }, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { attendeesRoutes } from '@/modules/attendees'; + +const app = new Hono(); +app.route('/attendees', attendeesRoutes); + +const personSelect = { + id: true, + fullName: true, + email: true, + phone: true, + guardianName: true, + guardianPhone: true, + notes: true, +}; + +const person = { + id: 'person-1', + fullName: 'Ana Pérez', + email: 'ana@example.com', + phone: null, + guardianName: 'Luis Pérez', + guardianPhone: null, + notes: null, +}; + +const attendeeRow = { + id: 'attendee-1', + groupId: 'group-1', + personId: 'person-1', + notifyToken: null, + createdAt: new Date('2026-08-01T10:00:00.000Z'), + updatedAt: new Date('2026-08-01T10:00:00.000Z'), +}; + +// What the Prisma mock returns: the row plus the summary relations. +const attendee = { + ...attendeeRow, + person, + attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }], + payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }], +}; + +describe('attendees routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('lists attendees with pagination', async () => { + prisma.attendee.findMany.mockResolvedValue([attendee]); + prisma.attendee.count.mockResolvedValue(21); + + const res = await app.request('/attendees?page=2&pageSize=10'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + data: [ + { + ...attendeeRow, + fullName: person.fullName, + email: person.email, + phone: person.phone, + guardianName: person.guardianName, + guardianPhone: person.guardianPhone, + notes: person.notes, + createdAt: attendeeRow.createdAt.toISOString(), + updatedAt: attendeeRow.updatedAt.toISOString(), + // The query comes most recent first; the row shows them + // the other way around, with the most recent class on the right. + recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'], + payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' }, + }, + ], + pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 }, + }); + expect(prisma.attendee.findMany).toHaveBeenCalledWith({ + skip: 10, + take: 10, + orderBy: { createdAt: 'desc' }, + include: { + person: { select: personSelect }, + attendances: { + orderBy: { classSession: { startsAt: 'desc' } }, + take: RECENT_ATTENDANCE_LIMIT, + select: { status: true }, + }, + payments: { + where: { status: { not: 'CANCELLED' } }, + orderBy: { dueDate: 'desc' }, + take: 3, + select: { status: true, dueDate: true }, + }, + }, + }); + expect(prisma.attendee.count).toHaveBeenCalledWith(); + }); + + it('uses default pagination', async () => { + prisma.attendee.findMany.mockResolvedValue([]); + prisma.attendee.count.mockResolvedValue(0); + + const res = await app.request('/attendees'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + data: [], + pagination: { page: 1, pageSize: 10, total: 0, totalPages: 0 }, + }); + }); + + it('rejects invalid pagination query parameters', async () => { + const res = await app.request('/attendees?page=0&pageSize=25'); + + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ status: 400, title: 'Bad Request' }); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/attention.test.ts b/apps/backend/test/attention.test.ts new file mode 100644 index 0000000..db289fb --- /dev/null +++ b/apps/backend/test/attention.test.ts @@ -0,0 +1,130 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { Prisma } from '@generated/prisma/client'; +import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case'; +import { ResolveStudentAlert } from '@/modules/attention/features/resolve/use-case'; + +const NOW = new Date('2026-10-27T20:00:00.000Z'); +const DAY_MS = 24 * 60 * 60 * 1000; +const at = (days: number) => new Date(NOW.getTime() - days * DAY_MS); + +const db = { + group: { findMany: mock() }, + attendee: { findMany: mock(), findFirst: mock() }, + classSession: { findMany: mock() }, + attendance: { findMany: mock() }, + payment: { findMany: mock() }, + attendeeAlertResolution: { findMany: mock(), upsert: mock() }, + user: { findUnique: mock() }, +}; + +function overview() { + return new GetAttentionOverview({ db: db as never, now: NOW }); +} + +beforeEach(() => { + for (const delegate of Object.values(db)) { + for (const fn of Object.values(delegate)) fn.mockReset(); + } +}); + +describe('GetAttentionOverview', () => { + it('sin grupos no consulta nada más', async () => { + db.group.findMany.mockResolvedValue([]); + const result = await overview().execute('user-1'); + expect(result).toEqual({ ok: true, value: { groups: [] } }); + expect(db.attendee.findMany).not.toHaveBeenCalled(); + }); + + it('devuelve todos los miembros con sus alertas, sin las resueltas', async () => { + db.user.findUnique.mockResolvedValue({ country: 'AR' }); + db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]); + db.attendee.findMany.mockResolvedValue([ + { id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) }, + { id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) }, + { id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) }, + ]); + db.classSession.findMany.mockResolvedValue([ + { id: 's1', groupId: 'g1', startsAt: at(1) }, + { id: 's2', groupId: 'g1', startsAt: at(3) }, + { id: 's3', groupId: 'g1', startsAt: at(5) }, + ]); + const row = (attendeeId: string, sessionId: string, status: string, days: number) => ({ + attendeeId, + classSessionId: sessionId, + status, + classSession: { startsAt: at(days) }, + }); + db.attendance.findMany.mockResolvedValue([ + row('a1', 's1', 'ABSENT', 1), + row('a1', 's2', 'ABSENT', 3), + row('a1', 's3', 'ABSENT', 5), + // Valentina missed two classes, but the professor already resolved it. + row('a2', 's1', 'ABSENT', 1), + row('a2', 's2', 'ABSENT', 3), + row('a3', 's1', 'PRESENT', 1), + ]); + db.payment.findMany.mockResolvedValue([ + { + id: 'p1', + attendeeId: 'a2', + amount: new Prisma.Decimal('15000.00'), + currency: 'ARS', + dueDate: new Date('2026-10-10T12:00:00.000Z'), + checkoutUrl: 'https://mp.test/p1', + }, + ]); + db.attendeeAlertResolution.findMany.mockResolvedValue([ + { attendeeId: 'a2', kind: 'ATTENDANCE', signature: 's1' }, + ]); + + const result = await overview().execute('user-1'); + if (!result.ok) throw new Error('expected ok'); + + const [group] = result.value.groups; + expect(group).toMatchObject({ groupId: 'g1', groupName: 'Natación', capacity: 30 }); + expect(group.members.map((member) => member.attendeeId)).toEqual(['a1', 'a2', 'a3']); + + const [agustina, valentina, felipe] = group.members; + expect(agustina.phone).toBe('1155550000'); + expect(agustina.whatsappPhone).toBe('+5491155550000'); + expect(agustina.alerts).toMatchObject([{ tipo: 'asistencia', gravedad: 'urgente', etiqueta: '3 seguidas' }]); + + expect(valentina.phone).toBe('1166660000'); + expect(valentina.alerts).toMatchObject([{ tipo: 'pago', gravedad: 'vigilar', etiqueta: 'Cuota vencida' }]); + expect(valentina.overduePayments).toEqual([ + { id: 'p1', amount: 15000, currency: 'ARS', dueDate: '2026-10-10T12:00:00.000Z', checkoutUrl: 'https://mp.test/p1' }, + ]); + + expect(felipe.alerts).toEqual([]); + }); +}); + +describe('ResolveStudentAlert', () => { + it('guarda la firma con upsert por alumno y tipo', async () => { + db.attendee.findFirst.mockResolvedValue({ id: 'a1' }); + const result = await new ResolveStudentAlert({ db: db as never }).execute('a1', 'user-1', { + tipo: 'pago', + firma: 'p1,p2', + }); + + expect(result).toEqual({ ok: true, value: { attendeeId: 'a1', tipo: 'pago', firma: 'p1,p2' } }); + expect(db.attendeeAlertResolution.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + where: { attendeeId_kind: { attendeeId: 'a1', kind: 'PAYMENT' } }, + create: expect.objectContaining({ signature: 'p1,p2', resolvedById: 'user-1' }), + }), + ); + }); + + it('un alumno de un grupo ajeno es 404 y no escribe nada', async () => { + db.attendee.findFirst.mockResolvedValue(null); + const result = await new ResolveStudentAlert({ db: db as never }).execute('a9', 'user-1', { + tipo: 'asistencia', + firma: 's1', + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(404); + expect(db.attendeeAlertResolution.upsert).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/billing-entitlements.test.ts b/apps/backend/test/billing-entitlements.test.ts new file mode 100644 index 0000000..5dc8687 --- /dev/null +++ b/apps/backend/test/billing-entitlements.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements'; + +const now = new Date('2026-10-22T12:00:00.000Z'); +const days = (n: number) => new Date(now.getTime() + n * 24 * 60 * 60 * 1000); + +function makeDb(params: { + subscription?: Record | null; + groups?: number; + attendees?: number; +}) { + return { + billingSubscription: { findUnique: mock(async () => params.subscription ?? null) }, + group: { count: mock(async () => params.groups ?? 0) }, + // People with an active membership: someone in two groups counts once. + person: { count: mock(async () => params.attendees ?? 0) }, + }; +} + +function makeGuard(db: ReturnType, enforced = true) { + return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now }); +} + +describe('resolvePlan', () => { + it('is Free without a subscription', () => { + expect(resolvePlan(null, now, 7)).toEqual({ plan: 'FREE', graceUntil: null }); + }); + + it('is Pro while a charge covers today', () => { + const plan = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-20), paidThrough: days(10) }, now, 7); + expect(plan).toEqual({ plan: 'PRO', graceUntil: null }); + }); + + it('keeps Pro on grace after the paid period, then drops to Free', () => { + const onGrace = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-40), paidThrough: days(-2) }, now, 7); + expect(onGrace).toEqual({ plan: 'PRO', graceUntil: days(5) }); + + const lapsed = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-40), paidThrough: days(-8) }, now, 7); + expect(lapsed).toEqual({ plan: 'FREE', graceUntil: null }); + }); + + it('keeps Pro until the end of what was paid after a cancellation', () => { + const plan = resolvePlan({ status: 'CANCELLED', authorizedAt: days(-20), paidThrough: days(10) }, now, 7); + expect(plan.plan).toBe('PRO'); + }); + + it('is Pro right after authorizing, while the first charge is in flight', () => { + const plan = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-1), paidThrough: null }, now, 7); + expect(plan.plan).toBe('PRO'); + }); + + it('is Free for a subscription that was never authorized', () => { + const plan = resolvePlan({ status: 'PENDING', authorizedAt: null, paidThrough: null }, now, 7); + expect(plan.plan).toBe('FREE'); + }); +}); + +describe('PlanGuard', () => { + it('lets everything through without touching the database when not enforced', async () => { + const db = makeDb({ groups: 50, attendees: 500 }); + const guard = makeGuard(db, false); + + expect((await guard.canCreateGroup('user-1')).ok).toBe(true); + expect((await guard.canAddAttendees('user-1', 10)).ok).toBe(true); + expect((await guard.requireFeature('user-1', 'mpCharges')).ok).toBe(true); + expect((await guard.requireWritable('user-1')).ok).toBe(true); + expect(db.group.count).not.toHaveBeenCalled(); + }); + + it('stops a Free professor at the group limit', async () => { + const result = await makeGuard(makeDb({ groups: 1 })).canCreateGroup('user-1'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' }); + }); + + it('counts a whole import against the attendee limit', async () => { + const guard = makeGuard(makeDb({ groups: 1, attendees: 10 })); + + expect((await guard.canAddAttendees('user-1', 5)).ok).toBe(true); + const tooMany = await guard.canAddAttendees('user-1', 6); + expect(tooMany.ok).toBe(false); + if (!tooMany.ok) expect(tooMany.error.code).toBe('plan_limit_reached'); + }); + + it('keeps Pro-only features off for Free', async () => { + const result = await makeGuard(makeDb({})).requireFeature('user-1', 'whatsappAutomations'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' }); + }); + + it('puts a Free account over its limits in read-only', async () => { + const guard = makeGuard(makeDb({ groups: 3, attendees: 40 })); + + const entitlements = await guard.getEntitlements('user-1'); + expect(entitlements.readOnly).toBe(true); + const writable = await guard.requireWritable('user-1'); + expect(writable.ok).toBe(false); + if (!writable.ok) expect(writable.error.code).toBe('plan_read_only'); + }); + + it('gives Pro no limits', async () => { + const guard = makeGuard( + makeDb({ + subscription: { status: 'AUTHORIZED', authorizedAt: days(-5), paidThrough: days(25) }, + groups: 12, + attendees: 300, + }), + ); + + expect((await guard.canCreateGroup('user-1')).ok).toBe(true); + expect((await guard.canAddAttendees('user-1', 100)).ok).toBe(true); + expect((await guard.requireFeature('user-1', 'mpCharges')).ok).toBe(true); + expect((await guard.getEntitlements('user-1')).readOnly).toBe(false); + }); +}); diff --git a/apps/backend/test/billing-plan-guards.test.ts b/apps/backend/test/billing-plan-guards.test.ts new file mode 100644 index 0000000..77cc2bd --- /dev/null +++ b/apps/backend/test/billing-plan-guards.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { err } from '@gruperly/shared'; +import { + planFeatureRequiredProblem, + planLimitReachedProblem, +} from '@/http/problem-builders'; +import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case'; +import { CreateGroup } from '@/modules/groups/features/create/use-case'; +import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case'; +import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case'; + +const ownerId = 'owner-1'; + +describe('plan guards in the use cases', () => { + it('does not create a group past the Free limit', async () => { + const unitOfWork = { executeResult: mock() }; + const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) }; + + const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute( + {} as never, + ownerId, + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' }); + expect(unitOfWork.executeResult).not.toHaveBeenCalled(); + }); + + it('checks a bulk import against the group owner, with the number of new attendees', async () => { + const db = { + group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) }, + attendee: { create: mock() }, + // '1111' is already in this group; '4444' is active in another group. + person: { + findMany: mock(async () => [ + { id: 'p1', phone: '1111', attendees: [{ groupId: 'g1', status: 'ACTIVE' }] }, + { id: 'p4', phone: '4444', attendees: [{ groupId: 'g2', status: 'ACTIVE' }] }, + ]), + }, + }; + const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) }; + + const result = await new BulkCreateAttendeesUseCase({ db: db as never, planGuard }).execute('g1', 'admin-1', { + attendees: [ + { fullName: 'Ana', phone: '2222' }, + { fullName: 'Beto', phone: '3333' }, + { fullName: 'Repetido', phone: '1111' }, + { fullName: 'De otro grupo', phone: '4444' }, + ], + } as never); + + // Only the two new people: the one already active elsewhere takes no slot. + expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2); + expect(result.ok).toBe(false); + expect(db.attendee.create).not.toHaveBeenCalled(); + }); + + it('keeps charging with Mercado Pago for Pro', async () => { + const db = { + group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, price: 100, members: [] })) }, + attendee: { findMany: mock() }, + payment: { create: mock() }, + user: { findUnique: mock() }, + }; + const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('mpCharges'))) }; + + const result = await new CreatePaymentBatch({ db: db as never, planGuard }).execute('g1', ownerId, { + dueDate: '2026-11-05T12:00:00.000Z', + }); + + expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'mpCharges'); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' }); + expect(db.attendee.findMany).not.toHaveBeenCalled(); + }); + + it('blocks turning automations on for Free, but lets them be turned off', async () => { + const db = { + group: { + findUnique: mock(async () => ({ id: 'g1', createdById: ownerId })), + update: mock(async () => ({ autoPaymentReminders: false, autoReengagement: false })), + }, + }; + const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('whatsappAutomations'))) }; + const useCase = new UpdateGroupAutomationsUseCase({ db: db as never, planGuard }); + + const on = await useCase.execute('g1', ownerId, { autoPaymentReminders: true }); + expect(on.ok).toBe(false); + expect(db.group.update).not.toHaveBeenCalled(); + + const off = await useCase.execute('g1', ownerId, { autoPaymentReminders: false }); + expect(off.ok).toBe(true); + expect(db.group.update).toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/billing-stripe-provider.test.ts b/apps/backend/test/billing-stripe-provider.test.ts new file mode 100644 index 0000000..dac9cca --- /dev/null +++ b/apps/backend/test/billing-stripe-provider.test.ts @@ -0,0 +1,242 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { createHmac } from 'node:crypto'; +import { + fromStripeUnitAmount, + StripeBillingProvider, + toForm, + toStripeUnitAmount, + verifyStripeSignature, +} from '@/modules/billing/providers/stripe'; + +const now = new Date('2026-10-22T12:00:00.000Z'); +const seconds = (date: Date) => Math.floor(date.getTime() / 1000); + +type Call = { url: string; method: string; body: URLSearchParams | null }; + +/** A fake `fetch` answering by "METHOD path" (query left out). */ +function fakeStripe(routes: Record) { + const calls: Call[] = []; + const fetch = mock(async (input: string, init: RequestInit) => { + const url = new URL(input); + const method = init.method ?? 'GET'; + calls.push({ url: input, method, body: init.body ? new URLSearchParams(String(init.body)) : null }); + const key = `${method} ${url.pathname.replace('/v1', '')}`; + if (!(key in routes)) return new Response(JSON.stringify({ error: { code: 'resource_missing' } }), { status: 404 }); + return new Response(JSON.stringify(routes[key])); + }); + const provider = new StripeBillingProvider({ + config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }), + fetch: fetch as never, + now: () => now, + }); + return { provider, calls }; +} + +const startInput = { + userId: 'user-1', + country: 'MX' as const, + amount: 199, + currency: 'MXN', + payerEmail: null, + backUrl: 'http://web/billing?sub=return', +}; + +describe('Stripe amounts', () => { + it('uses minor units except for zero-decimal currencies', () => { + expect(toStripeUnitAmount(199, 'MXN')).toBe(19900); + expect(toStripeUnitAmount(9900, 'CLP')).toBe(9900); + expect(fromStripeUnitAmount(19900, 'mxn')).toBe(199); + expect(fromStripeUnitAmount(9900, 'clp')).toBe(9900); + }); + + it('encodes nested params the way Stripe expects', () => { + const form = toForm({ a: { b: [{ c: 1 }] }, skip: null }); + expect(form.toString()).toBe(new URLSearchParams({ 'a[b][0][c]': '1' }).toString()); + }); +}); + +describe('StripeBillingProvider.start', () => { + it('opens a subscription checkout priced inline in the local currency', async () => { + const { provider, calls } = fakeStripe({ + 'POST /checkout/sessions': { id: 'cs_1', url: 'https://checkout.stripe.com/cs_1' }, + }); + + const started = await provider.start(startInput); + + expect(started).toEqual({ checkoutUrl: 'https://checkout.stripe.com/cs_1', externalId: null, checkoutRef: 'cs_1' }); + const body = calls[0]?.body; + expect(body?.get('mode')).toBe('subscription'); + expect(body?.get('client_reference_id')).toBe('user-1'); + expect(body?.get('line_items[0][price_data][currency]')).toBe('mxn'); + expect(body?.get('line_items[0][price_data][unit_amount]')).toBe('19900'); + expect(body?.get('line_items[0][price_data][recurring][interval]')).toBe('month'); + expect(body?.get('subscription_data[metadata][gruperly_user_id]')).toBe('user-1'); + expect(body?.has('customer_email')).toBe(false); + expect(body?.has('subscription_data[trial_end]')).toBe(false); + }); + + it('defers the first charge to the end of a paid period', async () => { + const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://x' } }); + const startDate = new Date('2026-11-10T00:00:00.000Z'); + + await provider.start({ ...startInput, startDate }); + + expect(calls[0]?.body?.get('subscription_data[trial_end]')).toBe(String(seconds(startDate))); + }); + + it('charges right away when the paid period ends sooner than Checkout allows', async () => { + const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://x' } }); + + await provider.start({ ...startInput, startDate: new Date('2026-10-23T00:00:00.000Z') }); + + expect(calls[0]?.body?.has('subscription_data[trial_end]')).toBe(false); + }); +}); + +describe('StripeBillingProvider.fetch', () => { + it('is null while the checkout is open', async () => { + const { provider } = fakeStripe({ 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'open', subscription: null } }); + + expect(await provider.fetch({ country: 'MX', externalId: null, checkoutRef: 'cs_1' })).toBeNull(); + }); + + it('resolves the subscription through a completed checkout', async () => { + const periodEnd = new Date('2026-11-22T12:00:00.000Z'); + const { provider } = fakeStripe({ + 'GET /checkout/sessions/cs_1': { + id: 'cs_1', + status: 'complete', + subscription: 'sub_1', + customer_details: { email: 'card@mail.com' }, + }, + 'GET /subscriptions/sub_1': { + id: 'sub_1', + status: 'active', + metadata: { gruperly_user_id: 'user-1' }, + items: { data: [{ current_period_end: seconds(periodEnd) }] }, + customer: { id: 'cus_1', email: 'other@mail.com' }, + }, + }); + + expect(await provider.fetch({ country: 'MX', externalId: null, checkoutRef: 'cs_1' })).toEqual({ + externalId: 'sub_1', + ownerUserId: 'user-1', + status: 'AUTHORIZED', + nextPaymentDate: periodEnd, + payerEmail: 'card@mail.com', + }); + }); + + it('maps Stripe statuses to ours', async () => { + const statusOf = async (status: string) => { + const { provider } = fakeStripe({ + 'GET /subscriptions/sub_1': { id: 'sub_1', status, metadata: {}, items: { data: [] } }, + }); + return (await provider.fetch({ country: null, externalId: 'sub_1', checkoutRef: null }))?.status; + }; + + expect(await statusOf('incomplete')).toBe('PENDING'); + expect(await statusOf('past_due')).toBe('AUTHORIZED'); + expect(await statusOf('unpaid')).toBe('PAUSED'); + expect(await statusOf('canceled')).toBe('CANCELLED'); + expect(await statusOf('something_new')).toBeNull(); + }); +}); + +describe('StripeBillingProvider.listCharges', () => { + it('turns invoices into charges covering their period', async () => { + const paidAt = new Date('2026-10-22T12:00:00.000Z'); + const periodEnd = new Date('2026-11-22T12:00:00.000Z'); + const { provider } = fakeStripe({ + 'GET /invoices': { + data: [ + { + id: 'in_1', + status: 'paid', + total: 19900, + amount_paid: 19900, + currency: 'mxn', + status_transitions: { paid_at: seconds(paidAt) }, + lines: { data: [{ period: { end: seconds(periodEnd) } }] }, + }, + { id: 'in_2', status: 'open', total: 19900, amount_due: 19900, currency: 'mxn' }, + { id: 'in_3', status: 'uncollectible', total: 19900, amount_due: 19900, currency: 'mxn' }, + { id: 'in_trial', status: 'paid', total: 0, amount_paid: 0, currency: 'mxn' }, + { id: 'in_draft', status: 'draft', total: 19900, currency: 'mxn' }, + ], + }, + }); + + const charges = await provider.listCharges({ country: 'MX', externalId: 'sub_1', checkoutRef: null }); + + expect(charges).toEqual([ + { externalId: 'in_1', amount: 199, currency: 'MXN', status: 'approved', paidAt, coveredUntil: periodEnd }, + { externalId: 'in_2', amount: 199, currency: 'MXN', status: 'pending', paidAt: null, coveredUntil: null }, + { externalId: 'in_3', amount: 199, currency: 'MXN', status: 'rejected', paidAt: null, coveredUntil: null }, + ]); + }); +}); + +describe('StripeBillingProvider.cancel', () => { + it('cancels a live subscription', async () => { + const { provider, calls } = fakeStripe({ 'DELETE /subscriptions/sub_1': { id: 'sub_1', status: 'canceled' } }); + + await provider.cancel({ country: 'MX', externalId: 'sub_1', checkoutRef: 'cs_1' }); + + expect(calls.map((call) => `${call.method} ${new URL(call.url).pathname}`)).toEqual(['DELETE /v1/subscriptions/sub_1']); + }); + + it('expires a checkout that is still open', async () => { + const { provider, calls } = fakeStripe({ + 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'open' }, + 'POST /checkout/sessions/cs_1/expire': { id: 'cs_1', status: 'expired' }, + }); + + await provider.cancel({ country: 'MX', externalId: null, checkoutRef: 'cs_1' }); + + expect(calls.map((call) => call.method)).toEqual(['GET', 'POST']); + }); + + it('cancels the subscription of a checkout completed meanwhile', async () => { + const { provider, calls } = fakeStripe({ + 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'complete', subscription: 'sub_1' }, + 'DELETE /subscriptions/sub_1': { id: 'sub_1' }, + }); + + await provider.cancel({ country: 'MX', externalId: null, checkoutRef: 'cs_1' }); + + expect(calls.at(-1)?.method).toBe('DELETE'); + }); +}); + +describe('StripeBillingProvider without credentials', () => { + it('is not available and refuses to call Stripe', async () => { + const provider = new StripeBillingProvider({ config: () => null }); + + expect(provider.isAvailable('MX')).toBe(false); + await expect(provider.start(startInput)).rejects.toThrow('not configured'); + }); +}); + +describe('verifyStripeSignature', () => { + const secret = 'whsec_test'; + const rawBody = '{"id":"evt_1"}'; + const t = seconds(now); + const sign = (ts: number, body = rawBody) => createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex'); + + it('accepts a valid signature, including one among several v1', () => { + expect(verifyStripeSignature({ signature: `t=${t},v1=${sign(t)}`, rawBody, secret, now })).toBe(true); + expect(verifyStripeSignature({ signature: `t=${t},v1=${'0'.repeat(64)},v1=${sign(t)}`, rawBody, secret, now })).toBe( + true, + ); + }); + + it('rejects a tampered body, a missing header and an old timestamp', () => { + expect(verifyStripeSignature({ signature: `t=${t},v1=${sign(t)}`, rawBody: '{"id":"evt_2"}', secret, now })).toBe( + false, + ); + expect(verifyStripeSignature({ signature: null, rawBody, secret, now })).toBe(false); + const old = t - 10 * 60; + expect(verifyStripeSignature({ signature: `t=${old},v1=${sign(old)}`, rawBody, secret, now })).toBe(false); + }); +}); diff --git a/apps/backend/test/billing-subscribe.test.ts b/apps/backend/test/billing-subscribe.test.ts new file mode 100644 index 0000000..121c7b9 --- /dev/null +++ b/apps/backend/test/billing-subscribe.test.ts @@ -0,0 +1,299 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; +import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; +import type { BillingProvider } from '@/modules/billing/providers'; +import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago'; + +const userId = 'user-1'; +const now = new Date('2026-10-22T12:00:00.000Z'); +const credentials = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }); + +let calls: string[] = []; + +// Argentina: Mercado Pago. Any other country goes to Stripe. +function makeDb(existing: Record | null, country: string | null = 'AR') { + return { + user: { findUnique: mock(async () => ({ id: userId, country, email: 'login@mail.com' })) }, + billingSubscription: { + findUnique: mock(async () => existing), + upsert: mock(async (args: { create: Record }) => { + calls.push('upsert'); + return { id: 'sub-1', paidThrough: existing?.paidThrough ?? null, ...args.create }; + }), + update: mock(async () => { + calls.push('update'); + return {}; + }), + }, + }; +} + +function makeClient(): PreapprovalClient { + return { + createPreapproval: mock(async () => { + calls.push('createPreapproval'); + return { id: 'pre-1', status: 'pending', externalReference: userId, initPoint: 'https://mp/checkout', nextPaymentDate: null }; + }), + cancelPreapproval: mock(async () => { + calls.push('cancelPreapproval'); + return { id: 'old', status: 'cancelled', externalReference: userId, initPoint: null, nextPaymentDate: null }; + }), + getPreapproval: mock(), + getAuthorizedPayment: mock(), + searchAuthorizedPayments: mock(), + } as unknown as PreapprovalClient; +} + +function mpProvider(client: PreapprovalClient) { + return new MercadoPagoBillingProvider({ client, credentials }); +} + +function subscribe(db: ReturnType, client = makeClient()) { + const provider = mpProvider(client); + return { + client, + run: (returnTo: 'billing' | 'onboarding' = 'billing') => + new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute( + userId, + { payerEmail: 'profe@mail.com', returnTo }, + ), + }; +} + +describe('Subscribe', () => { + beforeEach(() => { + calls = []; + }); + + it('writes the PENDING row before asking Mercado Pago, in the country currency', async () => { + const db = makeDb(null); + const { client, run } = subscribe(db); + + const result = await run(); + + expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://mp/checkout' } }); + expect(calls).toEqual(['upsert', 'createPreapproval', 'update']); + expect(client.createPreapproval).toHaveBeenCalledWith('platform-token', { + reason: 'Gruperly Pro', + externalReference: userId, + payerEmail: 'profe@mail.com', + amount: 15000, + currencyId: 'ARS', + backUrl: 'http://web/billing?sub=return', + startDate: undefined, + }); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { externalId: 'pre-1', checkoutRef: null, lastSyncedAt: now }, + }); + }); + + it('sends the onboarding back to its own step', async () => { + const { client, run } = subscribe(makeDb(null)); + await run('onboarding'); + + expect((client.createPreapproval as ReturnType).mock.calls[0]?.[1]).toMatchObject({ + backUrl: 'http://web/onboarding?sub=return', + }); + }); + + it('refuses a second subscription while one is authorized', async () => { + const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', provider: 'MERCADO_PAGO', externalId: 'pre-0' })); + + const result = await run(); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 409, code: 'subscription_already_active' }); + expect(client.createPreapproval).not.toHaveBeenCalled(); + }); + + it('cancels an abandoned attempt before starting a new one', async () => { + const { run } = subscribe(makeDb({ status: 'PENDING', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null })); + + await run(); + + expect(calls).toEqual(['cancelPreapproval', 'upsert', 'createPreapproval', 'update']); + }); + + it('delays the first charge to the end of a period already paid', async () => { + const paidThrough = new Date('2026-11-10T00:00:00.000Z'); + const { client, run } = subscribe(makeDb({ status: 'CANCELLED', provider: 'MERCADO_PAGO', externalId: 'old', paidThrough })); + + await run(); + + expect(client.cancelPreapproval).not.toHaveBeenCalled(); + expect((client.createPreapproval as ReturnType).mock.calls[0]?.[1]).toMatchObject({ + startDate: paidThrough, + }); + }); + + it('answers 503 when Gruperly has no account in that country', async () => { + const db = makeDb(null, 'AR'); + const client = makeClient(); + const provider = new MercadoPagoBillingProvider({ client, credentials: () => null }); + const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, { + payerEmail: 'profe@mail.com', + returnTo: 'billing', + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' }); + expect(db.billingSubscription.upsert).not.toHaveBeenCalled(); + }); + + it('reports a Mercado Pago failure as 502 and keeps the row', async () => { + const client = makeClient(); + client.createPreapproval = mock(async () => { + throw new Error('down'); + }) as never; + const db = makeDb(null); + + const result = await subscribe(db, client).run(); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(502); + expect(db.billingSubscription.upsert).toHaveBeenCalled(); + }); +}); + +describe('CancelSubscription', () => { + it('cancels in Mercado Pago and keeps what was paid', async () => { + const db = { + billingSubscription: { + findUnique: mock(async () => ({ + id: 'sub-1', + status: 'AUTHORIZED', + provider: 'MERCADO_PAGO', + externalId: 'pre-1', + checkoutRef: null, + country: 'AR', + })), + update: mock(async () => ({})), + }, + }; + const client = makeClient(); + + const provider = mpProvider(client); + const result = await new CancelSubscription({ db: db as never, providers: () => provider }).execute(userId); + + expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } }); + expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1'); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + }); + + it('has nothing to cancel without a live subscription', async () => { + const db = { billingSubscription: { findUnique: mock(async () => null), update: mock() } }; + + const provider = mpProvider(makeClient()); + const result = await new CancelSubscription({ db: db as never, providers: () => provider }).execute(userId); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('no_active_subscription'); + }); +}); + +function fakeStripe(overrides: Partial = {}) { + return { + id: 'STRIPE', + requiresPayerEmail: false, + isAvailable: () => true, + start: mock(async () => { + calls.push('start'); + return { checkoutUrl: 'https://checkout.stripe/cs_1', externalId: null, checkoutRef: 'cs_1' }; + }), + fetch: mock(), + listCharges: mock(), + cancel: mock(async () => { + calls.push('cancel'); + }), + parseWebhook: mock(), + ...overrides, + } as BillingProvider; +} + +describe('Subscribe outside Argentina (Stripe)', () => { + beforeEach(() => { + calls = []; + }); + + it('picks the provider of the country and starts a checkout without asking the email', async () => { + const db = makeDb(null, 'MX'); + const stripe = fakeStripe(); + const resolved: string[] = []; + + const result = await new Subscribe({ + db: db as never, + providers: (id) => { + resolved.push(id); + return stripe; + }, + webOrigin: 'http://web', + now: () => now, + }).execute(userId, { returnTo: 'billing' }); + + expect(resolved).toEqual(['STRIPE']); + expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://checkout.stripe/cs_1' } }); + expect(stripe.start).toHaveBeenCalledWith({ + userId, + country: 'MX', + amount: 199, + currency: 'MXN', + payerEmail: null, + backUrl: 'http://web/billing?sub=return', + startDate: undefined, + }); + expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record }])[0].create).toMatchObject({ + provider: 'STRIPE', + payerEmail: 'login@mail.com', + }); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { externalId: null, checkoutRef: 'cs_1', lastSyncedAt: now }, + }); + }); + + it('voids an abandoned attempt with the provider it was created with', async () => { + const db = makeDb({ status: 'PENDING', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null }, 'MX'); + const client = makeClient(); + const mp = mpProvider(client); + const stripe = fakeStripe(); + + await new Subscribe({ + db: db as never, + providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe), + webOrigin: 'http://web', + now: () => now, + }).execute(userId, { returnTo: 'billing' }); + + expect(calls).toEqual(['cancelPreapproval', 'upsert', 'start', 'update']); + }); + + it('answers 503 when Stripe is not configured', async () => { + const db = makeDb(null, 'CL'); + const stripe = fakeStripe({ isAvailable: () => false }); + + const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, { + returnTo: 'billing', + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' }); + expect(db.billingSubscription.upsert).not.toHaveBeenCalled(); + }); + + it('still requires the payer email for Mercado Pago', async () => { + const db = makeDb(null, 'AR'); + const provider = mpProvider(makeClient()); + + const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, { + returnTo: 'billing', + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 400 }); + expect(db.billingSubscription.upsert).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/billing-sync.test.ts b/apps/backend/test/billing-sync.test.ts new file mode 100644 index 0000000..56bf0ba --- /dev/null +++ b/apps/backend/test/billing-sync.test.ts @@ -0,0 +1,275 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { SyncSubscription } from '@/modules/billing/lib/sync'; +import type { BillingProvider, ProviderSubscription } from '@/modules/billing/providers'; +import { + MercadoPagoBillingProvider, + type MpAuthorizedPayment, + type PreapprovalClient, +} from '@/modules/billing/providers/mercado-pago'; + +const userId = 'user-1'; +const now = new Date('2026-10-22T12:00:00.000Z'); +const credentials = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }); + +function subscription(overrides: Record = {}) { + return { + id: 'sub-1', + userId, + country: 'AR', + currency: 'ARS', + status: 'PENDING', + provider: 'MERCADO_PAGO', + externalId: 'pre-1', + checkoutRef: null, + authorizedAt: null, + paidThrough: null, + ...overrides, + }; +} + +function invoice(overrides: Partial = {}): MpAuthorizedPayment { + return { + id: 'inv-1', + preapprovalId: 'pre-1', + status: 'processed', + paymentStatus: 'approved', + amount: 15000, + currencyId: 'ARS', + debitDate: '2026-10-20T10:00:00.000Z', + createdAt: '2026-10-20T09:00:00.000Z', + ...overrides, + }; +} + +function makeDb(row: Record | null) { + return { + billingSubscription: { + findUnique: mock(async () => row), + update: mock(async () => ({})), + updateMany: mock(async () => ({ count: 0 })), + }, + billingCharge: { upsert: mock(async () => ({})) }, + }; +} + +function makeClient(params: { status?: string; externalReference?: string | null; invoices?: MpAuthorizedPayment[] }) { + return { + getPreapproval: mock(async (_token: string, id: string) => ({ + id, + status: params.status ?? 'authorized', + externalReference: params.externalReference === undefined ? userId : params.externalReference, + initPoint: null, + nextPaymentDate: '2026-11-20T10:00:00.000Z', + })), + searchAuthorizedPayments: mock(async () => params.invoices ?? []), + createPreapproval: mock(), + cancelPreapproval: mock(), + getAuthorizedPayment: mock(), + } as unknown as PreapprovalClient; +} + +// The real Mercado Pago adapter over a fake preapproval client: the sync and +// the adapter's mapping are tested together. +function sync(db: ReturnType, client: PreapprovalClient) { + const provider = new MercadoPagoBillingProvider({ client, credentials }); + return new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }); +} + +describe('SyncSubscription', () => { + it('marks the subscription authorized and extends paidThrough one month from the debit', async () => { + const db = makeDb(subscription()); + + const result = await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1'); + + expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } }); + expect(db.billingCharge.upsert).toHaveBeenCalledWith({ + where: { externalId: 'inv-1' }, + create: { + subscriptionId: 'sub-1', + externalId: 'inv-1', + amount: 15000, + currency: 'ARS', + status: 'approved', + paidAt: new Date('2026-10-20T10:00:00.000Z'), + }, + update: { status: 'approved', paidAt: new Date('2026-10-20T10:00:00.000Z') }, + }); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { + externalId: undefined, + status: 'AUTHORIZED', + authorizedAt: now, + nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'), + paidThrough: new Date('2026-11-20T10:00:00.000Z'), + payerEmail: undefined, + lastSyncedAt: now, + }, + }); + }); + + it('still marks the subscription authorized when listing the charges fails', async () => { + const db = makeDb(subscription()); + const client = makeClient({}); + (client.searchAuthorizedPayments as ReturnType).mockImplementation(async () => { + throw new Error('400 Invalid value for limit'); + }); + + const result = await sync(db, client).execute('sub-1'); + + expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } }); + expect(db.billingCharge.upsert).not.toHaveBeenCalled(); + const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record }])[0].data; + expect(data.status).toBe('AUTHORIZED'); + expect(data.authorizedAt).toEqual(now); + expect(data.paidThrough).toBeNull(); + // Without `lastSyncedAt` the next sync retries the charges. + expect(data.lastSyncedAt).toBeUndefined(); + }); + + it('records a rejected charge without extending what was paid', async () => { + const paidThrough = new Date('2026-10-25T00:00:00.000Z'); + const db = makeDb(subscription({ status: 'AUTHORIZED', authorizedAt: now, paidThrough })); + + await sync(db, makeClient({ invoices: [invoice({ paymentStatus: 'rejected' })] })).execute('sub-1'); + + const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record }])[0].data; + expect(data.paidThrough).toEqual(paidThrough); + expect(data.authorizedAt).toBeUndefined(); + }); + + it('never moves paidThrough back', async () => { + const paidThrough = new Date('2027-01-01T00:00:00.000Z'); + const db = makeDb(subscription({ status: 'AUTHORIZED', paidThrough })); + + await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1'); + + const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record }])[0].data; + expect(data.paidThrough).toEqual(paidThrough); + }); + + it('mirrors a cancellation done in Mercado Pago', async () => { + const db = makeDb(subscription({ status: 'AUTHORIZED' })); + + const result = await sync(db, makeClient({ status: 'cancelled' })).execute('sub-1'); + + expect(result.ok && result.value.status).toBe('CANCELLED'); + }); + + it('ignores a preapproval whose external_reference is not this user', async () => { + const db = makeDb(subscription()); + + const result = await sync(db, makeClient({ externalReference: 'someone-else' })).execute('sub-1'); + + expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } }); + expect(db.billingSubscription.update).not.toHaveBeenCalled(); + expect(db.billingCharge.upsert).not.toHaveBeenCalled(); + }); + + it('claims a preapproval that beat our own write of its id', async () => { + const db = makeDb(null); + let lookups = 0; + db.billingSubscription.findUnique = mock(async () => (++lookups === 1 ? null : subscription())) as never; + db.billingSubscription.updateMany = mock(async () => ({ count: 1 })); + + const result = await sync(db, makeClient({})).byExternalId('MERCADO_PAGO', 'pre-1', 'AR'); + + expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({ + where: { userId, provider: 'MERCADO_PAGO', externalId: null, country: 'AR' }, + data: { externalId: 'pre-1' }, + }); + expect(result.ok && result.value.synced).toBe(true); + }); + + it('does not claim a cancelled preapproval (a replaced attempt)', async () => { + const db = makeDb(null); + + const result = await sync(db, makeClient({ status: 'cancelled' })).byExternalId('MERCADO_PAGO', 'old', 'AR'); + + expect(result).toEqual({ ok: true, value: { synced: false, status: null } }); + expect(db.billingSubscription.updateMany).not.toHaveBeenCalled(); + }); + + it('follows the row provider, not the country (a Mercado Pago subscription outside Argentina)', async () => { + const db = makeDb(subscription({ country: 'MX', currency: 'MXN' })); + const resolved: string[] = []; + const provider = new MercadoPagoBillingProvider({ client: makeClient({}), credentials }); + + await new SyncSubscription({ + db: db as never, + providers: (id) => { + resolved.push(id); + return provider; + }, + now: () => now, + }).execute('sub-1'); + + expect(resolved).toEqual(['MERCADO_PAGO']); + }); + + it('does nothing while the Stripe checkout is not completed', async () => { + const db = makeDb(subscription({ provider: 'STRIPE', externalId: null, checkoutRef: 'cs_1' })); + const provider = fakeProvider(null); + + const result = await new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }).execute( + 'sub-1', + ); + + expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } }); + expect(provider.fetch).toHaveBeenCalledWith({ country: 'AR', externalId: null, checkoutRef: 'cs_1' }); + expect(db.billingSubscription.update).not.toHaveBeenCalled(); + }); + + it('stores the Stripe subscription id and payer email once the checkout completes', async () => { + const db = makeDb(subscription({ provider: 'STRIPE', country: 'MX', externalId: null, checkoutRef: 'cs_1' })); + const coveredUntil = new Date('2026-11-21T00:00:00.000Z'); + const provider = fakeProvider( + { + externalId: 'sub_stripe', + ownerUserId: userId, + status: 'AUTHORIZED', + nextPaymentDate: coveredUntil, + payerEmail: 'card@mail.com', + }, + [ + { + externalId: 'in_1', + amount: 199, + currency: 'MXN', + status: 'approved', + paidAt: new Date('2026-10-21T00:00:00.000Z'), + coveredUntil, + }, + ], + ); + + await new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }).execute('sub-1'); + + expect(provider.listCharges).toHaveBeenCalledWith({ country: 'MX', externalId: 'sub_stripe', checkoutRef: 'cs_1' }); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { + externalId: 'sub_stripe', + status: 'AUTHORIZED', + authorizedAt: now, + nextPaymentDate: coveredUntil, + paidThrough: coveredUntil, + payerEmail: 'card@mail.com', + lastSyncedAt: now, + }, + }); + }); +}); + +function fakeProvider(remote: ProviderSubscription | null, charges: Awaited> = []) { + return { + id: 'STRIPE', + requiresPayerEmail: false, + isAvailable: () => true, + start: mock(), + fetch: mock(async () => remote), + listCharges: mock(async () => charges), + cancel: mock(), + parseWebhook: mock(), + } satisfies BillingProvider; +} diff --git a/apps/backend/test/billing-webhook.test.ts b/apps/backend/test/billing-webhook.test.ts new file mode 100644 index 0000000..96b7fd4 --- /dev/null +++ b/apps/backend/test/billing-webhook.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { createHmac } from 'node:crypto'; +import { err, ok } from '@gruperly/shared'; +import { billingProviderErrorProblem } from '@/http/problem-builders'; +import { isPublicApiRequest } from '@/http/session-auth'; +import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case'; +import { + MercadoPagoBillingProvider, + type PreapprovalClient, + verifyMpSignature, +} from '@/modules/billing/providers/mercado-pago'; +import { StripeBillingProvider } from '@/modules/billing/providers/stripe'; + +const secret = 'webhook-secret'; +const credentials = () => ({ accessToken: 'platform-token', webhookSecret: secret }); + +function sign(dataId: string, requestId: string, ts = '1729600000') { + const v1 = createHmac('sha256', secret).update(`id:${dataId};request-id:${requestId};ts:${ts};`).digest('hex'); + return `ts=${ts},v1=${v1}`; +} + +function request(params: { type: string; dataId: string; requestId?: string; signature?: string }) { + const requestId = params.requestId ?? 'req-1'; + return { + routeParam: 'ar', + rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }), + headers: new Headers({ + 'x-request-id': requestId, + 'x-signature': params.signature ?? sign(params.dataId, requestId), + }), + query: new URLSearchParams({ 'data.id': params.dataId, type: params.type }), + }; +} + +function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const })) { + const db = { + billingWebhookEvent: { + create: mock(async () => ({})), + delete: mock(async () => ({})), + }, + }; + const sync = { byExternalId: mock(async () => syncResult) }; + const client = { + getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })), + } as unknown as PreapprovalClient; + return { db, sync, client }; +} + +function handler(deps: ReturnType) { + const provider = new MercadoPagoBillingProvider({ client: deps.client, credentials }); + return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider }); +} + +describe('verifyMpSignature', () => { + it('accepts Mercado Pago signatures and lower-cases alphanumeric ids', () => { + const signature = sign('abc123', 'req-1'); + expect(verifyMpSignature({ signature, requestId: 'req-1', dataId: 'ABC123', secret })).toBe(true); + }); + + it('rejects a tampered or missing signature', () => { + expect(verifyMpSignature({ signature: sign('1', 'req-1'), requestId: 'req-1', dataId: '2', secret })).toBe(false); + expect(verifyMpSignature({ signature: 'ts=1,v1=short', requestId: 'req-1', dataId: '1', secret })).toBe(false); + expect(verifyMpSignature({ signature: null, requestId: 'req-1', dataId: '1', secret })).toBe(false); + }); +}); + +describe('HandleBillingWebhook', () => { + it('rejects a bad signature before touching anything', async () => { + const deps = makeDeps(); + + const result = await handler(deps).execute( + 'MERCADO_PAGO', + request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }), + ); + + expect(result).toEqual(err('invalid_signature')); + expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled(); + expect(deps.sync.byExternalId).not.toHaveBeenCalled(); + }); + + it('re-fetches the preapproval instead of trusting the body', async () => { + const deps = makeDeps(); + + const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' })); + + expect(result).toEqual(ok({ duplicate: false, applied: true })); + expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-1', 'AR'); + expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'mp:AR', dedupeKey: 'req-1' } }); + }); + + it('resolves an invoice notification to its subscription', async () => { + const deps = makeDeps(); + + await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_authorized_payment', dataId: 'inv-1' })); + + expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1'); + expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-9', 'AR'); + }); + + it('answers a repeated delivery as a duplicate', async () => { + const deps = makeDeps(); + deps.db.billingWebhookEvent.create = mock(async () => { + throw Object.assign(new Error('unique'), { code: 'P2002' }); + }); + + const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' })); + + expect(result).toEqual(ok({ duplicate: true, applied: false })); + expect(deps.sync.byExternalId).not.toHaveBeenCalled(); + }); + + it('un-burns the dedupe key when syncing fails, so the retry gets in', async () => { + const deps = makeDeps(err(billingProviderErrorProblem()) as never); + + const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' })); + + expect(result).toEqual(err('sync_failed')); + expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({ + where: { source_dedupeKey: { source: 'mp:AR', dedupeKey: 'req-1' } }, + }); + }); + + it('acknowledges topics it does not handle', async () => { + const deps = makeDeps(); + + const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'payment', dataId: '123' })); + + expect(result).toEqual(ok({ duplicate: false, applied: false })); + expect(deps.sync.byExternalId).not.toHaveBeenCalled(); + }); + + it('is reachable without a session, and only that path', () => { + expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/mp/ar')).toBe(true); + expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/stripe')).toBe(true); + expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/stripe')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false); + }); +}); + +const stripeSecret = 'whsec_test'; +const stripeNow = new Date('2026-10-22T12:00:00.000Z'); + +function stripeRequest(event: Record, signature?: string) { + const rawBody = JSON.stringify(event); + const t = Math.floor(stripeNow.getTime() / 1000); + const v1 = createHmac('sha256', stripeSecret).update(`${t}.${rawBody}`).digest('hex'); + return { + routeParam: null, + rawBody, + headers: new Headers({ 'stripe-signature': signature ?? `t=${t},v1=${v1}` }), + query: new URLSearchParams(), + }; +} + +function stripeHandler(deps: ReturnType) { + const provider = new StripeBillingProvider({ + config: () => ({ secretKey: 'sk_test', webhookSecret: stripeSecret }), + fetch: mock(async () => { + throw new Error('the webhook must not call Stripe'); + }) as never, + now: () => stripeNow, + }); + return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider }); +} + +describe('HandleBillingWebhook with Stripe', () => { + it('syncs the subscription of a completed checkout, deduplicated by event id', async () => { + const deps = makeDeps(); + + const result = await stripeHandler(deps).execute( + 'STRIPE', + stripeRequest({ + id: 'evt_1', + type: 'checkout.session.completed', + data: { object: { id: 'cs_1', mode: 'subscription', subscription: 'sub_1' } }, + }), + ); + + expect(result).toEqual(ok({ duplicate: false, applied: true })); + expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'stripe', dedupeKey: 'evt_1' } }); + expect(deps.sync.byExternalId).toHaveBeenCalledWith('STRIPE', 'sub_1', null); + }); + + it('finds the subscription of an invoice event', async () => { + const deps = makeDeps(); + + await stripeHandler(deps).execute( + 'STRIPE', + stripeRequest({ + id: 'evt_2', + type: 'invoice.paid', + data: { object: { id: 'in_1', parent: { subscription_details: { subscription: 'sub_2' } } } }, + }), + ); + + expect(deps.sync.byExternalId).toHaveBeenCalledWith('STRIPE', 'sub_2', null); + }); + + it('rejects a bad signature', async () => { + const deps = makeDeps(); + + const result = await stripeHandler(deps).execute( + 'STRIPE', + stripeRequest({ id: 'evt_3', type: 'invoice.paid', data: { object: {} } }, 't=1,v1=deadbeef'), + ); + + expect(result).toEqual(err('invalid_signature')); + expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled(); + }); + + it('acknowledges events that do not concern a subscription', async () => { + const deps = makeDeps(); + + const result = await stripeHandler(deps).execute( + 'STRIPE', + stripeRequest({ id: 'evt_4', type: 'customer.created', data: { object: { id: 'cus_1' } } }), + ); + + expect(result).toEqual(ok({ duplicate: false, applied: false })); + expect(deps.sync.byExternalId).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/classes.test.ts b/apps/backend/test/classes.test.ts new file mode 100644 index 0000000..4533a58 --- /dev/null +++ b/apps/backend/test/classes.test.ts @@ -0,0 +1,514 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findMany: mock(), + }, + classSession: { + upsert: mock(), + findMany: mock(), + findUnique: mock(), + }, + attendee: { + findMany: mock(), + findUnique: mock(), + }, + payment: { + findMany: mock(), + }, + attendance: { + findMany: mock(), + upsert: mock(), + }, + slotRelease: { + findMany: mock(), + upsert: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { classesRoutes } from '@/modules/classes'; + +const userId = 'user-1'; +const UTC_WEEKDAYS = [ + 'SUNDAY', + 'MONDAY', + 'TUESDAY', + 'WEDNESDAY', + 'THURSDAY', + 'FRIDAY', + 'SATURDAY', +] as const; +const todayUtc = UTC_WEEKDAYS[new Date().getUTCDay()]; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/classes', classesRoutes); + return app; +} + +function makeSession(overrides: Record = {}) { + return { + id: 'session-1', + groupId: 'group-1', + startsAt: todayAtUtc(), + group: { + id: 'group-1', + name: 'Funcional', + createdById: userId, + members: [], + capacity: 10, + }, + ...overrides, + }; +} + +// "Today" at 19:00 UTC, on the runner's real day. +function todayAtUtc() { + const date = new Date(); + date.setUTCHours(19, 0, 0, 0); + return date; +} + +describe('classes routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + delete process.env.ABSENCE_RELEASE_HOURS; + }); + + describe('GET /classes/today', () => { + it('materializa y lista las clases de hoy del profesor', async () => { + const startsAt = todayAtUtc(); + prisma.group.findMany.mockResolvedValue([ + { + id: 'group-1', + name: 'Funcional', + days: [todayUtc], + time: '19:00', + capacity: 10, + _count: { attendees: 8 }, + }, + ]); + prisma.classSession.upsert.mockResolvedValue({ id: 'session-1' }); + prisma.classSession.findMany.mockResolvedValue([ + { id: 'session-1', groupId: 'group-1', startsAt, group: { id: 'group-1', name: 'Funcional', capacity: 10 } }, + ]); + prisma.attendance.findMany.mockResolvedValue([{ classSessionId: 'session-1' }]); + + const res = await makeApp({ id: userId }).request('/classes/today?timeZone=UTC'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + data: [ + { + sessionId: 'session-1', + groupId: 'group-1', + groupName: 'Funcional', + startsAt: startsAt.toISOString(), + enrolledCount: 8, + capacity: 10, + availableSlots: 2, + hasAttendance: true, + }, + ], + }); + expect(prisma.classSession.upsert).toHaveBeenCalledTimes(1); + expect(prisma.classSession.upsert).toHaveBeenCalledWith({ + where: { + groupId_startsAt: { groupId: 'group-1', startsAt }, + }, + create: { groupId: 'group-1', startsAt }, + update: {}, + select: { id: true }, + }); + }); + + it('devuelve lista vacía cuando ningún grupo tiene clase hoy', async () => { + prisma.group.findMany.mockResolvedValue([]); + + const res = await makeApp({ id: userId }).request('/classes/today?timeZone=UTC'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ data: [] }); + expect(prisma.classSession.upsert).not.toHaveBeenCalled(); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/classes/today'); + + expect(res.status).toBe(401); + expect(await res.json()).toMatchObject({ code: 'unauthorized' }); + }); + }); + + describe('GET /classes/:sessionId/students', () => { + it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'attendee-1', person: { fullName: 'Ana Pérez' } }, + { id: 'attendee-2', person: { fullName: 'Bruno Díaz' } }, + ]); + prisma.payment.findMany.mockResolvedValue([ + { attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') }, + { attendeeId: 'attendee-2', status: 'PAID', dueDate: new Date('2026-09-01T00:00:00.000Z') }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + { attendeeId: 'attendee-2', status: 'EXCUSED' }, + ]); + prisma.slotRelease.findMany.mockResolvedValue([]); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/students?timeZone=UTC', + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body).toMatchObject({ + sessionId: 'session-1', + groupId: 'group-1', + groupName: 'Funcional', + students: [ + { + attendeeId: 'attendee-1', + fullName: 'Ana Pérez', + paymentStatus: 'PENDING', + attendanceStatus: null, + notifiedAbsence: false, + }, + { + attendeeId: 'attendee-2', + fullName: 'Bruno Díaz', + paymentStatus: 'UP_TO_DATE', + attendanceStatus: 'EXCUSED', + notifiedAbsence: true, + }, + ], + }); + }); + + it('prohíbe el acceso a quien no es owner ni miembro del grupo', async () => { + prisma.classSession.findUnique.mockResolvedValue( + makeSession({ + group: { + id: 'group-1', + name: 'Funcional', + createdById: 'someone-else', + members: [], + }, + }), + ); + + const res = await makeApp({ id: userId }).request('/classes/session-1/students'); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('devuelve 404 si la sesión no existe', async () => { + prisma.classSession.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/classes/nope/students'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + }); + + describe('POST /classes/:sessionId/attendance', () => { + const validBody = { + classSessionId: 'session-1', + records: [ + { attendeeId: 'attendee-1', status: 'PRESENT' }, + { attendeeId: 'attendee-2', status: 'ABSENT' }, + ], + }; + + it('guarda la asistencia masiva con upsert', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'attendee-1' }, + { id: 'attendee-2' }, + ]); + prisma.attendance.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBody), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ classSessionId: 'session-1', marked: 2 }); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(2); + expect(prisma.attendance.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + where: { + attendeeId_classSessionId: { + attendeeId: 'attendee-1', + classSessionId: 'session-1', + }, + }, + }), + ); + }); + + it('rechaza cuando el classSessionId del body no coincide con la ruta', async () => { + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...validBody, classSessionId: 'other-session' }), + }); + + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ status: 400 }); + }); + + it('rechaza alumnos que no pertenecen al grupo', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findMany.mockResolvedValue([{ id: 'attendee-1' }]); + + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBody), + }); + + expect(res.status).toBe(400); + expect(prisma.attendance.upsert).not.toHaveBeenCalled(); + }); + + it('rechaza registros con status fuera del contrato', async () => { + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + classSessionId: 'session-1', + records: [{ attendeeId: 'attendee-1', status: 'EXCUSED' }], + }), + }); + + expect(res.status).toBe(400); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBody), + }); + + expect(res.status).toBe(401); + }); + }); + + describe('POST /classes/:sessionId/notify-absence (profesor)', () => { + const notifyBody = { + attendeeId: 'attendee-1', + classSessionId: 'session-1', + }; + + it('libera el cupo cuando la anticipación alcanza las 12 horas', async () => { + const startsAt = new Date(Date.now() + 24 * 60 * 60 * 1000); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + classSessionId: 'session-1', + notified: true, + slotReleased: true, + }); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(1); + expect(prisma.slotRelease.upsert).toHaveBeenCalledTimes(1); + }); + + it('marca EXCUSED sin liberar cupo si avisa con menos de 12 horas', async () => { + const startsAt = new Date(Date.now() + 60 * 60 * 1000); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ slotReleased: false }); + expect(prisma.slotRelease.upsert).not.toHaveBeenCalled(); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(1); + }); + + it('respeta el override configurable ABSENCE_RELEASE_HOURS', async () => { + process.env.ABSENCE_RELEASE_HOURS = '4'; + const startsAt = new Date(Date.now() + 6 * 60 * 60 * 1000); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ slotReleased: true }); + expect(prisma.slotRelease.upsert).toHaveBeenCalledTimes(1); + delete process.env.ABSENCE_RELEASE_HOURS; + }); + + it('rechaza un alumno de otro grupo', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'another-group', + }); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(400); + expect(prisma.attendance.upsert).not.toHaveBeenCalled(); + }); + }); + + describe('rutas públicas con token', () => { + it('GET /classes/absence devuelve 404 con token inválido', async () => { + prisma.attendee.findUnique.mockResolvedValue(null); + + const res = await makeApp(null).request('/classes/absence?token=bad-token'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + + it('GET /classes/absence devuelve las clases de hoy del alumno', async () => { + const mxWeekday = new Intl.DateTimeFormat('en-US', { + timeZone: 'America/Mexico_City', + weekday: 'long', + }) + .format(new Date()) + .toUpperCase(); + const startsAt = todayAtUtc(); + + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + person: { fullName: 'Ana Pérez' }, + group: { + id: 'group-1', + name: 'Funcional', + days: [mxWeekday], + time: '19:00', + }, + }); + prisma.classSession.upsert.mockResolvedValue({ id: 'session-1' }); + prisma.classSession.findMany.mockResolvedValue([ + { id: 'session-1', groupId: 'group-1', startsAt }, + ]); + prisma.attendance.findMany.mockResolvedValue([]); + prisma.slotRelease.findMany.mockResolvedValue([]); + + const res = await makeApp(null).request('/classes/absence?token=valid-token'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendeeId: 'attendee-1', + fullName: 'Ana Pérez', + groupName: 'Funcinal'.replace('Funcinal', 'Funcional'), + sessions: [ + { + sessionId: 'session-1', + groupName: 'Funcional', + startsAt: startsAt.toISOString(), + notified: false, + attendanceStatus: null, + }, + ], + }); + }); + + it('POST /classes/notify-absence público registra el aviso con token', async () => { + const startsAt = new Date(Date.now() + 24 * 60 * 60 * 1000); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp(null).request('/classes/notify-absence', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'valid-token', classSessionId: 'session-1' }), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ notified: true, slotReleased: true }); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(1); + }); + + it('POST /classes/notify-absence público devuelve 404 con token inválido', async () => { + prisma.attendee.findUnique.mockResolvedValue(null); + + const res = await makeApp(null).request('/classes/notify-absence', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'bad', classSessionId: 'session-1' }), + }); + + expect(res.status).toBe(404); + expect(prisma.attendance.upsert).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/backend/test/db/payment-review.db.test.ts b/apps/backend/test/db/payment-review.db.test.ts new file mode 100644 index 0000000..912a87a --- /dev/null +++ b/apps/backend/test/db/payment-review.db.test.ts @@ -0,0 +1,147 @@ +/* Teacher review of reported payments against a real Postgres (see + student-access.db.test.ts): confirm/reject/undo, the overdue alert and access + between teachers. */ +import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; +import { Prisma, PrismaClient } from '@generated/prisma/client'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { UnitOfWork } from '@/lib/prisma'; +import type { FileStorage } from '@/lib/storage'; +import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case'; +import { ReportedPayments } from '@/modules/payments/features/reported/use-case'; +import { sendReviewNotification } from '@/modules/payments/lib/review-notifications'; +import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case'; + +const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; +const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 73, 72, 68, 82]); +const storage: FileStorage = { + put: async () => {}, + signedUrl: (key, ttl) => `https://storage.test/${key}?ttl=${ttl}`, + remove: async () => {}, +}; + +describe.skipIf(!url)('payment review (real database)', () => { + let db: PrismaClient; + let unitOfWork: UnitOfWork; + const notified: string[] = []; + const ids = { + teacher: `r-teacher-${suffix}`, + other: `r-other-${suffix}`, + group: `r-group-${suffix}`, + ana: `r-ana-${suffix}`, + account: `r-acc-${suffix}`, + fee: `r-fee-${suffix}`, + }; + const NOW = new Date('2026-10-28T15:00:00.000Z'); + const reviews = (now = NOW) => + new ReportedPayments({ db, unitOfWork, storage, now, notify: (id) => void notified.push(id) }); + + const overdueFor = async () => { + const overview = await new GetAttentionOverview({ db: db as never, now: NOW }).execute(ids.teacher); + if (!overview.ok) throw new Error('overview failed'); + const member = overview.value.groups.flatMap((group) => group.members).find((item) => item.attendeeId === ids.ana); + return { alerts: member?.alerts.map((alert) => alert.tipo) ?? [], overdue: member?.overduePayments.length ?? 0 }; + }; + + const report = async () => { + const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.account, { + attendeeId: ids.ana, + paymentIds: [ids.fee], + file: { name: 'captura.png', bytes: PNG }, + }); + if (!result.ok) throw new Error(result.error.detail); + return result.value.id; + }; + + beforeAll(async () => { + db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); + unitOfWork = new UnitOfWork(db); + await db.user.createMany({ + data: [ + { id: ids.teacher, name: 'Caro', email: `${ids.teacher}@test.local`, country: 'AR' }, + { id: ids.other, name: 'Otro', email: `${ids.other}@test.local`, country: 'AR' }, + ], + }); + await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } }); + await db.person.create({ data: { id: `${ids.ana}-person`, createdById: ids.teacher, fullName: 'Ana' } }); + await db.attendee.create({ + data: { id: ids.ana, groupId: ids.group, personId: `${ids.ana}-person`, createdAt: new Date('2026-01-01T00:00:00Z') }, + }); + await db.studentAccount.create({ + data: { + id: ids.account, + name: 'Ana', + createdById: ids.teacher, + recoveryEmail: 'ana@test.local', + recoveryEmailVerifiedAt: NOW, + people: { create: { personId: `${ids.ana}-person` } }, + }, + }); + await db.payment.create({ + data: { id: ids.fee, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z') }, + }); + }); + + afterAll(async () => { + await db.user.deleteMany({ where: { id: { in: [ids.teacher, ids.other] } } }); + await db.$disconnect(); + }); + + it('un pago informado saca la cuota de la alerta y otro profe no lo ve', async () => { + expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 }); + const reportId = await report(); + expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 }); + + const mine = await reviews().list(ids.teacher); + if (!mine.ok) throw new Error('list failed'); + expect(mine.value.data.map((item) => item.id)).toEqual([reportId]); + expect(mine.value.data[0]?.receipt.thumbnailUrl).toContain('ttl=300'); + + const theirs = await reviews().list(ids.other); + expect(theirs).toEqual({ ok: true, value: { data: [] } }); + const foreign = await reviews().confirm(ids.other, reportId); + expect(!foreign.ok && foreign.error.status).toBe(404); + const foreignReceipt = await reviews().receiptUrl(ids.other, reportId); + expect(foreignReceipt.ok).toBe(false); + }); + + it('rechazar devuelve la alerta y deshacer la vuelve a sacar', async () => { + const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id; + const rejected = await reviews().reject(ids.teacher, reportId, 'No se ve el monto'); + expect(rejected.ok && rejected.value.status).toBe('rejected'); + expect(notified).toContain(reportId); + expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 }); + + const again = await reviews().confirm(ids.teacher, reportId); + expect(!again.ok && again.error.status).toBe(409); + + const undone = await reviews().undo(ids.teacher, reportId); + expect(undone.ok && undone.value.status).toBe('reported'); + expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 }); + }); + + it('confirmar marca las cuotas como pagadas; deshacer las vuelve a vencidas', async () => { + const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id; + const confirmed = await reviews().confirm(ids.teacher, reportId); + expect(confirmed.ok && confirmed.value.status).toBe('confirmed'); + expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'PAID', paidAt: NOW }); + + // Email only if the review still stands. + const sent: string[] = []; + const email = { sendStudentPaymentReviewed: async (data: { email: string }) => void sent.push(data.email) }; + expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(true); + expect(sent).toEqual(['ana@test.local']); + + const undone = await reviews().undo(ids.teacher, reportId); + expect(undone.ok).toBe(true); + expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'OVERDUE', paidAt: null }); + expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(false); + }); + + it('deshacer vence a los pocos minutos', async () => { + const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id; + expect((await reviews().confirm(ids.teacher, reportId)).ok).toBe(true); + const late = await reviews(new Date(NOW.getTime() + 11 * 60 * 1000)).undo(ids.teacher, reportId); + expect(!late.ok && late.error.status).toBe(409); + }); +}); diff --git a/apps/backend/test/db/student-access.db.test.ts b/apps/backend/test/db/student-access.db.test.ts new file mode 100644 index 0000000..870bb58 --- /dev/null +++ b/apps/backend/test/db/student-access.db.test.ts @@ -0,0 +1,176 @@ +/* Against a real Postgres: the single-use guarantee lives in the database + (conditional UPDATE under concurrency), so a mock can't prove it. Skipped + unless DB_TESTS=1 (`bun run test:db`), which uses DATABASE_URL from .env. + Creates its own teacher/group/attendee and deletes them at the end. */ +import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; +import { PrismaClient } from '@generated/prisma/client'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case'; +import { InviteStudent } from '@/modules/student-access/features/invite/use-case'; +import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case'; +import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case'; +import { hashToken } from '@/modules/student-portal/lib/tokens'; + +const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; +const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + +describe.skipIf(!url)('student access (real database)', () => { + let db: PrismaClient; + // Same contract as UnitOfWork.executeResult, built on this file's own client + // (other test files mock '@/lib/prisma'). + let unitOfWork: { executeResult: unknown }; + const ids = { + user: `test-user-${suffix}`, + group: `test-group-${suffix}`, + group2: `test-group2-${suffix}`, + person: `test-person-${suffix}`, + attendee: `test-att-${suffix}`, + attendee2: `test-att2-${suffix}`, + }; + + beforeAll(async () => { + db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); + unitOfWork = { + executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => { + const rollback = Symbol('rollback'); + try { + return await db.$transaction(async (tx) => { + const result = await callback(tx); + if (!result.ok) throw { [rollback]: result }; + return result; + }); + } catch (error) { + if (error && typeof error === 'object' && rollback in error) { + return (error as Record)[rollback]; + } + throw error; + } + }) as never, + }; + await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } }); + await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } }); + await db.group.create({ data: { id: ids.group2, name: 'Yoga', createdById: ids.user } }); + // One person in two groups of the teacher. + await db.person.create({ data: { id: ids.person, createdById: ids.user, fullName: 'Ana Pérez' } }); + await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, personId: ids.person } }); + await db.attendee.create({ data: { id: ids.attendee2, groupId: ids.group2, personId: ids.person } }); + }); + + afterAll(async () => { + await db.user.deleteMany({ where: { id: ids.user } }); + await db.$disconnect(); + }); + + const invite = (now = new Date()) => + new InviteStudent({ db, unitOfWork: unitOfWork as never, now }).execute(ids.group, ids.attendee, ids.user); + const tokenOf = (link: string) => link.split('/i/')[1] as string; + const consume = (token: string, now = new Date()) => + new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now }).execute({ + token, + ip: '203.0.113.7', + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1', + }); + + it('guarda solo el hash del token', async () => { + const result = await invite(); + if (!result.ok) throw new Error('invite failed'); + const token = tokenOf(result.value.url); + expect(token).toHaveLength(43); + expect(await db.studentAccessToken.count({ where: { tokenHash: token } })).toBe(0); + expect(await db.studentAccessToken.count({ where: { tokenHash: hashToken(token) } })).toBe(1); + }); + + it('el GET no consume el link', async () => { + const result = await invite(); + if (!result.ok) throw new Error('invite failed'); + const token = tokenOf(result.value.url); + + for (let i = 0; i < 3; i++) { + const info = await new GetStudentLinkInfo({ db }).execute(token); + expect(info).toMatchObject({ ok: true, value: { status: 'valid', name: 'Ana Pérez', teacherName: 'Profe Test', groupName: 'Natación' } }); + } + const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } }); + expect(row.usedAt).toBeNull(); + }); + + it('bajo concurrencia, solo un dispositivo consume el link', async () => { + const result = await invite(); + if (!result.ok) throw new Error('invite failed'); + const token = tokenOf(result.value.url); + + const attempts = await Promise.all(Array.from({ length: 10 }, () => consume(token))); + const winners = attempts.filter((attempt) => attempt.ok); + const losers = attempts.filter((attempt) => !attempt.ok); + expect(winners).toHaveLength(1); + expect(losers).toHaveLength(9); + for (const loser of losers) { + if (!loser.ok) expect(loser.error.status).toBe(410); + } + + const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } }); + const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } }); + expect(sessions).toHaveLength(1); + expect(sessions[0]?.device).toBe('iPhone · Safari'); + + const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } }); + expect(row.usedIp).toBe('203.0.113.7'); + expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } }); + }); + + it('un link vencido no sirve', async () => { + const past = new Date(Date.now() - 73 * 60 * 60 * 1000); + const result = await invite(past); + if (!result.ok) throw new Error('invite failed'); + const token = tokenOf(result.value.url); + + expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } }); + const attempt = await consume(token); + expect(attempt.ok).toBe(false); + }); + + it('reinvitar revoca las sesiones y los links anteriores', async () => { + const first = await invite(); + if (!first.ok) throw new Error('invite failed'); + const consumed = await consume(tokenOf(first.value.url)); + expect(consumed.ok).toBe(true); + const linked = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } }); + await db.studentPasskey.create({ + data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' }, + }); + const pendingOld = await invite(); + // A lost phone must not keep a way in: passkeys go too. + expect(await db.studentPasskey.count({ where: { accountId: linked.accountId } })).toBe(0); + if (!pendingOld.ok) throw new Error('invite failed'); + + const access = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user); + expect(access).toMatchObject({ ok: true, value: { status: 'invited', devices: [] } }); + + // Both previous links are dead: the consumed one and the pending one. + expect((await consume(tokenOf(first.value.url))).ok).toBe(false); + const reinvite = await invite(); + if (!reinvite.ok) throw new Error('invite failed'); + expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false); + expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true); + + const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } }); + expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1); + const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user); + expect(after).toMatchObject({ ok: true, value: { status: 'active' } }); + }); + + it('una sola cuenta por persona: invitar desde otro grupo la reutiliza', async () => { + const fromFirst = await invite(); + if (!fromFirst.ok) throw new Error('invite failed'); + const fromSecond = await new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute( + ids.group2, + ids.attendee2, + ids.user, + ); + if (!fromSecond.ok) throw new Error('invite failed'); + + expect(await db.studentAccountPerson.count({ where: { personId: ids.person } })).toBe(1); + // Same state from both groups: it is the person's access. + const fromGroup2 = await new GetStudentAccess({ db }).execute(ids.group2, ids.attendee2, ids.user); + expect(fromGroup2).toMatchObject({ ok: true, value: { status: 'invited' } }); + }); +}); diff --git a/apps/backend/test/db/student-portal.db.test.ts b/apps/backend/test/db/student-portal.db.test.ts new file mode 100644 index 0000000..d3b375b --- /dev/null +++ b/apps/backend/test/db/student-portal.db.test.ts @@ -0,0 +1,209 @@ +/* Student endpoints against a real Postgres (see student-access.db.test.ts): + absence notices, payment reports and authorization by linked attendee. */ +import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; +import { Prisma, PrismaClient } from '@generated/prisma/client'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { UnitOfWork } from '@/lib/prisma'; +import type { FileStorage } from '@/lib/storage'; +import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case'; +import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case'; +import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case'; +import { GetStudentMe } from '@/modules/student-portal/features/me/use-case'; +import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case'; + +const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; +const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 73, 72, 68, 82]); + +function memoryStorage() { + const objects = new Map(); + const storage: FileStorage = { + put: async (key, body) => void objects.set(key, body), + signedUrl: (key) => `https://storage.test/${key}?sig=1`, + remove: async (key) => void objects.delete(key), + }; + return { objects, storage }; +} + +describe.skipIf(!url)('student portal (real database)', () => { + let db: PrismaClient; + let unitOfWork: UnitOfWork; + const ids = { + user: `t-user-${suffix}`, + group: `t-group-${suffix}`, + yoga: `t-yoga-${suffix}`, + personAna: `t-p-ana-${suffix}`, + personBeto: `t-p-beto-${suffix}`, + ana: `t-ana-${suffix}`, + anaYoga: `t-ana-yoga-${suffix}`, + betoYoga: `t-beto-yoga-${suffix}`, + beto: `t-beto-${suffix}`, + accountAna: `t-acc-ana-${suffix}`, + accountBeto: `t-acc-beto-${suffix}`, + }; + // Wednesday 2026-10-28 12:00 in Buenos Aires: the group meets Mon/Wed/Fri at 18:00. + const NOW = new Date('2026-10-28T15:00:00.000Z'); + const WED_18 = '2026-10-28T21:00:00.000Z'; + const FRI_18 = '2026-10-30T21:00:00.000Z'; + const MON_18 = '2026-10-26T21:00:00.000Z'; + + beforeAll(async () => { + db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); + unitOfWork = new UnitOfWork(db); + await db.user.create({ + data: { id: ids.user, name: 'Caro', email: `${ids.user}@test.local`, country: 'AR', transferAlias: 'caro.natacion', transferHolder: 'Carolina Gómez' }, + }); + await db.group.create({ + data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' }, + }); + await db.group.create({ + data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' }, + }); + await db.person.createMany({ + data: [ + { id: ids.personAna, createdById: ids.user, fullName: 'Ana' }, + { id: ids.personBeto, createdById: ids.user, fullName: 'Beto' }, + ], + }); + // Ana and Beto are in both groups. + await db.attendee.createMany({ + data: [ + { id: ids.ana, groupId: ids.group, personId: ids.personAna }, + { id: ids.beto, groupId: ids.group, personId: ids.personBeto }, + { id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna }, + { id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto }, + ], + }); + await db.studentAccount.create({ + data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } }, + }); + await db.studentAccount.create({ + data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } }, + }); + await db.payment.createMany({ + data: [ + { id: `t-p1-${suffix}`, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z'), description: 'Septiembre' }, + { id: `t-p2-${suffix}`, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'PENDING', dueDate: new Date('2026-11-10T12:00:00Z'), description: 'Noviembre' }, + { id: `t-p3-${suffix}`, groupId: ids.group, attendeeId: ids.beto, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'PENDING', dueDate: new Date('2026-11-10T12:00:00Z') }, + ], + }); + }); + + afterAll(async () => { + await db.user.deleteMany({ where: { id: ids.user } }); + await db.$disconnect(); + }); + + it('lista las clases de la semana en la hora del profe', async () => { + const result = await new GetStudentClasses({ db, now: NOW }).execute(ids.accountAna, ids.ana); + if (!result.ok) throw new Error('classes failed'); + expect(result.value.timeZone).toBe('America/Argentina/Buenos_Aires'); + const starts = result.value.classes.map((item) => item.startsAt); + expect(starts.slice(0, 3)).toEqual([new Date(MON_18).toISOString(), new Date(WED_18).toISOString(), new Date(FRI_18).toISOString()]); + expect(result.value.classes[0]?.started).toBe(true); + expect(result.value.classes[1]?.started).toBe(false); + }); + + it('avisar falta la justifica y deshacer la revierte', async () => { + const notify = new NotifyStudentAbsences({ db, unitOfWork, now: NOW, releaseHours: 12 }); + const result = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [WED_18, FRI_18], reason: 'health', message: 'Fiebre' }); + if (!result.ok) throw new Error(result.error.detail); + expect(result.value.notified).toHaveLength(2); + + // Idempotent: notifying again creates nothing. + const again = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [WED_18] }); + expect(again).toEqual({ ok: true, value: { notified: [] } }); + + const attendances = await db.attendance.findMany({ where: { attendeeId: ids.ana } }); + expect(attendances.map((row) => row.status)).toEqual(['EXCUSED', 'EXCUSED']); + + const classes = await new GetStudentClasses({ db, now: NOW }).execute(ids.accountAna, ids.ana); + if (!classes.ok) throw new Error('classes failed'); + const wednesday = classes.value.classes.find((item) => item.startsAt === new Date(WED_18).toISOString()); + expect(wednesday?.notice).toMatchObject({ reason: 'health', message: 'Fiebre' }); + + const noticeId = result.value.notified[1]?.id as string; + expect((await new CancelStudentAbsence({ db, unitOfWork, now: NOW }).execute(ids.accountAna, noticeId)).ok).toBe(true); + expect(await db.attendance.count({ where: { attendeeId: ids.ana } })).toBe(1); + }); + + it('no se puede avisar una clase que ya empezó ni una que no existe', async () => { + const notify = new NotifyStudentAbsences({ db, unitOfWork, now: NOW }); + const started = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [MON_18] }); + expect(!started.ok && started.error.status).toBe(409); + const invented = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: ['2026-10-29T21:00:00.000Z'] }); + expect(!invented.ok && invented.error.status).toBe(400); + }); + + it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => { + const me = await new GetStudentMe({ db }).execute(ids.accountAna); + if (!me.ok) throw new Error('me failed'); + expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([ + [ids.ana, 'Natación'], + [ids.anaYoga, 'Yoga'], + ]); + + // Her membership in the second group is reachable; Beto's in that group is not. + expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true); + const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga); + expect(foreign.ok).toBe(false); + if (!foreign.ok) expect(foreign.error.status).toBe(404); + }); + + it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => { + expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false); + expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false); + const notify = await new NotifyStudentAbsences({ db, unitOfWork, now: NOW }).execute(ids.accountBeto, { attendeeId: ids.ana, startsAt: [FRI_18] }); + expect(!notify.ok && notify.error.status).toBe(404); + + const anaNotice = await db.absenceNotice.findFirstOrThrow({ where: { attendeeId: ids.ana, cancelledAt: null } }); + const cancel = await new CancelStudentAbsence({ db, unitOfWork, now: NOW }).execute(ids.accountBeto, anaNotice.id); + expect(!cancel.ok && cancel.error.status).toBe(404); + + const { storage } = memoryStorage(); + // Beto's account reporting Ana's fee, and Beto reporting Ana's fee id under his own attendee. + const asAna = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, { + attendeeId: ids.ana, paymentIds: [`t-p1-${suffix}`], file: { name: 'a.png', bytes: PNG }, + }); + expect(!asAna.ok && asAna.error.status).toBe(404); + const crossFee = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, { + attendeeId: ids.beto, paymentIds: [`t-p1-${suffix}`], file: { name: 'a.png', bytes: PNG }, + }); + expect(!crossFee.ok && crossFee.error.status).toBe(400); + }); + + it('informar pago guarda el comprobante privado y marca las cuotas como informadas', async () => { + const { objects, storage } = memoryStorage(); + const report = new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }); + const result = await report.execute(ids.accountAna, { + attendeeId: ids.ana, paymentIds: [`t-p1-${suffix}`, `t-p2-${suffix}`], file: { name: 'captura.png', bytes: PNG }, + }); + if (!result.ok) throw new Error(result.error.detail); + expect(objects.size).toBe(1); + const row = await db.reportedPayment.findUniqueOrThrow({ where: { id: result.value.id } }); + expect(row).toMatchObject({ status: 'REPORTED', receiptMime: 'image/png', currency: 'ARS' }); + expect(row.totalAmount.toNumber()).toBe(30000); + expect([...objects.keys()][0]).toBe(row.receiptKey as string); + + const fees = await new GetStudentFees({ db, now: NOW }).execute(ids.accountAna, ids.ana); + if (!fees.ok) throw new Error('fees failed'); + expect(fees.value.fees.map((fee) => fee.status)).toEqual(['reported', 'reported']); + expect(fees.value.transfer).toEqual({ alias: 'caro.natacion', holder: 'Carolina Gómez' }); + + // The same fee can't be in two unreviewed reports; the orphan file is removed. + const twice = await report.execute(ids.accountAna, { + attendeeId: ids.ana, paymentIds: [`t-p2-${suffix}`], file: { name: 'otra.png', bytes: PNG }, + }); + expect(!twice.ok && twice.error.status).toBe(409); + expect(objects.size).toBe(1); + }); + + it('valida el tipo real del archivo, no el nombre', async () => { + const { storage } = memoryStorage(); + const fake = new TextEncoder().encode(''); + const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, { + attendeeId: ids.beto, paymentIds: [`t-p3-${suffix}`], file: { name: 'comprobante.png', bytes: fake }, + }); + expect(!result.ok && result.error.status).toBe(400); + }); +}); diff --git a/apps/backend/test/groups.test.ts b/apps/backend/test/groups.test.ts index 4930fec..af70646 100644 --- a/apps/backend/test/groups.test.ts +++ b/apps/backend/test/groups.test.ts @@ -4,16 +4,12 @@ import { Hono } from 'hono'; const db = { group: { findMany: mock(), - findFirst: mock(), count: mock(), create: mock(), }, groupMember: { create: mock(), }, - organization: { - findUnique: mock(), - }, }; mock.module('@/lib/prisma', () => ({ @@ -27,6 +23,7 @@ mock.module('@/lib/prisma', () => ({ import prisma from '@/lib/prisma'; import { groupsRoutes } from '@/modules/groups'; +import { ListGroups } from '@/modules/groups/features/get-all/use-case'; const userId = 'user-1'; const group = { @@ -36,6 +33,15 @@ const group = { createdById: userId, createdAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'), + days: null, + time: null, + capacity: null, + price: null, + billingType: null, + dueDay: null, + inviteToken: null, + autoPaymentReminders: false, + autoReengagement: false, }; function makeApp(userValue: unknown) { @@ -54,7 +60,9 @@ describe('groups routes', () => { }); it('lists groups scoped to the current user', async () => { - prisma.group.findMany.mockResolvedValue([group]); + prisma.group.findMany.mockResolvedValue([ + { ...group, _count: { attendees: 4, waitlist: 1, payments: 3 } }, + ]); prisma.group.count.mockResolvedValue(1); const res = await makeApp({ id: userId }).request('/groups'); @@ -66,6 +74,9 @@ describe('groups routes', () => { ...group, createdAt: group.createdAt.toISOString(), updatedAt: group.updatedAt.toISOString(), + attendeesCount: 4, + waitlistCount: 1, + unpaidPaymentsCount: 3, }, ], pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 }, @@ -73,13 +84,20 @@ describe('groups routes', () => { const where = { OR: [{ createdById: userId }, { members: { some: { userId } } }], }; + // The occupancy counters ride along in the same query; the waitlist + // counts only PENDING, the ones still waiting for a spot. expect(prisma.group.findMany).toHaveBeenCalledWith({ where, - skip: 0, - take: 10, - orderBy: { createdAt: 'desc' }, + include: { + _count: { + select: { + attendees: true, + waitlist: { where: { status: 'PENDING' } }, + payments: { where: { status: { in: ['PENDING', 'OVERDUE'] } } }, + }, + }, + }, }); - expect(prisma.group.count).toHaveBeenCalledWith({ where }); }); it('rejects listing groups without a session', async () => { @@ -95,19 +113,89 @@ describe('groups routes', () => { expect(res.status).toBe(400); }); - it('creates a group from an owned organization', async () => { - const organization = { - id: 'org-1', - name: 'Escuela Alfa', - members: [{ userId, role: 'owner' }], - }; - prisma.organization.findUnique.mockResolvedValue(organization as never); - prisma.group.findFirst.mockResolvedValue(null); - prisma.group.create.mockResolvedValue(group); + it('rejects an invalid time zone', async () => { + const res = await makeApp({ id: userId }).request('/groups?timeZone=Marte/Olympus'); - const res = await makeApp({ id: userId }).request('/groups/from-organization', { + expect(res.status).toBe(400); + }); + + it('ordena los grupos por la clase más cercana y deja al final los sin horario', async () => { + prisma.group.findMany.mockResolvedValue([ + { ...group, id: 'sin-horario', name: 'Sin horario' }, + { ...group, id: 'proxima-semana', name: 'Próxima semana', days: ['MONDAY'], time: '08:00' }, + { ...group, id: 'manana', name: 'Mañana', days: ['TUESDAY'], time: '09:00' }, + { ...group, id: 'hoy-tarde', name: 'Hoy a la tarde', days: ['MONDAY'], time: '18:00' }, + { + ...group, + id: 'hoy-tarde-viejo', + name: 'Hoy a la tarde (viejo)', + days: ['MONDAY'], + time: '18:00', + createdAt: new Date('2026-07-01T10:00:00.000Z'), + }, + ]); + + // Monday 2026-01-05 at noon in Mexico City: the 18:00 class + // hasn't started yet, so that group goes first. + const result = await new ListGroups({ + db, + now: new Date('2026-01-05T18:00:00.000Z'), + }).execute({ page: 1, pageSize: 10, timeZone: 'America/Mexico_City' }, userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + // On a tie the newest one goes first, which was the previous criterion. + expect(result.value.data.map((item) => item.id)).toEqual([ + 'hoy-tarde', + 'hoy-tarde-viejo', + 'manana', + 'proxima-semana', + 'sin-horario', + ]); + expect(result.value.pagination).toEqual({ page: 1, pageSize: 10, total: 5, totalPages: 1 }); + }); + + it('pagina la lista ya ordenada por próxima clase', async () => { + prisma.group.findMany.mockResolvedValue([ + { ...group, id: 'a', name: 'A', days: ['MONDAY'], time: '10:00' }, + { ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' }, + ]); + + // Monday at noon: A's 10:00 class already happened, so its + // next occurrence is next Monday and B (Wednesday) goes first. + const result = await new ListGroups({ + db, + now: new Date('2026-01-05T18:00:00.000Z'), + }).execute({ page: 2, pageSize: 1, timeZone: 'UTC' }, userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.value.data.map((item) => item.id)).toEqual(['a']); + expect(result.value.pagination).toEqual({ page: 2, pageSize: 1, total: 2, totalPages: 2 }); + }); + + it('creates a group with billing configuration', async () => { + prisma.group.create.mockResolvedValue({ + ...group, + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + }); + + const res = await makeApp({ id: userId }).request('/groups', { method: 'POST', - body: JSON.stringify({ organizationId: 'org-1' }), + body: JSON.stringify({ + name: 'Cuadrilla Alfa', + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + }), headers: { 'Content-Type': 'application/json' }, }); @@ -115,77 +203,70 @@ describe('groups routes', () => { expect(await res.json()).toEqual({ group: { ...group, + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, createdAt: group.createdAt.toISOString(), updatedAt: group.updatedAt.toISOString(), }, - alreadyExists: false, }); expect(prisma.group.create).toHaveBeenCalledWith({ - data: { name: 'Escuela Alfa', createdById: userId }, + data: { + name: 'Cuadrilla Alfa', + createdById: userId, + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + }, + }); + expect(prisma.groupMember.create).toHaveBeenCalledWith({ + data: { groupId: 'group-1', userId, role: 'OWNER' }, }); }); - it('reuses an existing group with the same name', async () => { - const organization = { - id: 'org-1', - name: 'Escuela Alfa', - members: [{ userId, role: 'owner' }], - }; - prisma.organization.findUnique.mockResolvedValue(organization as never); - prisma.group.findFirst.mockResolvedValue(group); + it('creates a group without Mercado Pago linked, since linking is optional', async () => { + prisma.group.create.mockResolvedValue({ + ...group, + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + }); - const res = await makeApp({ id: userId }).request('/groups/from-organization', { + const res = await makeApp({ id: userId }).request('/groups', { method: 'POST', - body: JSON.stringify({ organizationId: 'org-1' }), + body: JSON.stringify({ + name: 'Cuadrilla Alfa', + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + }), headers: { 'Content-Type': 'application/json' }, }); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.alreadyExists).toBe(true); + expect(res.status).toBe(201); + expect(prisma.group.create).toHaveBeenCalled(); + }); + + it('rejects creating a group with an invalid payload', async () => { + const res = await makeApp({ id: userId }).request('/groups', { + method: 'POST', + body: JSON.stringify({ name: 'x' }), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(400); expect(prisma.group.create).not.toHaveBeenCalled(); }); - - it('rejects creating a group for an unknown organization', async () => { - prisma.organization.findUnique.mockResolvedValue(null); - - const res = await makeApp({ id: userId }).request('/groups/from-organization', { - method: 'POST', - body: JSON.stringify({ organizationId: 'missing' }), - headers: { 'Content-Type': 'application/json' }, - }); - - expect(res.status).toBe(404); - expect(await res.json()).toMatchObject({ code: 'organization_not_found' }); - expect(prisma.group.create).not.toHaveBeenCalled(); - }); - - it('rejects creating a group when the user is not the owner', async () => { - const organization = { - id: 'org-1', - name: 'Escuela Alfa', - members: [{ userId: 'other-user', role: 'owner' }], - }; - prisma.organization.findUnique.mockResolvedValue(organization as never); - - const res = await makeApp({ id: userId }).request('/groups/from-organization', { - method: 'POST', - body: JSON.stringify({ organizationId: 'org-1' }), - headers: { 'Content-Type': 'application/json' }, - }); - - expect(res.status).toBe(403); - expect(await res.json()).toMatchObject({ code: 'group_owner_required' }); - expect(prisma.group.create).not.toHaveBeenCalled(); - }); - - it('rejects creating a group without a session', async () => { - const res = await makeApp(null).request('/groups/from-organization', { - method: 'POST', - body: JSON.stringify({ organizationId: 'org-1' }), - headers: { 'Content-Type': 'application/json' }, - }); - - expect(res.status).toBe(401); - }); }); \ No newline at end of file diff --git a/apps/backend/test/home-scheduler.test.ts b/apps/backend/test/home-scheduler.test.ts new file mode 100644 index 0000000..fabb0cb --- /dev/null +++ b/apps/backend/test/home-scheduler.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'bun:test'; +import { CLASS_WINDOW_HOURS, nextClassOccurrence } from '@/modules/home/lib/scheduler'; + +const TZ = 'America/Mexico_City'; + +describe('nextClassOccurrence', () => { + it('devuelve la próxima clase de hoy cuando aún no arrancó', () => { + const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time + + const result = nextClassOccurrence({ + days: ['WEDNESDAY'], + time: '18:00', + now, + timeZone: TZ, + }); + + expect(result).toEqual({ + occurrenceAt: new Date('2026-09-24T00:00:00.000Z'), + isNow: false, + }); + }); + + it('marca en curso si la clase arrancó hace menos de la ventana', () => { + const now = new Date('2026-09-24T01:00:00.000Z'); // Wednesday 19:00 CDMX time (1 h after the class) + + const result = nextClassOccurrence({ + days: ['WEDNESDAY'], + time: '18:00', + now, + timeZone: TZ, + }); + + expect(result).toEqual({ + occurrenceAt: new Date('2026-09-24T00:00:00.000Z'), + isNow: true, + }); + }); + + it('salta a la próxima semana si la clase ya pasó la ventana', () => { + const now = new Date('2026-09-24T03:00:00.000Z'); // Wednesday 21:00 CDMX time (3 h after the class) + + const result = nextClassOccurrence({ + days: ['WEDNESDAY'], + time: '18:00', + now, + timeZone: TZ, + }); + + expect(result).toEqual({ + occurrenceAt: new Date('2026-10-01T00:00:00.000Z'), + isNow: false, + }); + }); + + it('elige la ocurrencia más próxima entre varios días', () => { + const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time + + const result = nextClassOccurrence({ + days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], + time: '18:00', + now, + timeZone: TZ, + }); + + expect(result).toEqual({ + occurrenceAt: new Date('2026-09-24T00:00:00.000Z'), + isNow: false, + }); + }); + + it('cruza de mes sin problema', () => { + const now = new Date('2026-09-29T18:00:00.000Z'); // Tuesday 12:00 CDMX time (September's last day is Wednesday the 30th) + + const result = nextClassOccurrence({ + days: ['THURSDAY'], + time: '09:00', + now, + timeZone: TZ, + }); + + expect(result).toEqual({ + occurrenceAt: new Date('2026-10-01T15:00:00.000Z'), + isNow: false, + }); + }); + + it('devuelve null si no hay días de clase', () => { + const result = nextClassOccurrence({ + days: [], + time: '18:00', + now: new Date('2026-09-23T18:00:00.000Z'), + timeZone: TZ, + }); + + expect(result).toBeNull(); + }); + + it('devuelve null si la hora es inválida', () => { + const result = nextClassOccurrence({ + days: ['WEDNESDAY'], + time: '99:99', + now: new Date('2026-09-23T18:00:00.000Z'), + timeZone: TZ, + }); + + expect(result).toBeNull(); + }); + + it('expone el tamaño de la ventana de "en curso"', () => { + expect(CLASS_WINDOW_HOURS).toBeGreaterThan(0); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/home.test.ts b/apps/backend/test/home.test.ts new file mode 100644 index 0000000..af66ce1 --- /dev/null +++ b/apps/backend/test/home.test.ts @@ -0,0 +1,281 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findMany: mock(), + }, + payment: { + aggregate: mock(), + findMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { homeRoutes } from '@/modules/home'; +import { GetHomeSummary } from '@/modules/home/features/get-summary/use-case'; + +const TZ = 'America/Mexico_City'; +const userId = 'user-1'; + +const groupA = { + id: 'g1', + name: 'Cuadrilla A', + days: ['WEDNESDAY'], + time: '18:00', + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + capacity: 8, + _count: { attendees: 3, preRegistrations: 2 }, +}; + +const groupB = { + id: 'g2', + name: 'Cuadrilla B', + days: [], + time: null, + price: null, + billingType: null, + dueDay: null, + capacity: null, + _count: { attendees: 2, preRegistrations: 0 }, +}; + +const madeUpAmount = (value: string) => ({ toString: () => value }); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/home', homeRoutes); + return app; +} + +describe('GetHomeSummary', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('agrega stats, próxima clase y próximos cobros del usuario', async () => { + prisma.group.findMany.mockResolvedValue([groupB, groupA]); + prisma.payment.aggregate.mockResolvedValue({ + _count: 4, + _sum: { amount: madeUpAmount('2100') }, + }); + prisma.payment.findMany.mockResolvedValue([ + { + id: 'p1', + amount: madeUpAmount('500'), + currency: 'MXN', + dueDate: new Date('2026-09-25T12:00:00.000Z'), + status: 'PENDING', + group: { name: 'Cuadrilla A' }, + attendee: { person: { fullName: 'Ana García' } }, + }, + ]); + + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T18:00:00.000Z'), timeZone: TZ }); + const result = await useCase.execute(userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value).toEqual({ + stats: { groups: 2, attendees: 5, pendingPayments: 4, pendingAmount: 2100 }, + nextClass: { + groupId: 'g1', + name: 'Cuadrilla A', + days: ['WEDNESDAY'], + time: '18:00', + occurrenceAt: '2026-09-24T00:00:00.000Z', + isNow: false, + }, + upcomingPayments: [ + { + id: 'p1', + amount: 500, + currency: 'MXN', + dueDate: '2026-09-25T12:00:00.000Z', + status: 'PENDING', + groupName: 'Cuadrilla A', + attendeeName: 'Ana García', + }, + ], + // Only the groups with something waiting: Cuadrilla B has none. + pendingPreRegistrations: [{ groupId: 'g1', groupName: 'Cuadrilla A', count: 2 }], + }); + + const where = { + OR: [{ createdById: userId }, { members: { some: { userId } } }], + }; + expect(prisma.group.findMany).toHaveBeenCalledWith({ where, select: expect.any(Object) }); + expect(prisma.payment.aggregate).toHaveBeenCalledWith({ + where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } }, + _count: true, + _sum: { amount: true }, + }); + expect(prisma.payment.findMany).toHaveBeenCalledWith({ + where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } }, + orderBy: [{ dueDate: 'asc' }], + take: 5, + include: { group: { select: { name: true } }, attendee: { select: { person: { select: { fullName: true } } } } }, + }); + }); + + it('marca como en curso la clase que ya arrancó', async () => { + prisma.group.findMany.mockResolvedValue([groupA]); + + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-24T01:00:00.000Z'), timeZone: TZ }); + const result = await useCase.execute(userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value.nextClass).toMatchObject({ + groupId: 'g1', + occurrenceAt: '2026-09-24T00:00:00.000Z', + isNow: true, + }); + }); + + it('elige el grupo con la próxima clase más cercana', async () => { + prisma.group.findMany.mockResolvedValue([ + groupA, + { + id: 'g3', + name: 'Cuadrilla C', + days: ['THURSDAY'], + time: '09:00', + price: null, + billingType: null, + dueDay: null, + capacity: null, + _count: { attendees: 0, preRegistrations: 0 }, + }, + ]); + + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T18:00:00.000Z'), timeZone: TZ }); + const result = await useCase.execute(userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value.nextClass?.groupId).toBe('g1'); + expect(result.value.nextClass?.occurrenceAt).toBe('2026-09-24T00:00:00.000Z'); + }); + + it('devuelve nextClass null si ningún grupo tiene horario', async () => { + prisma.group.findMany.mockResolvedValue([groupB]); + + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T18:00:00.000Z'), timeZone: TZ }); + const result = await useCase.execute(userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value.nextClass).toBeNull(); + expect(prisma.payment.aggregate).toHaveBeenCalled(); + expect(prisma.payment.findMany).toHaveBeenCalled(); + }); + + it('computa la próxima clase en la zona horaria del cliente', async () => { + prisma.group.findMany.mockResolvedValue([ + { ...groupA, days: ['WEDNESDAY'], time: '10:00' }, + ]); + + // 10:23 in Buenos Aires (UTC-3). The 10:00 class already started. + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') }); + const result = await useCase.execute(userId, { timeZone: 'America/Argentina/Buenos_Aires' }); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value.nextClass).toMatchObject({ + groupId: 'g1', + occurrenceAt: '2026-09-23T13:00:00.000Z', + isNow: true, + }); + }); + + it('usa la zona por defecto si no se envía una', async () => { + prisma.group.findMany.mockResolvedValue([ + { ...groupA, days: ['WEDNESDAY'], time: '10:00' }, + ]); + + // 10:23 in Buenos Aires, the default zone: the 10:00 class already started. + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') }); + const result = await useCase.execute(userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value.nextClass).toMatchObject({ + occurrenceAt: '2026-09-23T13:00:00.000Z', + isNow: true, + }); + }); + + it('devuelve ceros y listas vacías cuando el usuario no tiene grupos', async () => { + prisma.group.findMany.mockResolvedValue([]); + + const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T18:00:00.000Z'), timeZone: TZ }); + const result = await useCase.execute(userId); + + expect(result.ok).toBe(true); + if (!result.ok) return; + + expect(result.value).toEqual({ + stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 }, + nextClass: null, + upcomingPayments: [], + pendingPreRegistrations: [], + }); + expect(prisma.payment.aggregate).not.toHaveBeenCalled(); + expect(prisma.payment.findMany).not.toHaveBeenCalled(); + }); +}); + +describe('home routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('devuelve el resumen del home autenticado', async () => { + prisma.group.findMany.mockResolvedValue([]); + + const res = await makeApp({ id: userId }).request('/home'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 }, + nextClass: null, + upcomingPayments: [], + pendingPreRegistrations: [], + }); + }); + + it('rechaza el home sin sesión', async () => { + const res = await makeApp(null).request('/home'); + + expect(res.status).toBe(401); + expect(await res.json()).toMatchObject({ code: 'unauthorized' }); + }); + + it('rechaza una zona horaria inválida', async () => { + const res = await makeApp({ id: userId }).request('/home?timeZone=No/Es_Una_Zona'); + + expect(res.status).toBe(400); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/invitations.test.ts b/apps/backend/test/invitations.test.ts new file mode 100644 index 0000000..bb41613 --- /dev/null +++ b/apps/backend/test/invitations.test.ts @@ -0,0 +1,252 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + create: mock(), + count: mock(), + }, + groupPreRegistration: { + findFirst: mock(), + create: mock(), + update: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { invitationsRoutes } from '@/modules/invitations'; + +const app = new Hono(); +app.route('/invitations', invitationsRoutes); + +const mockGroup = { + id: 'group-1', + name: 'Taller de Cerámica', + description: 'Clases de cerámica los sábados', + days: ['SATURDAY'], + time: '10:00', + capacity: 15, + price: 500, + billingType: 'MONTHLY', + createdById: 'teacher-1', + owner: { name: 'Prof. Mario Rossi' }, +}; + +describe('public invitations routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('GET /invitations/:token', () => { + it('returns group details for a valid invite token', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await app.request('/invitations/valid-token-123'); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data).toEqual({ + id: 'group-1', + name: 'Taller de Cerámica', + description: 'Clases de cerámica los sábados', + teacherName: 'Prof. Mario Rossi', + days: ['SATURDAY'], + time: '10:00', + capacity: 15, + price: 500, + billingType: 'MONTHLY', + }); + expect(prisma.group.findUnique).toHaveBeenCalledWith({ + where: { inviteToken: 'valid-token-123' }, + include: { owner: { select: { name: true } } }, + }); + }); + + it('returns 404 when the invite token is invalid', async () => { + prisma.group.findUnique.mockResolvedValue(null); + + const res = await app.request('/invitations/invalid-token'); + + expect(res.status).toBe(404); + const body = await res.json(); + expect(body.title).toBe('Not Found'); + }); + }); + + describe('POST /invitations/:token/join', () => { + it('creates a pending pre-registration instead of an attendee', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.groupPreRegistration.findFirst.mockResolvedValue(null); + prisma.groupPreRegistration.create.mockResolvedValue({ + id: 'pre-1', + groupId: 'group-1', + fullName: 'Lucía Méndez', + email: 'lucia@test.com', + phone: '+5491122334455', + status: 'PENDING', + reviewedAt: null, + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + } as never); + + const res = await app.request('/invitations/valid-token-123/join', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Lucía', + lastName: 'Méndez', + phone: '+54 9 11 2233-4455', + email: 'lucia@test.com', + }), + }); + + expect(res.status).toBe(201); + const body = await res.json(); + expect(body.status).toBe('pre_registered'); + expect(body.attendee).toBeNull(); + expect(body.message).toContain('solicitud de inscripción'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupPreRegistration.create).toHaveBeenCalledWith({ + data: { + groupId: 'group-1', + fullName: 'Lucía Méndez', + phone: '+5491122334455', + email: 'lucia@test.com', + }, + }); + }); + + it('rejects registration when phone already exists in the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue({ id: 'existing-att' } as never); + + const res = await app.request('/invitations/valid-token-123/join', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Lucía', + lastName: 'Méndez', + phone: '1122334455', + }), + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('attendee_already_registered'); + expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled(); + }); + + it('rejects invalid inputs (missing required name/phone)', async () => { + const res = await app.request('/invitations/valid-token-123/join', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: '', + phone: '12', + }), + }); + + expect(res.status).toBe(400); + }); + + it('returns 409 when a pre-registration is already pending', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.groupPreRegistration.findFirst.mockResolvedValue({ + id: 'pre-1', + status: 'PENDING', + } as never); + + const res = await app.request('/invitations/valid-token-123/join', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Lucía', + lastName: 'Méndez', + phone: '+54 9 11 2233-4455', + }), + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('pre_registration_already_pending'); + expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled(); + expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled(); + }); + + it('returns 409 when the pre-registration was already approved', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.groupPreRegistration.findFirst.mockResolvedValue({ + id: 'pre-1', + status: 'APPROVED', + } as never); + + const res = await app.request('/invitations/valid-token-123/join', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Lucía', + lastName: 'Méndez', + phone: '+54 9 11 2233-4455', + }), + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('pre_registration_already_approved'); + expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled(); + }); + + it('reactivates a rejected pre-registration back to pending', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.groupPreRegistration.findFirst.mockResolvedValue({ + id: 'pre-1', + groupId: 'group-1', + fullName: 'Lucía Méndez', + phone: '+5491122334455', + status: 'REJECTED', + reviewedAt: new Date('2026-09-19T10:00:00.000Z'), + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-19T10:00:00.000Z'), + } as never); + + const res = await app.request('/invitations/valid-token-123/join', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + firstName: 'Lucía', + lastName: 'Méndez', + phone: '+54 9 11 2233-4455', + email: 'lucia@test.com', + }), + }); + + expect(res.status).toBe(201); + const body = await res.json(); + expect(body.status).toBe('pre_registered'); + expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled(); + expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({ + where: { id: 'pre-1' }, + data: { + status: 'PENDING', + fullName: 'Lucía Méndez', + email: 'lucia@test.com', + reviewedAt: null, + }, + }); + }); + }); +}); diff --git a/apps/backend/test/mp.test.ts b/apps/backend/test/mp.test.ts new file mode 100644 index 0000000..cc81ba3 --- /dev/null +++ b/apps/backend/test/mp.test.ts @@ -0,0 +1,1042 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + mpAccount: { + findUnique: mock(), + upsert: mock(), + update: mock(), + }, + mpOAuthState: { + create: mock(), + findUnique: mock(), + deleteMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { getMpAccessToken, mpRoutes } from '@/modules/mp'; +import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens'; +import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account'; +import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto'; +import { MpApiError } from '@/modules/mp/lib/mp-oauth'; + +const ownerId = 'user-1'; +const otherOwnerId = 'user-2'; +const WEB_URL = 'http://localhost:6173'; + +/** A key of the right length; the value never matters for these tests. */ +const ENCRYPTION_KEY = Buffer.alloc(32, 7).toString('base64'); +// Set before the fixtures below seal anything at describe-body time. +process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + +const storedState = { + state: 'state-abc', + ownerId, + codeVerifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk', + returnTo: 'onboarding', + expiresAt: new Date(Date.now() + 10 * 60 * 1000), +}; + +/** + * The wire body Mercado Pago returns, not the parsed shape: `user_id` arrives + * as a number, which the parser has to cope with. + */ +const mpWireTokens = { + access_token: 'APP_USR-access-token', + refresh_token: 'TG-refresh-token', + expires_in: 15552000, + scope: 'offline_access read write', + user_id: 9876543210, + live_mode: true, +}; + +const MP_USER_ID = '9876543210'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/mp', mpRoutes); + return app; +} + +function locationOf(res: Response): URL { + const location = res.headers.get('Location'); + if (!location) throw new Error('the callback did not redirect'); + return new URL(location); +} + +describe('modules/mp', () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + process.env.WEB_URL = WEB_URL; + }); + + describe('GET /mp/status', () => { + it('reports none when the teacher has never linked an account', async () => { + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + status: 'none', + liveMode: false, + expiresAt: null, + connectedAt: null, + mpUserIdSuffix: null, + }); + }); + + it('reports active without leaking tokens or the full Mercado Pago id', async () => { + const expiresAt = new Date('2027-03-01T12:00:00.000Z'); + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId, + mpUserId: '9876543210', + accessTokenEnc: 'v1:sealed', + refreshTokenEnc: 'v1:sealed', + expiresAt, + scope: 'offline_access read write', + liveMode: true, + status: 'ACTIVE', + connectedAt: new Date('2026-10-01T10:00:00.000Z'), + }); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + const body = await res.json(); + + expect(body).toEqual({ + status: 'active', + liveMode: true, + expiresAt: expiresAt.toISOString(), + connectedAt: '2026-10-01T10:00:00.000Z', + mpUserIdSuffix: '3210', + }); + expect(JSON.stringify(body)).not.toContain('sealed'); + expect(JSON.stringify(body)).not.toContain('9876543210'); + expect(JSON.stringify(body)).not.toContain('offline_access'); + }); + + it('reports requires_reauth when the renewal was refused', async () => { + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId, + mpUserId: '9876543210', + expiresAt: new Date('2027-03-01T12:00:00.000Z'), + liveMode: false, + status: 'REQUIRES_REAUTH', + connectedAt: new Date('2026-10-01T10:00:00.000Z'), + }); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + + expect((await res.json()).status).toBe('requires_reauth'); + }); + + it('reports none for a revoked row, since there is nothing usable left', async () => { + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId, + mpUserId: '9876543210', + expiresAt: new Date(0), + liveMode: false, + status: 'REVOKED', + connectedAt: new Date('2026-10-01T10:00:00.000Z'), + }); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + + expect((await res.json()).status).toBe('none'); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/mp/status'); + + expect(res.status).toBe(401); + expect(await res.json()).toMatchObject({ code: 'unauthorized' }); + }); + }); + + describe('GET /mp/connect', () => { + it('builds a PKCE authorization URL and stores the state', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + const res = await makeApp({ id: ownerId }).request('/mp/connect?returnTo=onboarding'); + + expect(res.status).toBe(200); + const { authorizationUrl } = (await res.json()) as { authorizationUrl: string }; + const url = new URL(authorizationUrl); + + expect(`${url.origin}${url.pathname}`).toBe( + 'https://auth.mercadopago.com/authorization', + ); + expect(url.searchParams.get('client_id')).toBe('client-123'); + expect(url.searchParams.get('response_type')).toBe('code'); + expect(url.searchParams.get('platform_id')).toBe('mp'); + expect(url.searchParams.get('redirect_uri')).toBe( + 'http://localhost:4000/api/v1/mp/callback', + ); + expect(url.searchParams.get('code_challenge_method')).toBe('S256'); + expect(url.searchParams.get('scope')).toBe('offline_access read write'); + + const state = url.searchParams.get('state'); + const challenge = url.searchParams.get('code_challenge'); + expect(state).toBeTruthy(); + expect(challenge).toBeTruthy(); + + const created = prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data; + expect(created.state).toBe(state); + expect(created.ownerId).toBe(ownerId); + expect(created.returnTo).toBe('onboarding'); + // Only the challenge is public: the verifier stays in the row. + expect(created.codeVerifier).toBeTruthy(); + expect(codeChallengeFromVerifier(created.codeVerifier)).toBe(challenge); + expect(created.expiresAt.getTime()).toBeGreaterThan(Date.now() + 9 * 60 * 1000); + }); + + it('never puts the code verifier in the URL it hands to the browser', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + const res = await makeApp({ id: ownerId }).request('/mp/connect'); + const { authorizationUrl } = (await res.json()) as { authorizationUrl: string }; + + const verifier = prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data.codeVerifier; + expect(authorizationUrl).not.toContain(verifier); + }); + + it('sweeps expired states and the previous attempt of the same teacher', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 2 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + await makeApp({ id: ownerId }).request('/mp/connect'); + + const where = prisma.mpOAuthState.deleteMany.mock.calls[0]?.[0]?.where; + expect(where.OR).toHaveLength(2); + expect(where.OR).toContainEqual({ ownerId }); + }); + + it('defaults the return target to settings', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + await makeApp({ id: ownerId }).request('/mp/connect'); + + expect(prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data.returnTo).toBe('settings'); + }); + + it('rejects a return target outside the enum', async () => { + const res = await makeApp({ id: ownerId }).request('/mp/connect?returnTo=https://evil.test'); + + expect(res.status).toBe(400); + expect(prisma.mpOAuthState.create).not.toHaveBeenCalled(); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/mp/connect'); + + expect(res.status).toBe(401); + expect(prisma.mpOAuthState.create).not.toHaveBeenCalled(); + }); + + it('reports a configuration problem when the credentials are missing', async () => { + delete process.env.MP_CLIENT_ID; + + const res = await makeApp({ id: ownerId }).request('/mp/connect'); + + expect(res.status).toBe(503); + expect(await res.json()).toMatchObject({ code: 'mp_not_configured' }); + expect(prisma.mpOAuthState.create).not.toHaveBeenCalled(); + }); + }); + + describe('GET /mp/callback', () => { + const callbackUrl = (query: string) => `/mp/callback${query}`; + + /** + * The route builds the use-case itself, so `fetch` is the seam: this + * answers Mercado Pago's token endpoint and hands back the restore function. + */ + function stubTokenEndpoint( + answer: Response | Error, + ): { calls: Array>; restore: () => void } { + const calls: Array> = []; + const original = globalThis.fetch; + globalThis.fetch = mock(async (_url: unknown, init: RequestInit) => { + calls.push(JSON.parse(String(init.body)) as Record); + if (answer instanceof Error) throw answer; + return answer.clone(); + }) as unknown as typeof fetch; + + return { + calls, + restore: () => { + globalThis.fetch = original; + }, + }; + } + + function tokenResponse(payload: unknown, status = 200): Response { + return new Response(JSON.stringify(payload), { + status, + headers: { 'Content-Type': 'application/json' }, + }); + } + + it('exchanges the code and stores the tokens encrypted', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('success'); + + const { create: data } = prisma.mpAccount.upsert.mock.calls[0]?.[0] ?? {}; + expect(data.ownerId).toBe(ownerId); + expect(data.mpUserId).toBe(MP_USER_ID); + expect(data.status).toBe('ACTIVE'); + expect(data.liveMode).toBe(true); + expect(data.scope).toBe('offline_access read write'); + + // Encrypted at rest: the ciphertext is not the token. + expect(data.accessTokenEnc).not.toBe(mpWireTokens.access_token); + expect(data.refreshTokenEnc).not.toBe(mpWireTokens.refresh_token); + expect(String(data.accessTokenEnc).startsWith('v1:')).toBe(true); + expect(openToken(data.accessTokenEnc)).toBe(mpWireTokens.access_token); + expect(openToken(data.refreshTokenEnc)).toBe(mpWireTokens.refresh_token); + + // expires_at comes from expires_in, not from a guess. + const expected = Date.now() + mpWireTokens.expires_in * 1000; + expect(Math.abs(data.expiresAt.getTime() - expected)).toBeLessThan(5_000); + }); + + it('sends the verifier and the exact redirect_uri to Mercado Pago', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(res.status).toBe(302); + expect(stub.calls[0]).toEqual({ + grant_type: 'authorization_code', + client_id: 'client-123', + client_secret: 'secret-abc', + code: 'auth-code-123', + redirect_uri: 'http://localhost:4000/api/v1/mp/callback', + code_verifier: storedState.codeVerifier, + }); + }); + + it('lands the teacher back on the onboarding step they left', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).pathname).toBe('/onboarding'); + }); + + it('still redirects when Mercado Pago appends query params we do not model', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc&error_description=&foo=bar'), + ); + stub.restore(); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('success'); + }); + + it('refuses an unknown state and never calls Mercado Pago', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(null); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=forged'), + ); + globalThis.fetch = original; + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('error'); + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('refuses an expired state without touching Mercado Pago', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue({ + ...storedState, + expiresAt: new Date(Date.now() - 1000), + }); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + globalThis.fetch = original; + + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('refuses a replayed state, even with a valid looking code', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + // Already consumed by the first callback: the delete matches nothing. + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + globalThis.fetch = original; + + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('refuses a callback without a code', async () => { + const res = await makeApp({ id: ownerId }).request(callbackUrl('?state=state-abc')); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + }); + + it('treats a rejected consent screen as mp_denied and burns the state', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?error=access_denied&error_description=user_denied&state=state-abc'), + ); + globalThis.fetch = original; + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('error'); + expect(locationOf(res).searchParams.get('reason')).toBe('mp_denied'); + expect(prisma.mpOAuthState.deleteMany).toHaveBeenCalledWith({ + where: { state: 'state-abc' }, + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses when the Mercado Pago account belongs to another teacher', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-9', ownerId: otherOwnerId }); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_account_in_use'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('maps the unique index violation to the same clear error', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockRejectedValue({ code: 'P2002' }); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_account_in_use'); + }); + + it('lets a teacher re-link their own account', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId }); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('mp')).toBe('success'); + + const args = prisma.mpAccount.upsert.mock.calls[0]?.[0]; + expect(args.where).toEqual({ ownerId }); + // Re-linking renews the credentials and clears a `requires_reauth`. + expect(args.update.status).toBe('ACTIVE'); + expect(args.update.connectedAt).toBeInstanceOf(Date); + }); + + it('reports mp_error when Mercado Pago rejects the exchange', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const original = globalThis.fetch; + globalThis.fetch = mock( + async () => + new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }), + ) as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + globalThis.fetch = original; + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_error'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('reports mp_error when Mercado Pago is unreachable', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const stub = stubTokenEndpoint(new Error('ECONNREFUSED')); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_error'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('never puts the code or the verifier in the redirect it sends the browser to', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=super-secret-code&state=state-abc'), + ); + stub.restore(); + + const location = locationOf(res); + expect(location.search).toContain('mp=success'); + expect(location.href).not.toContain('super-secret-code'); + expect(location.href).not.toContain(storedState.codeVerifier); + }); + + it('sends a teacher without a session to the login screen', async () => { + const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc')); + + expect(res.status).toBe(302); + expect(locationOf(res).pathname).toBe('/login'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + }); + + describe('DELETE /mp/connect', () => { + it('revokes the account and blanks the tokens', async () => { + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId }); + prisma.mpAccount.update.mockResolvedValue({}); + + const res = await makeApp({ id: ownerId }).request('/mp/connect', { method: 'DELETE' }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ disconnected: true }); + expect(prisma.mpAccount.update).toHaveBeenCalledWith({ + where: { ownerId }, + data: { + status: 'REVOKED', + accessTokenEnc: '', + refreshTokenEnc: '', + expiresAt: new Date(0), + }, + }); + }); + + it('is a no-op when there is nothing linked', async () => { + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: ownerId }).request('/mp/connect', { method: 'DELETE' }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ disconnected: false }); + expect(prisma.mpAccount.update).not.toHaveBeenCalled(); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/mp/connect', { method: 'DELETE' }); + + expect(res.status).toBe(401); + }); + }); +}); + +describe('modules/mp encryption and PKCE', () => { + beforeEach(() => { + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + it('round-trips a token through seal and open', () => { + const token = 'APP_USR-very-long-mercadopago-access-token'; + const sealed = sealToken(token); + + expect(sealed.startsWith('v1:')).toBe(true); + expect(sealed).not.toContain(token); + expect(openToken(sealed)).toBe(token); + }); + + it('produces a different ciphertext every time', () => { + expect(sealToken('same-token')).not.toBe(sealToken('same-token')); + }); + + it('refuses a tampered payload instead of returning garbage', () => { + const sealed = sealToken('token'); + const [version, iv, tag, ciphertext = ''] = sealed.split(':'); + if (!version || !iv || !tag || !ciphertext) throw new Error('unexpected payload shape'); + + // Flip the first ciphertext byte: the trailing base64url char of a GCM tag + // only carries two significant bits, so editing that one can decode back to + // the original tag and the payload would still verify. + const tampered = `${ciphertext[0] === 'A' ? 'B' : 'A'}${ciphertext.slice(1)}`; + + expect(() => openToken(`${version}:${iv}:${tag}:${tampered}`)).toThrow(); + }); + + it('refuses an unknown payload version', () => { + expect(() => openToken('v9:aaa:bbb:ccc')).toThrow('Unsupported token payload'); + }); + + it('refuses to work without a key of 32 bytes', () => { + process.env.TOKEN_ENCRYPTION_KEY = Buffer.alloc(16, 7).toString('base64'); + + expect(() => sealToken('token')).toThrow('must decode to 32 bytes'); + }); + + it('derives the S256 challenge from the RFC 7636 test vector', () => { + expect(codeChallengeFromVerifier('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe( + 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + ); + }); +}); + +describe('modules/mp access token', () => { + const activeAccount = { + id: 'mp-1', + ownerId, + status: 'ACTIVE', + accessTokenEnc: sealToken('APP_USR-current-token'), + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + }; + + beforeEach(() => { + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + it('fails with mp_not_connected when the teacher never linked an account', async () => { + const db = { mpAccount: { findUnique: mock(async () => null) } }; + + const result = await getMpAccessToken(ownerId, { + db: db as unknown as Parameters[1] extends undefined + ? never + : never, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_not_connected'); + }); + + it('tells mp_not_connected and mp_requires_reauth apart', async () => { + const notActive = { ...activeAccount, status: 'REQUIRES_REAUTH' }; + const refresh = { execute: mock() }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => notActive) } } as never, + refresh: refresh as never, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + // A locked account is never "fixed" by quietly attempting a renewal. + expect(refresh.execute).not.toHaveBeenCalled(); + }); + + it('decrypts a token that is still fresh, without calling Mercado Pago', async () => { + const refresh = { execute: mock() }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => activeAccount) } } as never, + refresh: refresh as never, + }); + + expect(result).toEqual({ + ok: true, + value: { accountId: 'mp-1', accessToken: 'APP_USR-current-token', expiresAt: activeAccount.expiresAt }, + }); + expect(refresh.execute).not.toHaveBeenCalled(); + }); + + it('renews on demand when the token is about to expire', async () => { + const stale = { ...activeAccount, expiresAt: new Date(Date.now() + 60 * 1000) }; + const renewed = { + ok: true as const, + value: { + accountId: 'mp-1', + accessToken: 'APP_USR-fresh-token', + expiresAt: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000), + }, + }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => stale) } } as never, + refresh: { execute: mock(async () => renewed) } as never, + }); + + expect(result).toEqual(renewed); + }); + + it('passes the renewal failure through instead of returning a stale token', async () => { + const stale = { ...activeAccount, expiresAt: new Date(Date.now() - 1000) }; + const failed = { + ok: false as const, + error: { + type: 'x', + title: 'Conflict', + status: 409, + detail: 'd', + code: 'mp_requires_reauth', + }, + }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => stale) } } as never, + refresh: { execute: mock(async () => failed) } as never, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + }); +}); + +describe('modules/mp RefreshMpAccount', () => { + const account = { + id: 'mp-1', + ownerId, + status: 'ACTIVE', + accessTokenEnc: sealToken('APP_USR-old-access'), + refreshTokenEnc: sealToken('TG-old-refresh'), + scope: 'offline_access read write', + }; + + beforeEach(() => { + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + function makeStore(overrides: Record = {}) { + return { + mpAccount: { + findUnique: mock(async () => account), + update: mock(async () => ({})), + ...overrides, + }, + }; + } + + it('sends the stored refresh token and stores both new tokens', async () => { + const store = makeStore(); + const refresh = mock(async () => ({ + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: 'offline_access read write', + mpUserId: MP_USER_ID, + liveMode: true, + })); + + const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute( + 'mp-1', + ); + + expect(result).toEqual({ + ok: true, + value: { + accountId: 'mp-1', + accessToken: 'APP_USR-new-access', + expiresAt: expect.any(Date) as unknown as Date, + }, + }); + // `webUrl` rides along in the config object but is never part of the + // request: `refreshMpTokens` picks the three fields the endpoint needs. + expect(refresh).toHaveBeenCalledWith({ + clientId: 'client-123', + clientSecret: 'secret-abc', + redirectUri: 'http://localhost:4000/api/v1/mp/callback', + webUrl: 'http://localhost:6173', + refreshToken: 'TG-old-refresh', + }); + + const data = store.mpAccount.update.mock.calls[0]?.[0]?.data; + // Mercado Pago rotates the refresh token: keeping the old one would break + // the next renewal. + expect(openToken(data.refreshTokenEnc)).toBe('TG-new-refresh'); + expect(openToken(data.accessTokenEnc)).toBe('APP_USR-new-access'); + expect(data.status).toBe('ACTIVE'); + }); + + it('keeps the stored scope when the renewal omits it', async () => { + const store = makeStore(); + const refresh = mock(async () => ({ + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: null, + mpUserId: MP_USER_ID, + liveMode: true, + })); + + await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute('mp-1'); + + expect(store.mpAccount.update.mock.calls[0]?.[0]?.data.scope).toBe( + 'offline_access read write', + ); + }); + + it('marks the account REQUIRES_REAUTH when Mercado Pago says invalid_grant', async () => { + const store = makeStore(); + const refresh = mock(async () => { + throw new MpApiError(401, 'invalid_grant'); + }); + + const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute( + 'mp-1', + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + expect(store.mpAccount.update).toHaveBeenCalledWith({ + where: { id: 'mp-1' }, + data: { status: 'REQUIRES_REAUTH' }, + }); + }); + + it('leaves the account untouched on a server error, so tomorrow can retry', async () => { + const store = makeStore(); + const refresh = mock(async () => { + throw new MpApiError(500, null); + }); + + const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute( + 'mp-1', + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_provider_error'); + expect(store.mpAccount.update).not.toHaveBeenCalled(); + }); + + it('reports the account when it disappears mid-run', async () => { + const store = makeStore({ findUnique: mock(async () => null) }); + + const result = await new RefreshMpAccount({ + db: store as never, + refresh: mock(async () => { + throw new Error('should not be called'); + }) as never, + }).execute('mp-1'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + }); +}); + +describe('modules/mp RefreshExpiringMpTokens', () => { + beforeEach(() => { + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + /** + * Fakes the transaction client, capturing the tagged-template SQL. The store + * hangs off the `tx` the job forwards, since the writes have to join the + * transaction holding the lock. + */ + function makeJobDb(rows: Array<{ id: string }>, store: { mpAccount: unknown }) { + const captured: { sql: string; values: unknown[] } = { sql: '', values: [] }; + const db = { + $transaction: mock(async (cb: (tx: unknown) => Promise) => + cb({ + mpAccount: store.mpAccount, + $queryRaw: (strings: TemplateStringsArray, ...values: unknown[]) => { + captured.sql = strings.join('?'); + captured.values = values; + return Promise.resolve(rows); + }, + }), + ), + }; + return { db, captured }; + } + + const refreshOk = mock(async () => ({ + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: 'offline_access read write', + mpUserId: MP_USER_ID, + liveMode: true, + })); + + function activeRow(id: string) { + return { + id, + ownerId, + status: 'ACTIVE', + accessTokenEnc: sealToken('APP_USR-old-access'), + refreshTokenEnc: sealToken('TG-old-refresh'), + scope: 'offline_access read write', + }; + } + + function jobDbReturning(rows: Array<{ id: string }>) { + const store = { + mpAccount: { + findUnique: mock(async ({ where }: { where: { id: string } }) => activeRow(where.id)), + update: mock(async () => ({})), + }, + }; + const { db, captured } = makeJobDb(rows, store); + return { db: db as never, captured, store }; + } + + it('selects only accounts expiring inside the 30 day window', async () => { + const { db, captured } = jobDbReturning([]); + + await new RefreshExpiringMpTokens({ db, refresh: refreshOk as never }).execute(); + + // Active accounts only, and anything closer than 30 days from expiring. + expect(captured.sql).toContain(`"status" = 'ACTIVE'`); + expect(captured.sql).toContain('"expires_at" <'); + // No lower bound on the window: a token that already expired is exactly the + // one worth recovering, as long as the grant is still alive. + expect(captured.sql).not.toContain('"expires_at" >'); + // Bounded work per run. + expect(captured.sql).toContain('FOR UPDATE SKIP LOCKED'); + expect(captured.sql).toContain('ORDER BY "expires_at" ASC'); + + const [horizon, limit] = captured.values; + expect(horizon).toBeInstanceOf(Date); + const daysAhead = ((horizon as Date).getTime() - Date.now()) / (24 * 60 * 60 * 1000); + expect(daysAhead).toBeGreaterThan(29.9); + expect(daysAhead).toBeLessThan(30.1); + expect(limit).toBe(20); + }); + + it('renews the accounts the query returned and counts them', async () => { + const { db, store } = jobDbReturning([{ id: 'mp-1' }, { id: 'mp-2' }]); + + const totals = await new RefreshExpiringMpTokens({ db, refresh: refreshOk as never }).execute(); + + expect(totals).toEqual({ refreshed: 2, requiresReauth: 0, failed: 0 }); + expect(store.mpAccount.update).toHaveBeenCalledTimes(2); + }); + + it('separates accounts that need a new authorization from transient failures', async () => { + const mixed = mock(async ({ refreshToken }: { refreshToken: string }) => { + if (refreshToken === 'TG-old-refresh') throw new MpApiError(500, null); + if (refreshToken === 'TG-dead-refresh') throw new MpApiError(401, 'invalid_grant'); + return { + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: null, + mpUserId: MP_USER_ID, + liveMode: true, + }; + }); + const store = { + mpAccount: { + findUnique: mock(async ({ where }: { where: { id: string } }) => { + // mp-1: Mercado Pago is having a bad day. mp-2: the grant is dead. + // mp-3: renews fine. + const token = + where.id === 'mp-2' ? 'TG-dead-refresh' : where.id === 'mp-3' ? 'TG-live-refresh' : 'TG-old-refresh'; + return { ...activeRow(where.id), refreshTokenEnc: sealToken(token) }; + }), + update: mock(async () => ({})), + }, + }; + const { db } = makeJobDb( + [{ id: 'mp-1' }, { id: 'mp-2' }, { id: 'mp-3' }], + store as unknown as { mpAccount: unknown }, + ); + + const totals = await new RefreshExpiringMpTokens({ + db: db as never, + refresh: mixed as never, + }).execute(); + + expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 }); + }); +}); diff --git a/apps/backend/test/onboarding-select-plan.test.ts b/apps/backend/test/onboarding-select-plan.test.ts new file mode 100644 index 0000000..7c6dcd9 --- /dev/null +++ b/apps/backend/test/onboarding-select-plan.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { err, ok } from '@gruperly/shared'; +import { noActiveSubscriptionProblem } from '@/http/problem-builders'; +import { SelectPlan } from '@/modules/onboarding/features/select-plan/use-case'; + +const userId = 'user-1'; +const now = new Date('2026-10-22T12:00:00.000Z'); + +function makeDb(subscription: Record | null, user: Record = {}) { + return { + user: { + findUnique: mock(async () => ({ id: userId, onboardingCompleted: false, ...user })), + update: mock(async () => ({})), + }, + billingSubscription: { + findUnique: mock(async () => subscription), + update: mock(async () => ({})), + }, + }; +} + +function makeDeps(db: ReturnType) { + return { + db: db as never, + subscribe: { execute: mock(async () => ok({ checkoutUrl: 'https://mp/checkout' })) }, + cancel: { execute: mock(async () => ok({ status: 'CANCELLED' as const })) }, + now: () => now, + }; +} + +describe('SelectPlan (onboarding)', () => { + it('stores the country first and marks Free as chosen', async () => { + const db = makeDb(null); + const deps = makeDeps(db); + + const result = await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'CL' }); + + expect(result).toEqual(ok({ plan: 'FREE', checkoutUrl: null })); + expect(db.user.update).toHaveBeenNthCalledWith(1, { where: { id: userId }, data: { country: 'CL' } }); + expect(db.user.update).toHaveBeenNthCalledWith(2, { where: { id: userId }, data: { planSelectedAt: now } }); + expect(deps.subscribe.execute).not.toHaveBeenCalled(); + }); + + it('voids an abandoned Pro attempt when switching to Free', async () => { + const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: 'pre-1' }); + const deps = makeDeps(db); + + await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(deps.cancel.execute).toHaveBeenCalledWith(userId); + }); + + it('voids it locally when Mercado Pago never got the attempt', async () => { + const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: null }); + const deps = makeDeps(db); + deps.cancel.execute = mock(async () => err(noActiveSubscriptionProblem())) as never; + + await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + }); + + it('starts the subscription for Pro and comes back to the onboarding', async () => { + const db = makeDb(null); + const deps = makeDeps(db); + + const result = await new SelectPlan(deps).execute(userId, { + plan: 'PRO', + country: 'AR', + payerEmail: 'profe@mail.com', + }); + + expect(result).toEqual(ok({ plan: 'PRO', checkoutUrl: 'https://mp/checkout' })); + expect(deps.subscribe.execute).toHaveBeenCalledWith(userId, { + payerEmail: 'profe@mail.com', + returnTo: 'onboarding', + }); + expect(db.user.update).toHaveBeenLastCalledWith({ where: { id: userId }, data: { planSelectedAt: now } }); + }); + + it('does not mark a plan when the subscription could not start', async () => { + const db = makeDb(null); + const deps = makeDeps(db); + deps.subscribe.execute = mock(async () => err({ title: 'x', status: 503, code: 'billing_not_available' })) as never; + + const result = await new SelectPlan(deps).execute(userId, { + plan: 'PRO', + country: 'PE', + payerEmail: 'profe@mail.com', + }); + + expect(result.ok).toBe(false); + expect(db.user.update).toHaveBeenCalledTimes(1); + }); + + it('never drops an authorized subscription from the onboarding', async () => { + const db = makeDb({ id: 'sub-1', status: 'AUTHORIZED' }); + + const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('subscription_already_active'); + }); + + it('refuses once the onboarding is completed', async () => { + const db = makeDb(null, { onboardingCompleted: true }); + + const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('onboarding_already_completed'); + }); +}); diff --git a/apps/backend/test/onboarding.test.ts b/apps/backend/test/onboarding.test.ts new file mode 100644 index 0000000..80f5684 --- /dev/null +++ b/apps/backend/test/onboarding.test.ts @@ -0,0 +1,308 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + user: { + findUnique: mock(), + update: mock(), + }, + mpAccount: { + findUnique: mock(), + }, + whatsappAccount: { + findUnique: mock(async () => null), + }, + billingSubscription: { + findUnique: mock(async () => null), + }, + group: { + create: mock(), + }, + groupMember: { + create: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { onboardingRoutes } from '@/modules/onboarding'; + +const userId = 'user-1'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/onboarding', onboardingRoutes); + return app; +} + +const group = { + id: 'group-1', + name: 'Clase de Yoga', + description: null, + createdById: userId, + createdAt: new Date('2026-08-01T10:00:00.000Z'), + updatedAt: new Date('2026-08-01T10:00:00.000Z'), + days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], + time: '09:00', + capacity: 20, + price: 150.5, + billingType: 'MONTHLY', + dueDay: 5, + autoPaymentReminders: false, + autoReengagement: false, +}; + +const firstGroupPayload = { + name: group.name, + days: group.days, + time: group.time, + capacity: group.capacity, + price: group.price, + billingType: group.billingType, + dueDay: group.dueDay, + country: 'AR', +}; + +const noPlan = { planSelected: false, selectedPlan: null, subscriptionStatus: null, country: null }; +const planSelectedAt = new Date('2026-08-01T09:00:00.000Z'); + +describe('onboarding routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('GET /onboarding/status', () => { + it('returns NOT_STARTED for a user that has not started', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + step: 'NOT_STARTED', + paymentConnected: false, + whatsappConnected: false, + completed: false, + ...noPlan, + }); + }); + + it('returns PAYMENT_CONNECTED when Mercado Pago is linked and active', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId: userId, status: 'ACTIVE' }); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + step: 'PAYMENT_CONNECTED', + paymentConnected: true, + whatsappConnected: false, + completed: false, + ...noPlan, + }); + }); + + it('returns NOT_STARTED when the account needs to be linked again', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId: userId, + status: 'REQUIRES_REAUTH', + }); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + step: 'NOT_STARTED', + paymentConnected: false, + whatsappConnected: false, + completed: false, + ...noPlan, + }); + }); + + it('returns COMPLETED when onboarding is already done', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true }); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + step: 'COMPLETED', + paymentConnected: true, + whatsappConnected: false, + completed: true, + ...noPlan, + }); + }); + + it('reports a chosen Pro plan while its subscription is still pending', async () => { + prisma.user.findUnique.mockResolvedValue({ + id: userId, + onboardingCompleted: false, + planSelectedAt, + country: 'MX', + }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.billingSubscription.findUnique.mockResolvedValueOnce({ status: 'PENDING' }); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(await res.json()).toMatchObject({ + planSelected: true, + selectedPlan: 'PRO', + subscriptionStatus: 'PENDING', + country: 'MX', + }); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/onboarding/status'); + + expect(res.status).toBe(401); + expect(await res.json()).toMatchObject({ code: 'unauthorized' }); + }); + }); + + describe('POST /onboarding/first-group', () => { + it('creates the first group and completes onboarding', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt }); + prisma.group.create.mockResolvedValue(group); + + const res = await makeApp({ id: userId }).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify(firstGroupPayload), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(201); + expect(await res.json()).toEqual({ + group: { + id: 'group-1', + name: 'Clase de Yoga', + description: null, + createdById: userId, + createdAt: group.createdAt.toISOString(), + updatedAt: group.updatedAt.toISOString(), + days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], + time: '09:00', + capacity: 20, + price: 150.5, + billingType: 'MONTHLY', + dueDay: 5, + autoPaymentReminders: false, + autoReengagement: false, + }, + onboardingCompleted: true, + }); + expect(prisma.group.create).toHaveBeenCalledWith({ + data: { + name: 'Clase de Yoga', + createdById: userId, + days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], + time: '09:00', + capacity: 20, + price: 150.5, + billingType: 'MONTHLY', + dueDay: 5, + }, + }); + expect(prisma.groupMember.create).toHaveBeenCalledWith({ + data: { groupId: 'group-1', userId, role: 'OWNER' }, + }); + expect(prisma.user.update).toHaveBeenCalledWith({ + where: { id: userId }, + data: { onboardingCompleted: true, country: 'AR' }, + }); + }); + + it('creates the group without Mercado Pago linked, since that step is skippable', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.group.create.mockResolvedValue(group); + + const res = await makeApp({ id: userId }).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify(firstGroupPayload), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(201); + expect(prisma.group.create).toHaveBeenCalled(); + }); + + it('rejects until a plan was chosen, since the Plan step is mandatory', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt: null }); + + const res = await makeApp({ id: userId }).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify(firstGroupPayload), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ code: 'plan_not_selected' }); + expect(prisma.group.create).not.toHaveBeenCalled(); + }); + + it('rejects when onboarding is already completed', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true }); + + const res = await makeApp({ id: userId }).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify(firstGroupPayload), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ code: 'onboarding_already_completed' }); + expect(prisma.group.create).not.toHaveBeenCalled(); + }); + + it('rejects invalid payloads', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + + const res = await makeApp({ id: userId }).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify({ + name: 'Ab', + days: [], + time: '25:99', + capacity: 0, + price: -1, + billingType: 'WEEKLY', + dueDay: 31, + }), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(400); + expect(prisma.group.create).not.toHaveBeenCalled(); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify(firstGroupPayload), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(401); + }); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/payments-batch.test.ts b/apps/backend/test/payments-batch.test.ts new file mode 100644 index 0000000..455746c --- /dev/null +++ b/apps/backend/test/payments-batch.test.ts @@ -0,0 +1,248 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + mpAccount: { + findUnique: mock(), + }, + group: { + findUnique: mock(), + }, + attendee: { + findMany: mock(), + }, + payment: { + create: mock(), + update: mock(), + }, + user: { + findUnique: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; +import { MpApiError } from '@/modules/mp/lib/mp-oauth'; +import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case'; + +const userId = 'user-1'; +const webOrigin = 'http://localhost:6173'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app; +} + +function okAccount() { + return { + ok: true, + value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() }, + }; +} + +const groupOwner = { + id: 'group-1', + name: 'Vinyasa', + createdById: userId, + price: { toString: () => '120.00' } as { toString(): string }, + members: [], +}; + +let getToken: ReturnType; +let createPreference: ReturnType; + +function batchUseCase() { + getToken = mock(async () => okAccount()); + createPreference = mock(async () => ({ + id: 'pref-1', + initPoint: 'https://mp.link/pay-1', + sandboxInitPoint: null, + })); + return new CreatePaymentBatch({ getToken, createPreference, webOrigin }); +} + +describe('create payments batch', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('creates one link per active attendee; keeps going when one preference fails', async () => { + prisma.group.findUnique.mockResolvedValue(groupOwner); + prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'att-1', person: { fullName: 'Juana' } }, + { id: 'att-2', person: { fullName: 'Pedro' } }, + ]); + prisma.payment.create + .mockResolvedValueOnce({ id: 'pay-1' }) + .mockResolvedValueOnce({ id: 'pay-2' }); + const useCase = batchUseCase(); + createPreference.mockResolvedValueOnce({ + id: 'pref-1', + initPoint: 'https://mp.link/pay-1', + sandboxInitPoint: null, + }); + createPreference.mockRejectedValue(new MpApiError(502, 'bad_gateway')); + + const result = await useCase.execute('group-1', userId, { + dueDate: '2026-10-05T12:00:00.000Z', + description: 'Octubre', + }); + + expect(result.ok).toBe(true); + if (!result.ok) throw new Error('expected ok'); + expect(result.value).toEqual({ + groupId: 'group-1', + total: 2, + linked: 1, + failed: 1, + items: [ + { + paymentId: 'pay-1', + attendeeId: 'att-1', + attendeeName: 'Juana', + amount: 120, + currency: 'ARS', + checkoutUrl: 'https://mp.link/pay-1', + outcome: 'LINKED', + reason: null, + }, + { + paymentId: 'pay-2', + attendeeId: 'att-2', + attendeeName: 'Pedro', + amount: 120, + currency: 'ARS', + checkoutUrl: null, + outcome: 'FAILED', + reason: 'mp_provider_error', + }, + ], + }); + + expect(prisma.payment.create).toHaveBeenCalledTimes(2); + expect(prisma.payment.update).toHaveBeenCalledTimes(1); + expect(prisma.payment.update).toHaveBeenCalledWith({ + where: { id: 'pay-1' }, + data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-1' }, + }); + expect(createPreference).toHaveBeenNthCalledWith(1, 'token-1', { + title: 'Octubre', + unitPrice: 120, + currencyId: 'ARS', + externalReference: 'pay-1', + backUrl: `${webOrigin}/student/payments`, + }); + }); + + it('derives the currency from the owner country and defaults when there is none', async () => { + prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } }); + prisma.user.findUnique.mockResolvedValue({ id: userId, country: null }); + prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', person: { fullName: 'Pedro' } }]); + prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' }); + const useCase = batchUseCase(); + createPreference.mockResolvedValueOnce({ + id: 'pref-2', + initPoint: 'https://mp.link/pay-2', + sandboxInitPoint: null, + }); + + const result = await useCase.execute('group-1', userId, { + dueDate: '2026-10-05T12:00:00.000Z', + attendeeIds: ['att-2'], + }); + + expect(result.ok).toBe(true); + if (!result.ok) throw new Error('expected ok'); + expect(result.value.items).toHaveLength(1); + expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' }); + expect(prisma.attendee.findMany).toHaveBeenCalledWith({ + where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } }, + include: { person: { select: { fullName: true } } }, + }); + }); + + it('propagates the not-connected problem and creates no rows', async () => { + prisma.group.findUnique.mockResolvedValue(groupOwner); + prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); + prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]); + getToken = mock(async () => ({ + ok: false, + error: { + type: 'https://gruperly.app/problems/conflict', + title: 'Conflict', + status: 409, + detail: 'No tenés una cuenta de Mercado Pago vinculada.', + code: 'mp_not_connected', + }, + })); + const createPreference = mock(async () => { + throw new Error('should not be called'); + }); + + const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute( + 'group-1', + userId, + { dueDate: '2026-10-05T12:00:00.000Z' }, + ); + + expect(result.ok).toBe(false); + expect(prisma.payment.create).not.toHaveBeenCalled(); + }); + + it('answers 409 over HTTP when the owner has no linked account', async () => { + prisma.group.findUnique.mockResolvedValue(groupOwner); + prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); + prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]); + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }), + }); + + expect(res.status).toBe(409); + expect(prisma.payment.create).not.toHaveBeenCalled(); + }); + + it('rejects a group without price', async () => { + prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: null }); + + const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }), + }); + + expect(res.status).toBe(409); + expect(prisma.attendee.findMany).not.toHaveBeenCalled(); + }); + + it('rejects a group the user has no access to', async () => { + prisma.group.findUnique.mockResolvedValue({ + ...groupOwner, + createdById: 'someone-else', + members: [], + }); + + const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }), + }); + + expect(res.status).toBe(403); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/payments-overdue.test.ts b/apps/backend/test/payments-overdue.test.ts new file mode 100644 index 0000000..fc349ce --- /dev/null +++ b/apps/backend/test/payments-overdue.test.ts @@ -0,0 +1,43 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; + +const db = { + payment: { + updateMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { MarkOverduePayments } from '@/modules/payments/jobs'; + +describe('mark overdue payments', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('marks PENDING payments whose due date passed more than a day ago', async () => { + prisma.payment.updateMany.mockResolvedValue({ count: 3 }); + const now = new Date('2026-10-08T12:00:00.000Z'); + + const result = await new MarkOverduePayments({ now }).execute(); + + expect(result).toEqual({ marked: 3 }); + expect(prisma.payment.updateMany).toHaveBeenCalledWith({ + where: { status: 'PENDING', dueDate: { lt: new Date('2026-10-07T12:00:00.000Z') } }, + data: { status: 'OVERDUE' }, + }); + }); + + it('leaves payments inside the grace period alone', async () => { + prisma.payment.updateMany.mockResolvedValue({ count: 0 }); + + const result = await new MarkOverduePayments({ now: new Date() }).execute(); + + expect(result).toEqual({ marked: 0 }); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/payments-reconcile.test.ts b/apps/backend/test/payments-reconcile.test.ts new file mode 100644 index 0000000..f1842cb --- /dev/null +++ b/apps/backend/test/payments-reconcile.test.ts @@ -0,0 +1,129 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; + +const db = { + payment: { + findMany: mock(), + update: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { MpApiError } from '@/modules/mp/lib/mp-oauth'; +import { ReconcilePayments } from '@/modules/payments/jobs'; + +const ownerId = 'user-1'; +const pendingPayment = (id: string, overrides: Record = {}) => ({ + id, + groupId: 'group-1', + status: 'PENDING', + checkoutUrl: 'https://mp.link/pay', + createdAt: new Date(Date.now() - 10 * 60 * 1000), + group: { createdById: ownerId }, + ...overrides, +}); + +function okAccount() { + return { + ok: true, + value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() }, + }; +} + +describe('reconcile payments', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('marks an approved Mercado Pago payment as PAID', async () => { + prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]); + const getToken = mock(async () => okAccount()); + const search = mock(async () => ({ + id: '999999999', + status: 'approved', + externalReference: 'pay-1', + liveMode: true, + dateApproved: '2026-10-01T12:30:00.000Z', + })); + + const result = await new ReconcilePayments({ getToken, search }).execute(); + + expect(result).toEqual({ paid: 1, skipped: 0, failed: 0 }); + expect(prisma.payment.update).toHaveBeenCalledWith({ + where: { id: 'pay-1' }, + data: { + status: 'PAID', + mpPaymentId: '999999999', + paidAt: new Date('2026-10-01T12:30:00.000Z'), + }, + }); + }); + + it('skips a payment that is still pending in Mercado Pago', async () => { + prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]); + const getToken = mock(async () => okAccount()); + const search = mock(async () => ({ + id: '999999999', + status: 'pending', + externalReference: 'pay-1', + liveMode: true, + dateApproved: null, + })); + + const result = await new ReconcilePayments({ getToken, search }).execute(); + + expect(result).toEqual({ paid: 0, skipped: 0, failed: 0 }); + expect(prisma.payment.update).not.toHaveBeenCalled(); + }); + + it('skips rows when the owner has no usable token', async () => { + prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]); + const getToken = mock(async () => ({ + ok: false, + error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' }, + })); + const search = mock(async () => { + throw new Error('should not be called'); + }); + + const result = await new ReconcilePayments({ getToken, search }).execute(); + + expect(result).toEqual({ paid: 0, skipped: 1, failed: 0 }); + expect(search).not.toHaveBeenCalled(); + }); + + it('counts an unreachable Mercado Pago as failed and leaves the row pending', async () => { + prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]); + const getToken = mock(async () => okAccount()); + const search = mock(async () => { + throw new MpApiError(0, null); + }); + + const result = await new ReconcilePayments({ getToken, search }).execute(); + + expect(result).toEqual({ paid: 0, skipped: 0, failed: 1 }); + expect(prisma.payment.update).not.toHaveBeenCalled(); + }); + + it('only reconciles payments linked for at least five minutes', async () => { + prisma.payment.findMany.mockResolvedValue([]); + const now = new Date('2026-10-01T12:00:00.000Z'); + + await new ReconcilePayments({ now }).execute(); + + expect(prisma.payment.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { + status: 'PENDING', + checkoutUrl: { not: null }, + createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') }, + }, + }), + ); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/payments-renew.test.ts b/apps/backend/test/payments-renew.test.ts new file mode 100644 index 0000000..9c5f16e --- /dev/null +++ b/apps/backend/test/payments-renew.test.ts @@ -0,0 +1,158 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + payment: { + findUnique: mock(), + update: mock(), + }, + user: { + findUnique: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import prisma from '@/lib/prisma'; +import { paymentsRoutes } from '@/modules/payments'; +import { RenewPaymentLink } from '@/modules/payments/features/renew/use-case'; + +const userId = 'user-1'; +const webOrigin = 'http://localhost:6173'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/payments', paymentsRoutes); + return app; +} + +function paymentWithoutLink(overrides: Record = {}) { + return { + id: 'pay-1', + groupId: 'group-1', + attendeeId: 'att-1', + amount: { toString: () => '120.00' } as { toString(): string }, + currency: 'ARS', + status: 'PENDING', + description: null, + checkoutUrl: null, + mpPreferenceId: null, + dueDate: new Date('2026-10-05T12:00:00.000Z'), + paidAt: null, + createdAt: new Date('2026-10-01T10:00:00.000Z'), + updatedAt: new Date('2026-10-01T10:00:00.000Z'), + attendee: { person: { fullName: 'Juana Pérez' } }, + group: { + name: 'Vinyasa', + price: { toString: () => '120.00' }, + createdById: userId, + members: [], + }, + ...overrides, + }; +} + +describe('renew payment link', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('creates a new link for a payment that lost it and returns the payment', async () => { + prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink()); + prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); + prisma.payment.update.mockResolvedValue({ + ...paymentWithoutLink(), + checkoutUrl: 'https://mp.link/pay-1', + group: { name: 'Vinyasa', price: { toString: () => '120.00' } }, + }); + const getToken = mock(async () => ({ + ok: true, + value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() }, + })); + const createPreference = mock(async () => ({ + id: 'pref-new', + initPoint: 'https://mp.link/pay-1', + sandboxInitPoint: null, + })); + + const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute( + 'pay-1', + userId, + ); + + expect(result.ok).toBe(true); + if (!result.ok) throw new Error('expected ok'); + expect(result.value).toMatchObject({ + id: 'pay-1', + groupName: 'Vinyasa', + attendeeName: 'Juana Pérez', + checkoutUrl: 'https://mp.link/pay-1', + }); + expect(createPreference).toHaveBeenCalledWith('token-1', { + title: 'Vinyasa', + unitPrice: 120, + currencyId: 'ARS', + externalReference: 'pay-1', + backUrl: `${webOrigin}/student/payments`, + }); + expect(prisma.payment.update).toHaveBeenCalledWith({ + where: { id: 'pay-1' }, + data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' }, + include: { + attendee: { select: { person: { select: { fullName: true } } } }, + group: { select: { name: true, price: true } }, + }, + }); + }); + + it('keeps an existing link: idempotent, no Mercado Pago call', async () => { + prisma.payment.findUnique.mockResolvedValue( + paymentWithoutLink({ checkoutUrl: 'https://mp.link/pay-1' }), + ); + + const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' }); + + expect(res.status).toBe(200); + expect(prisma.payment.update).not.toHaveBeenCalled(); + }); + + it('answers 409 when the owner has no linked account', async () => { + prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink()); + prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); + const getToken = mock(async () => ({ + ok: false, + error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' }, + })); + + const result = await new RenewPaymentLink({ getToken }).execute('pay-1', userId); + + expect(result.ok).toBe(false); + expect(prisma.payment.update).not.toHaveBeenCalled(); + }); + + it('rejects a payment of a group the user has no access to', async () => { + prisma.payment.findUnique.mockResolvedValue( + paymentWithoutLink({ + group: { + name: 'Vinyasa', + price: { toString: () => '120.00' }, + createdById: 'someone-else', + members: [], + }, + }), + ); + + const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' }); + + expect(res.status).toBe(403); + expect(prisma.payment.update).not.toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/payments.test.ts b/apps/backend/test/payments.test.ts index 22a1e27..255f7db 100644 --- a/apps/backend/test/payments.test.ts +++ b/apps/backend/test/payments.test.ts @@ -1,13 +1,18 @@ import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; import { Hono } from 'hono'; -mock.module('@/lib/prisma', () => ({ - default: { - payment: { - findMany: mock(), - count: mock(), - }, +const db = { + group: { + findMany: mock(), }, + payment: { + findMany: mock(), + count: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, getPrismaClient: mock(), UnitOfWork: class {}, })); @@ -15,32 +20,46 @@ mock.module('@/lib/prisma', () => ({ import prisma from '@/lib/prisma'; import { paymentsRoutes } from '@/modules/payments'; -const app = new Hono(); -app.route('/payments', paymentsRoutes); +const userId = 'user-1'; const payment = { id: 'payment-1', groupId: 'group-1', - studentId: 'student-1', + attendeeId: 'attendee-1', amount: { toString: () => '150.50' } as { toString(): string }, - currency: 'MXN', - status: 'pending', + currency: 'ARS', + status: 'PENDING', + description: 'Mensualidad de Septiembre', + checkoutUrl: 'https://mercadopago.com/checkout/payment-1', dueDate: new Date('2026-09-01T10:00:00.000Z'), paidAt: null, createdAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'), + group: { name: 'Cuadrilla Alfa', price: 150.5 }, + attendee: { person: { fullName: 'Juana Pérez' } }, }; +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/payments', paymentsRoutes); + return app; +} + describe('payments routes', () => { beforeEach(() => { vi.clearAllMocks(); }); - it('lists payments with pagination and converts Decimal amounts', async () => { + it('lists payments scoped to the user, with attendee and group names', async () => { + prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]); prisma.payment.findMany.mockResolvedValue([payment]); prisma.payment.count.mockResolvedValue(1); - const res = await app.request('/payments'); + const res = await makeApp({ id: userId }).request('/payments'); expect(res.status).toBe(200); expect(await res.json()).toEqual({ @@ -48,10 +67,14 @@ describe('payments routes', () => { { id: 'payment-1', groupId: 'group-1', - studentId: 'student-1', + groupName: 'Cuadrilla Alfa', + attendeeId: 'attendee-1', + attendeeName: 'Juana Pérez', amount: 150.5, - currency: 'MXN', - status: 'pending', + currency: 'ARS', + status: 'PENDING', + description: 'Mensualidad de Septiembre', + checkoutUrl: payment.checkoutUrl, dueDate: payment.dueDate.toISOString(), paidAt: null, createdAt: payment.createdAt.toISOString(), @@ -60,15 +83,49 @@ describe('payments routes', () => { ], pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 }, }); + expect(prisma.group.findMany).toHaveBeenCalledWith({ + where: { + OR: [{ createdById: userId }, { members: { some: { userId } } }], + }, + select: { id: true }, + }); expect(prisma.payment.findMany).toHaveBeenCalledWith({ + where: { groupId: { in: ['group-1'] } }, + include: { + group: { select: { name: true, price: true } }, + attendee: { select: { person: { select: { fullName: true } } } }, + }, skip: 0, take: 10, orderBy: { createdAt: 'desc' }, }); }); + it('filters payments by group and status', async () => { + prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]); + prisma.payment.findMany.mockResolvedValue([]); + prisma.payment.count.mockResolvedValue(0); + + const res = await makeApp({ id: userId }).request( + '/payments?groupId=group-1&status=OVERDUE', + ); + + expect(res.status).toBe(200); + expect(prisma.payment.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { groupId: 'group-1', status: 'OVERDUE' }, + }), + ); + }); + + it('rejects requests without a session user', async () => { + const res = await makeApp(null).request('/payments'); + + expect(res.status).toBe(401); + }); + it('rejects invalid pagination query parameters', async () => { - const res = await app.request('/payments?pageSize=101'); + const res = await makeApp({ id: userId }).request('/payments?pageSize=101'); expect(res.status).toBe(400); }); diff --git a/apps/backend/test/preregistrations.test.ts b/apps/backend/test/preregistrations.test.ts new file mode 100644 index 0000000..036bfd8 --- /dev/null +++ b/apps/backend/test/preregistrations.test.ts @@ -0,0 +1,389 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + count: mock(), + create: mock(), + }, + person: { + findFirst: mock(), + create: mock(), + deleteMany: mock(), + }, + groupWaitlistEntry: { + findFirst: mock(), + create: mock(), + }, + groupPreRegistration: { + findMany: mock(), + findFirst: mock(), + count: mock(), + create: mock(), + update: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const mockGroup = { + id: 'group-1', + name: 'Taller de Pintura', + description: null, + createdById: teacherId, + inviteToken: 'valid-token-123', + createdAt: new Date('2026-09-01T10:00:00.000Z'), + updatedAt: new Date('2026-09-01T10:00:00.000Z'), + days: ['MONDAY'], + time: '18:00', + capacity: 20, + price: 1500, + billingType: 'MONTHLY', + dueDay: 10, + members: [], +}; + +const preRegistration = (overrides: Record = {}) => ({ + id: 'pre-1', + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + status: 'PENDING', + reviewedAt: null, + createdAt: new Date('2026-09-10T10:00:00.000Z'), + updatedAt: new Date('2026-09-10T10:00:00.000Z'), + ...overrides, +}); + +const attendee = (overrides: Record = {}) => ({ + id: 'att-1', + groupId: 'group-1', + personId: 'person-1', + person: { + id: 'person-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + guardianName: null, + guardianPhone: null, + notes: null, + }, + notifyToken: 'notify-1', + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + ...overrides, +}); + +const waitlistEntry = (overrides: Record = {}) => ({ + id: 'wl-1', + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + notes: null, + status: 'PENDING', + createdAt: new Date('2026-09-10T10:00:00.000Z'), + updatedAt: new Date('2026-09-10T10:00:00.000Z'), + ...overrides, +}); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app; +} + +describe('group pre-registrations', () => { + beforeEach(() => { + vi.clearAllMocks(); + // The phone is nobody the teacher has yet: promoting creates the person. + prisma.person.findFirst.mockResolvedValue(null); + prisma.person.create.mockResolvedValue({ id: 'person-1' } as never); + }); + + describe('GET /groups/:groupId/preregistrations', () => { + it('lists pending pre-registrations in FIFO order with pagination', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findMany.mockResolvedValue([ + preRegistration({ id: 'pre-1', fullName: 'Ana García', createdAt: new Date('2026-09-08T10:00:00.000Z') }), + preRegistration({ id: 'pre-2', fullName: 'Pedro López', createdAt: new Date('2026-09-09T10:00:00.000Z') }), + ] as never); + prisma.groupPreRegistration.count.mockResolvedValue(2); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/preregistrations'); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.data).toHaveLength(2); + expect(data.data[0].fullName).toBe('Ana García'); + expect(data.data[0].status).toBe('PENDING'); + expect(data.pagination).toEqual({ page: 1, pageSize: 10, total: 2, totalPages: 1 }); + expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({ + where: { groupId: 'group-1', status: 'PENDING' }, + skip: 0, + take: 10, + orderBy: { createdAt: 'asc' }, + }); + }); + + it('filters by status when provided', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findMany.mockResolvedValue([] as never); + prisma.groupPreRegistration.count.mockResolvedValue(0); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations?status=REJECTED', + ); + + expect(res.status).toBe(200); + expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({ + where: { groupId: 'group-1', status: 'REJECTED' }, + skip: 0, + take: 10, + orderBy: { createdAt: 'asc' }, + }); + }); + + it('rejects user without access to the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/preregistrations'); + + expect(res.status).toBe(403); + expect(prisma.groupPreRegistration.findMany).not.toHaveBeenCalled(); + }); + }); + + describe('POST /groups/:groupId/preregistrations/:entryId/approve', () => { + it('adds the person to the group when there is free capacity', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); + prisma.attendee.count.mockResolvedValue(5); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.create.mockResolvedValue(attendee() as never); + prisma.groupPreRegistration.update.mockResolvedValue( + preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.outcome).toBe('added'); + expect(body.attendee.fullName).toBe('Martín Gómez'); + expect(body.waitlistEntry).toBeNull(); + expect(prisma.person.create).toHaveBeenCalledWith({ + data: { + createdById: teacherId, + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + notes: null, + }, + select: { id: true }, + }); + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { groupId: 'group-1', personId: 'person-1' }, + include: { person: { select: expect.any(Object) } }, + }); + expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({ + where: { id: 'pre-1' }, + data: { status: 'APPROVED', reviewedAt: expect.any(Date) }, + }); + }); + + it('moves the person to the waitlist when the group is full', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); + prisma.attendee.count.mockResolvedValue(20); // capacity full + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + prisma.groupWaitlistEntry.create.mockResolvedValue(waitlistEntry() as never); + prisma.groupPreRegistration.update.mockResolvedValue( + preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.outcome).toBe('waitlisted'); + expect(body.attendee).toBeNull(); + expect(body.waitlistEntry.fullName).toBe('Martín Gómez'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({ + data: { + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + }, + }); + expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({ + where: { id: 'pre-1' }, + data: { status: 'APPROVED', reviewedAt: expect.any(Date) }, + }); + }); + + it('reuses an existing waitlist entry instead of duplicating it', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); + prisma.attendee.count.mockResolvedValue(20); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + prisma.groupPreRegistration.update.mockResolvedValue( + preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(200); + expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled(); + }); + + it('returns 409 when the phone already belongs to a member', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); + prisma.attendee.count.mockResolvedValue(5); + prisma.person.findFirst.mockResolvedValue({ + id: 'person-1', + fullName: 'Martín Gómez', + email: null, + phone: '+5491133445566', + attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }], + } as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('attendee_already_registered'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled(); + }); + + it('returns 409 when the pre-registration was already reviewed', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue( + preRegistration({ status: 'APPROVED' }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('pre_registration_already_reviewed'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('returns 404 when the pre-registration does not exist', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/missing/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(404); + }); + + it('rejects approval from a user who is not the owner', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request( + '/groups/group-1/preregistrations/pre-1/approve', + { method: 'POST' }, + ); + + expect(res.status).toBe(403); + expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled(); + }); + }); + + describe('POST /groups/:groupId/preregistrations/:entryId/reject', () => { + it('marks the pre-registration as rejected', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); + prisma.groupPreRegistration.update.mockResolvedValue( + preRegistration({ status: 'REJECTED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/reject', + { method: 'POST' }, + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.entry.status).toBe('REJECTED'); + expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({ + where: { id: 'pre-1' }, + data: { status: 'REJECTED', reviewedAt: expect.any(Date) }, + }); + }); + + it('returns 409 when the pre-registration was already reviewed', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupPreRegistration.findFirst.mockResolvedValue( + preRegistration({ status: 'REJECTED' }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/preregistrations/pre-1/reject', + { method: 'POST' }, + ); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('pre_registration_already_reviewed'); + expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled(); + }); + + it('rejects rejection from a user who is not the owner', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request( + '/groups/group-1/preregistrations/pre-1/reject', + { method: 'POST' }, + ); + + expect(res.status).toBe(403); + expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/backend/test/session-auth.test.ts b/apps/backend/test/session-auth.test.ts index 8876781..2faca6f 100644 --- a/apps/backend/test/session-auth.test.ts +++ b/apps/backend/test/session-auth.test.ts @@ -35,7 +35,30 @@ describe('session auth', () => { expect(isPublicApiRequest('GET', '/api/v1/health')).toBe(true); expect(isPublicApiRequest('POST', '/api/v1/auth/sign-in/email')).toBe(true); expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false); - expect(isPublicApiRequest('GET', '/api/v1/students')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/attendees')).toBe(false); + }); + + it('classifies absence notification endpoints as public (token-based)', () => { + expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true); + expect(isPublicApiRequest('POST', '/api/v1/classes/notify-absence')).toBe(true); + // The authenticated class routes stay protected. + expect(isPublicApiRequest('GET', '/api/v1/classes/today')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false); + expect( + isPublicApiRequest('POST', '/api/v1/classes/session-1/notify-absence'), + ).toBe(false); + }); + + it('classifies the WhatsApp provider webhooks as public (signature-based)', () => { + expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/openwa')).toBe(true); + expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/kapso/')).toBe(true); + // Everything else under /whatsapp needs the teacher's session. + expect(isPublicApiRequest('GET', '/api/v1/whatsapp/webhooks/openwa')).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/other')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/whatsapp/status')).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/whatsapp/connect')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/whatsapp/callback')).toBe(false); }); it('allows public requests without a session', async () => { diff --git a/apps/backend/test/student-alerts.test.ts b/apps/backend/test/student-alerts.test.ts new file mode 100644 index 0000000..9fd216e --- /dev/null +++ b/apps/backend/test/student-alerts.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, it } from 'bun:test'; +import { + applyResolutions, + compareByWorstAlert, + computeStudentAlerts, + type MemberAttendance, + type MemberClassSession, + STUDENT_ALERT_RULES, + type StudentAlert, + worstAlert, +} from '@gruperly/shared'; + +/* The single source of the "Requiere atención" alerts. These tests pin the + thresholds (attendance through the shared risk rule, fees through + `STUDENT_ALERT_RULES`), the copy the screens show and the order. */ + +const DAY_MS = 24 * 60 * 60 * 1000; +const NOW = new Date('2026-10-27T20:00:00.000Z'); +const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString(); + +type Status = MemberClassSession['status']; + +/** Classes on consecutive days, oldest first; the last one is `ses_1`. */ +function attendance(statuses: Status[]): MemberAttendance { + return { + attendeeId: 'at_1', + fullName: 'Agustina Pérez', + enrolledAt: daysAgo(365), + sessions: statuses.map((status, index) => ({ + sessionId: `ses_${statuses.length - index}`, + startsAt: daysAgo(statuses.length - index), + status, + })), + }; +} + +const fee = (id: string, dueDate: string) => ({ id, dueDate }); + +function alertsFor(statuses: Status[], fees: { id: string; dueDate: string }[] = []) { + return computeStudentAlerts({ attendance: attendance(statuses), overduePayments: fees }, NOW); +} + +describe('computeStudentAlerts: asistencia', () => { + it('sin faltas ni cuotas no hay alertas', () => { + expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT'])).toEqual([]); + }); + + it('3 faltas seguidas son urgentes y lo dicen así', () => { + const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']); + expect(alert).toMatchObject({ + tipo: 'asistencia', + gravedad: 'urgente', + etiqueta: '3 seguidas', + detalle: 'No viene hace 3 clases seguidas.', + firma: 'ses_1', + }); + }); + + it('4 de las últimas 6 sin racha son urgentes', () => { + const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']); + expect(alert).toMatchObject({ + gravedad: 'urgente', + etiqueta: '4 faltas', + detalle: 'Faltó a 4 de las últimas 6 clases.', + firma: 'ses_2', + }); + }); + + it('2 faltas recientes son "a vigilar"', () => { + expect(alertsFor(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])[0]).toMatchObject({ + gravedad: 'vigilar', + etiqueta: '2 faltas', + detalle: 'Faltó a las últimas 2 clases.', + }); + expect(alertsFor(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])[0]).toMatchObject({ + gravedad: 'vigilar', + detalle: 'Faltó a 2 de las últimas 4 clases.', + }); + }); + + it('una sola falta no alcanza', () => { + expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])).toEqual([]); + }); + + it('las justificadas y las clases sin registro no cuentan como faltas', () => { + expect(alertsFor(['PRESENT', 'EXCUSED', 'ABSENT', null, 'EXCUSED'])).toEqual([]); + }); +}); + +describe('computeStudentAlerts: pagos', () => { + it('1 cuota vencida es "a vigilar" con su fecha', () => { + expect(alertsFor([], [fee('pay_1', '2026-10-10T12:00:00.000Z')])).toEqual([ + { + tipo: 'pago', + gravedad: 'vigilar', + etiqueta: 'Cuota vencida', + detalle: 'La cuota de octubre venció el 10/10.', + razon: 'cuota', + valores: { cuotas: 1, vencimientos: ['2026-10-10T12:00:00.000Z'] }, + firma: 'pay_1', + peso: 1, + }, + ]); + }); + + it(`${STUDENT_ALERT_RULES.urgentOverdue} o más cuotas vencidas son urgentes y nombran los meses`, () => { + const [alert] = alertsFor( + [], + [fee('pay_b', '2026-10-10T12:00:00.000Z'), fee('pay_a', '2026-09-10T12:00:00.000Z')], + ); + expect(alert).toMatchObject({ + gravedad: 'urgente', + etiqueta: '2 cuotas', + detalle: 'Debe las cuotas de septiembre y octubre.', + firma: 'pay_a,pay_b', + }); + }); + + it('con tres meses los separa con coma y "y"', () => { + const [alert] = alertsFor( + [], + [ + fee('p1', '2026-08-10T12:00:00.000Z'), + fee('p2', '2026-09-10T12:00:00.000Z'), + fee('p3', '2026-10-10T12:00:00.000Z'), + ], + ); + expect(alert.detalle).toBe('Debe las cuotas de agosto, septiembre y octubre.'); + }); + + it('dos cuotas del mismo mes caen al conteo', () => { + const [alert] = alertsFor([], [fee('p1', '2026-10-01T12:00:00.000Z'), fee('p2', '2026-10-20T12:00:00.000Z')]); + expect(alert.detalle).toBe('Debe 2 cuotas vencidas.'); + }); +}); + +describe('orden por gravedad', () => { + it('con varias alertas, la urgente va primero', () => { + const alerts = alertsFor( + ['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'], + [fee('p1', '2026-09-10T12:00:00.000Z'), fee('p2', '2026-10-10T12:00:00.000Z')], + ); + expect(alerts.map((alert) => [alert.tipo, alert.gravedad])).toEqual([ + ['pago', 'urgente'], + ['asistencia', 'vigilar'], + ]); + expect(worstAlert(alerts)?.tipo).toBe('pago'); + }); + + it('ordena alumnos por su peor alerta, después por la fuerza y por nombre', () => { + const alert = (gravedad: StudentAlert['gravedad'], peso: number): StudentAlert => ({ + tipo: 'asistencia', + gravedad, + etiqueta: '', + detalle: '', + firma: 'x', + peso, + }); + const students = [ + { fullName: 'Zoe', alerts: [] }, + { fullName: 'Martina', alerts: [alert('vigilar', 2)] }, + { fullName: 'Tomás', alerts: [alert('urgente', 3)] }, + { fullName: 'Agustina', alerts: [alert('urgente', 4)] }, + { fullName: 'Bruno', alerts: [alert('vigilar', 2)] }, + ]; + expect([...students].sort(compareByWorstAlert).map((student) => student.fullName)).toEqual([ + 'Agustina', + 'Tomás', + 'Bruno', + 'Martina', + 'Zoe', + ]); + }); +}); + +describe('applyResolutions', () => { + const statuses: Status[] = ['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']; + + it('oculta la alerta resuelta mientras la firma sea la misma', () => { + const alerts = alertsFor(statuses); + expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }])).toEqual([]); + }); + + it('una falta nueva cambia la firma y la alerta vuelve', () => { + const alerts = alertsFor([...statuses, 'ABSENT']); + expect(alerts[0].firma).toBe('ses_1'); + // The resolution was stored when the last absence was `ses_2`. + expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_2' }])).toHaveLength(1); + }); + + it('resolver la asistencia no oculta los pagos', () => { + const alerts = alertsFor(statuses, [fee('p1', '2026-10-10T12:00:00.000Z')]); + expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }]).map((a) => a.tipo)).toEqual(['pago']); + }); +}); diff --git a/apps/backend/test/student-portal-auth.test.ts b/apps/backend/test/student-portal-auth.test.ts new file mode 100644 index 0000000..6bd53b6 --- /dev/null +++ b/apps/backend/test/student-portal-auth.test.ts @@ -0,0 +1,394 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { Hono } from 'hono'; +import { isPublicApiRequest } from '@/http/session-auth'; +import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case'; +import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case'; +import { StudentPasskeys } from '@/modules/student-portal/features/passkeys/use-case'; +import { + RECOVERY_LIMIT_PER_EMAIL, + RECOVERY_LIMIT_PER_IP, + RequestRecoveryLink, +} from '@/modules/student-portal/features/request-recovery/use-case'; +import { describeDevice } from '@/modules/student-portal/lib/device'; +import { hashToken } from '@/modules/student-portal/lib/tokens'; +import { requireStudentSession, studentOriginGuard } from '@/modules/student-portal/middleware'; + +const NOW = new Date('2026-10-27T15:00:00.000Z'); +const WEB = process.env.WEB_URL ?? 'http://localhost:6173'; + +/* In-memory rate limit table: enough to count hits by key and window. */ +function fakeRateLimit() { + let rows: { key: string; createdAt: Date }[] = []; + return { + deleteMany: mock(async ({ where }: { where: { key: string; createdAt: { lt: Date } } }) => { + rows = rows.filter((row) => !(row.key === where.key && row.createdAt < where.createdAt.lt)); + return { count: 0 }; + }), + count: mock(async ({ where }: { where: { key: string; createdAt: { gte: Date } } }) => + rows.filter((row) => row.key === where.key && row.createdAt >= where.createdAt.gte).length), + create: mock(async ({ data }: { data: { key: string; createdAt: Date } }) => { + rows.push(data); + return data; + }), + }; +} + +describe('link del alumno', () => { + it('un token mal formado es inválido sin tocar la base', async () => { + const db = { studentAccessToken: { findUnique: mock() } }; + const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute('abc'); + expect(result).toEqual({ ok: true, value: { status: 'invalid' } }); + expect(db.studentAccessToken.findUnique).not.toHaveBeenCalled(); + }); + + it('usado, revocado o vencido responde lo mismo, sin datos del dueño', async () => { + const token = 'a'.repeat(43); + const base = { + kind: 'INVITATION', + usedAt: null, + revokedAt: null, + expiresAt: new Date(NOW.getTime() + 1000), + account: { name: 'Ana', attendees: [] }, + }; + for (const row of [ + { ...base, usedAt: NOW }, + { ...base, revokedAt: NOW }, + { ...base, expiresAt: NOW }, + { ...base, kind: 'EMAIL_CONFIRMATION' }, + null, + ]) { + const db = { studentAccessToken: { findUnique: mock(async () => row) } }; + const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token); + expect(result).toEqual({ ok: true, value: { status: 'invalid' } }); + } + }); + + it('el GET solo lee: busca por hash y nunca actualiza', async () => { + const token = 'b'.repeat(43); + const db = { + studentAccessToken: { + findUnique: mock(async () => ({ + kind: 'INVITATION', + usedAt: null, + revokedAt: null, + expiresAt: new Date(NOW.getTime() + 1000), + account: { + name: 'Ana', + people: [{ person: { attendees: [{ group: { name: 'Natación', owner: { name: 'Caro' } } }] } }], + }, + })), + updateMany: mock(), + }, + }; + const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token); + expect(result).toEqual({ + ok: true, + value: { status: 'valid', kind: 'invitation', name: 'Ana', teacherName: 'Caro', groupName: 'Natación' }, + }); + expect(db.studentAccessToken.findUnique.mock.calls[0]?.[0]).toMatchObject({ where: { tokenHash: hashToken(token) } }); + expect(db.studentAccessToken.updateMany).not.toHaveBeenCalled(); + }); + + it('el POST consume con un update condicional y reemplaza la sesión del dispositivo', async () => { + const tx = { + studentAccessToken: { + updateMany: mock(async () => ({ count: 1 })), + findUniqueOrThrow: mock(async () => ({ accountId: 'acc-1', account: { welcomedAt: null } })), + }, + studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 1 })) }, + }; + const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) }; + const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({ + token: 'tok', + ip: '1.2.3.4', + userAgent: 'UA', + currentSessionToken: 'old-session', + }); + + expect(result.ok && result.value.firstLogin).toBe(true); + expect(tx.studentAccessToken.updateMany.mock.calls[0]?.[0]).toMatchObject({ + where: { tokenHash: hashToken('tok'), usedAt: null, revokedAt: null, expiresAt: { gt: NOW } }, + }); + expect(tx.studentSession.updateMany.mock.calls[0]?.[0]).toMatchObject({ + where: { tokenHash: hashToken('old-session') }, + }); + // A new identifier: the stored hash is not the old session's. + const created = (tx.studentSession.create.mock.calls[0] as unknown as [{ data: { tokenHash: string } }])[0]; + expect(created.data.tokenHash).not.toBe(hashToken('old-session')); + }); + + it('si otro dispositivo ganó, responde 410 y no crea sesión', async () => { + const tx = { + studentAccessToken: { updateMany: mock(async () => ({ count: 0 })), findUniqueOrThrow: mock() }, + studentSession: { create: mock() }, + }; + const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) }; + const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({ + token: 'tok', + ip: null, + userAgent: null, + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(410); + expect(tx.studentSession.create).not.toHaveBeenCalled(); + }); +}); + +describe('pedir un link al mail', () => { + function setup(accounts: { id: string; name: string }[]) { + const db = { + rateLimitEvent: fakeRateLimit(), + studentAccount: { findMany: mock(async () => accounts) }, + studentAccessToken: { create: mock(async () => ({})) }, + }; + const email = { sendStudentRecoveryLinks: mock(async () => {}) }; + const tasks: Promise[] = []; + const useCase = new RequestRecoveryLink({ + db: db as never, + email, + now: NOW, + defer: (task) => tasks.push(task()), + }); + return { db, email, useCase, flush: () => Promise.all(tasks) }; + } + + it('responde idéntico exista o no el mail', async () => { + const known = setup([{ id: 'acc-1', name: 'Ana' }]); + const unknown = setup([]); + const a = await known.useCase.execute({ email: 'ana@mail.com', ip: '1.1.1.1' }); + const b = await unknown.useCase.execute({ email: 'nadie@mail.com', ip: '1.1.1.1' }); + expect(a).toEqual(b); + await Promise.all([known.flush(), unknown.flush()]); + expect(known.email.sendStudentRecoveryLinks).toHaveBeenCalledTimes(1); + expect(unknown.email.sendStudentRecoveryLinks).not.toHaveBeenCalled(); + // Only verified emails recover. + expect(known.db.studentAccount.findMany.mock.calls[0]?.[0]).toMatchObject({ + where: { recoveryEmail: 'ana@mail.com', recoveryEmailVerifiedAt: { not: null } }, + }); + const sent = (known.email.sendStudentRecoveryLinks.mock.calls[0] as unknown as [{ links: { url: string }[] }])[0]; + expect(sent.links[0]?.url).toStartWith(`${WEB}/i/`); + }); + + it(`limita a ${RECOVERY_LIMIT_PER_EMAIL} pedidos por mail, exista o no`, async () => { + for (const accounts of [[{ id: 'acc-1', name: 'Ana' }], []]) { + const { useCase } = setup(accounts); + for (let i = 0; i < RECOVERY_LIMIT_PER_EMAIL; i++) { + expect((await useCase.execute({ email: 'x@mail.com', ip: `10.0.0.${i}` })).ok).toBe(true); + } + const blocked = await useCase.execute({ email: 'x@mail.com', ip: '10.0.0.99' }); + expect(blocked.ok).toBe(false); + if (!blocked.ok) expect(blocked.error.status).toBe(429); + } + }); + + it(`limita a ${RECOVERY_LIMIT_PER_IP} pedidos por IP`, async () => { + const { useCase } = setup([]); + for (let i = 0; i < RECOVERY_LIMIT_PER_IP; i++) { + expect((await useCase.execute({ email: `u${i}@mail.com`, ip: '9.9.9.9' })).ok).toBe(true); + } + expect((await useCase.execute({ email: 'otro@mail.com', ip: '9.9.9.9' })).ok).toBe(false); + }); +}); + +describe('passkeys', () => { + function setup() { + const challenges = new Map>(); + let nextId = 0; + const db = { + rateLimitEvent: fakeRateLimit(), + studentAccount: { + findUniqueOrThrow: mock(async () => ({ name: 'Ana', passkeys: [] })), + }, + studentWebauthnChallenge: { + deleteMany: mock(async ({ where }: { where: { id?: string } }) => { + if (!where.id) return { count: 0 }; + return { count: challenges.delete(where.id) ? 1 : 0 }; + }), + create: mock(async ({ data }: { data: Record }) => { + const id = `ch-${nextId++}`; + challenges.set(id, { id, ...data }); + return { id }; + }), + findUnique: mock(async ({ where }: { where: { id: string } }) => challenges.get(where.id) ?? null), + }, + studentPasskey: { + upsert: mock(async () => ({})), + findUnique: mock(async () => ({ + id: 'pk-1', + accountId: 'acc-1', + credentialId: 'cred-1', + publicKey: new Uint8Array([1, 2, 3]), + counter: 4, + transports: ['internal'], + })), + update: mock(async () => ({})), + deleteMany: mock(async () => ({ count: 1 })), + }, + studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 0 })) }, + }; + const webauthn = { + generateRegistrationOptions: mock(async () => ({ challenge: 'reg-challenge' })), + verifyRegistrationResponse: mock(async () => ({ + verified: true, + registrationInfo: { credential: { id: 'cred-1', publicKey: new Uint8Array([1, 2, 3]), counter: 0, transports: ['internal'] } }, + })), + generateAuthenticationOptions: mock(async () => ({ challenge: 'login-challenge' })), + verifyAuthenticationResponse: mock(async () => ({ verified: true, authenticationInfo: { newCounter: 5 } })), + }; + const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(db) }; + const passkeys = new StudentPasskeys({ + db: db as never, + webauthn: webauthn as never, + unitOfWork: unitOfWork as never, + now: NOW, + }); + return { db, webauthn, passkeys }; + } + + it('registra una passkey con preferred en residentKey y userVerification', async () => { + const { db, webauthn, passkeys } = setup(); + const options = await passkeys.registrationOptions('acc-1'); + if (!options.ok) throw new Error('options failed'); + expect(webauthn.generateRegistrationOptions.mock.calls[0]?.[0]).toMatchObject({ + authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' }, + }); + + const iPhone = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1'; + const result = await passkeys.verifyRegistration('acc-1', { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, iPhone); + expect(result.ok).toBe(true); + expect(webauthn.verifyRegistrationResponse.mock.calls[0]?.[0]).toMatchObject({ expectedChallenge: 'reg-challenge' }); + expect(db.studentPasskey.upsert.mock.calls[0]?.[0]).toMatchObject({ + create: { accountId: 'acc-1', credentialId: 'cred-1', device: 'iPhone · Safari' }, + }); + }); + + it('el challenge sirve una sola vez y solo para su cuenta', async () => { + const { passkeys } = setup(); + const options = await passkeys.registrationOptions('acc-1'); + if (!options.ok) throw new Error('options failed'); + const input = { challengeId: options.value.challengeId, response: { id: 'cred-1' } }; + + expect((await passkeys.verifyRegistration('acc-2', input, null)).ok).toBe(false); + expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(true); + expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(false); + }); + + it('el login con passkey crea una sesión nueva y actualiza el contador', async () => { + const { db, passkeys } = setup(); + const options = await passkeys.loginOptions('1.1.1.1'); + if (!options.ok) throw new Error('options failed'); + const result = await passkeys.verifyLogin( + { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, + { userAgent: null }, + ); + expect(result.ok).toBe(true); + expect(db.studentPasskey.update.mock.calls[0]?.[0]).toMatchObject({ data: { counter: 5 } }); + expect(db.studentSession.create.mock.calls[0]?.[0]).toMatchObject({ data: { accountId: 'acc-1' } }); + }); + + it('un challenge de registro no sirve para login', async () => { + const { passkeys } = setup(); + const options = await passkeys.registrationOptions('acc-1'); + if (!options.ok) throw new Error('options failed'); + const result = await passkeys.verifyLogin( + { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, + { userAgent: null }, + ); + expect(result.ok).toBe(false); + }); + + it('una firma inválida no inicia sesión', async () => { + const { db, webauthn, passkeys } = setup(); + webauthn.verifyAuthenticationResponse.mockImplementationOnce(async () => { + throw new Error('bad signature'); + }); + const options = await passkeys.loginOptions('1.1.1.1'); + if (!options.ok) throw new Error('options failed'); + const result = await passkeys.verifyLogin( + { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, + { userAgent: null }, + ); + expect(result.ok).toBe(false); + expect(db.studentSession.create).not.toHaveBeenCalled(); + }); +}); + +describe('separación de roles y CSRF', () => { + const session = (overrides: Record = {}) => ({ + id: 'ses-1', + accountId: 'acc-1', + revokedAt: null, + expiresAt: new Date(NOW.getTime() + 1000 * 60 * 60 * 24), + lastUsedAt: NOW, + ...overrides, + }); + let db: { studentSession: { findUnique: ReturnType; update: ReturnType } }; + + function app() { + const hono = new Hono(); + hono.use('*', studentOriginGuard); + hono.get('/me', requireStudentSession({ db: db as never, now: () => NOW }), (c) => c.json(c.get('student'))); + hono.post('/action', (c) => c.json({ ok: true })); + return hono; + } + + beforeEach(() => { + db = { studentSession: { findUnique: mock(async () => session()), update: mock(async () => ({})) } }; + }); + + it('las rutas del alumno quedan fuera del middleware del profe, y las del profe no', () => { + expect(isPublicApiRequest('GET', '/api/v1/student-portal/me')).toBe(true); + expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/students/status')).toBe(false); + }); + + it('la cookie de sesión del profe no sirve en las rutas del alumno', async () => { + const res = await app().request('/me', { + headers: { Cookie: 'better-auth.session_token=teacher-token' }, + }); + expect(res.status).toBe(401); + expect(db.studentSession.findUnique).not.toHaveBeenCalled(); + }); + + it('con la cookie del alumno setea su cuenta', async () => { + const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ accountId: 'acc-1', sessionId: 'ses-1' }); + expect(db.studentSession.findUnique.mock.calls[0]?.[0]).toEqual({ where: { tokenHash: hashToken('student-token') } }); + }); + + it('una sesión revocada o vencida no entra', async () => { + for (const row of [session({ revokedAt: NOW }), session({ expiresAt: NOW })]) { + db.studentSession.findUnique.mockImplementationOnce(async () => row); + const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } }); + expect(res.status).toBe(401); + } + }); + + it('la sesión se desliza: con más de una hora sin uso se renueva por 90 días', async () => { + db.studentSession.findUnique.mockImplementationOnce(async () => + session({ lastUsedAt: new Date(NOW.getTime() - 2 * 60 * 60 * 1000) })); + const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } }); + expect(res.status).toBe(200); + expect(db.studentSession.update.mock.calls[0]?.[0]).toMatchObject({ + data: { lastUsedAt: NOW, expiresAt: new Date(NOW.getTime() + 90 * 24 * 60 * 60 * 1000) }, + }); + expect(res.headers.get('Set-Cookie')).toContain('HttpOnly'); + expect(res.headers.get('Set-Cookie')).toContain('SameSite=Lax'); + }); + + it('un POST sin Origin o de otro origen se rechaza', async () => { + expect((await app().request('/action', { method: 'POST' })).status).toBe(403); + expect((await app().request('/action', { method: 'POST', headers: { Origin: 'https://evil.test' } })).status).toBe(403); + expect((await app().request('/action', { method: 'POST', headers: { Origin: WEB } })).status).toBe(200); + }); +}); + +describe('dispositivo legible', () => { + it('describe navegador y plataforma', () => { + expect(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/130.0 Mobile/15E148 Safari/604.1')).toBe('iPhone · Chrome'); + expect(describeDevice('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36')).toBe('Android · Chrome'); + expect(describeDevice('Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/26.0 Chrome/122.0 Mobile Safari/537.36')).toBe('Android · Samsung Internet'); + expect(describeDevice(null)).toBe('Dispositivo desconocido'); + }); +}); diff --git a/apps/backend/test/student-portal-files.test.ts b/apps/backend/test/student-portal-files.test.ts new file mode 100644 index 0000000..7c9175f --- /dev/null +++ b/apps/backend/test/student-portal-files.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'bun:test'; +import { REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared'; +import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type'; +import type { FileStorage } from '@/lib/storage'; +import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler'; +import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case'; + +const pad = (head: number[]) => new Uint8Array([...head, ...new Array(16).fill(0)]); +const ascii = (text: string) => [...text].map((char) => char.charCodeAt(0)); + +describe('tipo real del comprobante (magic bytes)', () => { + it('reconoce JPG, PNG, WEBP, HEIC y PDF', () => { + expect(detectReceiptType(pad([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg'); + expect(detectReceiptType(pad([0x89, ...ascii('PNG'), 0x0d, 0x0a, 0x1a, 0x0a]))).toBe('image/png'); + expect(detectReceiptType(pad([...ascii('RIFF'), 0, 0, 0, 0, ...ascii('WEBP')]))).toBe('image/webp'); + expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypheic')]))).toBe('image/heic'); + expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypmif1')]))).toBe('image/heic'); + expect(detectReceiptType(pad(ascii('%PDF-1.7')))).toBe('application/pdf'); + }); + + it('rechaza lo demás aunque se llame .png', () => { + expect(detectReceiptType(pad(ascii(' { + const puts: string[] = []; + const storage: FileStorage = { put: async (key) => void puts.push(key), signedUrl: () => '', remove: async () => {} }; + const attendee = { + id: 'a1', + groupId: 'g1', + group: { createdById: 't1', owner: { country: 'AR' } }, + }; + const db = { attendee: { findFirst: async () => attendee }, payment: { findMany: async () => [] } }; + const useCase = new ReportStudentPayment({ db: db as never, storage }); + + const big = await useCase.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: new Uint8Array(RECEIPT_MAX_BYTES + 1) } }); + expect(!big.ok && big.error.errors).toEqual({ file: ['too_large'] }); + const html = await useCase.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.png', bytes: pad(ascii('')) } }); + expect(!html.ok && html.error.errors).toEqual({ file: ['invalid_type'] }); + expect(puts).toEqual([]); + + const noStorage = new ReportStudentPayment({ db: db as never, storage: null }); + const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } }); + expect(!unavailable.ok && unavailable.error.status).toBe(503); + + const longNote = await useCase.execute('acc', { + attendeeId: 'a1', + paymentIds: ['p1'], + note: 'x'.repeat(REPORTED_PAYMENT_NOTE_MAX + 1), + file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) }, + }); + expect(!longNote.ok && longNote.error.errors).toEqual({ note: ['too_long'] }); + expect(puts).toEqual([]); + }); +}); + +describe('clases de un rango en la hora del profe', () => { + const TZ = 'America/Argentina/Buenos_Aires'; + + it('lista lunes y miércoles a las 18 de una semana', () => { + const from = startOfWeekInTimeZone(new Date('2026-10-28T15:00:00Z'), TZ); + expect(from.toISOString()).toBe('2026-10-26T03:00:00.000Z'); + const to = new Date(from.getTime() + 7 * 24 * 60 * 60 * 1000); + const starts = occurrencesBetween({ days: ['MONDAY', 'WEDNESDAY'], time: '18:00', from, to, timeZone: TZ }); + expect(starts.map((date) => date.toISOString())).toEqual(['2026-10-26T21:00:00.000Z', '2026-10-28T21:00:00.000Z']); + }); + + it('sin horario no hay clases', () => { + const now = new Date(); + expect(occurrencesBetween({ days: ['MONDAY'], time: null, from: now, to: new Date(now.getTime() + 1e9), timeZone: TZ })).toEqual([]); + expect(occurrencesBetween({ days: [], time: '18:00', from: now, to: new Date(now.getTime() + 1e9), timeZone: TZ })).toEqual([]); + }); +}); diff --git a/apps/backend/test/students.test.ts b/apps/backend/test/students.test.ts deleted file mode 100644 index 6dfd088..0000000 --- a/apps/backend/test/students.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; -import { Hono } from 'hono'; - -mock.module('@/lib/prisma', () => ({ - default: { - student: { - findMany: mock(), - count: mock(), - }, - }, - getPrismaClient: mock(), - UnitOfWork: class {}, -})); - -import prisma from '@/lib/prisma'; -import { studentsRoutes } from '@/modules/students'; - -const app = new Hono(); -app.route('/students', studentsRoutes); - -const student = { - id: 'student-1', - groupId: 'group-1', - fullName: 'Ana Pérez', - email: 'ana@example.com', - phone: null, - guardianName: 'Luis Pérez', - guardianPhone: null, - notes: null, - createdAt: new Date('2026-08-01T10:00:00.000Z'), - updatedAt: new Date('2026-08-01T10:00:00.000Z'), -}; - -describe('students routes', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it('lists students with pagination', async () => { - prisma.student.findMany.mockResolvedValue([student]); - prisma.student.count.mockResolvedValue(21); - - const res = await app.request('/students?page=2&pageSize=10'); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ - data: [ - { - ...student, - createdAt: student.createdAt.toISOString(), - updatedAt: student.updatedAt.toISOString(), - }, - ], - pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 }, - }); - expect(prisma.student.findMany).toHaveBeenCalledWith({ - skip: 10, - take: 10, - orderBy: { createdAt: 'desc' }, - }); - expect(prisma.student.count).toHaveBeenCalledWith(); - }); - - it('uses default pagination', async () => { - prisma.student.findMany.mockResolvedValue([]); - prisma.student.count.mockResolvedValue(0); - - const res = await app.request('/students'); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ - data: [], - pagination: { page: 1, pageSize: 10, total: 0, totalPages: 0 }, - }); - }); - - it('rejects invalid pagination query parameters', async () => { - const res = await app.request('/students?page=0&pageSize=25'); - - expect(res.status).toBe(400); - expect(await res.json()).toMatchObject({ status: 400, title: 'Bad Request' }); - }); -}); \ No newline at end of file diff --git a/apps/backend/test/waitlist-management.test.ts b/apps/backend/test/waitlist-management.test.ts new file mode 100644 index 0000000..edca032 --- /dev/null +++ b/apps/backend/test/waitlist-management.test.ts @@ -0,0 +1,447 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + findMany: mock(), + count: mock(), + create: mock(), + delete: mock(), + }, + person: { + findFirst: mock(), + create: mock(), + deleteMany: mock(), + }, + groupWaitlistEntry: { + findMany: mock(), + findFirst: mock(), + count: mock(), + create: mock(), + delete: mock(), + }, + payment: { + count: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const mockGroup = { + id: 'group-1', + name: 'Taller de Pintura', + description: null, + createdById: teacherId, + inviteToken: null, + createdAt: new Date('2026-09-01T10:00:00.000Z'), + updatedAt: new Date('2026-09-01T10:00:00.000Z'), + days: ['MONDAY'], + time: '18:00', + capacity: 20, + price: 1500, + billingType: 'MONTHLY', + dueDay: 10, + members: [], +}; + +const waitlistEntry = (overrides: Record = {}) => ({ + id: 'wl-1', + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + notes: null, + status: 'PENDING', + createdAt: new Date('2026-09-10T10:00:00.000Z'), + updatedAt: new Date('2026-09-10T10:00:00.000Z'), + ...overrides, +}); + +const attendee = (overrides: Record = {}) => ({ + id: 'att-1', + groupId: 'group-1', + personId: 'person-1', + person: { + id: 'person-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + guardianName: null, + guardianPhone: null, + notes: null, + }, + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + ...overrides, +}); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app; +} + +describe('group waitlist management', () => { + beforeEach(() => { + vi.clearAllMocks(); + // The phone is nobody the teacher has yet: promoting creates the person. + prisma.person.findFirst.mockResolvedValue(null); + prisma.person.create.mockResolvedValue({ id: 'person-1' } as never); + }); + + describe('GET /groups/:groupId/waitlist', () => { + it('lists pending entries in FIFO order with pagination', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupWaitlistEntry.findMany.mockResolvedValue([ + waitlistEntry({ id: 'wl-1', fullName: 'Ana García', createdAt: new Date('2026-09-08T10:00:00.000Z') }), + waitlistEntry({ id: 'wl-2', fullName: 'Pedro López', createdAt: new Date('2026-09-09T10:00:00.000Z') }), + ] as never); + prisma.groupWaitlistEntry.count.mockResolvedValue(2); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist'); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.data).toHaveLength(2); + expect(data.data[0].fullName).toBe('Ana García'); + expect(data.pagination).toEqual({ page: 1, pageSize: 10, total: 2, totalPages: 1 }); + expect(prisma.groupWaitlistEntry.findMany).toHaveBeenCalledWith({ + where: { groupId: 'group-1', status: 'PENDING' }, + skip: 0, + take: 10, + orderBy: { createdAt: 'asc' }, + }); + }); + + it('rejects user without access to the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/waitlist'); + + expect(res.status).toBe(403); + expect(prisma.groupWaitlistEntry.findMany).not.toHaveBeenCalled(); + }); + }); + + describe('POST /groups/:groupId/waitlist/:entryId/promote', () => { + it('creates an attendee from the entry and removes it from the waitlist', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + prisma.attendee.count.mockResolvedValue(5); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.create.mockResolvedValue(attendee() as never); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', { + method: 'POST', + }); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.attendee.fullName).toBe('Martín Gómez'); + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { groupId: 'group-1', personId: 'person-1' }, + include: { person: { select: expect.any(Object) } }, + }); + expect(prisma.person.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ createdById: teacherId, fullName: 'Martín Gómez', phone: '+5491133445566' }), + select: { id: true }, + }); + expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); + }); + + it('rejects with 409 when the group reached its capacity', async () => { + prisma.group.findUnique.mockResolvedValue({ ...mockGroup, capacity: 5 } as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + prisma.attendee.count.mockResolvedValue(5); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', { + method: 'POST', + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('group_capacity_reached'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the person is already a member of the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + prisma.attendee.count.mockResolvedValue(5); + prisma.person.findFirst.mockResolvedValue({ + id: 'person-1', + fullName: 'Martín Gómez', + email: null, + phone: '+5491133445566', + attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }], + } as never); + prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', { + method: 'POST', + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('attendee_already_registered'); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('returns 404 when the entry does not exist', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-missing/promote', { + method: 'POST', + }); + + expect(res.status).toBe(404); + }); + + it('rejects a non-owner user', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/waitlist/wl-1/promote', { + method: 'POST', + }); + + expect(res.status).toBe(403); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + const promoteTo = (targetGroupId: string) => + makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ targetGroupId }), + }); + + it('places the entry in another group of the teacher and removes it from the origin waitlist', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(mockGroup as never) + .mockResolvedValueOnce({ ...mockGroup, id: 'group-2', name: 'Taller de Cerámica' } as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + prisma.attendee.count.mockResolvedValue(5); + prisma.attendee.findFirst.mockResolvedValue(null); + prisma.attendee.create.mockResolvedValue(attendee({ groupId: 'group-2' }) as never); + + const res = await promoteTo('group-2'); + + expect(res.status).toBe(200); + expect(prisma.group.findUnique).toHaveBeenLastCalledWith({ where: { id: 'group-2' } }); + expect(prisma.attendee.count).toHaveBeenCalledWith({ where: { groupId: 'group-2', status: 'ACTIVE' } }); + expect(prisma.attendee.create).toHaveBeenCalledWith({ + data: { groupId: 'group-2', personId: 'person-1' }, + include: { person: { select: expect.any(Object) } }, + }); + expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); + }); + + it('rejects a target group owned by another teacher', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(mockGroup as never) + .mockResolvedValueOnce({ ...mockGroup, id: 'group-2', createdById: 'other-user' } as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + + const res = await promoteTo('group-2'); + + expect(res.status).toBe(403); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled(); + }); + + it('returns 404 when the target group does not exist', async () => { + prisma.group.findUnique.mockResolvedValueOnce(mockGroup as never).mockResolvedValueOnce(null); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + + const res = await promoteTo('group-missing'); + + expect(res.status).toBe(404); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the target group reached its capacity', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(mockGroup as never) + .mockResolvedValueOnce({ ...mockGroup, id: 'group-2', capacity: 5 } as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + prisma.attendee.count.mockResolvedValue(5); + + const res = await promoteTo('group-2'); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('group_capacity_reached'); + expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled(); + }); + }); + + describe('DELETE /groups/:groupId/waitlist/:entryId', () => { + it('removes a waitlist entry', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1', { + method: 'DELETE', + }); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.deleted).toBe(true); + expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); + }); + + it('returns 404 when the entry does not exist', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-missing', { + method: 'DELETE', + }); + + expect(res.status).toBe(404); + expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled(); + }); + + it('rejects a non-owner user', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/waitlist/wl-1', { + method: 'DELETE', + }); + + expect(res.status).toBe(403); + expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled(); + }); + }); + + describe('DELETE /groups/:groupId/attendees/:attendeeId', () => { + it('removes an attendee without promotion', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + prisma.payment.count.mockResolvedValue(0); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/attendees/att-1', { + method: 'DELETE', + }); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.removedAttendeeId).toBe('att-1'); + expect(body.promoted).toBeNull(); + expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } }); + // Their last group: the person goes too (no-op if they are in others). + expect(prisma.person.deleteMany).toHaveBeenCalledWith({ + where: { id: 'person-1', attendees: { none: {} } }, + }); + }); + + it('removes an attendee and promotes the first pending waitlist entry atomically', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockImplementation(async ({ where }: { where?: { id?: string } }) => { + if (where?.id) return attendee() as never; + return null; + }); + prisma.payment.count.mockResolvedValue(0); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue( + waitlistEntry({ id: 'wl-1', fullName: 'Sofía Ruiz', phone: '+5491133778899' }) as never, + ); + prisma.attendee.count.mockResolvedValue(5); + prisma.attendee.create.mockResolvedValue( + attendee({ id: 'att-2', fullName: 'Sofía Ruiz', phone: '+5491133778899' }) as never, + ); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/attendees/att-1?promoteFromWaitlist=true', + { method: 'DELETE' }, + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.removedAttendeeId).toBe('att-1'); + expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' }); + expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } }); + expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); + expect(prisma.person.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }), + select: { id: true }, + }); + }); + + it('removes the attendee when promote requested but waitlist is empty', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + prisma.payment.count.mockResolvedValue(0); + prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: teacherId }).request( + '/groups/group-1/attendees/att-1?promoteFromWaitlist=true', + { method: 'DELETE' }, + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.removedAttendeeId).toBe('att-1'); + expect(body.promoted).toBeNull(); + expect(prisma.attendee.create).not.toHaveBeenCalled(); + }); + + it('blocks removal when the attendee has payments', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + prisma.payment.count.mockResolvedValue(2); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/attendees/att-1', { + method: 'DELETE', + }); + + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.code).toBe('attendee_has_payments'); + expect(prisma.attendee.delete).not.toHaveBeenCalled(); + }); + + it('returns 404 when the attendee does not belong to the group', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + prisma.attendee.findFirst.mockResolvedValue(null); + + const res = await makeApp({ id: teacherId }).request('/groups/group-1/attendees/att-missing', { + method: 'DELETE', + }); + + expect(res.status).toBe(404); + expect(prisma.attendee.delete).not.toHaveBeenCalled(); + }); + + it('rejects a non-owner user', async () => { + prisma.group.findUnique.mockResolvedValue(mockGroup as never); + + const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/attendees/att-1', { + method: 'DELETE', + }); + + expect(res.status).toBe(403); + expect(prisma.attendee.delete).not.toHaveBeenCalled(); + }); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/whatsapp-core.test.ts b/apps/backend/test/whatsapp-core.test.ts new file mode 100644 index 0000000..0bc2942 --- /dev/null +++ b/apps/backend/test/whatsapp-core.test.ts @@ -0,0 +1,655 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { ok } from '@gruperly/shared'; +import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case'; +import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case'; +import { DisconnectWhatsapp } from '@/modules/whatsapp/features/disconnect/use-case'; +import { RequestWhatsappPairingCode } from '@/modules/whatsapp/features/pairing-code/use-case'; +import { GetWhatsappStatus } from '@/modules/whatsapp/features/status/use-case'; +import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case'; +import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case'; +import { toVisibleWhatsappStatus } from '@/modules/whatsapp/lib/account'; +import type { + MessagingProvider, + NormalizedEvent, +} from '@/modules/whatsapp/providers/messaging-provider'; + +/* The domain side of WhatsApp, driven through a fake provider: these tests pin + what the use cases do with whatever any provider answers, so they do not + change when an adapter does. Dependencies go in through constructors (no + `mock.module`), as AGENTS.md asks for provider code. */ + +const ownerId = 'user-1'; +const now = new Date('2026-10-19T13:00:00.000Z'); + +function fakeProvider(overrides: Partial = {}): MessagingProvider { + return { + id: 'OPENWA', + startConnection: mock(async () => + ok({ + start: { type: 'qr' as const, qrCode: 'data:image/png;base64,QR1' }, + externalId: 'session-1', + providerData: { sessionName: 'gruperly-user-1' }, + }), + ), + refreshConnection: mock(async () => ok({ state: 'pending' as const, qrCode: 'data:QR2' })), + disconnect: mock(async () => ok(undefined)), + readiness: mock(async () => 'ready' as const), + resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: e164 })), + send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })), + parseWebhook: mock(() => ok({ dedupeKey: 'delivery-1', events: [] as NormalizedEvent[] })), + ...overrides, + } as MessagingProvider; +} + +function account(overrides: Record = {}) { + return { + id: 'wa-1', + ownerId, + provider: 'OPENWA', + status: 'PENDING', + externalId: 'session-1', + displayPhoneNumber: null, + providerData: { sessionName: 'gruperly-user-1' }, + connectedAt: null, + ...overrides, + }; +} + +function makeDb() { + return { + whatsappAccount: { + findUnique: mock(), + findFirst: mock(), + upsert: mock(async () => ({})), + update: mock(async ({ data }: { data: Record }) => account({ ...data })), + }, + whatsappWebhookEvent: { + create: mock(async () => ({})), + delete: mock(async () => ({})), + }, + outboundMessage: { + updateMany: mock(async () => ({ count: 1 })), + }, + group: { + findUnique: mock(), + update: mock(), + }, + user: { + findUnique: mock(async () => ({ country: 'AR' })), + }, + }; +} + +type Db = ReturnType; +let db: Db; + +beforeEach(() => { + db = makeDb(); +}); + +describe('visible WhatsApp status', () => { + it('maps rows of the active provider', () => { + expect(toVisibleWhatsappStatus(null, 'OPENWA')).toBe('none'); + expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'PENDING' }, 'OPENWA')).toBe('pending'); + expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'OPENWA')).toBe('active'); + expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'OPENWA')).toBe( + 'disconnected', + ); + }); + + it('asks to reconnect an account linked with another provider', () => { + expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'KAPSO')).toBe( + 'requires_reconnect', + ); + expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'KAPSO')).toBe('none'); + }); +}); + +describe('start connection', () => { + it('stores a PENDING account and hands the QR to the browser', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(null); + const provider = fakeProvider(); + + const result = await new StartWhatsappConnection({ db: db as never, provider }).execute( + { id: ownerId, name: 'Ana Profe' }, + 'onboarding', + ); + + expect(result).toEqual({ + ok: true, + value: { start: { type: 'qr', qrCode: 'data:image/png;base64,QR1' } }, + }); + expect(provider.startConnection).toHaveBeenCalledWith({ + ownerId, + ownerName: 'Ana Profe', + returnTo: 'onboarding', + account: null, + }); + const upsert = db.whatsappAccount.upsert.mock.calls[0]?.[0] as { + create: Record; + update: Record; + }; + expect(upsert.create).toMatchObject({ + ownerId, + provider: 'OPENWA', + status: 'PENDING', + externalId: 'session-1', + }); + expect(upsert.update).toMatchObject({ status: 'PENDING', connectedAt: null }); + }); + + it('passes the redirect through for hosted linkings', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(null); + const provider = fakeProvider({ + id: 'KAPSO', + startConnection: mock(async () => + ok({ + start: { type: 'redirect' as const, url: 'https://app.kapso.ai/whatsapp/setup/abc' }, + externalId: null, + providerData: { customerId: 'cust-1', setupLinkId: 'link-1' }, + }), + ), + }); + + const result = await new StartWhatsappConnection({ db: db as never, provider }).execute( + { id: ownerId, name: 'Ana' }, + 'settings', + ); + + expect(result.ok && result.value.start).toEqual({ + type: 'redirect', + url: 'https://app.kapso.ai/whatsapp/setup/abc', + }); + }); + + it('does not touch the account when the provider fails', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(null); + const provider = fakeProvider({ + startConnection: mock(async () => ({ + ok: false as const, + error: { type: 'x', title: 'Bad Gateway', status: 502, code: 'whatsapp_provider_error' }, + })), + }); + + const result = await new StartWhatsappConnection({ db: db as never, provider }).execute( + { id: ownerId, name: 'Ana' }, + 'settings', + ); + + expect(result.ok).toBe(false); + expect(db.whatsappAccount.upsert).not.toHaveBeenCalled(); + }); +}); + +describe('status', () => { + it('reports no account', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(null); + + const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute( + ownerId, + ); + + expect(result).toEqual({ + ok: true, + value: { + status: 'none', + provider: 'OPENWA', + displayPhoneNumber: null, + connectedAt: null, + qrCode: null, + readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' }, + }, + }); + }); + + it('returns the fresh QR while the linking is pending', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account()); + + const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute( + ownerId, + ); + + expect(result.ok && result.value).toMatchObject({ status: 'pending', qrCode: 'data:QR2' }); + expect(db.whatsappAccount.update).not.toHaveBeenCalled(); + }); + + it('activates the account once the provider reports it linked', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account()); + const onConnected = mock(async () => undefined); + const provider = fakeProvider({ + refreshConnection: mock(async () => + ok({ state: 'active' as const, displayPhoneNumber: '+5491123456789' }), + ), + onConnected, + }); + + const result = await new GetWhatsappStatus({ db: db as never, provider, now: () => now }).execute( + ownerId, + ); + + expect(db.whatsappAccount.update).toHaveBeenCalledWith({ + where: { id: 'wa-1' }, + data: { status: 'ACTIVE', connectedAt: now, displayPhoneNumber: '+5491123456789' }, + }); + expect(onConnected).toHaveBeenCalledTimes(1); + expect(result.ok && result.value).toMatchObject({ + status: 'active', + displayPhoneNumber: '+5491123456789', + connectedAt: now.toISOString(), + readiness: { PAYMENT_REMINDER: 'ready', REENGAGEMENT: 'ready' }, + }); + }); + + it('marks a failed linking as disconnected', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account()); + const provider = fakeProvider({ + refreshConnection: mock(async () => ok({ state: 'disconnected' as const, reason: 'failed' })), + }); + + const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId); + + expect(db.whatsappAccount.update).toHaveBeenCalledWith({ + where: { id: 'wa-1' }, + data: { status: 'DISCONNECTED' }, + }); + expect(result.ok && result.value.status).toBe('disconnected'); + }); + + it('does not poll the provider for an account linked elsewhere', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO', status: 'ACTIVE' })); + const provider = fakeProvider(); + + const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId); + + expect(provider.refreshConnection).not.toHaveBeenCalled(); + expect(result.ok && result.value).toMatchObject({ + status: 'requires_reconnect', + readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' }, + }); + }); + + it('reports a template still under review', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' })); + const provider = fakeProvider({ + readiness: mock(async (_account, kind) => (kind === 'REENGAGEMENT' ? 'pending' : 'ready')), + }); + + const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId); + + expect(result.ok && result.value.readiness).toEqual({ + PAYMENT_REMINDER: 'ready', + REENGAGEMENT: 'pending', + }); + }); +}); + +describe('pairing code', () => { + const withPairing = () => + fakeProvider({ requestPairingCode: mock(async () => ok('ABCD1234')) }); + + it('normalizes the number with the teacher country and returns the code', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account()); + const provider = withPairing(); + + const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute( + ownerId, + '011 15 2345-6789', + ); + + expect(result).toEqual({ ok: true, value: { pairingCode: 'ABCD1234' } }); + expect(provider.requestPairingCode).toHaveBeenCalledWith( + expect.objectContaining({ id: 'wa-1' }), + '5491123456789', + ); + }); + + it('needs a linking in progress with the active provider', async () => { + for (const current of [null, account({ status: 'ACTIVE' }), account({ provider: 'KAPSO' })]) { + db.whatsappAccount.findUnique.mockResolvedValue(current); + const provider = withPairing(); + + const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute( + ownerId, + '1123456789', + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('whatsapp_linking_not_started'); + expect(provider.requestPairingCode).not.toHaveBeenCalled(); + } + }); + + it('rejects a number it cannot normalize', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account()); + const provider = withPairing(); + + const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute( + ownerId, + '12345', + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(400); + expect(provider.requestPairingCode).not.toHaveBeenCalled(); + }); + + it('answers 409 when the provider only links by QR or redirect', async () => { + const result = await new RequestWhatsappPairingCode({ + db: db as never, + provider: fakeProvider(), + }).execute(ownerId, '1123456789'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('whatsapp_pairing_unsupported'); + }); +}); + +describe('disconnect', () => { + it('unlinks on the provider and frees the number locally', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' })); + const provider = fakeProvider(); + + const result = await new DisconnectWhatsapp({ db: db as never, provider }).execute(ownerId); + + expect(result).toEqual({ ok: true, value: { disconnected: true } }); + expect(provider.disconnect).toHaveBeenCalledTimes(1); + expect(db.whatsappAccount.update).toHaveBeenCalledWith({ + where: { id: 'wa-1' }, + data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null }, + }); + }); + + it('is a no-op without a linked account', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(null); + + const result = await new DisconnectWhatsapp({ db: db as never, provider: fakeProvider() }).execute( + ownerId, + ); + + expect(result).toEqual({ ok: true, value: { disconnected: false } }); + expect(db.whatsappAccount.update).not.toHaveBeenCalled(); + }); +}); + +describe('redirect callback', () => { + it('activates the account the provider confirmed', async () => { + db.whatsappAccount.findUnique.mockResolvedValue( + account({ provider: 'KAPSO', externalId: null, providerData: { customerId: 'cust-1' } }), + ); + const provider = fakeProvider({ + id: 'KAPSO', + completeRedirect: mock(async () => + ok({ + externalId: 'phone-1', + displayPhoneNumber: '+5491100000000', + providerData: { businessAccountId: 'waba-1' }, + }), + ), + }); + + const outcome = await new CompleteWhatsappSetup({ db: db as never, provider, now: () => now }).execute( + ownerId, + { setup_link_id: 'link-1', phone_number_id: 'phone-1', status: 'completed' }, + ); + + expect(outcome).toEqual({ kind: 'success' }); + expect(db.whatsappAccount.update).toHaveBeenCalledWith({ + where: { id: 'wa-1' }, + data: { + status: 'ACTIVE', + connectedAt: now, + externalId: 'phone-1', + displayPhoneNumber: '+5491100000000', + providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' }, + }, + }); + }); + + it('reports a number already linked to someone else', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO' })); + db.whatsappAccount.update.mockRejectedValueOnce(Object.assign(new Error('unique'), { code: 'P2002' })); + const provider = fakeProvider({ + id: 'KAPSO', + completeRedirect: mock(async () => ok({ externalId: 'phone-1', displayPhoneNumber: null })), + }); + + const outcome = await new CompleteWhatsappSetup({ db: db as never, provider }).execute(ownerId, {}); + + expect(outcome).toEqual({ kind: 'error', reason: 'number_in_use' }); + }); + + it('refuses a provider without hosted linking', async () => { + db.whatsappAccount.findUnique.mockResolvedValue(account()); + + const outcome = await new CompleteWhatsappSetup({ db: db as never, provider: fakeProvider() }).execute( + ownerId, + {}, + ); + + expect(outcome).toEqual({ kind: 'error', reason: 'invalid_setup' }); + }); +}); + +describe('webhook', () => { + const headers = new Headers(); + + it('rejects an invalid signature before touching the database', async () => { + const provider = fakeProvider({ + parseWebhook: mock(() => ({ ok: false as const, error: 'invalid_signature' as const })), + }); + + const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute( + 'OPENWA', + '{}', + headers, + ); + + expect(result).toEqual({ ok: false, error: 'invalid_signature' }); + expect(db.whatsappWebhookEvent.create).not.toHaveBeenCalled(); + }); + + it('ignores a delivery it already processed', async () => { + db.whatsappWebhookEvent.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' })); + const provider = fakeProvider({ + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-1', + events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }], + }), + ), + }); + + const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute( + 'OPENWA', + '{}', + headers, + ); + + expect(result).toEqual({ ok: true, value: { duplicate: true, applied: 0 } }); + expect(db.outboundMessage.updateMany).not.toHaveBeenCalled(); + }); + + it('advances a message status without moving it backwards', async () => { + const provider = fakeProvider({ + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-2', + events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'DELIVERED' as const }], + }), + ), + }); + + await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers); + + expect(db.whatsappWebhookEvent.create).toHaveBeenCalledWith({ + data: { provider: 'OPENWA', dedupeKey: 'delivery-2' }, + }); + expect(db.outboundMessage.updateMany).toHaveBeenCalledWith({ + where: { + provider: 'OPENWA', + providerMessageId: 'wamid-1', + status: { in: ['QUEUED', 'SENT'] }, + }, + data: { status: 'DELIVERED' }, + }); + }); + + it('records why a message failed', async () => { + const provider = fakeProvider({ + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-3', + events: [ + { + type: 'message_status' as const, + providerMessageId: 'wamid-1', + status: 'FAILED' as const, + errorCode: '131026', + errorMessage: 'Message undeliverable', + }, + ], + }), + ), + }); + + await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers); + + expect(db.outboundMessage.updateMany.mock.calls[0]?.[0]).toMatchObject({ + data: { status: 'FAILED', errorCode: '131026', errorMessage: 'Message undeliverable' }, + }); + }); + + it('activates the account a connection event names and runs the setup once', async () => { + db.whatsappAccount.findFirst.mockResolvedValueOnce(account()); + const onConnected = mock(async () => undefined); + const provider = fakeProvider({ + onConnected, + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-4', + events: [ + { + type: 'connection' as const, + externalId: 'session-1', + status: 'active' as const, + displayPhoneNumber: '+5491123456789', + }, + ], + }), + ), + }); + + const result = await new HandleWhatsappWebhook({ db: db as never, provider, now: () => now }).execute( + 'OPENWA', + '{}', + headers, + ); + + expect(result).toEqual({ ok: true, value: { duplicate: false, applied: 1 } }); + expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({ + where: { id: 'wa-1' }, + data: { status: 'ACTIVE', connectedAt: now, externalId: 'session-1' }, + }); + expect(onConnected).toHaveBeenCalledTimes(1); + }); + + it('falls back to the owner reference when the number is new to us', async () => { + db.whatsappAccount.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(account({ provider: 'KAPSO' })); + const provider = fakeProvider({ + id: 'KAPSO', + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-5', + events: [{ type: 'connection' as const, externalId: 'phone-1', ownerId, status: 'active' as const }], + }), + ), + }); + + await new HandleWhatsappWebhook({ db: db as never, provider }).execute('KAPSO', '{}', headers); + + expect(db.whatsappAccount.findFirst.mock.calls[1]?.[0]).toEqual({ + where: { provider: 'KAPSO', ownerId, status: { not: 'DISCONNECTED' } }, + }); + expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({ + data: { status: 'ACTIVE', externalId: 'phone-1' }, + }); + }); + + it('marks an unlinked number as disconnected', async () => { + db.whatsappAccount.findFirst.mockResolvedValueOnce(account({ status: 'ACTIVE' })); + const provider = fakeProvider({ + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-6', + events: [{ type: 'connection' as const, externalId: 'session-1', status: 'disconnected' as const }], + }), + ), + }); + + await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers); + + expect(db.whatsappAccount.update).toHaveBeenCalledWith({ + where: { id: 'wa-1' }, + data: { status: 'DISCONNECTED' }, + }); + }); + + it('un-burns the delivery when applying it fails, so the retry gets through', async () => { + db.outboundMessage.updateMany.mockRejectedValueOnce(new Error('db down')); + const provider = fakeProvider({ + parseWebhook: mock(() => + ok({ + dedupeKey: 'delivery-7', + events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }], + }), + ), + }); + + await expect( + new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers), + ).rejects.toThrow('db down'); + expect(db.whatsappWebhookEvent.delete).toHaveBeenCalledWith({ + where: { provider_dedupeKey: { provider: 'OPENWA', dedupeKey: 'delivery-7' } }, + }); + }); +}); + +describe('group automations', () => { + it('lets the owner turn an automation on', async () => { + db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: ownerId }); + db.group.update.mockResolvedValue({ autoPaymentReminders: true, autoReengagement: false }); + + const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, { + autoPaymentReminders: true, + }); + + expect(result).toEqual({ ok: true, value: { autoPaymentReminders: true, autoReengagement: false } }); + expect(db.group.update).toHaveBeenCalledWith({ + where: { id: 'group-1' }, + data: { autoPaymentReminders: true }, + select: { autoPaymentReminders: true, autoReengagement: true }, + }); + }); + + it('refuses anyone but the owner', async () => { + db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: 'someone-else' }); + + const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, { + autoReengagement: true, + }); + + expect(result.ok).toBe(false); + expect(!result.ok && result.error.status).toBe(403); + expect(db.group.update).not.toHaveBeenCalled(); + }); + + it('answers 404 for an unknown group', async () => { + db.group.findUnique.mockResolvedValue(null); + + const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('nope', ownerId, { + autoReengagement: true, + }); + + expect(!result.ok && result.error.status).toBe(404); + }); +}); diff --git a/apps/backend/test/whatsapp-jobs.test.ts b/apps/backend/test/whatsapp-jobs.test.ts new file mode 100644 index 0000000..9b43f2e --- /dev/null +++ b/apps/backend/test/whatsapp-jobs.test.ts @@ -0,0 +1,389 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { ok, toWhatsappE164 } from '@gruperly/shared'; +import { SendPaymentReminders, SendReengagementMessages } from '@/modules/whatsapp/jobs'; +import { isoWeekKey } from '@/modules/whatsapp/lib/period'; +import { renderMessage } from '@/modules/whatsapp/lib/render-message'; +import type { MessagingProvider } from '@/modules/whatsapp/providers/messaging-provider'; + +/* The weekly jobs, with the provider faked through constructor deps. */ + +const now = new Date('2026-10-19T13:00:00.000Z'); // Monday +const ownerId = 'user-1'; + +const activeAccount = { + id: 'wa-1', + ownerId, + provider: 'OPENWA', + status: 'ACTIVE', + externalId: 'session-1', + displayPhoneNumber: '+5491100000000', + providerData: null, +}; + +function eligibleGroup(overrides: Record = {}) { + return { + id: 'group-1', + name: 'Yoga Martes', + createdById: ownerId, + owner: { country: 'AR', whatsappAccount: activeAccount }, + ...overrides, + }; +} + +function payment(id: string, attendee: Record, overrides: Record = {}) { + return { + id, + amount: { toString: () => '25000' }, + currency: 'ARS', + dueDate: new Date('2026-10-20T15:00:00.000Z'), + checkoutUrl: `https://mpago.la/${id}`, + attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } }, + ...overrides, + }; +} + +function fakeProvider(overrides: Partial = {}): MessagingProvider { + return { + id: 'OPENWA', + startConnection: mock(), + refreshConnection: mock(), + disconnect: mock(), + readiness: mock(async () => 'ready' as const), + resolveRecipient: mock(async (_account, e164: string) => ({ + ok: true as const, + to: `${e164.slice(1)}@c.us`, + })), + send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })), + parseWebhook: mock(() => ok({ dedupeKey: 'k', events: [] })), + ...overrides, + } as MessagingProvider; +} + +function makeDb() { + let counter = 0; + return { + group: { findMany: mock(async () => [eligibleGroup()]) }, + payment: { findMany: mock(async () => [] as unknown[]) }, + attendee: { findMany: mock(async () => [] as unknown[]) }, + classSession: { findMany: mock(async () => [] as unknown[]) }, + attendance: { findMany: mock(async () => [] as unknown[]) }, + outboundMessage: { + create: mock(async () => ({ id: `msg-${++counter}` })), + update: mock(async () => ({})), + delete: mock(async () => ({})), + findMany: mock(async () => [] as unknown[]), + }, + }; +} + +let db: ReturnType; +const sleep = mock(async () => undefined); + +beforeEach(() => { + db = makeDb(); + sleep.mockClear(); +}); + +function reminders(provider: MessagingProvider) { + return new SendPaymentReminders({ db: db as never, provider, now, intervalMs: 5000, sleep }); +} + +function reengagement(provider: MessagingProvider) { + return new SendReengagementMessages({ db: db as never, provider, now, intervalMs: 5000, sleep }); +} + +describe('payment reminders', () => { + it('only looks at groups with the automation on and an active account of this provider', async () => { + await reminders(fakeProvider()).execute(); + + expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({ + where: { + autoPaymentReminders: true, + owner: { whatsappAccount: { is: { provider: 'OPENWA', status: 'ACTIVE' } } }, + }, + }); + }); + + it('asks for open charges with a link due within a week', async () => { + await reminders(fakeProvider()).execute(); + + expect(db.payment.findMany.mock.calls[0]?.[0]).toMatchObject({ + where: { + groupId: 'group-1', + status: { in: ['PENDING', 'OVERDUE'] }, + checkoutUrl: { not: null }, + dueDate: { lte: new Date('2026-10-26T13:00:00.000Z') }, + attendee: { status: 'ACTIVE' }, + }, + orderBy: { dueDate: 'asc' }, + }); + }); + + it('sends one reminder per member, logged before the send and keyed by the row id', async () => { + db.payment.findMany.mockResolvedValue([ + payment('pay-1', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }), + payment('pay-2', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }), + ]); + const provider = fakeProvider(); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 }); + expect(db.outboundMessage.create).toHaveBeenCalledWith({ + data: { + ownerId, + groupId: 'group-1', + attendeeId: 'att-1', + paymentId: 'pay-1', + kind: 'PAYMENT_REMINDER', + provider: 'OPENWA', + periodKey: '2026-W43', + toPhone: '+5491123456789', + status: 'QUEUED', + }, + select: { id: true }, + }); + const [, to, message, key] = (provider.send as ReturnType).mock.calls[0] ?? []; + expect(to).toBe('5491123456789@c.us'); + expect(key).toBe('msg-1'); + expect(message).toMatchObject({ + kind: 'PAYMENT_REMINDER', + studentName: 'Ana López', + groupName: 'Yoga Martes', + dueDate: '20/10', + paymentLink: 'https://mpago.la/pay-1', + }); + expect(db.outboundMessage.update).toHaveBeenCalledWith({ + where: { id: 'msg-1' }, + data: expect.objectContaining({ status: 'SENT', providerMessageId: 'wamid-1' }), + }); + }); + + it('skips a member already handled this week', async () => { + db.payment.findMany.mockResolvedValue([ + payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' }), + ]); + db.outboundMessage.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' })); + const provider = fakeProvider(); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 }); + expect(provider.send).not.toHaveBeenCalled(); + }); + + it('falls back to the guardian phone and skips members without a usable one', async () => { + db.payment.findMany.mockResolvedValue([ + payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }), + payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }), + ]); + + const totals = await reminders(fakeProvider()).execute(); + + expect(totals).toEqual({ sent: 1, skipped: 1, failed: 0 }); + expect(db.outboundMessage.create.mock.calls[1]?.[0]).toMatchObject({ + data: { attendeeId: 'att-2', status: 'SKIPPED', errorCode: 'invalid_phone' }, + }); + }); + + it('logs numbers without WhatsApp as skipped', async () => { + db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]); + const provider = fakeProvider({ + resolveRecipient: mock(async () => ({ ok: false as const, code: 'no_whatsapp' as const })), + }); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 }); + expect(db.outboundMessage.create.mock.calls[0]?.[0]).toMatchObject({ + data: { status: 'SKIPPED', errorCode: 'no_whatsapp' }, + }); + expect(provider.send).not.toHaveBeenCalled(); + }); + + it('skips owners whose templates are not approved yet', async () => { + db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]); + const provider = fakeProvider({ readiness: mock(async () => 'pending' as const) }); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 }); + expect(db.payment.findMany).not.toHaveBeenCalled(); + }); + + it('paces sends and keeps going after a failure', async () => { + db.payment.findMany.mockResolvedValue([ + payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }), + payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }), + payment('pay-3', { id: 'att-3', fullName: 'Caro', phone: '1123456783' }), + ]); + const send = mock(async () => ({ ok: true as const, providerMessageId: 'wamid' })); + send.mockResolvedValueOnce({ ok: true, providerMessageId: 'wamid-a' }); + send.mockResolvedValueOnce({ + ok: false, + retryable: true, + code: 'http_500', + message: 'engine error', + } as never); + const provider = fakeProvider({ send }); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 2, skipped: 0, failed: 1 }); + expect(sleep).toHaveBeenCalledTimes(2); + expect(sleep).toHaveBeenCalledWith(5000); + expect(db.outboundMessage.update).toHaveBeenCalledWith({ + where: { id: 'msg-2' }, + data: { status: 'FAILED', errorCode: 'http_500', errorMessage: 'engine error' }, + }); + }); + + it('stops the account when the gateway rate limits it, freeing the unsent row', async () => { + db.payment.findMany.mockResolvedValue([ + payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }), + payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }), + ]); + const send = mock(async () => ({ + ok: false as const, + retryable: true, + rateLimitedForMs: 60_000, + code: 'SEND_PACING_LIMITED', + message: 'cap', + })); + const provider = fakeProvider({ send }); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 }); + expect(send).toHaveBeenCalledTimes(1); + expect(db.outboundMessage.delete).toHaveBeenCalledWith({ where: { id: 'msg-1' } }); + }); + + it('does nothing when no group has the automation on', async () => { + db.group.findMany.mockResolvedValue([]); + const provider = fakeProvider(); + + const totals = await reminders(provider).execute(); + + expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 }); + expect(provider.readiness).not.toHaveBeenCalled(); + }); +}); + +describe('re-engagement messages', () => { + function atRiskGroup() { + // Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM). + const s1 = new Date('2026-10-16T10:00:00Z'); + const s2 = new Date('2026-10-14T10:00:00Z'); + const enrolled = new Date('2026-09-01T10:00:00Z'); + db.classSession.findMany.mockResolvedValue([ + { id: 's1', startsAt: s1 }, + { id: 's2', startsAt: s2 }, + ]); + db.attendee.findMany + .mockResolvedValueOnce([ + { id: 'att-1', person: { fullName: 'Ana López', phone: '1123456789' }, createdAt: enrolled }, + { id: 'att-2', person: { fullName: 'Beto', phone: '1198765432' }, createdAt: enrolled }, + ]) + .mockResolvedValueOnce([ + { id: 'att-1', person: { phone: '1123456789', guardianPhone: null } }, + ]); + db.attendance.findMany.mockResolvedValue([ + { attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } }, + { attendeeId: 'att-1', classSessionId: 's2', status: 'ABSENT', classSession: { startsAt: s2 } }, + { attendeeId: 'att-2', classSessionId: 's1', status: 'PRESENT', classSession: { startsAt: s1 } }, + { attendeeId: 'att-2', classSessionId: 's2', status: 'PRESENT', classSession: { startsAt: s2 } }, + ]); + } + + it('writes to the members at risk, with the copy of the manual button', async () => { + atRiskGroup(); + const provider = fakeProvider(); + + const totals = await reengagement(provider).execute(); + + expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { autoReengagement: true } }); + expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 }); + const [, , message] = (provider.send as ReturnType).mock.calls[0] ?? []; + expect(message).toEqual({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga Martes' }); + }); + + it('leaves alone members written to in the last 14 days', async () => { + atRiskGroup(); + db.outboundMessage.findMany.mockResolvedValue([{ attendeeId: 'att-1' }]); + const provider = fakeProvider(); + + const totals = await reengagement(provider).execute(); + + expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 }); + expect(db.outboundMessage.findMany.mock.calls[0]?.[0]).toMatchObject({ + where: { + kind: 'REENGAGEMENT', + attendeeId: { in: ['att-1'] }, + status: { in: ['SENT', 'DELIVERED', 'READ'] }, + createdAt: { gte: new Date('2026-10-05T13:00:00.000Z') }, + }, + }); + expect(provider.send).not.toHaveBeenCalled(); + }); +}); + +describe('helpers', () => { + it('keys messages by ISO week', () => { + expect(isoWeekKey(new Date('2026-10-19T13:00:00Z'))).toBe('2026-W43'); + expect(isoWeekKey(new Date('2026-10-25T23:59:00Z'))).toBe('2026-W43'); + expect(isoWeekKey(new Date('2027-01-01T10:00:00Z'))).toBe('2026-W53'); + expect(isoWeekKey(new Date('2025-12-29T10:00:00Z'))).toBe('2026-W01'); + }); + + it('renders the free-text messages with the first name', () => { + expect( + renderMessage({ + kind: 'PAYMENT_REMINDER', + studentName: 'Ana López', + groupName: 'Yoga', + amount: '$ 25.000', + dueDate: '20/10', + paymentLink: 'https://mpago.la/x', + }), + ).toBe( + '¡Hola Ana! Te recordamos el pago de Yoga por $ 25.000, con vencimiento el 20/10. ' + + 'Podés pagarlo desde este link: https://mpago.la/x', + ); + expect(renderMessage({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' })).toStartWith( + '¡Hola Ana! 👋 Te extrañamos en Yoga.', + ); + }); +}); + +describe('toWhatsappE164', () => { + it.each([ + ['11 2345-6789', 'AR', '+5491123456789'], + ['011 15 2345-6789', 'AR', '+5491123456789'], + ['0351 15 123-4567', 'AR', '+5493511234567'], + ['9 11 2345 6789', 'AR', '+5491123456789'], + ['5491123456789', 'AR', '+5491123456789'], + ['+54 11 2345 6789', 'AR', '+5491123456789'], + ['+34 612 345 678', 'AR', '+34612345678'], + ['0034612345678', 'AR', '+34612345678'], + ['(11) 98765-4321', 'BR', '+5511987654321'], + ['9 8765 4321', 'CL', '+56987654321'], + ['300 123 4567', 'CO', '+573001234567'], + ['55 1234 5678', 'MX', '+525512345678'], + ['987 654 321', 'PE', '+51987654321'], + ['099 123 456', 'UY', '+59899123456'], + ] as const)('%s (%s) → %s', (input, country, expected) => { + expect(toWhatsappE164(input, country)).toBe(expected); + }); + + it.each([['', 'AR'], ['1234', 'AR'], ['12 3456', 'MX'], ['abc', 'UY']] as const)( + 'rejects %p (%s)', + (input, country) => { + expect(toWhatsappE164(input, country)).toBeNull(); + }, + ); + + it('assumes Argentina when the teacher has no country yet', () => { + expect(toWhatsappE164('11 2345 6789', null)).toBe('+5491123456789'); + }); +}); diff --git a/apps/backend/test/whatsapp-providers.test.ts b/apps/backend/test/whatsapp-providers.test.ts new file mode 100644 index 0000000..25224f9 --- /dev/null +++ b/apps/backend/test/whatsapp-providers.test.ts @@ -0,0 +1,641 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { createHmac } from 'node:crypto'; +import { KapsoProvider } from '@/modules/whatsapp/providers/kapso'; +import type { WhatsappAccountRecord } from '@/modules/whatsapp/providers/messaging-provider'; +import { OpenWaProvider, openWaSessionName } from '@/modules/whatsapp/providers/openwa'; + +/* Both adapters against a recorded `fetch`: the requests they make and how they + read the answers. No network, no `mock.module`. */ + +type Route = { method: string; path: string; status?: number; body?: unknown }; + +function fakeFetch(routes: Route[]) { + const calls: { method: string; url: string; headers: Record; body: unknown }[] = []; + const fn = mock(async (url: string, init?: RequestInit) => { + const method = init?.method ?? 'GET'; + calls.push({ + method, + url, + headers: (init?.headers ?? {}) as Record, + body: init?.body ? JSON.parse(String(init.body)) : undefined, + }); + const route = routes.find((candidate) => candidate.method === method && url.endsWith(candidate.path)); + if (!route) return new Response(JSON.stringify({ statusCode: 404 }), { status: 404 }); + return new Response(route.body === undefined ? null : JSON.stringify(route.body), { + status: route.status ?? 200, + }); + }); + return { fn, calls }; +} + +const openWaConfig = { + apiUrl: 'http://openwa:2785/api', + apiKey: 'owa_k1_test', + webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/openwa', + webhookSecret: 'a-very-long-webhook-secret', +}; + +function openWaAccount(overrides: Partial = {}): WhatsappAccountRecord { + return { + id: 'wa-1', + ownerId: 'user-1', + provider: 'OPENWA', + status: 'ACTIVE', + externalId: 'sess-1', + displayPhoneNumber: null, + providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' }, + ...overrides, + }; +} + +function sign(body: string, secret: string) { + return createHmac('sha256', secret).update(body).digest('hex'); +} + +describe('OpenWA provider', () => { + it('creates a session, subscribes the webhook, starts it and returns the QR', async () => { + const { fn, calls } = fakeFetch([ + { + method: 'POST', + path: '/sessions', + status: 201, + body: { id: 'sess-1', name: 'gruperly-user-1', status: 'created', engineLoaded: false }, + }, + { method: 'POST', path: '/sessions/sess-1/webhooks', status: 201, body: { id: 'wh-1' } }, + { + method: 'POST', + path: '/sessions/sess-1/start', + body: { id: 'sess-1', name: 'gruperly-user-1', status: 'initializing', engineLoaded: true }, + }, + { method: 'GET', path: '/sessions/sess-1/qr', body: { qrCode: 'data:image/png;base64,QR', status: 'qr_ready' } }, + ]); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn }); + + const result = await provider.startConnection({ + ownerId: 'user-1', + ownerName: 'Ana', + returnTo: 'settings', + account: null, + }); + + expect(result).toEqual({ + ok: true, + value: { + start: { type: 'qr', qrCode: 'data:image/png;base64,QR' }, + externalId: 'sess-1', + providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' }, + }, + }); + expect(calls[0]).toMatchObject({ method: 'POST', body: { name: 'gruperly-user-1' } }); + expect(calls[0]?.headers['X-API-Key']).toBe('owa_k1_test'); + expect(calls[1]?.body).toMatchObject({ + url: openWaConfig.webhookUrl, + secret: openWaConfig.webhookSecret, + events: expect.arrayContaining(['message.ack', 'session.authenticated']), + }); + }); + + it('adopts a session that already exists under the teacher name', async () => { + const { fn } = fakeFetch([ + { method: 'POST', path: '/sessions', status: 409, body: { statusCode: 409 } }, + { + method: 'GET', + path: '/sessions?name=gruperly-user-1', + body: [{ id: 'sess-9', name: 'gruperly-user-1', status: 'qr_ready', engineLoaded: true }], + }, + { method: 'POST', path: '/sessions/sess-9/webhooks', status: 201, body: { id: 'wh-9' } }, + { method: 'GET', path: '/sessions/sess-9/qr', status: 400, body: { statusCode: 400 } }, + ]); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn }); + + const result = await provider.startConnection({ + ownerId: 'user-1', + ownerName: 'Ana', + returnTo: 'settings', + account: null, + }); + + expect(result.ok && result.value).toMatchObject({ + start: { type: 'qr', qrCode: null }, + externalId: 'sess-9', + }); + }); + + it('answers a provider problem when OpenWA is down', async () => { + const fn = mock(async () => { + throw new TypeError('fetch failed'); + }); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn }); + + const result = await provider.startConnection({ + ownerId: 'user-1', + ownerName: 'Ana', + returnTo: 'settings', + account: null, + }); + + expect(!result.ok && result.error.code).toBe('whatsapp_provider_error'); + }); + + it('maps session states', async () => { + const cases = [ + [{ status: 'ready', phone: '5491123456789', engineLoaded: true }, { state: 'active', displayPhoneNumber: '+5491123456789' }], + [{ status: 'initializing', engineLoaded: true }, { state: 'pending', qrCode: null }], + [{ status: 'disconnected', engineLoaded: true }, { state: 'pending', qrCode: null }], + [{ status: 'failed', lastError: 'boom', engineLoaded: false }, { state: 'disconnected', reason: 'boom' }], + ] as const; + + for (const [session, expected] of cases) { + const { fn } = fakeFetch([{ method: 'GET', path: '/sessions/sess-1', body: { id: 'sess-1', ...session } }]); + const result = await new OpenWaProvider(openWaConfig, { fetch: fn }).refreshConnection( + openWaAccount({ status: 'PENDING' }), + ); + expect(result).toEqual({ ok: true, value: expected as never }); + } + }); + + it('resolves recipients through the contact check', async () => { + const { fn, calls } = fakeFetch([ + { + method: 'GET', + path: '/sessions/sess-1/contacts/check/5491123456789', + body: { exists: true, whatsappId: '541123456789@c.us' }, + }, + ]); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn }); + + expect(await provider.resolveRecipient(openWaAccount(), '+5491123456789')).toEqual({ + ok: true, + to: '541123456789@c.us', + }); + expect(calls).toHaveLength(1); + }); + + it('sends free text with an idempotency key', async () => { + const { fn, calls } = fakeFetch([ + { + method: 'POST', + path: '/sessions/sess-1/messages/send-text', + status: 201, + body: { messageId: 'true_5491123456789@c.us_3EB0', timestamp: 1 }, + }, + ]); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn }); + + const outcome = await provider.send( + openWaAccount(), + '5491123456789@c.us', + { kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' }, + 'msg-1', + ); + + expect(outcome).toEqual({ ok: true, providerMessageId: 'true_5491123456789@c.us_3EB0' }); + expect(calls[0]?.headers['Idempotency-Key']).toBe('msg-1'); + expect(calls[0]?.body).toMatchObject({ chatId: '5491123456789@c.us' }); + expect(String((calls[0]?.body as { text?: string } | undefined)?.text)).toStartWith('¡Hola Ana!'); + }); + + it('turns send pacing into a rate limit for the account', async () => { + const { fn } = fakeFetch([ + { + method: 'POST', + path: '/sessions/sess-1/messages/send-text', + status: 429, + body: { statusCode: 429, code: 'SEND_PACING_LIMITED', retryAfterSeconds: 120 }, + }, + ]); + const outcome = await new OpenWaProvider(openWaConfig, { fetch: fn }).send( + openWaAccount(), + 'x@c.us', + { kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' }, + 'msg-1', + ); + + expect(outcome).toMatchObject({ ok: false, rateLimitedForMs: 120_000, code: 'SEND_PACING_LIMITED' }); + }); + + it('verifies the webhook signature and normalizes acks and session events', () => { + const provider = new OpenWaProvider(openWaConfig); + const ack = JSON.stringify({ + event: 'message.ack', + sessionId: 'sess-1', + idempotencyKey: 'ack_sess-1_m1_read', + deliveryId: 'dlv_1', + data: { id: 'row', messageId: 'm1', status: 'read', ack: 3 }, + }); + const good = new Headers({ + 'X-OpenWA-Signature': `sha256=${sign(ack, openWaConfig.webhookSecret)}`, + 'X-OpenWA-Idempotency-Key': 'ack_sess-1_m1_read', + }); + + expect(provider.parseWebhook(ack, good)).toEqual({ + ok: true, + value: { + dedupeKey: 'ack_sess-1_m1_read', + events: [{ type: 'message_status', providerMessageId: 'm1', status: 'READ', errorCode: null }], + }, + }); + + const tampered = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(`${ack} `, openWaConfig.webhookSecret)}` }); + expect(provider.parseWebhook(ack, tampered)).toEqual({ ok: false, error: 'invalid_signature' }); + expect(provider.parseWebhook(ack, new Headers())).toEqual({ ok: false, error: 'invalid_signature' }); + + const auth = JSON.stringify({ + event: 'session.authenticated', + sessionId: 'sess-1', + idempotencyKey: 'auth_1', + data: { sessionId: 'sess-1', phone: '5491123456789' }, + }); + const authHeaders = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(auth, openWaConfig.webhookSecret)}` }); + expect(provider.parseWebhook(auth, authHeaders)).toEqual({ + ok: true, + value: { + dedupeKey: 'auth_1', + events: [ + { type: 'connection', externalId: 'sess-1', status: 'active', displayPhoneNumber: '+5491123456789' }, + ], + }, + }); + }); + + it('builds valid session names', () => { + expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd'); + expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars'); + }); + + it('asks OpenWA for a pairing code with the digits of the number', async () => { + const { fn, calls } = fakeFetch([ + { + method: 'POST', + path: '/sessions/sess-1/pairing-code', + status: 201, + body: { pairingCode: 'ABCD1234', status: 'qr_ready' }, + }, + ]); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn }); + + const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789'); + + expect(result).toEqual({ ok: true, value: 'ABCD1234' }); + expect(calls[0]?.body).toEqual({ phoneNumber: '5491123456789' }); + }); + + it('waits while the session is not ready for a code, then gives up with 409', async () => { + let answered = 0; + const fn = mock(async () => { + answered += 1; + return answered < 3 + ? new Response(JSON.stringify({ statusCode: 409 }), { status: 409 }) + : new Response(JSON.stringify({ pairingCode: 'WXYZ9876' }), { status: 201 }); + }); + const sleep = mock(async () => {}); + const provider = new OpenWaProvider(openWaConfig, { fetch: fn, sleep }); + + const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789'); + + expect(result).toEqual({ ok: true, value: 'WXYZ9876' }); + expect(sleep).toHaveBeenCalledTimes(2); + + const busy = mock(async () => new Response(JSON.stringify({ statusCode: 409 }), { status: 409 })); + const stuck = new OpenWaProvider(openWaConfig, { fetch: busy, sleep }); + const failed = await stuck.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789'); + + expect(failed.ok).toBe(false); + if (!failed.ok) expect(failed.error.code).toBe('whatsapp_pairing_not_ready'); + }); +}); + +const kapsoConfig = { + apiUrl: 'https://api.kapso.ai', + apiKey: 'kapso-key', + callbackUrl: 'https://api.example.com/api/v1/whatsapp/callback', + webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/kapso', + webhookSecret: 'kapso-webhook-secret', +}; + +function kapsoAccount(overrides: Partial = {}): WhatsappAccountRecord { + return { + id: 'wa-1', + ownerId: 'user-1', + provider: 'KAPSO', + status: 'PENDING', + externalId: null, + displayPhoneNumber: null, + providerData: { customerId: 'cust-1', setupLinkId: 'link-1' }, + ...overrides, + }; +} + +function kapsoDb() { + return { + whatsappAccount: { update: mock(async () => ({})) }, + whatsappTemplate: { + findUnique: mock(async () => null as unknown), + findMany: mock(async () => [] as unknown[]), + create: mock(async () => ({})), + update: mock(async () => ({})), + }, + }; +} + +describe('Kapso provider', () => { + it('creates the customer once and a customer-billed setup link', async () => { + const { fn, calls } = fakeFetch([ + { method: 'POST', path: '/platform/v1/customers', status: 201, body: { data: { id: 'cust-1' } } }, + { + method: 'POST', + path: '/platform/v1/customers/cust-1/setup_links', + status: 201, + body: { data: { id: 'link-1', url: 'https://app.kapso.ai/whatsapp/setup/abc' } }, + }, + ]); + const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }); + + const result = await provider.startConnection({ + ownerId: 'user-1', + ownerName: 'Ana Profe', + returnTo: 'onboarding', + account: null, + }); + + expect(result).toEqual({ + ok: true, + value: { + start: { type: 'redirect', url: 'https://app.kapso.ai/whatsapp/setup/abc' }, + externalId: null, + providerData: { customerId: 'cust-1', setupLinkId: 'link-1' }, + }, + }); + expect(calls[0]?.body).toEqual({ customer: { name: 'Ana Profe', external_customer_id: 'user-1' } }); + expect(calls[1]?.body).toMatchObject({ + setup_link: { + success_redirect_url: `${kapsoConfig.callbackUrl}?returnTo=onboarding`, + meta_billing_mode: 'customer_managed', + language: 'es', + }, + }); + + // Linking again reuses the customer. + const again = fakeFetch([ + { + method: 'POST', + path: '/platform/v1/customers/cust-1/setup_links', + status: 201, + body: { data: { id: 'link-2', url: 'https://app.kapso.ai/whatsapp/setup/def' } }, + }, + ]); + await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: again.fn }).startConnection({ + ownerId: 'user-1', + ownerName: 'Ana', + returnTo: 'settings', + account: kapsoAccount(), + }); + expect(again.calls).toHaveLength(1); + }); + + it('does not trust the callback query', async () => { + const { fn } = fakeFetch([ + { + method: 'GET', + path: '/platform/v1/whatsapp/phone_numbers/phone-1', + body: { + data: { + phone_number_id: 'phone-1', + business_account_id: 'waba-1', + display_phone_number: '+54 9 11 2345-6789', + customer_id: 'someone-else', + }, + }, + }, + ]); + const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }); + + expect( + await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'other', phone_number_id: 'phone-1' }), + ).toEqual({ ok: false, error: 'invalid_setup' }); + expect( + await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'link-1', error_code: 'facebook_auth_failed' }), + ).toEqual({ ok: false, error: 'setup_failed' }); + expect( + await provider.completeRedirect(kapsoAccount(), { + setup_link_id: 'link-1', + status: 'completed', + phone_number_id: 'phone-1', + }), + ).toEqual({ ok: false, error: 'invalid_setup' }); + }); + + it('completes a setup confirmed by Kapso', async () => { + const { fn } = fakeFetch([ + { + method: 'GET', + path: '/platform/v1/whatsapp/phone_numbers/phone-1', + body: { + data: { + phone_number_id: 'phone-1', + business_account_id: 'waba-1', + display_phone_number: '+54 9 11 2345-6789', + customer_id: 'cust-1', + }, + }, + }, + ]); + const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }); + + expect( + await provider.completeRedirect(kapsoAccount(), { + setup_link_id: 'link-1', + status: 'completed', + phone_number_id: 'phone-1', + }), + ).toEqual({ + ok: true, + value: { + externalId: 'phone-1', + displayPhoneNumber: '+5491123456789', + providerData: { customerId: 'cust-1', setupLinkId: 'link-1', businessAccountId: 'waba-1' }, + }, + }); + }); + + it('subscribes the number and submits both templates after connecting', async () => { + const { fn, calls } = fakeFetch([ + { + method: 'POST', + path: '/platform/v1/whatsapp/phone_numbers/phone-1/webhooks', + status: 201, + body: { data: { id: 'wh-1' } }, + }, + { + method: 'POST', + path: '/meta/whatsapp/v24.0/waba-1/message_templates', + body: { id: 'tpl-1', status: 'PENDING', category: 'UTILITY' }, + }, + ]); + const db = kapsoDb(); + const provider = new KapsoProvider(kapsoConfig, { db: db as never, fetch: fn }); + + await provider.onConnected( + kapsoAccount({ + status: 'ACTIVE', + externalId: 'phone-1', + providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' }, + }), + ); + + expect(calls[0]?.body).toMatchObject({ + whatsapp_webhook: { url: kapsoConfig.webhookUrl, secret_key: kapsoConfig.webhookSecret, kind: 'kapso' }, + }); + const templates = calls.filter((call) => call.url.endsWith('/message_templates')); + expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([ + expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }), + expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }), + ]); + expect(db.whatsappAccount.update).toHaveBeenCalledWith({ + where: { id: 'wa-1' }, + data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } }, + }); + expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(2); + }); + + it('is ready only once the template is approved', async () => { + const db = kapsoDb(); + const provider = new KapsoProvider(kapsoConfig, { db: db as never }); + const active = kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }); + + db.whatsappTemplate.findUnique.mockResolvedValueOnce(null); + expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('pending'); + db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'APPROVED' }); + expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('ready'); + db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'REJECTED' }); + expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('blocked'); + expect(await provider.readiness(kapsoAccount(), 'PAYMENT_REMINDER')).toBe('blocked'); + }); + + it('sends the approved template with named parameters', async () => { + const { fn, calls } = fakeFetch([ + { + method: 'POST', + path: '/meta/whatsapp/v24.0/phone-1/messages', + body: { messaging_product: 'whatsapp', messages: [{ id: 'wamid.ABC' }] }, + }, + ]); + const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }); + + const outcome = await provider.send( + kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }), + '5491123456789', + { + kind: 'PAYMENT_REMINDER', + studentName: 'Ana López', + groupName: 'Yoga', + amount: '$ 25.000', + dueDate: '20/10', + paymentLink: 'https://mpago.la/x', + }, + 'msg-1', + ); + + expect(outcome).toEqual({ ok: true, providerMessageId: 'wamid.ABC' }); + expect(calls[0]?.body).toMatchObject({ + to: '5491123456789', + type: 'template', + template: { + name: 'gruperly_payment_reminder', + language: { code: 'es_AR' }, + components: [ + { + type: 'body', + parameters: expect.arrayContaining([ + { type: 'text', parameter_name: 'student_name', text: 'Ana' }, + { type: 'text', parameter_name: 'payment_link', text: 'https://mpago.la/x' }, + ]), + }, + ], + }, + }); + }); + + it('does not retry a marketing opt-out', async () => { + const { fn } = fakeFetch([ + { + method: 'POST', + path: '/meta/whatsapp/v24.0/phone-1/messages', + status: 422, + body: { error: { code: 'marketing_preference_stopped' } }, + }, + ]); + const outcome = await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }).send( + kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }), + '5491123456789', + { kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' }, + 'msg-1', + ); + + expect(outcome).toMatchObject({ ok: false, retryable: false, code: 'marketing_preference_stopped' }); + }); + + it('verifies the webhook and normalizes number and message events', () => { + const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never }); + const created = JSON.stringify({ + phone_number_id: 'phone-1', + business_account_id: 'waba-1', + display_phone_number: '+54 9 11 2345 6789', + customer: { id: 'cust-1', external_id: 'user-1' }, + }); + const headers = new Headers({ + 'X-Webhook-Signature': sign(created, kapsoConfig.webhookSecret), + 'X-Webhook-Event': 'whatsapp.phone_number.created', + 'X-Idempotency-Key': 'idem-1', + }); + + expect(provider.parseWebhook(created, headers)).toEqual({ + ok: true, + value: { + dedupeKey: 'idem-1', + events: [ + { + type: 'connection', + externalId: 'phone-1', + ownerId: 'user-1', + status: 'active', + displayPhoneNumber: '+5491123456789', + providerData: { businessAccountId: 'waba-1' }, + }, + ], + }, + }); + + const failed = JSON.stringify({ + phone_number_id: 'phone-1', + message: { + id: 'wamid.ABC', + kapso: { status: 'failed', statuses: [{ status: 'failed', errors: [{ code: 131026, title: 'Undeliverable' }] }] }, + }, + }); + const failedHeaders = new Headers({ + 'X-Webhook-Signature': sign(failed, kapsoConfig.webhookSecret), + 'X-Webhook-Event': 'whatsapp.message.failed', + 'X-Idempotency-Key': 'idem-2', + }); + expect(provider.parseWebhook(failed, failedHeaders)).toEqual({ + ok: true, + value: { + dedupeKey: 'idem-2', + events: [ + { + type: 'message_status', + providerMessageId: 'wamid.ABC', + status: 'FAILED', + errorCode: '131026', + errorMessage: 'Undeliverable', + }, + ], + }, + }); + + expect( + provider.parseWebhook(created, new Headers({ 'X-Webhook-Signature': 'deadbeef', 'X-Idempotency-Key': 'x' })), + ).toEqual({ ok: false, error: 'invalid_signature' }); + }); +}); diff --git a/apps/web/bunfig.toml b/apps/web/bunfig.toml new file mode 100644 index 0000000..4d01a7b --- /dev/null +++ b/apps/web/bunfig.toml @@ -0,0 +1,3 @@ +[test] +# Inicializa i18n en es-AR: los tests asertan el copy en español. +preload = ["./test/setup.ts"] diff --git a/apps/web/index.html b/apps/web/index.html index 55e9213..ddce394 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -2,8 +2,34 @@ - + + Gruperly + + + + + + + + + + +
diff --git a/apps/web/nginx.conf b/apps/web/nginx.conf new file mode 100644 index 0000000..8a47b81 --- /dev/null +++ b/apps/web/nginx.conf @@ -0,0 +1,70 @@ +# Nginx para el build de @gruperly/web. +# Sirve los assets estáticos y hace de proxy de /api hacia el servicio `api`. +# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión +# es first-party y el CORS del backend queda como red de seguridad. + +# DNS interno de Docker: resuelve `api` en cada request, así el proxy sobrevive +# a un recreate del contenedor (que cambia la IP). +resolver 127.0.0.11 valid=10s ipv6=off; + +server { + listen 80; + server_name _; + + root /usr/share/nginx/html; + index index.html; + + client_max_body_size 10m; + + # ── API ──────────────────────────────────────────────────────────────────── + location /api/ { + set $api http://api:4000; + proxy_pass $api$request_uri; + + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header Connection ""; + + proxy_connect_timeout 10s; + proxy_read_timeout 60s; + } + + # ── Assets con hash en el nombre ─────────────────────────────────────────── + # Solo `add_header`: `expires` agregaría un segundo Cache-Control. + location /assets/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + + # ── Service worker y manifest ───────────────────────────────────────────── + # Nunca se cachean: el navegador tiene que ver la versión nueva en el próximo + # load. `=404` y no el fallback del SPA, porque un 404 del SW debe ser un 404. + location = /manifest.webmanifest { + # `mime.types` de alpine no conoce `webmanifest` y lo sirve como + # octet-stream. Un `types` acá reemplaza el mapa heredado, pero esta location + # solo sirve un archivo, así que no puede romper nada más. + types { application/manifest+json webmanifest; } + default_type application/manifest+json; + add_header Cache-Control "no-cache"; + try_files $uri =404; + } + + location ~ ^/(sw\.js|workbox-[^/]+\.js)$ { + add_header Cache-Control "no-cache"; + try_files $uri =404; + } + + # ── SPA ──────────────────────────────────────────────────────────────────── + location = /index.html { + add_header Cache-Control "no-cache"; + } + + location / { + add_header Cache-Control "no-cache"; + try_files $uri $uri/ /index.html; + } +} diff --git a/apps/web/package.json b/apps/web/package.json index d1620ca..b75b53c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,31 +7,41 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "typecheck": "tsc --noEmit" + "icons": "bun run scripts/generate-icons.ts", + "typecheck": "tsc --noEmit", + "test": "bun test" }, "dependencies": { "@better-auth/passkey": "^1.7.2", + "@fontsource-variable/inter": "^5.3.0", "@gruperly/shared": "workspace:*", "@hookform/resolvers": "^3.9.0", + "@simplewebauthn/browser": "13.3.0", "@tanstack/react-query": "^5.62.0", - "@tanstack/react-router": "^1.90.0", + "@tanstack/react-router": "^1.170.38", "better-auth": "1.7.2", "clsx": "^2.1.1", + "i18next": "^26.5.11", "lucide-react": "^1.34.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-hook-form": "^7.54.0", + "react-i18next": "^17.1.9", "tailwind-merge": "^3.6.0", "zod": "3.24.2" }, "devDependencies": { "@gruperly/config": "workspace:*", "@tailwindcss/vite": "^4.3.3", + "@tanstack/router-plugin": "^1.168.40", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.0", + "sharp": "^0.35.4", "tailwindcss": "^4.0.0", "typescript": "^5.7.0", - "vite": "^6.0.0" + "vite": "^6.0.0", + "vite-plugin-pwa": "^1.3.0", + "workbox-window": "^7.4.1" } } diff --git a/apps/web/public/apple-touch-icon-180.png b/apps/web/public/apple-touch-icon-180.png new file mode 100644 index 0000000..bf4c013 Binary files /dev/null and b/apps/web/public/apple-touch-icon-180.png differ diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 0000000..56d29ed --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1,12 @@ + + Gruperly + + + + \ No newline at end of file diff --git a/apps/web/public/pwa-192x192.png b/apps/web/public/pwa-192x192.png new file mode 100644 index 0000000..206ff3e Binary files /dev/null and b/apps/web/public/pwa-192x192.png differ diff --git a/apps/web/public/pwa-512x512.png b/apps/web/public/pwa-512x512.png new file mode 100644 index 0000000..ff74991 Binary files /dev/null and b/apps/web/public/pwa-512x512.png differ diff --git a/apps/web/public/pwa-maskable-512x512.png b/apps/web/public/pwa-maskable-512x512.png new file mode 100644 index 0000000..db1319a Binary files /dev/null and b/apps/web/public/pwa-maskable-512x512.png differ diff --git a/apps/web/scripts/generate-icons.ts b/apps/web/scripts/generate-icons.ts new file mode 100644 index 0000000..ba92f48 --- /dev/null +++ b/apps/web/scripts/generate-icons.ts @@ -0,0 +1,66 @@ +/** + * Generates the PWA icon set from the brand isotype SVG. + * + * Usage: bun --filter @gruperly/web icons + * + * The outputs are versioned in `public/`; the Vite build does not regenerate + * them (sharp is a devDependency and must not end up in the Docker image). + * Re-run only when `src/assets/brand/isotipo-y-organica.svg` changes. + */ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import sharp from 'sharp' + +const webDir = dirname(dirname(fileURLToPath(import.meta.url))) +const source = join(webDir, 'src/assets/brand/isotipo-y-organica.svg') +const publicDir = join(webDir, 'public') + +/** Light theme background; it also serves as the canvas for opaque icons. */ +const BACKGROUND = '#ffffff' +const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const + +type IconTarget = { + file: string + size: number + /** Fills the canvas with `BACKGROUND` instead of leaving it transparent. */ + opaque: boolean + /** Fraction of the side the logo takes up. 1 = no padding. */ + contentRatio: number +} + +const targets: IconTarget[] = [ + { file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 }, + { file: 'pwa-512x512.png', size: 512, opaque: false, contentRatio: 0.9 }, + // Android crops adaptive icons in a circle: the useful content lives in the + // central 80% of the canvas, so the logo goes on white and scaled. + { file: 'pwa-maskable-512x512.png', size: 512, opaque: true, contentRatio: 0.8 }, + { file: 'apple-touch-icon-180.png', size: 180, opaque: true, contentRatio: 0.82 }, +] + +// The isotype viewBox does not start at 0 and leaves air around the glyph: +// `trim` crops that margin so the framing uses the drawing's real area. +const logo = await sharp(await readFile(source), { density: 512 }) + .trim({ threshold: 1 }) + .png() + .toBuffer() + +await mkdir(publicDir, { recursive: true }) + +for (const { file, size, opaque, contentRatio } of targets) { + const box = Math.round(size * contentRatio) + const layer = await sharp(logo) + .resize(box, box, { fit: 'inside' }) + .png() + .toBuffer() + + const output = await sharp({ + create: { width: size, height: size, channels: 4, background: opaque ? BACKGROUND : TRANSPARENT }, + }) + .composite([{ input: layer, gravity: 'center' }]) + .png({ compressionLevel: 9 }) + .toBuffer() + + await writeFile(join(publicDir, file), output) + console.log(`${file.padEnd(28)} ${size}x${size} ${(output.byteLength / 1024).toFixed(1)} KB`) +} diff --git a/apps/web/src/assets/brand/isotipo-y-organica-oscuro.svg b/apps/web/src/assets/brand/isotipo-y-organica-oscuro.svg new file mode 100644 index 0000000..1ac5bc2 --- /dev/null +++ b/apps/web/src/assets/brand/isotipo-y-organica-oscuro.svg @@ -0,0 +1,6 @@ + + Gruperly — isotipo y orgánica + Y orgánica con rama corta blanco azulado #EEF4FF y diagonal larga celeste #93B4FD, separadas, sobre fondo transparente. + + + \ No newline at end of file diff --git a/apps/web/src/assets/brand/isotipo-y-organica.svg b/apps/web/src/assets/brand/isotipo-y-organica.svg new file mode 100644 index 0000000..a7f9dcd --- /dev/null +++ b/apps/web/src/assets/brand/isotipo-y-organica.svg @@ -0,0 +1,6 @@ + + Gruperly — isotipo y orgánica + Y orgánica con rama corta azul noche #171D54 y diagonal larga celeste #93B4FD, separadas, sobre fondo transparente. + + + \ No newline at end of file diff --git a/apps/web/src/assets/brand/logotipo-y-organica-oscuro.svg b/apps/web/src/assets/brand/logotipo-y-organica-oscuro.svg new file mode 100644 index 0000000..2335bda --- /dev/null +++ b/apps/web/src/assets/brand/logotipo-y-organica-oscuro.svg @@ -0,0 +1,7 @@ + +Gruperly — y orgánica bicolor +Rama corta azul noche y diagonal larga celeste, separadas, con curvas suaves y terminales redondeados. + + + + \ No newline at end of file diff --git a/apps/web/src/assets/brand/logotipo-y-organica.svg b/apps/web/src/assets/brand/logotipo-y-organica.svg new file mode 100644 index 0000000..5a4f989 --- /dev/null +++ b/apps/web/src/assets/brand/logotipo-y-organica.svg @@ -0,0 +1,7 @@ + +Gruperly — y orgánica bicolor +Rama corta azul noche y diagonal larga celeste, separadas, con curvas suaves y terminales redondeados. + + + + \ No newline at end of file diff --git a/apps/web/src/components/auth/index.ts b/apps/web/src/components/auth/index.ts deleted file mode 100644 index ecfc46d..0000000 --- a/apps/web/src/components/auth/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { AuthShell } from './AuthShell' \ No newline at end of file diff --git a/apps/web/src/components/brand/Logo.tsx b/apps/web/src/components/brand/Logo.tsx index 514b481..22e5512 100644 --- a/apps/web/src/components/brand/Logo.tsx +++ b/apps/web/src/components/brand/Logo.tsx @@ -1,23 +1,35 @@ -import { forwardRef, type HTMLAttributes } from 'react' +import { forwardRef, type SVGProps } from 'react' import { cn } from '../../lib/utils' -export type LogoProps = Omit, 'children'> & { - className?: string -} +export type LogoProps = SVGProps -export const Logo = forwardRef( +export const Logo = forwardRef( ({ className, ...props }, ref) => { return ( - - gruperl - y - + Gruperly + + + + ) }, ) -Logo.displayName = 'Logo' +Logo.displayName = 'Logo' \ No newline at end of file diff --git a/apps/web/src/components/brand/LogoIcon.tsx b/apps/web/src/components/brand/LogoIcon.tsx index 2250e30..e3993aa 100644 --- a/apps/web/src/components/brand/LogoIcon.tsx +++ b/apps/web/src/components/brand/LogoIcon.tsx @@ -10,30 +10,24 @@ export const LogoIcon = forwardRef( return ( - Gruperly + - ) }, ) -LogoIcon.displayName = 'LogoIcon' +LogoIcon.displayName = 'LogoIcon' \ No newline at end of file diff --git a/apps/web/src/components/layout/AppLayoutGuard.tsx b/apps/web/src/components/layout/AppLayoutGuard.tsx new file mode 100644 index 0000000..79f5718 --- /dev/null +++ b/apps/web/src/components/layout/AppLayoutGuard.tsx @@ -0,0 +1,35 @@ +import { useEffect } from 'react' +import type { ReactNode } from 'react' +import { useQuery } from '@tanstack/react-query' +import { useNavigate } from '@tanstack/react-router' +import { Loader2 } from 'lucide-react' +import { useAuth } from '../../context/AuthProvider' +import { getOnboardingStatus } from '../../lib/api' +import { RootLayout } from './RootLayout' + +export function AppLayoutGuard({ children }: { children: ReactNode }) { + const { user, isPending } = useAuth() + const navigate = useNavigate() + + const statusQuery = useQuery({ + queryKey: ['onboarding', 'status'], + queryFn: getOnboardingStatus, + enabled: !!user, + staleTime: 5 * 60 * 1000, + }) + + useEffect(() => { + if (!user || !statusQuery.data || statusQuery.data.completed) return + void navigate({ to: '/onboarding', replace: true }) + }, [user, statusQuery.data, navigate]) + + if (isPending || (user && statusQuery.isPending)) { + return ( +
+ +
+ ) + } + + return {children} +} \ No newline at end of file diff --git a/apps/web/src/components/layout/BottomNav.tsx b/apps/web/src/components/layout/BottomNav.tsx index 5cd17a0..5cff42c 100644 --- a/apps/web/src/components/layout/BottomNav.tsx +++ b/apps/web/src/components/layout/BottomNav.tsx @@ -1,29 +1,40 @@ import { Link, useLocation } from '@tanstack/react-router' +import { useTranslation } from 'react-i18next' import { cn } from '../../lib/utils' -import { NAV_ITEMS } from './nav-items' +import { NavBadge } from './NavBadge' +import { isNavItemActive, NAV_ITEMS } from './nav-items' export function BottomNav() { const location = useLocation() + const { t } = useTranslation('layout') return ( -