34 Commits

Author SHA1 Message Date
Jose Selesan
060a4f09e4 feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)
- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo
  atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys
  opcionales (SimpleWebAuthn) y mail de recuperación con rate limit.
- Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta,
  pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil.
- Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar),
  "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de
  grupo y datos para transferir en Ajustes.
- "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas.
- Zona horaria por defecto: Buenos Aires.
- Migración add_student_access, tests contra Postgres real (test:db) y docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:39:09 -03:00
Jose Selesan
b99bc4d519 feat: rediseño de Grupos y pantalla "Requiere atención"
- Grupos: subtítulo con resumen (grupos · alumnos · lugares libres),
  sección "Requiere atención" con los 4 alumnos más urgentes y tarjetas
  con avatares (punteados por lugar libre en grupos chicos, superpuestos
  con "+N" en grandes; con alerta primero y anillo de gravedad).
- Pantalla nueva /groups/attention: filtros Todos/Asistencia/Pagos,
  secciones Urgente y A vigilar, Contactar / Enviar recordatorio por
  wa.me y "Resuelto" persistente con update optimista.
- FAB "Nuevo grupo" que se pliega al scrollear (respeta reduced motion);
  los toasts en mobile suben para no quedar debajo.
- Alertas centralizadas en computeStudentAlerts (shared). La regla de
  asistencia pasa a: urgente = 3 seguidas o 4 de las últimas 6; a vigilar
  = 2 de las últimas 4 (sin inactividad por días ni tendencia). Cuotas:
  1 vencida vigilar, 2+ urgente.
- Backend: GET /attention y POST /attention/:attendeeId/resolve; tabla
  attendee_alert_resolutions (la alerta vuelve si cambia la firma).
- Tokens de gravedad para claro y oscuro; se quita el indicador de pills.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:35:07 -03:00
Jose Selesan
90f31290d4 feat(web): pulido mobile de ficha de grupo, alumno, nuevo grupo y ajustes
- Ficha de grupo: "Agregar miembro" a todo el ancho y debajo Estadísticas,
  Cobrar y Compartir con icono y texto (antes iconos sueltos en mobile).
  Los mensajes automáticos de WhatsApp quedan en una fila plegable que
  arranca cerrada si no hay ninguno activo.
- Historial del alumno: arranca en la primera clase registrada si es
  anterior al alta, como la lista y la regla de riesgo ("1 de 5" en ambos).
- Nuevo grupo: cupo 10 por defecto, precio vacío obligatorio y foco
  inicial en el nombre.
- Ajustes: chevron en Seguridad; el botón de tema del header queda solo
  en desktop (en mobile vive en Apariencia).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:33:37 -03:00
Jose Selesan
e6d405a71e feat: una sola regla de riesgo y preinscripciones pendientes en Inicio
- Estadísticas ("Alumnos en riesgo") y el job de reenganche usan la misma
  regla de dominio que la lista de grupos e Inicio
  (summarizeMemberAttendance). El armado del historial por alumno vive en
  analytics/lib/member-attendance.ts y se borra el clasificador viejo
  (racha o asistencia mensual < 50%).
- El badge de alumnos en riesgo muestra el motivo real (faltas seguidas,
  días sin venir o asistencia en baja).
- GET /home devuelve pendingPreRegistrations por grupo (en la misma
  consulta de grupos) y "Para atender" las lista con link a la ficha en
  la pestaña Pendientes (?section=pending).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:28:21 -03:00
Jose Selesan
b12ffdda37 feat(web): rediseño de Inicio en mobile y criterio de inactividad por clases faltadas
- Inicio: saludo con fecha, estadísticas compactas en fila (arregla el
  "0 / 0 por cobrar"), sección "Para atender" (alumnos en riesgo alto y
  cobros vencidos), tarjeta de clase de hoy con CTA a todo el ancho y
  estado vacío de cobros que lleva a vincular Mercado Pago.
- Riesgo: la inactividad se mide desde la última presencia hasta la última
  clase faltada, no contra hoy; un grupo sin clases registradas ya no pone
  a todos sus miembros en riesgo alto.
- Tarjeta de grupo: el aviso usa el motivo real ("12 días sin venir") en
  vez de "0 faltas".
- Días del horario en orden de calendario (sortWeekDays).
- Toast por encima del BottomNav en mobile; ficha de alumno sin flecha de
  volver en mobile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:18:18 -03:00
Jose Selesan
9617447e05 feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y
  Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor
  solo para suscripciones nuevas; sync, cancel y webhook usan row.provider.
- Migración add_billing_providers (provider, checkout_ref, ids genéricos).
- fix: /authorized_payments/search respondía 400 "Invalid value for limit";
  se pagina por offset sin limit.
- fix: si falla la consulta de cobros, la sync guarda igual el estado de la
  suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:01:07 -03:00
Jose Selesan
cd82a1e549 feat: add subscription plans. Add admin panel. Add password recovery 2026-10-24 18:31:55 -03:00
Jose Selesan
f5e77c99f6 feat(billing): planes Free/Pro con Suscripciones de Mercado Pago
- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales
  de plataforma por país, webhook firmado y reconciliación por polling.
- PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o
  activan automatizaciones (402 plan_limit_reached / plan_feature_required /
  plan_read_only), detrás de BILLING_ENFORCEMENT.
- Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se
  saltean Cobros y WhatsApp.
- Web: pantalla /billing, aviso de Pro desde el MutationCache.
- Migración billing_subscriptions y docs/billing.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:49:27 -03:00
Jose Selesan
f4d2c26e29 feat(whatsapp): vincular con el número de teléfono además del QR
Desde el teléfono no se puede escanear el QR de la propia pantalla. Con
OpenWA el profesor ahora puede escribir su número y recibir un código de
8 caracteres para ingresar en WhatsApp (POST /whatsapp/connect/pairing-code).
En mobile el modal arranca por el número y en desktop por el QR.

- Puerto: requestPairingCode opcional (Kapso no lo implementa).
- OpenWA: reintenta el 409 mientras la sesión arranca.
- Número normalizado con el país del profesor (toWhatsappE164).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:15:02 -03:00
Jose Selesan
bef4056f8e fix(web): distinguir WhatsApp no configurado de otros errores de estado
Ajustes y el paso del onboarding mostraban "no está disponible" ante
cualquier fallo de GET /whatsapp/status. Ahora solo un 503 da ese
mensaje; el resto muestra el código del error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:02:14 -03:00
Jose Selesan
2467ebc0f6 chore(whatsapp): sacar OpenWA del docker-compose
OpenWA se instala por separado: la API le habla por OPENWA_API_URL (sin
default). La guía documenta el compose recomendado y el alta de la key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:34:53 -03:00
Jose Selesan
ec65c2198d feat(whatsapp): mensajes automáticos semanales con proveedor intercambiable
- Puerto MessagingProvider con adaptadores OpenWA (MVP, QR) y Kapso
  (setup link de Meta + templates), elegido con WHATSAPP_PROVIDER.
- Vinculación del WhatsApp del profesor en el onboarding y en Ajustes.
- Job semanal (lunes 10:00 AR): recordatorio de pago y reenganche a
  alumnos en riesgo (cooldown 14 días), con switches por grupo.
- Idempotencia por (kind, attendee, semana ISO), webhooks firmados con
  HMAC y deduplicados, normalización de teléfonos a E.164.
- Servicio openwa en docker-compose y guía en docs/whatsapp.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:38:09 -03:00
Jose Selesan
8c5caecdda feat: add country selection during onboarding and implement payment management features
- Introduced CountryStep component for selecting the country during onboarding, affecting payment currency.
- Updated FirstGroupStep to include country information.
- Enhanced PaymentsProvider to manage payment states and renewals.
- Created PaymentRow component for displaying individual payment details.
- Implemented PaymentsView for listing and filtering payments by group and status.
- Added API endpoints for fetching and creating payments, including batch processing.
- Defined payment schemas for validation and data handling.
- Updated GroupHeader and GroupDetailView to include charging functionality for group members.
2026-10-08 11:42:13 -03:00
b11dd47534 Merge pull request 'feat(mp): add Mercado Pago reauthorization notice and status card components' (#10) from feat/add-mercado-pago into development
Reviewed-on: #10
2026-10-07 15:03:36 +00:00
Jose Selesan
21a4c69f38 feat(mp): add Mercado Pago reauthorization notice and status card components
- Implemented MpReauthNotice component to notify users when reauthorization is needed.
- Created MpStatusCard component to display the current status of the Mercado Pago account.
- Added utility functions and constants for handling Mercado Pago status and messages.
- Introduced hooks for managing the connection and disconnection of Mercado Pago accounts.
- Developed a disconnect confirmation modal for user actions.
- Added tests for the new functionality and utility functions.
- Defined schemas for Mercado Pago account status and callback reasons in shared package.
2026-10-07 12:00:38 -03:00
e03f510874 Merge pull request 'feat/improve-member-details' (#9) from feat/improve-member-details into development
Reviewed-on: #9
2026-10-02 12:58:07 +00:00
Jose Selesan
59a4d18ce6 feat: enhance MembersWaitlistSection and PendingView for improved layout and sticky controls 2026-10-02 09:42:11 -03:00
Jose Selesan
faf949fc9b feat(attendee-detail): enhance attendee detail view with payment and notes sections
- Added payment presentation logic to display payment status and due dates.
- Introduced AttendeeNotesSection and AttendeePaymentsSection components for managing notes and payments.
- Implemented forms for editing contact information and notes with validation.
- Updated API to support attendee updates and added corresponding tests.
- Improved attendance summary logic to reflect all visible sessions.
- Enhanced UI with loading states and error handling for better user experience.
2026-10-01 18:41:55 -03:00
Jose Selesan
6d120f4b1f feat: rename camelCase columns to snake_case in database models for consistency 2026-10-01 17:09:12 -03:00
Jose Selesan
69275c37b4 chore: update comments and documentation for clarity and consistency across various files
- Translated comments from Spanish to English in vite.config.ts, docker-compose.yml, attendance-risk.ts, analytics.ts, attendance.ts, attendees.ts, enums.ts, groups.ts, and onboarding.ts.
- Improved descriptions for better understanding of code functionality and purpose.
- Ensured uniformity in terminology and phrasing throughout the codebase.
2026-10-01 16:06:54 -03:00
Jose Selesan
01b35691df feat: improve UI layout and accessibility for group components 2026-10-01 14:25:43 -03:00
a93450579a Merge pull request 'task/improve-ui' (#8) from task/improve-ui into development
Reviewed-on: #8
2026-10-01 15:36:44 +00:00
Jose Selesan
ef38f98747 feat: enhance UI spacing and layout for attendee detail sections 2026-10-01 12:35:57 -03:00
Jose Selesan
ea722a42f1 feat: enhance group management features with improved attendance tracking and UI components 2026-10-01 12:12:14 -03:00
Jose Selesan
416c6f12e1 feat: enhance AttendanceCapacityIndicator and GroupCard for improved UI and accessibility 2026-10-01 10:22:41 -03:00
Jose Selesan
b5a00b309d feat: add attendance risk management features
- Export attendance risk related schemas and types from shared package.
- Introduce new schemas for attendance risk levels and urgent member summaries.
- Implement attendance risk calculation logic in the shared library.
- Create tests for attendance risk calculations and group attendance summaries.
- Add a new component for visualizing attendance capacity indicators in the web app.
2026-10-01 10:01:38 -03:00
Jose Selesan
454f20ed25 feat(api): add timezone support for group fetching and increase page size
feat(attendance): refactor attendance summary logic and update tests

feat(analytics): extend GroupRiskSummary schema with absence and attendance counts

feat(groups): enhance group schema with attendee and waitlist counts

chore(skills): add frontend design skill with guidelines and license

feat(attendee-detail): implement AttendeePhoneLine component for phone display

feat(groups): create AttendanceBadge and CapacityIndicator components for group cards

feat(groups): add card utility functions for attendance alerts and capacity summaries

test(groups): implement tests for attendance alert and capacity summary logic
2026-09-30 17:39:13 -03:00
Jose Selesan
4e86096653 refactor: remove unused attendee detail components and provider 2026-09-30 13:37:42 -03:00
Jose Selesan
27bff32e76 feat: enhance UI components for better accessibility and consistency 2026-09-30 10:33:06 -03:00
Jose Selesan
13c1446977 Improve group detail UI 2026-09-30 10:07:05 -03:00
e9b44caf54 Merge pull request 'feat/pre-registration' (#7) from feat/pre-registration into development
Reviewed-on: #7
2026-09-30 00:24:31 +00:00
Jose Selesan
581cf2f2b2 feat: implement immersive routes with Large Title component
- Added Large Title component to manage immersive screen headers.
- Created ImmersiveBarProvider to handle the sticky bar for immersive routes.
- Updated RootLayout to conditionally render Header based on immersive routes.
- Modified Sidebar to adjust its position and height in immersive mode.
- Integrated Large Title in ClassAttendanceView and AnalyticsView for consistent header display.
- Updated GroupHeader to use Large Title for better layout management.
- Implemented isImmersiveRoute function to determine immersive routes.
- Added tests for immersive route detection.
2026-09-29 21:23:56 -03:00
Jose Selesan
81ed5747f3 feat: add region handling for currency and locale formatting, including comprehensive tests 2026-09-29 21:01:24 -03:00
Jose Selesan
8ccff20473 feat: add accessible Tooltip component with hover, focus, and tap support 2026-09-29 20:12:06 -03:00
549 changed files with 38913 additions and 2198 deletions

View File

@@ -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

View File

@@ -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.

View File

@@ -1,31 +1,33 @@
# Plantilla de variables para `docker compose`. # Variable template for `docker compose`.
# #
# Local: copiá este archivo a `.env` en la raíz y completá los valores. # Local: copy this file to `.env` at the root and fill in the values.
# Dokploy: no hace falta el archivo; definí las mismas variables en la pestaña # Dokploy: no file needed; define the same variables in the Environment tab of
# Environment del servicio Compose (Dokploy las escribe en un `.env` al lado del # the Compose service (Dokploy writes them to a `.env` next to the compose
# compose, que es de donde salen los `${...}`). # file, which is where the `${...}` come from).
# Origen público de la app, sin barra final. El mismo valor alimenta WEB_URL y # Public origin of the app, no trailing slash. The same value feeds WEB_URL and
# BETTER_AUTH_URL porque nginx hace de proxy de /api: la web y la API comparten # BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
# dominio y por lo tanto la cookie de sesión es first-party. # domain, so the session cookie is first-party.
WEB_URL="http://localhost:8080" WEB_URL="http://localhost:8080"
# PostgreSQL de producción. # Production PostgreSQL.
# La password va percent-encoded: si tiene #, @, :, /, ?, % o espacio, escapala # The password must be percent-encoded: if it has #, @, :, /, ?, % or a space,
# (%23, %40, %3A, %2F, %3F, %25, %20). Sin eso Prisma corta la URL donde empieza # escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the
# el fragmento y falla con P1013 "invalid port number in database URL". # 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" DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
# Generalo con: openssl rand -base64 32 # Generate it with: openssl rand -base64 32
BETTER_AUTH_SECRET="" BETTER_AUTH_SECRET=""
# ── Opcionales ─────────────────────────────────────────────────────────────── # ── Optional ─────────────────────────────────────────────────────────────────
# Login social con Google. Sin client id/secret no se registra el provider. # Social login with Google. Without a client id/secret the provider is not
# registered.
# GOOGLE_CLIENT_ID="" # GOOGLE_CLIENT_ID=""
# GOOGLE_CLIENT_SECRET="" # GOOGLE_CLIENT_SECRET=""
# Envío de emails (mismas variables que apps/backend/.env.example). # Email sending (same variables as apps/backend/.env.example).
# EMAIL_PROVIDER="smtp" # EMAIL_PROVIDER="smtp"
# EMAIL_SERVER_HOST="" # EMAIL_SERVER_HOST=""
# EMAIL_SERVER_PORT="587" # EMAIL_SERVER_PORT="587"
@@ -33,6 +35,47 @@ BETTER_AUTH_SECRET=""
# EMAIL_SERVER_PASSWORD="" # EMAIL_SERVER_PASSWORD=""
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>" # EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
# Solo si querés la API en otro dominio: se hornea en el bundle de Vite y obliga # Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales
# a sacar el proxy /api de apps/web/nginx.conf. Vacío = mismo origen (recomendado). # 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="" # VITE_API_URL=""

View File

@@ -0,0 +1,954 @@
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Gruperly — Rediseño detalle de grupo (2 estados)</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap"
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<script src="https://cdn.jsdelivr.net/npm/lucide@0.469.0/dist/umd/lucide.min.js"></script>
<style type="text/tailwindcss">
@theme inline {
--color-background: var(--background);
--color-surface: var(--surface);
--color-primary: var(--primary);
--color-primary-soft: var(--primary-soft);
--color-foreground: var(--foreground);
--color-accent: var(--accent);
--color-accent-strong: var(--accent-strong);
--color-accent-soft: var(--accent-soft);
--color-accent-fg: var(--accent-fg);
--color-border: var(--border);
--color-on-accent: var(--on-accent);
--color-success: var(--success);
--color-success-soft: var(--success-soft);
--color-warning: var(--warning);
--color-warning-soft: var(--warning-soft);
--color-danger: var(--danger);
--color-danger-soft: var(--danger-soft);
--radius-xl: 0.75rem;
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
--animate-fade-in: fade-in 0.2s ease-out;
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
}
:root {
color-scheme: dark;
--background: #020617;
--surface: #0f172a;
--primary: #f1f5f9;
--primary-soft: #1e293b;
--foreground: #94a3b8;
--accent: #2544ea;
--accent-strong: #1d33d8;
--accent-soft: color-mix(in srgb, #3b63f5 15%, transparent);
--accent-fg: #93b4fd;
--border: #1e293b;
--on-accent: #ffffff;
--success: #34d399;
--success-soft: color-mix(in srgb, #34d399 15%, transparent);
--warning: #fcd34d;
--warning-soft: color-mix(in srgb, #fcd34d 15%, transparent);
--danger: #fb7185;
--danger-soft: color-mix(in srgb, #fb7185 15%, transparent);
}
html,
body {
background: var(--background);
}
</style>
<style>
.frames {
display: flex;
flex-wrap: wrap;
gap: 32px;
align-items: flex-start;
}
.frame {
width: 390px;
}
.screen {
background: var(--background);
border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
border-radius: 24px;
padding: 16px 12px 24px;
overflow: hidden;
}
/* Botón (equivalente a components/ui/button.tsx, clases ya fusionadas) */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
white-space: nowrap;
border-radius: 0.75rem;
font-weight: 500;
font-size: 14px;
line-height: 20px;
padding: 0 16px;
height: 44px;
cursor: pointer;
border: 0;
font-family: inherit;
}
.btn-outline {
border: 1px solid var(--border);
background: var(--surface);
color: var(--primary);
}
.btn-ghost {
background: transparent;
color: var(--primary);
}
.btn-primary {
background: var(--accent);
color: var(--on-accent);
}
.btn-block {
width: 100%;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 44px;
border-radius: 9999px;
border: 1px solid var(--border);
padding: 0 14px;
font-size: 12px;
font-weight: 600;
background: var(--surface);
color: color-mix(in srgb, var(--foreground) 80%, transparent);
cursor: pointer;
}
.chip-active {
border-color: transparent;
background: var(--accent);
color: var(--on-accent);
box-shadow: 0 1px 2px rgb(0 0 0 / 0.05);
}
.pill {
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 9999px;
padding: 2px 6px;
font-size: 10px;
font-weight: 700;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.pill-warn {
background: var(--warning-soft);
color: var(--warning);
}
.pill-neutral {
background: var(--primary-soft);
color: color-mix(in srgb, var(--foreground) 60%, transparent);
}
.pill-on-accent {
background: color-mix(in srgb, var(--on-accent) 25%, transparent);
color: var(--on-accent);
}
.label-cell {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.02em;
color: color-mix(in srgb, var(--foreground) 70%, transparent);
}
.avatar {
display: flex;
width: 36px;
height: 36px;
flex-shrink: 0;
align-items: center;
justify-content: center;
border-radius: 9999px;
background: color-mix(in srgb, var(--accent) 10%, transparent);
font-size: 12px;
font-weight: 600;
color: var(--accent);
}
.row {
border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
cursor: pointer;
}
.row:last-child {
border-bottom: 0;
}
table {
width: 100%;
table-layout: fixed;
text-align: left;
font-size: 14px;
}
th {
font-size: 12px;
font-weight: 600;
color: color-mix(in srgb, var(--foreground) 80%, transparent);
padding: 0 12px 8px;
}
td {
padding: 10px 12px;
vertical-align: middle;
}
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tabular {
font-variant-numeric: tabular-nums;
}
svg.lucide {
width: 16px;
height: 16px;
stroke-width: 2;
}
.icon-20 svg.lucide,
svg.icon-20 {
width: 20px;
height: 20px;
}
.icon-40 svg.lucide,
svg.icon-40 {
width: 40px;
height: 40px;
}
</style>
</head>
<body class="antialiased">
<div class="mx-auto max-w-[1780px] px-6 py-8">
<header class="mb-8 max-w-3xl">
<p class="text-xs font-semibold uppercase tracking-wide text-accent-fg">
Gruperly · /groups/$groupId
</p>
<h1 class="mt-1 text-2xl font-bold text-primary">Rediseño del detalle de grupo</h1>
<p class="mt-2 text-sm leading-relaxed text-foreground/80">
Dos pestañas (<strong class="text-primary">Miembros</strong> ·
<strong class="text-primary">Pendientes</strong>), 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 <code class="text-accent-fg">apps/web/src/index.css</code>.
</p>
</header>
<div class="frames">
<!-- ═══════════════ ESTADO 1 · MIEMBROS ═══════════════ -->
<div class="frame">
<p class="mb-2 text-sm font-semibold text-primary">
1 · Con miembros + pre-inscripciones — pestaña “Miembros”
</p>
<div class="screen">
<section class="space-y-5">
<!-- Header -->
<div>
<div class="flex flex-col gap-3">
<div class="min-w-0">
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
Tai chi para principiantes. Trae ropa cómoda.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
>
<span class="size-1.5 rounded-full bg-success"></span>Activo
</span>
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
>
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
</span>
</div>
</div>
<!-- Acciones: dos outline + "Agregar" ghost (no compite) -->
<div class="mt-4 grid grid-cols-2 gap-2.5">
<button class="btn btn-outline btn-block">
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
</button>
<button class="btn btn-outline btn-block">
<i data-lucide="share-2" class="text-accent"></i><span>Compartir Link</span>
</button>
<button class="btn btn-ghost btn-block col-span-2">
<i data-lucide="user-plus" class="text-accent"></i
><span>Agregar Miembros</span>
</button>
</div>
</div>
<!-- Tarjeta de info: Horario → Cupo → Cobro -->
<div
class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4"
>
<div class="flex items-start gap-3 py-3 first:pt-0">
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Horario</p>
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
</div>
</div>
<div class="flex items-start gap-3 py-3">
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Miembros &amp; Cupo</p>
<p
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
>
<span>3</span><span class="text-base font-medium text-foreground/70">/4</span>
</p>
<div
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
>
<div class="h-full w-3/4 rounded-full bg-accent"></div>
</div>
<p class="mt-1.5 text-sm text-foreground">1 lugar libre · 1 en espera</p>
</div>
</div>
<div class="flex items-start gap-3 py-3 last:pb-0">
<div
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
>
$
</div>
<div class="min-w-0 flex-1">
<p class="label-cell">Cobro</p>
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
</div>
</div>
</div>
<!-- Listados -->
<div class="rounded-2xl bg-primary-soft p-2">
<div class="space-y-2 p-2">
<div class="flex flex-col gap-2.5">
<div class="flex w-full flex-wrap items-center gap-2">
<button class="chip chip-active">
<i data-lucide="users"></i><span>Miembros</span
><span class="pill pill-on-accent">3</span>
</button>
<button class="chip">
<i data-lucide="inbox"></i><span>Pendientes</span
><span class="pill pill-warn">3</span>
</button>
</div>
<div class="relative w-full">
<i
data-lucide="search"
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
></i>
<input
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
placeholder="Buscar por nombre o teléfono..."
/>
</div>
</div>
<p class="text-xs leading-relaxed text-foreground/80">
Listado de todos los miembros incorporados al grupo.
</p>
</div>
<div class="rounded-lg bg-surface p-1 shadow-xs">
<table>
<thead>
<tr class="border-b border-border/70">
<th scope="col" class="w-[48%]">Nombre</th>
<th scope="col">Teléfono</th>
<th scope="col" class="w-9 px-1"><span class="sr-only">Detalle</span></th>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<div class="flex min-w-0 items-center gap-2.5">
<div class="avatar">A</div>
<span class="min-w-0 truncate font-medium text-primary">Ana López</span>
</div>
</td>
<td class="min-w-0 text-foreground/80">
<span class="block truncate tabular">55 1234 5678</span>
</td>
<td class="w-9 px-1 text-foreground/50">
<i data-lucide="chevron-right" class="ml-auto block"></i>
</td>
</tr>
<tr class="row">
<td>
<div class="flex min-w-0 items-center gap-2.5">
<div class="avatar">C</div>
<span class="min-w-0 truncate font-medium text-primary"
>Carlos Mendoza</span
>
</div>
</td>
<td class="min-w-0 text-foreground/80">
<span class="block truncate tabular">55 2345 6789</span>
</td>
<td class="w-9 px-1 text-foreground/50">
<i data-lucide="chevron-right" class="ml-auto block"></i>
</td>
</tr>
<tr class="row">
<td>
<div class="flex min-w-0 items-center gap-2.5">
<div class="avatar">L</div>
<span class="min-w-0 truncate font-medium text-primary"
>Lucía Hernández</span
>
</div>
</td>
<td class="min-w-0 text-foreground/80">
<span class="block truncate tabular">55 3456 7890</span>
</td>
<td class="w-9 px-1 text-foreground/50">
<i data-lucide="chevron-right" class="ml-auto block"></i>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
Un solo tono activo: el chip “Miembros”. “Agregar Miembros” es
<code class="text-foreground/80">ghost</code> — disponible, no dominante. Cupo
escaneable como <strong class="text-primary">3/4</strong> + barra.
</p>
</div>
<!-- ═══════════════ ESTADO 1 · PENDIENTES ═══════════════ -->
<div class="frame">
<p class="mb-2 text-sm font-semibold text-primary">
1 · Con miembros + pre-inscripciones — pestaña “Pendientes”
</p>
<div class="screen">
<section class="space-y-5">
<div>
<div class="flex flex-col gap-3">
<div class="min-w-0">
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
Tai chi para principiantes. Trae ropa cómoda.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
>
<span class="size-1.5 rounded-full bg-success"></span>Activo
</span>
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
>
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
</span>
</div>
</div>
<div class="mt-4 grid grid-cols-2 gap-2.5">
<button class="btn btn-outline btn-block">
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
</button>
<button class="btn btn-outline btn-block">
<i data-lucide="share-2" class="text-accent"></i><span>Compartir Link</span>
</button>
<button class="btn btn-ghost btn-block col-span-2">
<i data-lucide="user-plus" class="text-accent"></i
><span>Agregar Miembros</span>
</button>
</div>
</div>
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
<div class="flex items-start gap-3 py-3 first:pt-0">
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Horario</p>
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
</div>
</div>
<div class="flex items-start gap-3 py-3">
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Miembros &amp; Cupo</p>
<p
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
>
<span>3</span><span class="text-base font-medium text-foreground/70">/4</span>
</p>
<div
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
>
<div class="h-full w-3/4 rounded-full bg-accent"></div>
</div>
<p class="mt-1.5 text-sm text-foreground">1 lugar libre · 1 en espera</p>
</div>
</div>
<div class="flex items-start gap-3 py-3 last:pb-0">
<div
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
>
$
</div>
<div class="min-w-0 flex-1">
<p class="label-cell">Cobro</p>
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
</div>
</div>
</div>
<div class="rounded-2xl bg-primary-soft p-2">
<div class="space-y-2 p-2">
<div class="flex flex-col gap-2.5">
<div class="flex w-full flex-wrap items-center gap-2">
<button class="chip">
<i data-lucide="users"></i><span>Miembros</span
><span class="pill pill-neutral">3</span>
</button>
<button class="chip chip-active">
<i data-lucide="inbox"></i><span>Pendientes</span
><span class="pill pill-on-accent">3</span>
</button>
</div>
<div class="relative w-full">
<i
data-lucide="search"
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
></i>
<input
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
placeholder="Buscar por nombre o teléfono..."
/>
</div>
</div>
<p class="text-xs leading-relaxed text-foreground/80">
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por
un cupo libre.
</p>
</div>
<div class="rounded-lg bg-surface p-1 shadow-xs">
<!-- Pre-inscripciones -->
<section>
<div class="flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3">
<i data-lucide="user-check" class="shrink-0 text-accent"></i>
<h3 class="text-xs font-semibold uppercase tracking-wide text-foreground/70">
Pre-inscripciones
</h3>
<span class="pill pill-warn ml-auto">2</span>
</div>
<div class="pt-1">
<table>
<thead>
<tr class="border-b border-border/70">
<th scope="col" class="w-[46%]">Nombre</th>
<th scope="col">Teléfono</th>
<th scope="col" class="hidden w-9 px-1 sm:table-cell"
><span class="sr-only">Detalle</span></th
>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<div class="flex min-w-0 items-center gap-2.5">
<div class="avatar">J</div>
<div class="min-w-0">
<p class="truncate font-medium text-primary">Jorge Ramírez</p>
<p class="truncate text-xs text-foreground/70">
jorge.r@correo.mx
</p>
</div>
</div>
</td>
<td class="min-w-0 text-foreground/80">
<span class="block truncate tabular">55 4567 8901</span>
</td>
<td class="w-9 px-1 text-foreground/50">
<i data-lucide="chevron-right" class="ml-auto block"></i>
</td>
</tr>
<tr class="row">
<td>
<div class="flex min-w-0 items-center gap-2.5">
<div class="avatar">S</div>
<div class="min-w-0">
<p class="truncate font-medium text-primary">Sofía Torres</p>
<p class="truncate text-xs text-foreground/70">
sofia.t@correo.mx
</p>
</div>
</div>
</td>
<td class="min-w-0 text-foreground/80">
<span class="block truncate tabular">55 5678 9012</span>
</td>
<td class="w-9 px-1 text-foreground/50">
<i data-lucide="chevron-right" class="ml-auto block"></i>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Lista de espera -->
<section>
<div class="flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3">
<i data-lucide="clock" class="shrink-0 text-accent"></i>
<h3 class="text-xs font-semibold uppercase tracking-wide text-foreground/70">
Lista de espera
</h3>
<span class="pill pill-neutral ml-auto">1</span>
</div>
<div class="pt-1">
<table>
<thead>
<tr class="border-b border-border/70">
<th scope="col" class="w-[48%]">Nombre</th>
<th scope="col">Teléfono</th>
<th scope="col" class="w-9 px-1"
><span class="sr-only">Detalle</span></th
>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<div class="flex min-w-0 items-center gap-2.5">
<div class="avatar">D</div>
<div class="min-w-0">
<p class="truncate font-medium text-primary">Diego Peña</p>
<p class="truncate text-xs text-foreground/70">
Prefiere horario de 19:00
</p>
</div>
</div>
</td>
<td class="min-w-0 text-foreground/80">
<span class="block truncate tabular">55 6789 0123</span>
</td>
<td class="w-9 px-1 text-foreground/50">
<i data-lucide="chevron-right" class="ml-auto block"></i>
</td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
</div>
</section>
</div>
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
“Pendientes” agrupa Pre-inscripciones (pill ámbar = requiere decisión) y Lista de
espera como secciones apiladas — sin una tercera pestaña.
</p>
</div>
<!-- ═══════════════ ESTADO 2 · VACÍO (MIEMBROS) ═══════════════ -->
<div class="frame">
<p class="mb-2 text-sm font-semibold text-primary">
2 · Estado vacío — pestaña “Miembros” (sin miembros ni pre-inscripciones)
</p>
<div class="screen">
<section class="space-y-5">
<div>
<div class="flex flex-col gap-3">
<div class="min-w-0">
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
Tai chi para principiantes. Trae ropa cómoda.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
>
<span class="size-1.5 rounded-full bg-success"></span>Activo
</span>
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
>
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
</span>
</div>
</div>
<!-- Grupo vacío: el header no repite Compartir/Agregar; los lleva el empty state. -->
<div class="mt-4 grid grid-cols-2 gap-2.5">
<button class="btn btn-outline btn-block">
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
</button>
</div>
</div>
<!-- Tarjeta vacía: 0/4 -->
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
<div class="flex items-start gap-3 py-3 first:pt-0">
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Horario</p>
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
</div>
</div>
<div class="flex items-start gap-3 py-3">
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Miembros &amp; Cupo</p>
<p
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
>
<span>0</span><span class="text-base font-medium text-foreground/70">/4</span>
</p>
<div
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
>
<div class="h-full w-0 rounded-full bg-accent"></div>
</div>
<p class="mt-1.5 text-sm text-foreground">4 lugares libres</p>
</div>
</div>
<div class="flex items-start gap-3 py-3 last:pb-0">
<div
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
>
$
</div>
<div class="min-w-0 flex-1">
<p class="label-cell">Cobro</p>
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
</div>
</div>
</div>
<div class="rounded-2xl bg-primary-soft p-2">
<div class="space-y-2 p-2">
<div class="flex flex-col gap-2.5">
<div class="flex w-full flex-wrap items-center gap-2">
<button class="chip chip-active">
<i data-lucide="users"></i><span>Miembros</span>
</button>
<button class="chip">
<i data-lucide="inbox"></i><span>Pendientes</span>
</button>
</div>
<div class="relative w-full">
<i
data-lucide="search"
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
></i>
<input
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
placeholder="Buscar por nombre o teléfono..."
/>
</div>
</div>
<p class="text-xs leading-relaxed text-foreground/80">
Listado de todos los miembros incorporados al grupo.
</p>
</div>
<div class="rounded-lg bg-surface p-1 shadow-xs">
<div class="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
<i
data-lucide="users"
class="icon-40 mx-auto mb-2 block text-foreground/40"
></i>
<p class="text-sm font-semibold text-primary">
Todavía no hay miembros en este grupo
</p>
<p class="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
Puedes compartir el enlace de invitación único o agregar miembros de forma
manual o masiva.
</p>
<div class="mt-4 flex flex-col gap-2.5">
<button class="btn btn-outline btn-block">
<i data-lucide="share-2"></i><span>Compartir Enlace</span>
</button>
<button class="btn btn-primary btn-block">
<i data-lucide="plus"></i><span>Agregar Miembros</span>
</button>
</div>
</div>
</div>
</div>
</section>
</div>
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
Exactamente <strong class="text-primary">un primario</strong>: “Agregar Miembros” en el
empty state. El header no repite Compartir/Agregar —solo queda Estadísticas—, así que
no compiten dos CTA idénticos.
</p>
</div>
<!-- ═══════════════ ESTADO 2 · VACÍO (PENDIENTES) ═══════════════ -->
<div class="frame">
<p class="mb-2 text-sm font-semibold text-primary">
2 · Estado vacío — pestaña “Pendientes”
</p>
<div class="screen">
<section class="space-y-5">
<div>
<div class="flex flex-col gap-3">
<div class="min-w-0">
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
Tai chi para principiantes. Trae ropa cómoda.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
>
<span class="size-1.5 rounded-full bg-success"></span>Activo
</span>
<span
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
>
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
</span>
</div>
</div>
<!-- Grupo vacío: el header no repite Compartir/Agregar; los lleva el empty state. -->
<div class="mt-4 grid grid-cols-2 gap-2.5">
<button class="btn btn-outline btn-block">
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
</button>
</div>
</div>
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
<div class="flex items-start gap-3 py-3 first:pt-0">
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Horario</p>
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
</div>
</div>
<div class="flex items-start gap-3 py-3">
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
<div class="min-w-0 flex-1">
<p class="label-cell">Miembros &amp; Cupo</p>
<p
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
>
<span>0</span><span class="text-base font-medium text-foreground/70">/4</span>
</p>
<div
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
>
<div class="h-full w-0 rounded-full bg-accent"></div>
</div>
<p class="mt-1.5 text-sm text-foreground">4 lugares libres</p>
</div>
</div>
<div class="flex items-start gap-3 py-3 last:pb-0">
<div
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
>
$
</div>
<div class="min-w-0 flex-1">
<p class="label-cell">Cobro</p>
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
</div>
</div>
</div>
<div class="rounded-2xl bg-primary-soft p-2">
<div class="space-y-2 p-2">
<div class="flex flex-col gap-2.5">
<div class="flex w-full flex-wrap items-center gap-2">
<button class="chip">
<i data-lucide="users"></i><span>Miembros</span>
</button>
<button class="chip chip-active">
<i data-lucide="inbox"></i><span>Pendientes</span>
</button>
</div>
<div class="relative w-full">
<i
data-lucide="search"
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
></i>
<input
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
placeholder="Buscar por nombre o teléfono..."
/>
</div>
</div>
<p class="text-xs leading-relaxed text-foreground/80">
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por
un cupo libre.
</p>
</div>
<div class="rounded-lg bg-surface p-1 shadow-xs">
<div class="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
<i
data-lucide="inbox"
class="icon-40 mx-auto mb-2 block text-foreground/40"
></i>
<p class="text-sm font-semibold text-primary">No hay pendientes</p>
<p class="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
Las pre-inscripciones que lleguen por el enlace compartido y las personas en
lista de espera aparecerán aquí para que las revises.
</p>
<div class="mt-4 flex justify-center">
<button class="btn btn-primary btn-block">
<i data-lucide="share-2"></i><span>Compartir Enlace</span>
</button>
</div>
</div>
</div>
</div>
</section>
</div>
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
Cada pestaña vacía explica qué aparecerá ahí y ofrece
<strong class="text-primary">una</strong> acción primaria concreta.
</p>
</div>
</div>
<footer class="mt-10 max-w-3xl border-t border-border pt-6 text-xs leading-relaxed text-foreground/70">
<p>
<strong class="text-primary">Jerarquía de la tarjeta:</strong> label 11px · dato 16px ·
cupo 24px (único hero). Orden de lectura: Horario → Cupo → Cobro.
<strong class="text-primary">Objetivos táctiles:</strong> chips, botones y buscador a
44px; filas de tabla ~56px. <strong class="text-primary">Badges</strong> “Activo” y
“Riesgo moderado” conservados.
</p>
</footer>
</div>
<script>
window.addEventListener('load', () => {
if (window.lucide) window.lucide.createIcons();
});
</script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 314 KiB

View File

@@ -36,14 +36,21 @@ accent azul; copy en español, verbos en infinitivo.
## Patrón focal ## Patrón focal
**Un punto focal por bloque y por estado.** La tarjeta de info manda con el cupo; el header **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` (las tres acciones son `outline`) y el `primary` vive en 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. 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) ## Componentes (valores exactos)
### Chip de sección — `detail/SectionChips.tsx` ### Chip de sección — `detail/SectionChips.tsx`
- Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist). - Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist).
- Chip: `min-h-10 rounded-full border px-3 text-xs font-semibold gap-1.5`, - 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`, 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`, 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`. focus `ring-2 ring-accent ring-offset-2 ring-offset-primary-soft`.
@@ -52,10 +59,42 @@ el empty state de la vista que lo explica. Así nunca hay dos elementos azules c
neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`. 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. - `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 `<main>`
(`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` ### Acciones de cabecera — `detail/GroupHeader.tsx`
- `variant="outline"` con icono `text-accent`; `md` (`h-10 px-4`). `primary` solo en empty states. - 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`. - 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`. - 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` ### 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, - Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil,
@@ -76,7 +115,7 @@ el empty state de la vista que lo explica. Así nunca hay dos elementos azules c
### Empty state ### Empty state
`rounded-lg bg-primary-soft/50 px-4 py-10 text-center` · icono `size-10 text-foreground/40` · `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` · título `text-sm font-semibold text-primary` · cuerpo `max-w-sm text-sm text-foreground/80` ·
acciones: **una** `primary` + el resto `outline`. acciones: **una** `primary` + el resto `outline`, todas `h-11`.
### Tablas — `detail/*Table.tsx` ### Tablas — `detail/*Table.tsx`
`table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5` `table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5`

View File

@@ -31,35 +31,71 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`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/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
- `src/logger.ts` — pino + pino-pretty. - `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`, `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. - 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`). - `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/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). - `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 ## 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`. - **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. - **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/<nombre>/`.
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_<CC>`, 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.
- **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. - **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.
- **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 `<link>` 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. - **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 `<link>` 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). - **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`, `/acceso`, `/alumno/*`)**: 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 vinculado a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. Vincular tutores a varios hijos (N:N en `student_account_attendees`) 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`.
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia). - `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
## Convenciones repo-específicas ## Convenciones repo-específicas
- **Frontend en español**: copy de UI, comentarios y textos en español. - **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")`. - **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. - **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`). - **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 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 `<Outlet />`). - **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 `<Outlet />`).
- **Vistas en `apps/web/src/features/<feature>/`**: 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<Feature>()` y las forms locales mantienen su propio estado. - **Vistas en `apps/web/src/features/<feature>/`**: 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<Feature>()` 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. - 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 `<Header />`, `<main>` 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 `<main>`. (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 `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` 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. - **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+`. - 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 `<main>` 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. - **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 `<main>` 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). 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. - **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 ## Fuentes de contexto
- `stack.md` — arquitectura y spec técnica de referencia (UI tokens exactos, stack por app). - `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. - `README.md` — setup de la base de datos y comandos generales.

View File

@@ -5,21 +5,21 @@ FROM oven/bun:1.4-alpine AS base
WORKDIR /app WORKDIR /app
ENV CI=1 ENV CI=1
# ─── Dependencias ──────────────────────────────────────────────────────────── # ─── Dependencies ────────────────────────────────────────────────────────────
# Solo los package.json:bun no necesita el código fuente para resolver el lockfile. # Only the package.json files: bun needs no source code to resolve the lockfile.
FROM base AS deps FROM base AS deps
COPY package.json bun.lock bunfig.toml turbo.json ./ COPY package.json bun.lock bunfig.toml turbo.json ./
COPY apps/backend/package.json ./apps/backend/ COPY apps/backend/package.json ./apps/backend/
COPY apps/web/package.json ./apps/web/ COPY apps/web/package.json ./apps/web/
COPY packages/config/package.json ./packages/config/ COPY packages/config/package.json ./packages/config/
COPY packages/shared/package.json ./packages/shared/ COPY packages/shared/package.json ./packages/shared/
# El cache global de bun pesa ~370MB: se borra en la misma capa. # bun's global cache weighs ~370MB: it is dropped in the same layer.
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
# ─── Prisma Client ─────────────────────────────────────────────────────────── # ─── Prisma Client ───────────────────────────────────────────────────────────
# El generator "prisma-client" emite TypeScript, así que el cliente generado se # The "prisma-client" generator emits TypeScript, so the generated client runs
# ejecuta con Bun sin compilar nada. La URL es un placeholder: `generate` no # with Bun without compilation. The URL is a placeholder: `generate` only needs
# necesita conexión, solo leer el schema. # to read the schema, not connect to a database.
FROM deps AS generate FROM deps AS generate
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
ENV DATABASE_URL=$DATABASE_URL ENV DATABASE_URL=$DATABASE_URL
@@ -28,7 +28,7 @@ COPY apps/backend/prisma ./apps/backend/prisma
WORKDIR /app/apps/backend WORKDIR /app/apps/backend
RUN bun run db:generate RUN bun run db:generate
# ─── Imagen de la API ──────────────────────────────────────────────────────── # ─── API image ───────────────────────────────────────────────────────────────
FROM base AS api FROM base AS api
ENV NODE_ENV=production \ ENV NODE_ENV=production \
PORT=4000 PORT=4000
@@ -37,30 +37,30 @@ COPY package.json bun.lock bunfig.toml ./
COPY apps/backend/package.json ./apps/backend/ COPY apps/backend/package.json ./apps/backend/
COPY packages/config/package.json ./packages/config/ COPY packages/config/package.json ./packages/config/
COPY packages/shared/package.json ./packages/shared/ COPY packages/shared/package.json ./packages/shared/
# `prisma` y `dotenv` son dependencies (no dev) porque el entrypoint corre # `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs
# `prisma migrate deploy` en cada arranque. Con `--production` no entra el resto # `prisma migrate deploy` on every boot. With `--production` the rest of the
# del tooling: biome, typescript, turbo. # tooling does not come in: biome, typescript, turbo.
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
# El CLI de Prisma carga prisma.config.ts, que apunta al schema. # The Prisma CLI loads prisma.config.ts, which points to the schema.
COPY apps/backend/prisma ./apps/backend/prisma COPY apps/backend/prisma ./apps/backend/prisma
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
COPY apps/backend/tsconfig.json ./apps/backend/ COPY apps/backend/tsconfig.json ./apps/backend/
COPY apps/backend/src ./apps/backend/src COPY apps/backend/src ./apps/backend/src
# @gruperly/shared se consume como fuente TS; @gruperly/config aporta el # @gruperly/shared is consumed as TS source; @gruperly/config provides the base
# tsconfig base del que extiende el tsconfig del backend. # tsconfig that the backend tsconfig extends.
COPY packages ./packages COPY packages ./packages
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh RUN chmod +x /usr/local/bin/docker-entrypoint.sh
WORKDIR /app/apps/backend WORKDIR /app/apps/backend
EXPOSE 4000 EXPOSE 4000
# Sin `${...}`: el CMD corre bajo /bin/sh (ash), donde eso es un error de sintaxis. # 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 \ 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))" 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"] ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
# Bun ejecuta el TypeScript directamente y resuelve `@/*` con el tsconfig.json, # Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
# igual que `bun start` en local. # same as `bun start` locally.
CMD ["bun", "src/server.ts"] CMD ["bun", "src/server.ts"]

View File

@@ -5,27 +5,27 @@ FROM oven/bun:1.4-alpine AS base
WORKDIR /app WORKDIR /app
ENV CI=1 ENV CI=1
# ─── Dependencias ──────────────────────────────────────────────────────────── # ─── Dependencies ────────────────────────────────────────────────────────────
FROM base AS deps FROM base AS deps
COPY package.json bun.lock bunfig.toml turbo.json ./ COPY package.json bun.lock bunfig.toml turbo.json ./
COPY apps/backend/package.json ./apps/backend/ COPY apps/backend/package.json ./apps/backend/
COPY apps/web/package.json ./apps/web/ COPY apps/web/package.json ./apps/web/
COPY packages/config/package.json ./packages/config/ COPY packages/config/package.json ./packages/config/
COPY packages/shared/package.json ./packages/shared/ COPY packages/shared/package.json ./packages/shared/
# El cache global de bun pesa ~370MB: se borra en la misma capa. # bun's global cache weighs ~370MB: it is dropped in the same layer.
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
# ─── Build de Vite ─────────────────────────────────────────────────────────── # ─── Vite build ──────────────────────────────────────────────────────────────
FROM deps AS build FROM deps AS build
# Vite reemplaza import.meta.env.* en tiempo de build, no de runtime. # Vite replaces import.meta.env.* at build time, not at runtime.
# Vacío = mismo origen: el proxy /api de nginx hace de API. # Empty = same origin: nginx's /api proxy acts as the API.
ARG VITE_API_URL="" ARG VITE_API_URL=""
ENV VITE_API_URL=$VITE_API_URL ENV VITE_API_URL=$VITE_API_URL
COPY apps/web ./apps/web COPY apps/web ./apps/web
COPY packages ./packages COPY packages ./packages
RUN bun --filter @gruperly/web build RUN bun --filter @gruperly/web build
# ─── Imagen final ──────────────────────────────────────────────────────────── # ─── Final image ─────────────────────────────────────────────────────────────
FROM nginx:1.27-alpine AS web FROM nginx:1.27-alpine AS web
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/apps/web/dist /usr/share/nginx/html COPY --from=build /app/apps/web/dist /usr/share/nginx/html

110
README.md
View File

@@ -67,6 +67,113 @@ En DevTools → Application: el manifest sin warnings, el service worker `activa
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`. 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). 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: <cookie de sesión>' | 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) ## Deploy en producción (Docker / Dokploy)
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx). Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
@@ -87,6 +194,9 @@ El compose las interpola desde el entorno. En Dokploy van en la pestaña **Envir
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` | | `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider | | `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`) | | `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 | | `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 | | `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |

View File

@@ -18,4 +18,79 @@ EMAIL_SERVER_HOST=""
EMAIL_SERVER_PORT="587" EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER="" EMAIL_SERVER_USER=""
EMAIL_SERVER_PASSWORD="" EMAIL_SERVER_PASSWORD=""
EMAIL_FROM="Gruperly <no-reply@gruperly.com>" EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
# 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"

View File

@@ -1,12 +1,12 @@
#!/bin/sh #!/bin/sh
# Entrypoint de producción del backend: aplica las migraciones y levanta el # Production entrypoint for the backend: applies the migrations and starts the
# servidor en el mismo contenedor. # server in the same container.
# #
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo # This is POSIX sh, not bash: the image is alpine and does not ship bash
# serían ~10MB por un shebang). # installed (adding it would be ~10MB for a shebang).
# #
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una # Set RUN_MIGRATIONS=false to start without touching the database (for example,
# base ya migrada a mano o una que se gestiona fuera de este despliegue). # a database already migrated by hand, or one managed outside this deployment).
set -e set -e
: "${DATABASE_URL:?falta DATABASE_URL}" : "${DATABASE_URL:?falta DATABASE_URL}"
@@ -18,8 +18,8 @@ else
delay="${MIGRATE_RETRY_DELAY:-5}" delay="${MIGRATE_RETRY_DELAY:-5}"
i=1 i=1
# La base puede seguir arrancando cuando este contenedor ya empezó, y un # The database may still be starting up when this container is already
# deploy suele convivir con un reinicio de Postgres. # running, and a deploy usually overlaps a Postgres restart.
while [ "$i" -le "$attempts" ]; do while [ "$i" -le "$attempts" ]; do
if bun run db:deploy; then if bun run db:deploy; then
echo "migrate: listo" echo "migrate: listo"
@@ -37,6 +37,6 @@ else
done done
fi fi
# exec para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop` # exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma). # (the server uses it to close Bun.serve and disconnect Prisma).
exec "$@" exec "$@"

View File

@@ -9,6 +9,7 @@
"build": "prisma generate && tsc", "build": "prisma generate && tsc",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "bun test", "test": "bun test",
"test:db": "DB_TESTS=1 bun test test/db",
"test:watch": "bun test --watch", "test:watch": "bun test --watch",
"lint": "biome check .", "lint": "biome check .",
"lint:fix": "biome check . --write", "lint:fix": "biome check . --write",
@@ -23,6 +24,7 @@
"@gruperly/shared": "workspace:*", "@gruperly/shared": "workspace:*",
"@prisma/adapter-pg": "^7.10.0", "@prisma/adapter-pg": "^7.10.0",
"@prisma/client": "^7.10.0", "@prisma/client": "^7.10.0",
"@simplewebauthn/server": "13.3.3",
"better-auth": "1.7.2", "better-auth": "1.7.2",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"hono": "^4.13.3", "hono": "^4.13.3",

View File

@@ -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";

View File

@@ -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";

View File

@@ -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");

View File

@@ -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;

View File

@@ -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;

View File

@@ -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:<CC>` or `stripe`)
ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";

View File

@@ -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;

View File

@@ -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;

View File

@@ -8,43 +8,44 @@ enum AttendanceStatus {
model ClassSession { model ClassSession {
id String @id @default(cuid()) id String @id @default(cuid())
groupId String groupId String @map("group_id")
startsAt DateTime startsAt DateTime @map("starts_at")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
attendances Attendance[] attendances Attendance[]
slotReleases SlotRelease[] slotReleases SlotRelease[]
absenceNotices AbsenceNotice[]
@@unique([groupId, startsAt]) @@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
@@map("class_sessions") @@map("class_sessions")
} }
model Attendance { model Attendance {
id String @id @default(cuid()) id String @id @default(cuid())
attendeeId String attendeeId String @map("attendee_id")
classSessionId String classSessionId String @map("class_session_id")
status AttendanceStatus status AttendanceStatus
markedAt DateTime @default(now()) markedAt DateTime @default(now()) @map("marked_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "attendances_attendeeId_fkey")
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade) classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "attendances_classSessionId_fkey")
@@unique([attendeeId, classSessionId]) @@unique([attendeeId, classSessionId], map: "attendances_attendeeId_classSessionId_key")
@@map("attendances") @@map("attendances")
} }
model SlotRelease { model SlotRelease {
id String @id @default(cuid()) id String @id @default(cuid())
attendeeId String attendeeId String @map("attendee_id")
classSessionId String classSessionId String @map("class_session_id")
isClaimed Boolean @default(false) isClaimed Boolean @default(false) @map("is_claimed")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "slot_releases_attendeeId_fkey")
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade) classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "slot_releases_classSessionId_fkey")
@@unique([attendeeId, classSessionId]) @@unique([attendeeId, classSessionId], map: "slot_releases_attendeeId_classSessionId_key")
@@map("slot_releases") @@map("slot_releases")
} }

View File

@@ -1,63 +1,72 @@
// Auth (Better Auth) - required tables // Auth (Better Auth) - required tables
model User { model User {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
email String @unique email String @unique
emailVerified Boolean @default(false) emailVerified Boolean @default(false) @map("email_verified")
image String? image String?
onboardingCompleted Boolean @default(false) onboardingCompleted Boolean @default(false) @map("onboarding_completed")
createdAt DateTime @default(now()) country String? @map("country_code")
updatedAt DateTime @updatedAt // 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[] accounts Account[]
sessions Session[] sessions Session[]
passkeys Passkey[] passkeys Passkey[]
groupsMember GroupMember[] groupsMember GroupMember[]
groupsOwner Group[] @relation("OwnerGroups") groupsOwner Group[] @relation("OwnerGroups")
orgMemberships Member[] orgMemberships Member[]
orgInvitations Invitation[] @relation("InvitedBy") orgInvitations Invitation[] @relation("InvitedBy")
waitlist WaitlistEntry[] waitlist WaitlistEntry[]
merchantAccount MerchantAccount? mpAccount MpAccount?
whatsappAccount WhatsappAccount?
subscription BillingSubscription?
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
@@map("users") @@map("users")
} }
model Account { model Account {
id String @id @default(cuid()) id String @id @default(cuid())
userId String userId String @map("user_id")
providerId String providerId String @map("provider_id")
accountId String accountId String @map("account_id")
issuer String issuer String
accessToken String? accessToken String? @map("access_token")
refreshToken String? refreshToken String? @map("refresh_token")
idToken String? idToken String? @map("id_token")
accessTokenExpiresAt DateTime? accessTokenExpiresAt DateTime? @map("access_token_expires_at")
refreshTokenExpiresAt DateTime? refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
scope String? scope String?
password String? password String?
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt 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]) @@unique([issuer, accountId], map: "accounts_issuer_accountId_key")
@@index([userId]) @@index([userId], map: "accounts_userId_idx")
@@map("accounts") @@map("accounts")
} }
model Session { model Session {
id String @id @default(cuid()) id String @id @default(cuid())
userId String userId String @map("user_id")
token String @unique token String @unique
expiresAt DateTime expiresAt DateTime @map("expires_at")
ipAddress String? ipAddress String? @map("ip_address")
userAgent String? userAgent String? @map("user_agent")
activeOrganizationId String? activeOrganizationId String? @map("active_organization_id")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt 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") @@map("sessions")
} }
@@ -66,9 +75,9 @@ model Verification {
id String @id @default(cuid()) id String @id @default(cuid())
identifier String identifier String
value String value String
expiresAt DateTime expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt @map("updated_at")
@@unique([identifier, value]) @@unique([identifier, value])
@@map("verifications") @@map("verifications")
@@ -81,8 +90,8 @@ model Organization {
slug String @unique slug String @unique
logo String? logo String?
metadata Json? metadata Json?
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt @map("updated_at")
members Member[] members Member[]
invitations Invitation[] invitations Invitation[]
@@ -92,32 +101,32 @@ model Organization {
model Member { model Member {
id String @id @default(cuid()) id String @id @default(cuid())
organizationId String organizationId String @map("organization_id")
userId String userId String @map("user_id")
role String @default("member") role String @default("member")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
organization Organization @relation(fields: [organizationId], 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) 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") @@map("members")
} }
model Invitation { model Invitation {
id String @id @default(cuid()) id String @id @default(cuid())
organizationId String organizationId String @map("organization_id")
email String email String
role String role String
status String @default("pending") status String @default("pending")
inviterId String inviterId String @map("inviter_id")
expiresAt DateTime expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
organization Organization @relation(fields: [organizationId], 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) inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade, map: "invitations_inviterId_fkey")
@@index([organizationId]) @@index([organizationId], map: "invitations_organizationId_idx")
@@map("invitations") @@map("invitations")
} }
@@ -125,18 +134,18 @@ model Invitation {
model Passkey { model Passkey {
id String @id @default(cuid()) id String @id @default(cuid())
name String? name String?
publicKey String publicKey String @map("public_key")
credentialID String @unique credentialID String @unique(map: "passkeys_credentialID_key") @map("credential_id")
userId String userId String @map("user_id")
counter Int counter Int
deviceType String deviceType String @map("device_type")
backedUp Boolean backedUp Boolean @map("backed_up")
transports String? transports String?
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
aaguid String? 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") @@map("passkeys")
} }

View File

@@ -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:<CC>`
// (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")
}

View File

@@ -1,27 +1,32 @@
// Domain models // Domain models
model Group { model Group {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
description String? description String?
days WeekDay[] days WeekDay[]
time String? time String?
capacity Int? capacity Int?
price Decimal? @db.Decimal(10, 2) price Decimal? @db.Decimal(10, 2)
billingType BillingType? billingType BillingType? @map("billing_type")
dueDay Int? dueDay Int? @map("due_day")
inviteToken String? @unique // Weekly WhatsApp automations, off until the teacher turns them on.
createdById String autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
createdAt DateTime @default(now()) autoReengagement Boolean @default(false) @map("auto_reengagement")
updatedAt DateTime @updatedAt 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) owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
members GroupMember[] members GroupMember[]
attendees Attendee[] attendees Attendee[]
payments Payment[] payments Payment[]
waitlist GroupWaitlistEntry[] waitlist GroupWaitlistEntry[]
preRegistrations GroupPreRegistration[] preRegistrations GroupPreRegistration[]
classSessions ClassSession[] classSessions ClassSession[]
outboundMessages OutboundMessage[]
reportedPayments ReportedPayment[]
@@map("groups") @@map("groups")
} }
@@ -42,16 +47,16 @@ enum BillingType {
} }
model GroupMember { model GroupMember {
id String @id @default(cuid()) id String @id @default(cuid())
groupId String groupId String @map("group_id")
userId String userId String @map("user_id")
role Role @default(MEMBER) // OWNER, ADMIN, MEMBER role Role @default(MEMBER) // OWNER, ADMIN, MEMBER
joinedAt DateTime @default(now()) joinedAt DateTime @default(now()) @map("joined_at")
group Group @relation(fields: [groupId], 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) 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") @@map("group_members")
} }
@@ -69,44 +74,77 @@ enum AttendeeStatus {
model Attendee { model Attendee {
id String @id @default(cuid()) id String @id @default(cuid())
groupId String groupId String @map("group_id")
fullName String fullName String @map("full_name")
email String? email String?
phone String? phone String?
guardianName String? guardianName String? @map("guardian_name")
guardianPhone String? guardianPhone String? @map("guardian_phone")
notes String? notes String?
notifyToken String? @unique @default(cuid()) notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
status AttendeeStatus @default(ACTIVE) status AttendeeStatus @default(ACTIVE)
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
payments Payment[] payments Payment[]
attendances Attendance[] attendances Attendance[]
slotReleases SlotRelease[] slotReleases SlotRelease[]
outboundMessages OutboundMessage[]
alertResolutions AttendeeAlertResolution[]
studentAccounts StudentAccountAttendee[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@index([groupId]) @@index([groupId], map: "attendees_groupId_idx")
@@map("attendees") @@map("attendees")
} }
model Payment { enum StudentAlertKind {
id String @id @default(cuid()) ATTENDANCE
groupId String PAYMENT
attendeeId String }
amount Decimal @db.Decimal(10, 2)
currency String @default("MXN") // "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED // it hides the alert while its signature (last absence / overdue fees) stays
dueDate DateTime // the same, so a new absence or a new overdue fee brings it back on its own.
paidAt DateTime? model AttendeeAlertResolution {
createdAt DateTime @default(now()) id String @id @default(cuid())
updatedAt DateTime @updatedAt attendeeId String @map("attendee_id")
kind StudentAlertKind
signature String
resolvedById String @map("resolved_by_id")
resolvedAt DateTime @default(now()) @map("resolved_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@index([groupId]) @@unique([attendeeId, kind])
@@index([attendeeId]) @@map("attendee_alert_resolutions")
}
model Payment {
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, map: "payments_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
outboundMessages OutboundMessage[]
reportedItems ReportedPaymentItem[]
@@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx")
@@map("payments") @@map("payments")
} }
@@ -118,16 +156,16 @@ enum PaymentStatus {
} }
model WaitlistEntry { model WaitlistEntry {
id String @id @default(cuid()) id String @id @default(cuid())
email String email String
name String? name String?
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt 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]) @@unique([email])
@@map("waitlist_entries") @@map("waitlist_entries")
@@ -135,19 +173,19 @@ model WaitlistEntry {
model GroupWaitlistEntry { model GroupWaitlistEntry {
id String @id @default(cuid()) id String @id @default(cuid())
groupId String groupId String @map("group_id")
fullName String fullName String @map("full_name")
phone String phone String
email String? email String?
notes String? notes String?
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_waitlist_entries_groupId_fkey")
@@unique([groupId, phone]) @@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key")
@@index([groupId]) @@index([groupId], map: "group_waitlist_entries_groupId_idx")
@@map("group_waitlist_entries") @@map("group_waitlist_entries")
} }
@@ -165,39 +203,66 @@ enum PreRegistrationStatus {
} }
model GroupPreRegistration { model GroupPreRegistration {
id String @id @default(cuid()) id String @id @default(cuid())
groupId String groupId String @map("group_id")
fullName String fullName String @map("full_name")
phone String phone String
email String? email String?
status PreRegistrationStatus @default(PENDING) status PreRegistrationStatus @default(PENDING)
reviewedAt DateTime? reviewedAt DateTime? @map("reviewed_at")
createdAt DateTime @default(now()) createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey")
@@unique([groupId, phone]) @@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
@@index([groupId]) @@index([groupId], map: "group_pre_registrations_groupId_idx")
@@map("group_pre_registrations") @@map("group_pre_registrations")
} }
enum PaymentProvider { enum MpAccountStatus {
MERCADO_PAGO ACTIVE
STRIPE REQUIRES_REAUTH
REVOKED
} }
model MerchantAccount { // Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
id String @id @default(cuid()) // Tokens are stored encrypted (AES-256-GCM); there is a single active account per
userId String @unique // teacher and a Mercado Pago user cannot be linked to two teachers.
provider PaymentProvider model MpAccount {
accessToken String? id String @id @default(cuid())
sandbox Boolean @default(true) ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
connectedAt DateTime @default(now()) mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
createdAt DateTime @default(now()) accessTokenEnc String @map("access_token_enc")
updatedAt DateTime @updatedAt 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")
user User @relation(fields: [userId], references: [id], onDelete: Cascade) owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
@@map("merchant_accounts") // 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")
}

View File

@@ -0,0 +1,235 @@
// 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)
attendees StudentAccountAttendee[]
tokens StudentAccessToken[]
sessions StudentSession[]
passkeys StudentPasskey[]
challenges StudentWebauthnChallenge[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@index([recoveryEmail])
@@index([createdById])
@@map("student_accounts")
}
model StudentAccountAttendee {
accountId String @map("account_id")
attendeeId String @map("attendee_id")
createdAt DateTime @default(now()) @map("created_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@id([accountId, attendeeId])
@@index([attendeeId])
@@map("student_account_attendees")
}
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:<sha256>", "recovery:ip:<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")
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")
}

View File

@@ -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")
}

View File

@@ -7,4 +7,4 @@ generator client {
datasource db { datasource db {
provider = "postgresql" provider = "postgresql"
} }

View File

@@ -10,20 +10,26 @@ import { requestLoggerMiddleware } from '@/http/request-logger';
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers'; import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
import { sessionAuthMiddleware } from '@/http/session-auth'; import { sessionAuthMiddleware } from '@/http/session-auth';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { adminRoutes } from './modules/admin';
import { import {
groupsRiskOverviewRoute, groupsRiskOverviewRoute,
studentStatusRoutes, studentStatusRoutes,
} from './modules/analytics'; } from './modules/analytics';
import { attendeesRoutes } from './modules/attendees'; import { attendeesRoutes } from './modules/attendees';
import { attentionRoutes } from './modules/attention';
import { authRoutes } from './modules/auth'; import { authRoutes } from './modules/auth';
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
import { classesRoutes } from './modules/classes'; import { classesRoutes } from './modules/classes';
import { groupsRoutes } from './modules/groups'; import { groupsRoutes } from './modules/groups';
import { healthCheckRoutes } from './modules/health-check'; import { healthCheckRoutes } from './modules/health-check';
import { homeRoutes } from './modules/home'; import { homeRoutes } from './modules/home';
import { invitationsRoutes } from './modules/invitations'; import { invitationsRoutes } from './modules/invitations';
import { mpRoutes } from './modules/mp';
import { onboardingRoutes } from './modules/onboarding'; import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments'; import { paymentsRoutes } from './modules/payments';
import { studentPortalRoutes } from './modules/student-portal';
import { waitlistRoutes } from './modules/waitlist'; import { waitlistRoutes } from './modules/waitlist';
import { whatsappRoutes } from './modules/whatsapp';
const app = new Hono<BackendEnv>(); const app = new Hono<BackendEnv>();
@@ -38,18 +44,31 @@ const api = app.basePath('/api/v1');
api.use('*', sessionAuthMiddleware); 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('/auth', authRoutes);
api.route('/health', healthCheckRoutes); api.route('/health', healthCheckRoutes);
api.route('/invitations', invitationsRoutes); api.route('/invitations', invitationsRoutes);
api.route('/groups', groupsRoutes); api.route('/groups', groupsRoutes);
api.route('/home', homeRoutes); api.route('/home', homeRoutes);
api.route('/onboarding', onboardingRoutes); api.route('/onboarding', onboardingRoutes);
api.route('/mp', mpRoutes);
api.route('/whatsapp', whatsappRoutes);
api.route('/attendees', attendeesRoutes); api.route('/attendees', attendeesRoutes);
api.route('/payments', paymentsRoutes); api.route('/payments', paymentsRoutes);
api.route('/billing', billingRoutes);
api.route('/waitlist', waitlistRoutes); api.route('/waitlist', waitlistRoutes);
api.route('/classes', classesRoutes); api.route('/classes', classesRoutes);
api.route('/students', studentStatusRoutes); api.route('/students', studentStatusRoutes);
api.route('/groups-risk', groupsRiskOverviewRoute); api.route('/groups-risk', groupsRiskOverviewRoute);
api.route('/attention', attentionRoutes);
api.route('/student-portal', studentPortalRoutes);
app.notFound((c) => { app.notFound((c) => {
return problemJson(c, notFoundProblem(c.req.path)); return problemJson(c, notFoundProblem(c.req.path));

View File

@@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth';
type AuthSession = typeof auth.$Infer.Session; 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 = { export type BackendEnv = {
Variables: { Variables: {
user: AuthSession['user'] | null; user: AuthSession['user'] | null;
session: AuthSession['session'] | null; session: AuthSession['session'] | null;
requestId: string; requestId: string;
student: StudentContext | null;
}; };
}; };
@@ -15,5 +19,6 @@ declare module 'hono' {
user: AuthSession['user'] | null; user: AuthSession['user'] | null;
session: AuthSession['session'] | null; session: AuthSession['session'] | null;
requestId: string; requestId: string;
student: StudentContext | null;
} }
} }

View File

@@ -71,13 +71,108 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl
return notFoundProblem(`${resourceName} ${id}`); return notFoundProblem(`${resourceName} ${id}`);
} }
export function paymentNotSetupProblem(): ProblemDetails { export function mpNotConnectedProblem(): ProblemDetails {
return conflictProblem({ return conflictProblem({
detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.', detail: 'No tenés una cuenta de Mercado Pago vinculada.',
code: 'payment_not_setup', 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 { export function onboardingAlreadyCompletedProblem(): ProblemDetails {
return conflictProblem({ return conflictProblem({
detail: 'Ya completaste el onboarding de Gruperly.', detail: 'Ya completaste el onboarding de Gruperly.',
@@ -106,4 +201,111 @@ export function attendeeHasPaymentsProblem(): ProblemDetails {
detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.', detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.',
code: 'attendee_has_payments', 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 }): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/plan`,
title: 'Payment Required',
status: 402,
detail: params.detail,
code: params.code,
};
}
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',
});
}
/** 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',
});
}
/** 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',
});
}

View File

@@ -27,19 +27,39 @@ export function isPublicApiRequest(method: string, path: string): boolean {
const normalizedPath = normalizePath(path); const normalizedPath = normalizePath(path);
// Aviso de ausencia con token personal del alumno (sin sesión). // Absence notice sent with the attendee's personal token (no session).
if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') { if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
return true; return true;
} }
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') { if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
return true; 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 ( return (
normalizedPath === '/api/v1/health' normalizedPath === '/api/v1/health'
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth') || matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|| matchesPublicPrefix(normalizedPath, '/api/auth') || matchesPublicPrefix(normalizedPath, '/api/auth')
|| matchesPublicPrefix(normalizedPath, '/api/v1/invitations') || 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')
); );
} }

View File

@@ -4,15 +4,24 @@ import nodemailer, { type Transporter } from 'nodemailer'
type VerificationEmailData = { email: string; url: string; name?: string } type VerificationEmailData = { email: string; url: string; name?: string }
type PasswordResetEmailData = { email: string; url: string; name?: string } type PasswordResetEmailData = { email: string; url: string; name?: string }
type InvitationEmailData = { email: string; url: string; organizationName: 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
}
// Colores de marca (mismo sistema que la web: index.css de apps/web). // Brand colors (same system as the web app: index.css in apps/web).
const BRAND_600 = '#2544ea' const BRAND_600 = '#2544ea'
const TEXT_STRONG = '#0f172a' const TEXT_STRONG = '#0f172a'
const TEXT_MUTED = '#475569' const TEXT_MUTED = '#475569'
const ON_ACCENT = '#ffffff' const ON_ACCENT = '#ffffff'
const LINK_BG = BRAND_600 const LINK_BG = BRAND_600
// Logotipo embebido como data URI para que los mails no dependan de hosting. // Logo embedded as a data URI so the emails don't depend on hosting.
function loadLogoTypoDataUri(): string { function loadLogoTypoDataUri(): string {
try { try {
const base64 = readFileSync( const base64 = readFileSync(
@@ -26,10 +35,27 @@ function loadLogoTypoDataUri(): string {
const LOGO_DATA_URI = loadLogoTypoDataUri() const LOGO_DATA_URI = loadLogoTypoDataUri()
interface EmailProvider { export interface EmailProvider {
sendVerificationEmail(data: VerificationEmailData): Promise<void> sendVerificationEmail(data: VerificationEmailData): Promise<void>
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void> sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
sendOrganizationInvitation(data: InvitationEmailData): Promise<void> sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
}
// Names come from what teachers and students type: never raw into the HTML.
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
function button(url: string, label: string): string {
return `<a href="${escapeHtml(url)}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">${escapeHtml(label)}</a>`
} }
class SMTPEmailProvider implements EmailProvider { class SMTPEmailProvider implements EmailProvider {
@@ -66,7 +92,7 @@ class SMTPEmailProvider implements EmailProvider {
} }
private async send(to: string, subject: string, html: string) { 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) { if (!process.env.EMAIL_SERVER_HOST) {
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`) console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
return return
@@ -109,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.<br/><br/>${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
? `<p style="margin:12px 0 4px;">${escapeHtml(link.name)}</p>${button(link.url, 'Ingresar')}`
: button(link.url, 'Ingresar'),
)
.join('<br/>')
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.<br/><br/>${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 ? `<br/><br/>Motivo: ${escapeHtml(reason)}` : ''}<br/><br/>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). // Future: transactional providers (Resend, SendGrid, Postmark).
// Añadir implementaciones y alternar con EMAIL_PROVIDER. // Add implementations and switch between them with EMAIL_PROVIDER.
export function createEmailProvider(): EmailProvider { export function createEmailProvider(): EmailProvider {
return new SMTPEmailProvider() return new SMTPEmailProvider()
} }

View File

@@ -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<ReceiptMime, string> = {
'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;
}

View File

@@ -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<void>;
/** GET URL valid for `expiresInSeconds`. */
signedUrl(key: string, expiresInSeconds: number): string;
remove(key: string): Promise<void>;
}
/* 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<void> {
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<void> {
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;
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'billingCharge'>;
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<Result<AdminAccountDetail, ProblemDetails>> {
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),
});
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'group'>;
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<Result<AdminAccountList, ProblemDetails>> {
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<string, AccountUsage>();
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),
});
}
}

View File

@@ -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;

View File

@@ -0,0 +1 @@
export { default as adminRoutes } from './routes';

View File

@@ -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<string, string | undefined> = 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<string, string | undefined> = process.env,
): MiddlewareHandler<BackendEnv> {
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();
};
}

View File

@@ -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<AccountRecord, 'planSelectedAt' | 'subscription'>,
{ 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<AdminAccountQuery, 'search' | 'country' | 'plan' | 'subscriptionStatus'>,
{ 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 } : {};
}

View File

@@ -0,0 +1,9 @@
export { adminOnlyMiddleware, isAdminEmail } from './access';
export {
type AccountRecord,
type AccountUsage,
accountPlan,
buildAccountWhere,
type PlanContext,
toAccountListItem,
} from './account-summary';

View File

@@ -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;

View File

@@ -33,14 +33,27 @@ export class GetAttendeeHistory {
const attendee = await db.attendee.findFirst({ const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId }, where: { id: attendeeId, groupId },
select: { id: true, fullName: true }, select: { id: true, fullName: true, createdAt: true },
}); });
if (!attendee) { if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId)); 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({ const sessions = await db.classSession.findMany({
where: { groupId }, where: { groupId, startsAt: { gte: since } },
orderBy: { startsAt: 'desc' }, orderBy: { startsAt: 'desc' },
take: HISTORY_SESSIONS_LIMIT, take: HISTORY_SESSIONS_LIMIT,
select: { id: true, startsAt: true }, select: { id: true, startsAt: true },
@@ -80,4 +93,4 @@ export class GetAttendeeHistory {
sessions: orderedSessions, sessions: orderedSessions,
}); });
} }
} }

View File

@@ -6,15 +6,17 @@ import type {
GroupsRiskOverview, GroupsRiskOverview,
ProblemDetails, ProblemDetails,
Result, Result,
UrgentMemberSummary,
} from '@gruperly/shared';
import {
ATTENDANCE_RISK_RULES,
getGroupAttendanceSummary,
ok,
URGENT_MEMBERS_LIMIT,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
classifyRisk,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
type GetGroupsRiskOverviewDeps = { type GetGroupsRiskOverviewDeps = {
@@ -27,18 +29,26 @@ type GetGroupsRiskOverviewDeps = {
now?: Date; now?: Date;
}; };
type GroupRow = { id: string; name: string }; type GroupRow = {
type AttendeeRow = { id: string; groupId: string }; id: string;
type SessionRow = { id: string; groupId: 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 = { type AttendanceRow = {
attendeeId: string; attendeeId: string;
classSessionId: string;
status: AttendanceStatus; status: AttendanceStatus;
classSession: { startsAt: Date }; classSession: { startsAt: Date };
}; };
// Resumen de semáforo de riesgo por grupo para la lista de grupos. // Risk summary per group for the group listing and Home. Everything comes from
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si // the domain rule (`getGroupAttendanceSummary`): the status light is the worst
// alguno en riesgo moderado y NONE en caso contrario. // 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 { export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -49,30 +59,39 @@ export class GetGroupsRiskOverview {
const groups = (await db.group.findMany({ const groups = (await db.group.findMany({
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
select: { id: true, name: true }, select: {
})) as GroupRow[]; id: true,
name: true,
capacity: true,
_count: { select: { waitlist: { where: { status: 'PENDING' } } } },
},
})) as unknown as GroupRow[];
if (groups.length === 0) { if (groups.length === 0) {
return ok({ items: [] }); return ok({ items: [] });
} }
const groupIds = groups.map((group) => group.id); const groupIds = groups.map((group) => group.id);
const attendeeGroup = new Map<string, string>();
const sessionCountByGroup = new Map<string, number>();
const [attendees, sessions, attendances] = await Promise.all([ const [attendees, sessions, attendances] = await Promise.all([
db.attendee.findMany({ db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' }, where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true }, select: { id: true, groupId: true, fullName: true, createdAt: true },
}) as Promise<AttendeeRow[]>, }) as Promise<AttendeeRow[]>,
db.classSession.findMany({ db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { gte: since } }, where: { groupId: { in: groupIds }, startsAt: { gte: since } },
select: { id: true, groupId: true }, select: { id: true, groupId: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}) as Promise<SessionRow[]>, }) as Promise<SessionRow[]>,
/* 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({ db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds } } }, where: { attendee: { groupId: { in: groupIds } } },
select: { select: {
attendeeId: true, attendeeId: true,
classSessionId: true,
status: true, status: true,
classSession: { select: { startsAt: true } }, classSession: { select: { startsAt: true } },
}, },
@@ -80,51 +99,93 @@ export class GetGroupsRiskOverview {
}) as Promise<AttendanceRow[]>, }) as Promise<AttendanceRow[]>,
]); ]);
for (const attendee of attendees) { const sessionsByGroup = new Map<string, SessionRow[]>();
attendeeGroup.set(attendee.id, attendee.groupId);
}
for (const session of sessions) { for (const session of sessions) {
sessionCountByGroup.set(session.groupId, (sessionCountByGroup.get(session.groupId) ?? 0) + 1); const list = sessionsByGroup.get(session.groupId) ?? [];
list.push(session);
sessionsByGroup.set(session.groupId, list);
} }
const streamByAttendee = groupAttendanceByAttendee(attendances); const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>(); const items: GroupRiskSummary[] = groups.map((group) =>
for (const attendee of attendees) { buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
const groupId = attendeeGroup.get(attendee.id)!; );
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const streak = trailingAbsentStreak(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
sessionCountByGroup.get(groupId) ?? 0,
);
const riskLevel = classifyRisk(streak, monthlyRate);
if (!riskLevel) {
continue;
}
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
if (
riskLevel === 'HIGH' ||
(riskLevel === 'MEDIUM' && current === 'NONE')
) {
worstRiskByGroup.set(groupId, riskLevel);
}
}
const items: GroupRiskSummary[] = groups.map((group) => ({
groupId: group.id,
groupName: group.name,
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
}));
return ok({ items }); 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<string, SessionRow[]>,
attendanceByAttendee: Map<string, AttendanceRow[]>,
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<string, AttendanceRow[]> { function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
const byAttendee = new Map<string, AttendanceRow[]>(); const byAttendee = new Map<string, AttendanceRow[]>();
for (const row of rows) { for (const row of rows) {
@@ -133,4 +194,4 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
byAttendee.set(row.attendeeId, list); byAttendee.set(row.attendeeId, list);
} }
return byAttendee; return byAttendee;
} }

View File

@@ -6,24 +6,21 @@ import type {
StudentAtRisk, StudentAtRisk,
StudentsAtRisk, StudentsAtRisk,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok, summarizeMemberAttendance } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
import { import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
classifyRisk, import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
lastAttendedAt,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
type GetStudentsAtRiskDeps = { type GetStudentsAtRiskDeps = {
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>; db?: AnalyticsAccessDb & StudentsAtRiskDb;
now?: Date; now?: Date;
}; };
type AttendanceStreamRow = { type AttendanceStreamRow = {
attendeeId: string; attendeeId: string;
classSessionId: string;
status: AttendanceStatus; status: AttendanceStatus;
classSession: { startsAt: Date }; classSession: { startsAt: Date };
}; };
@@ -37,72 +34,13 @@ export class GetStudentsAtRisk {
): Promise<Result<StudentsAtRisk, ProblemDetails>> { ): Promise<Result<StudentsAtRisk, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date(); const now = this.deps.now ?? new Date();
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
const access = await findGroupForUser(db, groupId, userId); const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) { if (!access.ok) {
return access; return access;
} }
const [windowSessions, attendees, attendances] = await Promise.all([ const atRisk = await findStudentsAtRisk(db, groupId, now);
db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
select: { id: true },
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true },
}),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {
attendeeId: 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 stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const consecutiveAbsences = trailingAbsentStreak(stream);
const attendedAt = lastAttendedAt(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
totalWindowSessions,
);
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
if (!riskLevel) {
continue;
}
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 ok({ return ok({
groupName: access.value.name, groupName: access.value.name,
@@ -111,6 +49,88 @@ export class GetStudentsAtRisk {
} }
} }
export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
/**
* 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<StudentAtRisk[]> {
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, fullName: true, phone: true, createdAt: true },
}),
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<string, AttendanceStreamRow[]> { function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
const byAttendee = new Map<string, AttendanceStreamRow[]>(); const byAttendee = new Map<string, AttendanceStreamRow[]>();
for (const row of rows) { for (const row of rows) {

View File

@@ -12,7 +12,7 @@ type GroupWithAccess = {
members: { userId: string }[]; members: { userId: string }[];
}; };
// Verifica que el usuario sea owner o miembro del grupo. Devuelve el grupo si tiene acceso. // Verifies the user is the group owner or a member. Returns the group if they have access.
export async function findGroupForUser( export async function findGroupForUser(
db: AnalyticsAccessDb, db: AnalyticsAccessDb,
groupId: string, groupId: string,

View File

@@ -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<Date | null>(
(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,
}));
}

View File

@@ -3,22 +3,7 @@ export type AttendanceStreamEntry = {
occurredAt: Date; occurredAt: Date;
}; };
export type RiskLevel = 'HIGH' | 'MEDIUM'; // Date of the last class the attendee showed up to (PRESENT), or null.
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
let streak = 0;
for (const entry of entries) {
if (entry.status !== 'ABSENT') {
break;
}
streak += 1;
}
return streak;
}
// Fecha de la última clase a la que el alumno asistió (PRESENT), o null.
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null { export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
for (const entry of entries) { for (const entry of entries) {
if (entry.status === 'PRESENT') { if (entry.status === 'PRESENT') {
@@ -28,8 +13,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
return null; return null;
} }
// Porcentaje de asistencia sobre el total de sesiones del período. // Attendance rate over the total number of sessions in the period.
// Las sesiones sin registrar cuentan como no asistidas. // Sessions with no record count as not attended.
export function monthlyAttendanceRate( export function monthlyAttendanceRate(
entries: AttendanceStreamEntry[], entries: AttendanceStreamEntry[],
totalSessions: number, totalSessions: number,
@@ -40,17 +25,3 @@ export function monthlyAttendanceRate(
const present = entries.filter((entry) => entry.status === 'PRESENT').length; const present = entries.filter((entry) => entry.status === 'PRESENT').length;
return Math.round((present / totalSessions) * 100); return Math.round((present / totalSessions) * 100);
} }
// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 50%.
export function classifyRisk(
consecutiveAbsences: number,
monthlyRate: number,
): RiskLevel | null {
if (consecutiveAbsences >= 3) {
return 'HIGH';
}
if (consecutiveAbsences === 2 || monthlyRate < 50) {
return 'MEDIUM';
}
return null;
}

View File

@@ -8,10 +8,12 @@ import type {
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type BulkCreateAttendeesDeps = { type BulkCreateAttendeesDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
export class BulkCreateAttendeesUseCase { export class BulkCreateAttendeesUseCase {
@@ -41,7 +43,7 @@ export class BulkCreateAttendeesUseCase {
return err(noGroupAccessProblem()); return err(noGroupAccessProblem());
} }
// Cargar teléfonos existentes del grupo // Load the group's existing phone numbers
const existingAttendees = await db.attendee.findMany({ const existingAttendees = await db.attendee.findMany({
where: { groupId }, where: { groupId },
select: { phone: true }, select: { phone: true },
@@ -88,6 +90,16 @@ export class BulkCreateAttendeesUseCase {
}); });
} }
// 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,
toCreateData.length,
);
if (!allowed.ok) {
return allowed;
}
const createdRecords: AttendeeRecord[] = []; const createdRecords: AttendeeRecord[] = [];
for (const data of toCreateData) { for (const data of toCreateData) {
const record = await db.attendee.create({ data }); const record = await db.attendee.create({ data });

View File

@@ -9,10 +9,12 @@ import {
notFoundResourceProblem, notFoundResourceProblem,
} from '@/http/problem-builders'; } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type CreateAttendeeDeps = { type CreateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
type CreateAttendeeOptions = { type CreateAttendeeOptions = {
@@ -106,6 +108,12 @@ export class CreateAttendeeUseCase {
} }
} }
// The owner's plan pays for the attendee, whoever adds it.
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
if (!allowed.ok) {
return allowed;
}
const attendee = await db.attendee.create({ const attendee = await db.attendee.create({
data: { data: {
groupId, groupId,

View File

@@ -1,10 +1,10 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared'; import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers'; import { toAttendeeListItemDto } from '../../lib/helpers';
type ListAttendeesDeps = { type ListAttendeesDeps = {
db?: Pick<PrismaClient, 'attendee'>; db?: Pick<PrismaClient, 'attendee'>;
@@ -18,18 +18,37 @@ export class ListAttendees {
const where = query.groupId ? { groupId: query.groupId } : undefined; const where = query.groupId ? { groupId: query.groupId } : undefined;
const [records, total] = await Promise.all([ 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({ db.attendee.findMany({
...(where ? { where } : {}), ...(where ? { where } : {}),
skip: getPaginationOffset(query), skip: getPaginationOffset(query),
take: query.pageSize, take: query.pageSize,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: {
// 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(), where ? db.attendee.count({ where }) : db.attendee.count(),
]); ]);
return ok({ return ok({
data: records.map((r) => toAttendeeDto(r as AttendeeRecord)), data: records.map((record) => toAttendeeListItemDto(record)),
pagination: getPaginationMetadata(query, total), pagination: getPaginationMetadata(query, total),
}); });
} }
} }

View File

@@ -1,14 +1,15 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; import type { AttendeeDetailDto, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { toAttendeeDto } from '../../lib/helpers'; import { toAttendeeDetailDto } from '../../lib/helpers';
type GetAttendeeDeps = { type GetAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee'>;
now?: () => Date;
}; };
export class GetAttendee { export class GetAttendee {
@@ -18,7 +19,7 @@ export class GetAttendee {
groupId: string, groupId: string,
attendeeId: string, attendeeId: string,
userId: string, userId: string,
): Promise<Result<AttendeeDto, ProblemDetails>> { ): Promise<Result<AttendeeDetailDto, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const access = await findGroupForUser(db, groupId, userId); const access = await findGroupForUser(db, groupId, userId);
@@ -26,11 +27,32 @@ export class GetAttendee {
return access; return access;
} }
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } }); const billingPeriod = currentMonthRange((this.deps.now ?? (() => new Date()))());
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
include: {
payments: {
where: {
status: { not: 'CANCELLED' },
dueDate: { gte: billingPeriod.start, lt: billingPeriod.end },
},
orderBy: { dueDate: 'desc' },
take: 1,
select: { status: true, dueDate: true },
},
},
});
if (!attendee) { if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId)); return err(notFoundResourceProblem('Attendee', attendeeId));
} }
return ok(toAttendeeDto(attendee)); return ok(toAttendeeDetailDto(attendee));
} }
} }
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)),
};
}

View File

@@ -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;

View File

@@ -0,0 +1,44 @@
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 { toAttendeeDto } from '../../lib/helpers';
type UpdateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
};
type UpdateAttendeeCommand = {
groupId: string;
attendeeId: string;
userId: string;
input: UpdateAttendee;
};
export class UpdateAttendeeDetails {
constructor(private readonly deps: UpdateAttendeeDeps = {}) {}
async execute(command: UpdateAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
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 } });
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
const updated = await db.attendee.update({
where: { id: attendeeId },
data: normalizeEditableFields(input),
});
return ok(toAttendeeDto(updated));
}
}
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
return Object.fromEntries(
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]),
);
}

View File

@@ -1,4 +1,4 @@
import type { AttendeeDto } from '@gruperly/shared'; import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
export type AttendeeRecord = { export type AttendeeRecord = {
id: string; id: string;
@@ -14,6 +14,19 @@ export type AttendeeRecord = {
updatedAt: Date; updatedAt: Date;
}; };
/** Listing item with the attendance and payment summary already resolved. */
export type AttendeeListItemRecord = AttendeeRecord & {
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
payments: {
status: NonNullable<AttendeeListItem['payment']>['status'];
dueDate: Date;
}[];
};
export type AttendeeDetailRecord = AttendeeRecord & {
payments: AttendeeListItemRecord['payments'];
};
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
return { return {
id: record.id, id: record.id,
@@ -30,9 +43,47 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
}; };
} }
/* 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),
};
}
/* 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),
};
}
/** /**
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos. * Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
* Conserva el '+' si lo tiene al inicio para números internacionales. * Keeps a leading '+' for international numbers.
*/ */
export function normalizePhone(rawPhone: string): string { export function normalizePhone(rawPhone: string): string {
const trimmed = rawPhone.trim(); const trimmed = rawPhone.trim();

View File

@@ -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;

View File

@@ -0,0 +1,181 @@
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 { buildGroupWhereForUser } from '@/modules/groups/lib';
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<Result<AttentionOverview, ProblemDetails>> {
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, fullName: true, phone: true, guardianPhone: true, createdAt: true },
orderBy: { createdAt: 'asc' },
}) as Promise<AttendeeRow[]>,
// 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<SessionRow[]>,
db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
select: {
attendeeId: true,
classSessionId: true,
status: true,
classSession: { select: { startsAt: true } },
},
}) as Promise<AttendanceRow[]>,
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<PaymentRow[]>,
db.attendeeAlertResolution.findMany({
where: { attendee: { groupId: { in: groupIds } } },
select: { attendeeId: true, kind: true, signature: true },
}) as Promise<ResolutionRow[]>,
]);
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 = attendee.phone ?? attendee.guardianPhone;
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<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
const map = new Map<string, T[]>();
for (const row of rows) {
const list = map.get(key(row)) ?? [];
list.push(row);
map.set(key(row), list);
}
return map;
}

View File

@@ -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;

View File

@@ -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<Result<ResolveAlertResult, ProblemDetails>> {
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 });
}
}

View File

@@ -0,0 +1 @@
export { default as attentionRoutes } from './routes';

View File

@@ -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<StudentAlertKind, StudentAlertType> = {
ATTENDANCE: 'asistencia',
PAYMENT: 'pago',
};
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
asistencia: 'ATTENDANCE',
pago: 'PAYMENT',
};

View File

@@ -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;

View File

@@ -14,6 +14,7 @@ export const auth = betterAuth({
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
minPasswordLength: 8, minPasswordLength: 8,
revokeSessionsOnPasswordReset: true,
sendResetPassword: async ({ user, url }) => { sendResetPassword: async ({ user, url }) => {
await emailProvider.sendPasswordResetEmail({ await emailProvider.sendPasswordResetEmail({
email: user.email, email: user.email,

View File

@@ -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;

View File

@@ -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<PrismaClient, 'billingSubscription'>;
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<Result<{ status: SubscriptionStatus }, ProblemDetails>> {
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' });
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'billingCharge'> };
/** The professor's own Pro charges, newest first. */
export class ListBillingCharges {
constructor(private readonly deps: ListBillingChargesDeps = {}) {}
async execute(
query: BillingChargesQuery,
userId: string,
): Promise<Result<BillingChargeList, ProblemDetails>> {
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),
});
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'billingSubscription'>;
guard?: PlanGuard;
sync?: Pick<SyncSubscription, 'execute'>;
providers?: BillingProviderResolver;
now?: () => Date;
};
export class GetBillingStatus {
constructor(private readonly deps: GetBillingStatusDeps = {}) {}
async execute(userId: string): Promise<Result<BillingStatusDto, ProblemDetails>> {
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,
});
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'billingSubscription'>;
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<Result<SubscribeResultDto, ProblemDetails>> {
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<ReturnType<typeof provider.start>>;
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 });
}
}

View File

@@ -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<BillingWebhookFailure, 401 | 404 | 500 | 503> = {
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;

View File

@@ -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<PrismaClient, 'billingWebhookEvent'>;
providers?: BillingProviderResolver;
sync?: Pick<SyncSubscription, 'byExternalId'>;
};
/** 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<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
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');
}
}
}

View File

@@ -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';

View File

@@ -0,0 +1,2 @@
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
export { startBillingJobs } from './schedule';

View File

@@ -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<PrismaClient, 'billingSubscription'>;
sync?: Pick<SyncSubscription, 'execute'>;
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<ReconcileTotals> {
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;
}
}

View File

@@ -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();
}

View File

@@ -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<string, string | undefined> = 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<string, string | undefined> = process.env): number {
const value = Number(env.BILLING_GRACE_DAYS);
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
}

View File

@@ -0,0 +1,173 @@
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<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
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<Entitlements> {
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 } }),
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
]);
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<Result<void, ProblemDetails>> {
if (!this.enforced) return ok(undefined);
const entitlements = await this.getEntitlements(ownerId);
return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined);
}
async canCreateGroup(ownerId: string): Promise<Result<void, ProblemDetails>> {
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<Result<void, ProblemDetails>> {
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<Result<void, ProblemDetails>> {
return (await this.hasFeature(ownerId, feature))
? ok(undefined)
: err(planFeatureRequiredProblem(feature));
}
async hasFeature(ownerId: string, feature: PlanFeature): Promise<boolean> {
if (!this.enforced) return true;
const { limits } = await this.getEntitlements(ownerId);
return limits[feature];
}
}

View File

@@ -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;

View File

@@ -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';

View File

@@ -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<BackendEnv> {
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();
};
}

View File

@@ -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<PrismaClient, 'billingSubscription' | 'billingCharge'>;
providers?: BillingProviderResolver;
now?: () => Date;
};
export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null };
export function subscriptionRefOf(
row: Pick<BillingSubscription, 'country' | 'externalId' | 'checkoutRef'>,
): 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<Result<SyncOutcome, ProblemDetails>> {
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<Result<SyncOutcome, ProblemDetails>> {
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 });
}
}

View File

@@ -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/<name>/`. 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:<CC>` 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<StartedSubscription>;
/** `null` while the professor has not completed the checkout. */
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
/** Stops the monthly charge, or voids a checkout never completed. */
cancel(ref: SubscriptionRef): Promise<void>;
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
}
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();
}

View File

@@ -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/<name>/` 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();
}
};

View File

@@ -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<string, string | undefined> = 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 };
}

View File

@@ -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<string, SubscriptionStatus> = {
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<MpAuthorizedPayment, 'status' | 'paymentStatus'>): 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<StartedSubscription> {
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<ProviderSubscription | null> {
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<ProviderCharge[]> {
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<void> {
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<Result<BillingWebhookHint, BillingWebhookFailure>> {
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 };
}
}

View File

@@ -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<Record<string, unknown>> {
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<string, unknown> | 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<string, unknown>;
}
function toPreapproval(payload: Record<string, unknown>): 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<MpPreapproval> {
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<MpPreapproval> {
return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`));
}
export async function cancelPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
return toPreapproval(
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
method: 'PUT',
body: { status: 'cancelled' },
}),
);
}
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
const payment = (payload.payment ?? null) as Record<string, unknown> | 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<MpAuthorizedPayment> {
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<MpAuthorizedPayment[]> {
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<string, unknown>[]) : [];
invoices.push(...results.map(toAuthorizedPayment));
const total = Number((payload.paging as Record<string, unknown> | 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,
};

View File

@@ -0,0 +1,40 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
/**
* Checks Mercado Pago's `x-signature` header (`ts=<ts>,v1=<hex>`).
*
* 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);
}

View File

@@ -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<string, string | undefined> = 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 };
}

View File

@@ -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<string, SubscriptionStatus> = {
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<string, ChargeStatus> = {
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<StartedSubscription> {
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<ProviderSubscription | null> {
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<ProviderCharge[]> {
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<void> {
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<Result<BillingWebhookHint, BillingWebhookFailure>> {
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;
}

View File

@@ -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<string, unknown>;
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<string, FormValue>): 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<string, FormValue>; query?: URLSearchParams },
) => Promise<StripeObject>;
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;
};
}

View File

@@ -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=<ts>,v1=<hex>[,v1=<hex>…]`).
*
* Stripe signs `<ts>.<raw body>` 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);
});
}

View File

@@ -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;

View File

@@ -7,7 +7,7 @@ import { GetAbsenceDetails } from './use-case';
const route = new Hono(); const route = new Hono();
// Ruta pública (whitelistada en session-auth): el alumno entra con su token personal. // Public route (whitelisted in session-auth): the attendee gets in with their personal token.
route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => { route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => {
const query = c.req.valid('query') as AbsenceQuery; const query = c.req.valid('query') as AbsenceQuery;
const useCase = new GetAbsenceDetails(); const useCase = new GetAbsenceDetails();

View File

@@ -7,7 +7,7 @@ import { PublicNotifyAbsenceUseCase } from './use-case';
const route = new Hono(); const route = new Hono();
// Ruta pública (whitelistada en session-auth): el alumno avisa su ausencia con token. // Public route (whitelisted in session-auth): the attendee reports an absence with a token.
route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => { route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => {
const payload = c.req.valid('json') as PublicNotifyAbsence; const payload = c.req.valid('json') as PublicNotifyAbsence;
const useCase = new PublicNotifyAbsenceUseCase(); const useCase = new PublicNotifyAbsenceUseCase();

View File

@@ -18,8 +18,8 @@ type PaymentLike = {
dueDate: Date; dueDate: Date;
}; };
// Estado de cobro calculado en tiempo real (sin columna denormalizada): // Payment status computed in real time (no denormalized column):
// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó. // PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed.
export function resolvePaymentStatus( export function resolvePaymentStatus(
payments: PaymentLike[], payments: PaymentLike[],
startOfToday: Date, startOfToday: Date,
@@ -52,7 +52,7 @@ type GroupWithAccess = {
members: { userId: string }[]; members: { userId: string }[];
}; };
// Verifica que el usuario sea owner o miembro del grupo dueño de la sesión. // Verifies the user is the owner or a member of the group that owns the session.
export function ensureSessionAccess( export function ensureSessionAccess(
session: ClassSessionRecord & { group: GroupWithAccess }, session: ClassSessionRecord & { group: GroupWithAccess },
userId: string, userId: string,

Some files were not shown because too many files have changed in this diff Show More