Compare commits
37 Commits
feat/atten
...
b11dd47534
| Author | SHA1 | Date | |
|---|---|---|---|
| b11dd47534 | |||
|
|
21a4c69f38 | ||
| e03f510874 | |||
|
|
59a4d18ce6 | ||
|
|
faf949fc9b | ||
|
|
6d120f4b1f | ||
|
|
69275c37b4 | ||
|
|
01b35691df | ||
| a93450579a | |||
|
|
ef38f98747 | ||
|
|
ea722a42f1 | ||
|
|
416c6f12e1 | ||
|
|
b5a00b309d | ||
|
|
454f20ed25 | ||
|
|
4e86096653 | ||
|
|
27bff32e76 | ||
|
|
13c1446977 | ||
| e9b44caf54 | |||
|
|
581cf2f2b2 | ||
|
|
81ed5747f3 | ||
|
|
8ccff20473 | ||
|
|
9520763ec3 | ||
|
|
5ef393fa64 | ||
|
|
45a1f50231 | ||
|
|
0f02331dfc | ||
|
|
df510cfe45 | ||
|
|
9f2e770509 | ||
|
|
2be59f99dd | ||
|
|
56096b1e35 | ||
|
|
2fd1826014 | ||
|
|
05da085e36 | ||
|
|
2e027408e6 | ||
|
|
54f1c7ab34 | ||
|
|
88c8b2ec90 | ||
|
|
0cd74194e3 | ||
|
|
f05fbf9e30 | ||
| 2370895710 |
177
.agents/skills/frontend-design/LICENSE.txt
Normal file
177
.agents/skills/frontend-design/LICENSE.txt
Normal 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
|
||||
71
.agents/skills/frontend-design/SKILL.md
Normal file
71
.agents/skills/frontend-design/SKILL.md
Normal 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.
|
||||
29
.dockerignore
Normal file
29
.dockerignore
Normal file
@@ -0,0 +1,29 @@
|
||||
# Dependencias y artefactos locales: el build los regenera adentro de la imagen.
|
||||
node_modules
|
||||
**/node_modules
|
||||
|
||||
# Se generan en el builder (prisma generate, vite build).
|
||||
apps/backend/generated
|
||||
apps/backend/dist
|
||||
apps/web/dist
|
||||
.turbo
|
||||
**/.turbo
|
||||
|
||||
# Secretos: en Dokploy llegan por variables de entorno.
|
||||
.env
|
||||
**/.env
|
||||
!.env.example
|
||||
**/.env.example
|
||||
|
||||
# Ruido del repo.
|
||||
.git
|
||||
.gitignore
|
||||
.github
|
||||
.DS_Store
|
||||
*.log
|
||||
README.md
|
||||
stack.md
|
||||
skills-lock.json
|
||||
**/skills-lock.json
|
||||
.agents
|
||||
**/.agents
|
||||
52
.env.example
Normal file
52
.env.example
Normal file
@@ -0,0 +1,52 @@
|
||||
# Variable template for `docker compose`.
|
||||
#
|
||||
# Local: copy this file to `.env` at the root and fill in the values.
|
||||
# Dokploy: no file needed; define the same variables in the Environment tab of
|
||||
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
||||
# file, which is where the `${...}` come from).
|
||||
|
||||
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
||||
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
||||
# domain, so the session cookie is first-party.
|
||||
WEB_URL="http://localhost:8080"
|
||||
|
||||
# Production PostgreSQL.
|
||||
# The password must be percent-encoded: if it has #, @, :, /, ?, % or a space,
|
||||
# escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the
|
||||
# URL where the fragment starts and fails with P1013 "invalid port number in
|
||||
# database URL".
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
|
||||
|
||||
# Generate it with: openssl rand -base64 32
|
||||
BETTER_AUTH_SECRET=""
|
||||
|
||||
# ── Optional ─────────────────────────────────────────────────────────────────
|
||||
|
||||
# Social login with Google. Without a client id/secret the provider is not
|
||||
# registered.
|
||||
# GOOGLE_CLIENT_ID=""
|
||||
# GOOGLE_CLIENT_SECRET=""
|
||||
|
||||
# Email sending (same variables as apps/backend/.env.example).
|
||||
# EMAIL_PROVIDER="smtp"
|
||||
# EMAIL_SERVER_HOST=""
|
||||
# EMAIL_SERVER_PORT="587"
|
||||
# EMAIL_SERVER_USER=""
|
||||
# EMAIL_SERVER_PASSWORD=""
|
||||
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales
|
||||
# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando
|
||||
# (el paso "Cobros" del onboarding es salteable).
|
||||
# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded.
|
||||
# TOKEN_ENCRYPTION_KEY=""
|
||||
# Redirect URL registered in the Mercado Pago panel, character for character.
|
||||
# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel.
|
||||
# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback"
|
||||
# MP_CLIENT_ID=""
|
||||
# MP_CLIENT_SECRET=""
|
||||
|
||||
# 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=""
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -90,6 +90,8 @@ out
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
# Service worker que vite-plugin-pwa escribe al serving en dev
|
||||
dev-dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
|
||||
954
.interface-design/group-detail-redesign.html
Normal file
954
.interface-design/group-detail-redesign.html
Normal 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 & 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 & 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 & 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 & 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>
|
||||
BIN
.interface-design/group-detail-redesign.png
Normal file
BIN
.interface-design/group-detail-redesign.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 314 KiB |
136
.interface-design/system.md
Normal file
136
.interface-design/system.md
Normal file
@@ -0,0 +1,136 @@
|
||||
# Gruperly — sistema de interfaz (apps/web)
|
||||
|
||||
Aplicado en el rediseño de `/groups/$groupId` (sept 2026). Fuente de verdad de tokens:
|
||||
`apps/web/src/index.css` (`@theme`). Ojo: `stack.md` trae tokens viejos (accent `#1e90ff`);
|
||||
el accent real es **`#2544ea`**.
|
||||
|
||||
## Dirección y sensación
|
||||
|
||||
Herramienta diaria de un profesor/organizador que abre la pantalla para responder tres
|
||||
preguntas: ¿quién está? ¿quién falta? ¿qué cobro?. Sensación: **calma operativa** — densa
|
||||
pero escaneable, nada grita salvo lo que requiere decisión. Tema oscuro slate + un solo
|
||||
accent azul; copy en español, verbos en infinitivo.
|
||||
|
||||
## Profundidad y espaciado
|
||||
|
||||
- **Estrategia de depth**: cambios de superficie + bordes de baja opacidad. Sombras solo
|
||||
`shadow-xs` en tarjetas/paneles. Nada de drop shadows marcados.
|
||||
- **Unidad base 4px.** Densidad: padding de componente 8–16px, separación entre bloques
|
||||
`space-y-5 sm:space-y-6` (20/24px).
|
||||
- **Radius**: default `rounded-xl` (0.75rem). Concéntrico: contenedor `rounded-2xl` (16px) +
|
||||
padding 8px → interior `rounded-lg` (8px). Chips y pills: `rounded-full`.
|
||||
|
||||
## Jerarquía tipográfica (ratio ~1.25)
|
||||
|
||||
| nivel | valor | uso |
|
||||
| --- | --- | --- |
|
||||
| label | 11px semibold uppercase `tracking-wide` `text-foreground/70` | títulos de celda/sección |
|
||||
| body | 14px (`text-sm`) `text-foreground/80` | descripciones, filas |
|
||||
| value | 16px semibold `text-primary` (`text-base`) | dato principal de una celda |
|
||||
| hero | 24px semibold `tracking-tight` `tabular-nums` | **solo uno por bloque** (hoy: el cupo `1/4`) |
|
||||
| micro | 10–12px | pills de conteo (`text-[10px] font-bold`), captions |
|
||||
|
||||
- Cuatro niveles de color de texto: `text-primary` → `text-foreground` → `/70` → `/50`.
|
||||
- **Todo dato numérico lleva `tabular-nums`** (contadores, teléfonos, precios, fechas).
|
||||
|
||||
## Patrón focal
|
||||
|
||||
**Un punto focal por bloque y por estado.** La tarjeta de info manda con el cupo; el header
|
||||
de grupo no tiene ningún `primary` (Estadísticas y Compartir son `outline` y **Agregar es
|
||||
`ghost`**: con miembros en el grupo deja de competir con el listado) y el `primary` vive en
|
||||
el empty state de la vista que lo explica. Así nunca hay dos elementos azules compitiendo.
|
||||
|
||||
**Objetivos táctiles ≥ 44px** en esta pantalla: chips (`min-h-11`), botones del header y del
|
||||
empty state (`h-11`), buscador (`h-11`). Filas de tabla ~56px.
|
||||
|
||||
Preview visual de los dos estados (con miembros + vacío):
|
||||
`group-detail-redesign.html` / `.png` (mismo directorio).
|
||||
|
||||
## Componentes (valores exactos)
|
||||
|
||||
### Chip de sección — `detail/SectionChips.tsx`
|
||||
- Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist).
|
||||
- Chip: `min-h-11 rounded-full border px-3.5 text-xs font-semibold gap-1.5`,
|
||||
activo `border-transparent bg-accent text-on-accent shadow-xs`,
|
||||
inactivo `border-border bg-surface text-foreground/80 hover:border-accent/40 hover:bg-primary-soft hover:text-primary`,
|
||||
focus `ring-2 ring-accent ring-offset-2 ring-offset-primary-soft`.
|
||||
- Pill de conteo: `px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums`;
|
||||
**oculto si el conteo es 0**; atención `bg-warning-soft text-warning`;
|
||||
neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`.
|
||||
- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta.
|
||||
|
||||
### Encabezado de pantalla — `components/layout/LargeTitle.tsx`
|
||||
- Patrón iOS: título grande que al scrollear se desliza debajo de una barra de
|
||||
navegación que se opaca y recibe el título en versión chica.
|
||||
- Caja de la barra: `h-14` (56px) `sticky top-0 z-40` + `bg-background/80 backdrop-blur-md`
|
||||
y `border-b`, con opacidad ligada al progreso. `h-14` tiene que coincidir con
|
||||
`BAR_HEIGHT` de `hooks/useLargeTitleCollapse.ts`.
|
||||
- Título grande: `text-[2.125rem] leading-[1.1] tracking-tight`, `sm:text-[2.5rem]`,
|
||||
con `text-balance` para nombres largos.
|
||||
- Título de la barra: `text-base font-semibold`, `truncate`, `aria-hidden` (es
|
||||
duplicado visual del `h1`).
|
||||
- El progreso sale de la posición del título en cada frame (`rAF` agrupa los
|
||||
eventos de scroll), no de una transición: por eso se siente pegado al dedo. El
|
||||
estado vive dentro de `LargeTitle` para que `children` no se re-renderice en
|
||||
cada frame.
|
||||
- La barra se monta en una caja que el layout pone arriba de `<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`
|
||||
- Título, badges y descripción los dibuja `LargeTitle`; las acciones quedan
|
||||
debajo, en el flujo normal.
|
||||
- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros:
|
||||
`variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px).
|
||||
- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** —
|
||||
Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado.
|
||||
- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`.
|
||||
- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`,
|
||||
en su propia fila bajo el título grande (`mt-3`) y se van al colapsar la barra.
|
||||
|
||||
### Tarjeta de info — `detail/GroupInfoCard.tsx`
|
||||
- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil,
|
||||
`md:grid md:grid-cols-3 md:divide-x md:divide-y-0`.
|
||||
- Celda: `flex items-start gap-3 py-3 first:pt-0 last:pb-0 md:py-0` + `md:pr-6` / `md:px-6` / `md:pl-6`.
|
||||
- Barra de cupo: `h-1.5 max-w-[9rem] rounded-full bg-accent/15`, fill `bg-accent`
|
||||
(o `bg-warning` si `total >= capacity`), `transition-[width] duration-300 ease-out`,
|
||||
con `role="progressbar"` + `aria-valuetext`.
|
||||
|
||||
### Sección de listados — `detail/MembersWaitlistSection.tsx`
|
||||
- Externo `rounded-2xl bg-primary-soft p-2`; interno `space-y-2 p-2 sm:p-3`.
|
||||
- Panel de contenido: `rounded-lg bg-surface p-1 shadow-xs sm:p-2`.
|
||||
- Fila header: chips + buscador (`sm:w-72 lg:shrink-0`), apilados hasta `lg`.
|
||||
- Sub-encabezado de sección apilada (`PendingView.tsx`):
|
||||
`flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3`,
|
||||
título label 11px, pill a la derecha con `ml-auto`; tabla envuelta en `pt-1`.
|
||||
|
||||
### Empty state
|
||||
`rounded-lg bg-primary-soft/50 px-4 py-10 text-center` · icono `size-10 text-foreground/40` ·
|
||||
título `text-sm font-semibold text-primary` · cuerpo `max-w-sm text-sm text-foreground/80` ·
|
||||
acciones: **una** `primary` + el resto `outline`, todas `h-11`.
|
||||
|
||||
### Tablas — `detail/*Table.tsx`
|
||||
`table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5`
|
||||
con `border-b border-border/70 last:border-b-0 hover:bg-primary-soft/60` ·
|
||||
avatar `size-9 rounded-full bg-accent/10 text-xs font-semibold text-accent` ·
|
||||
columnas secundarias con `hidden sm:table-cell` (en móvil manda el teléfono).
|
||||
|
||||
### Botón — `components/ui/button.tsx`
|
||||
`rounded-xl font-medium h-10 px-4 text-sm` · `active:scale-[0.96] motion-reduce:active:scale-100` ·
|
||||
focus `ring-2 ring-accent` · variantes `primary` (`bg-accent`/`hover:bg-accent-strong`),
|
||||
`outline`, `ghost`.
|
||||
|
||||
## Convenciones que sostienen el sistema
|
||||
|
||||
- Sin Radix/shadcn instalado: primitivos propios en `components/ui/` + `cn()` (clsx + tailwind-merge).
|
||||
- Sin botón "volver" en mobile: `hidden lg:inline-flex`.
|
||||
- Elementos fijos abajo: `env(safe-area-inset-bottom)` en el padding.
|
||||
- Los controles nuevos deben pasar el squint test: si dos cosas brillan, sobra una.
|
||||
15
AGENTS.md
15
AGENTS.md
@@ -21,6 +21,7 @@ bun run lint:fix # biome check --write
|
||||
bun --filter @gruperly/backend typecheck # verificación de un solo paquete
|
||||
bun --filter @gruperly/backend test # bun test (backend)
|
||||
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
||||
bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web/public/ (sharp)
|
||||
```
|
||||
|
||||
## Estructura y fronteras
|
||||
@@ -30,29 +31,35 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
||||
- `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/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 }`).
|
||||
- `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`).
|
||||
- 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: "/"`), `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.
|
||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||
|
||||
## Gotchas operativos
|
||||
|
||||
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||
- `.env`, `dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<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).
|
||||
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||
|
||||
## Convenciones repo-específicas
|
||||
|
||||
- **Frontend en español**: copy de UI, comentarios y textos en español.
|
||||
- **Base de datos**: todas las tablas usan **snake_case** vía `@@map` en `prisma/models/*.prisma` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`). Al agregar un modelo nuevo, incluir siempre `@@map("nombre_tabla")`.
|
||||
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
|
||||
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
|
||||
- **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`).
|
||||
- **Router 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.
|
||||
- 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.
|
||||
- **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición.
|
||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<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.
|
||||
|
||||
## Fuentes de contexto
|
||||
|
||||
66
Dockerfile.backend
Normal file
66
Dockerfile.backend
Normal file
@@ -0,0 +1,66 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||
FROM oven/bun:1.4-alpine AS base
|
||||
WORKDIR /app
|
||||
ENV CI=1
|
||||
|
||||
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||
# Only the package.json files: bun needs no source code to resolve the lockfile.
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY apps/web/package.json ./apps/web/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||
|
||||
# ─── Prisma Client ───────────────────────────────────────────────────────────
|
||||
# The "prisma-client" generator emits TypeScript, so the generated client runs
|
||||
# with Bun without compilation. The URL is a placeholder: `generate` only needs
|
||||
# to read the schema, not connect to a database.
|
||||
FROM deps AS generate
|
||||
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
|
||||
ENV DATABASE_URL=$DATABASE_URL
|
||||
COPY apps/backend/prisma.config.ts ./apps/backend/
|
||||
COPY apps/backend/prisma ./apps/backend/prisma
|
||||
WORKDIR /app/apps/backend
|
||||
RUN bun run db:generate
|
||||
|
||||
# ─── API image ───────────────────────────────────────────────────────────────
|
||||
FROM base AS api
|
||||
ENV NODE_ENV=production \
|
||||
PORT=4000
|
||||
|
||||
COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs
|
||||
# `prisma migrate deploy` on every boot. With `--production` the rest of the
|
||||
# tooling does not come in: biome, typescript, turbo.
|
||||
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
|
||||
|
||||
# The Prisma CLI loads prisma.config.ts, which points to the schema.
|
||||
COPY apps/backend/prisma ./apps/backend/prisma
|
||||
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
|
||||
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
|
||||
COPY apps/backend/tsconfig.json ./apps/backend/
|
||||
COPY apps/backend/src ./apps/backend/src
|
||||
# @gruperly/shared is consumed as TS source; @gruperly/config provides the base
|
||||
# tsconfig that the backend tsconfig extends.
|
||||
COPY packages ./packages
|
||||
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
WORKDIR /app/apps/backend
|
||||
EXPOSE 4000
|
||||
# No `${...}` here: the CMD runs under /bin/sh (ash), where that is a syntax error.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||
# Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
|
||||
# same as `bun start` locally.
|
||||
CMD ["bun", "src/server.ts"]
|
||||
35
Dockerfile.web
Normal file
35
Dockerfile.web
Normal file
@@ -0,0 +1,35 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||
FROM oven/bun:1.4-alpine AS base
|
||||
WORKDIR /app
|
||||
ENV CI=1
|
||||
|
||||
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY apps/web/package.json ./apps/web/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||
|
||||
# ─── Vite build ──────────────────────────────────────────────────────────────
|
||||
FROM deps AS build
|
||||
# Vite replaces import.meta.env.* at build time, not at runtime.
|
||||
# Empty = same origin: nginx's /api proxy acts as the API.
|
||||
ARG VITE_API_URL=""
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
COPY apps/web ./apps/web
|
||||
COPY packages ./packages
|
||||
RUN bun --filter @gruperly/web build
|
||||
|
||||
# ─── Final image ─────────────────────────────────────────────────────────────
|
||||
FROM nginx:1.27-alpine AS web
|
||||
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||
CMD wget --quiet --tries=1 --spider http://127.0.0.1/ || exit 1
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
137
README.md
137
README.md
@@ -7,7 +7,7 @@ Monorepo de Gruperly. Consulta [stack.md](./stack.md) para arquitectura y especi
|
||||
- Package manager: [Bun](https://bun.sh/) 1.4
|
||||
- Monorepo: bun workspaces + Turborepo
|
||||
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
||||
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4
|
||||
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 + PWA (vite-plugin-pwa / Workbox)
|
||||
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
||||
|
||||
## Estructura
|
||||
@@ -31,9 +31,144 @@ bun run lint # biome check (backend y shared)
|
||||
bun --filter @gruperly/backend test # bun test (backend)
|
||||
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
|
||||
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
||||
bun --filter @gruperly/web icons # Regenera los iconos PWA de public/ desde el isotipo SVG
|
||||
```
|
||||
|
||||
## PWA
|
||||
|
||||
La web es instalable y abre sin conexión el shell de la app (rutas, JS, CSS, tipografía e iconos). Los datos de la API **no** se cachean: son cobros y una respuesta vieja sería peor que un error, así que offline la app carga pero las consultas fallan.
|
||||
|
||||
- **Manifest y service worker**: `apps/web/vite.config.ts` (`VitePWA`, `generateSW`, `registerType: 'autoUpdate'`). El registro se hace desde `apps/web/src/features/pwa/PwaProvider.tsx` (`injectRegister: null`) para poder avisar con un toast cuando la app ya quedó lista para offline.
|
||||
- **`workbox-window` es dependencia directa de `apps/web` a propósito**: `virtual:pwa-register` la importa desde el grafo de la app, pero llega como dependencia transitiva de `vite-plugin-pwa`. Localmente bun la hoistea a la raíz y todo anda; en la imagen de Docker bun usa el layout aislado y la deja solo en `node_modules/.bun/`, así que Rollup falla con `failed to resolve import "workbox-window"` y el build de Dokploy se cae. Declararla en `apps/web/package.json` la hace resoluble desde `apps/web/node_modules/`. **No la borres por "no estar imports en el código".**
|
||||
- **Iconos**: se generan con sharp desde `apps/web/src/assets/brand/isotipo-y-organica.svg` y se versionan en `apps/web/public/` (`pwa-192x192`, `pwa-512x512`, `pwa-maskable-512x512`, `apple-touch-icon-180`). El build **no** los regenera; corré `bun --filter @gruperly/web icons` cuando cambie el isotipo.
|
||||
- **Tipografía**: Inter variable auto-hospedada vía `@fontsource-variable/inter`, declarada a mano en `apps/web/src/index.css`. No hay `<link>` a `fonts.googleapis.com`: era una dependencia de red en runtime.
|
||||
- **Aviso de instalación**: la lógica de *cuándo* se ofrece vive en `apps/web/src/features/pwa/PwaProvider.tsx` (captura `beforeinstallprompt`, gate de sesión, dwell y descarte) y el dibujo en `InstallPrompt.tsx` → `InstallBanner.tsx` (Chromium) o `IosInstallHint.tsx` (Safari en iOS, que no dispara el evento y hay que instruir con Compartir → Agregar a pantalla de inicio).
|
||||
- Se ofrece solo con **sesión iniciada**, **fuera del onboarding** y después de **20 s seguidos en la misma ruta**; `beforeinstallprompt` llega a los segundos y sin ese margen el aviso cae en medio de la primera tarea de la visita. Navegar antes de que se cumpla el tiempo reinicia la cuenta; una vez cumplido no se oculta más al navegar.
|
||||
- El descarte es definitivo: se guarda en `localStorage['pwa-install-dismissed']` y no vuelve a preguntar en ese navegador.
|
||||
- El timer vive en el provider y no en el componente que dibuja el aviso a propósito: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un timer en el hijo se perdería en cada navegación. El provider, en cambio, sigue montado y se suscribe al router (`router.subscribe('onResolved')`) porque está fuera del `RouterProvider`.
|
||||
- Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` sin usuario—, así que el gate se chequea en el provider y no se puede inferir de dónde se monte el prompt.
|
||||
- **nginx**: `apps/web/nginx.conf` sirve `sw.js`, `workbox-*.js` y `manifest.webmanifest` con `Cache-Control: no-cache` y `=404` (no el fallback del SPA), para que una versión vieja no quede cacheada para siempre.
|
||||
|
||||
### Requisitos para que funcione
|
||||
|
||||
El service worker necesita un **contexto seguro**: HTTPS, o `http://localhost`. Probar por IP de LAN sobre `http://` no registra el SW en silencio, sin error visible. En producción el TLS lo termina Traefik adelante de nginx.
|
||||
|
||||
### Verificar
|
||||
|
||||
```bash
|
||||
bun --filter @gruperly/web build
|
||||
bun --filter @gruperly/web preview # http://localhost:4173
|
||||
```
|
||||
|
||||
En DevTools → Application: el manifest sin warnings, el service worker `activated`, y en Network → Offline un reload de `/` o `/groups` tiene que seguir pintando la app. `bun dev` también registra el SW (está en `devOptions`), así que se puede probar sin build, pero `dev-dist/` queda gitignoreado.
|
||||
|
||||
## Setup de base de datos
|
||||
|
||||
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
||||
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
||||
|
||||
## 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`). Los links de pago, webhooks y WhatsApp quedan fuera de este módulo.
|
||||
|
||||
**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 pagos, cuando existan, se prueban aparte con credenciales de prueba.
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
## Deploy en producción (Docker / Dokploy)
|
||||
|
||||
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
||||
|
||||
- `api` corre Bun sobre el TypeScript fuente (`bun src/server.ts`), igual que en local: el cliente de Prisma se genera como TS y el tsconfig resuelve los aliases `@/*`.
|
||||
- Al arrancar, `apps/backend/docker-entrypoint.sh` aplica `prisma migrate deploy` y recién después levanta el servidor. Si la migración falla, el contenedor no levanta y el error queda en los logs del servicio. Reintenta hasta 30 veces (5s) porque la base puede seguir arrancando.
|
||||
- `web` compila con Vite y lo sirve nginx, que además hace de proxy de `/api` hacia `api`. Así el navegador siempre pega al mismo origen: la cookie de sesión es first-party y el CORS del backend no se activa.
|
||||
- Ambos servicios se enchufan a `dokploy-network`, la red donde Dokploy deja las bases de datos que administra. Dokploy solo agrega esa red al servicio al que le asociás el dominio, así que está declarada a mano en el compose: sin ella, `api` no alcanza a la base y Prisma falla con `P1001 Can't reach database server`.
|
||||
|
||||
### Variables de entorno
|
||||
|
||||
El compose las interpola desde el entorno. En Dokploy van en la pestaña **Environment** del servicio Compose (Dokploy las guarda en un `.env` al lado del `docker-compose.yml`); en local, copiá `.env.example` → `.env` en la raíz.
|
||||
|
||||
| Variable | ¿Obligatoria? | Descripción |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | sí | `postgresql://user:pass@host:5432/gruperly?schema=public`. La password va percent-encoded: `#` → `%23`, `@` → `%40`, `:` → `%3A`, `/` → `%2F`, `?` → `%3F`, `%` → `%25`, espacio → `%20`. Sin eso, Prisma corta la URL en el fragmento y falla con `P1013 invalid port number` |
|
||||
| `WEB_URL` | sí | Origen público de la app, sin barra final (`https://gruperly.com`). Alimenta `WEB_URL` y `BETTER_AUTH_URL` del contenedor, porque el proxy de nginx deja web y API en el mismo dominio |
|
||||
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider |
|
||||
| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) |
|
||||
| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) |
|
||||
| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo |
|
||||
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
|
||||
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||
|
||||
Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre de la variable en el mensaje.
|
||||
|
||||
### Pasos en Dokploy
|
||||
|
||||
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
||||
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
||||
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
|
||||
4. Deploy.
|
||||
|
||||
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
|
||||
|
||||
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
|
||||
|
||||
### Correr las migraciones a mano
|
||||
|
||||
```bash
|
||||
docker compose exec api bun run db:deploy
|
||||
```
|
||||
|
||||
### Comprobar el compose en local
|
||||
|
||||
Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la declara como externa:
|
||||
|
||||
```bash
|
||||
docker network create dokploy-network # una sola vez
|
||||
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
|
||||
docker compose up --build -d
|
||||
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
||||
curl http://localhost:8080/api/v1/health
|
||||
```
|
||||
|
||||
@@ -19,3 +19,15 @@ EMAIL_SERVER_PORT="587"
|
||||
EMAIL_SERVER_USER=""
|
||||
EMAIL_SERVER_PASSWORD=""
|
||||
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=""
|
||||
42
apps/backend/docker-entrypoint.sh
Executable file
42
apps/backend/docker-entrypoint.sh
Executable file
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Production entrypoint for the backend: applies the migrations and starts the
|
||||
# server in the same container.
|
||||
#
|
||||
# This is POSIX sh, not bash: the image is alpine and does not ship bash
|
||||
# installed (adding it would be ~10MB for a shebang).
|
||||
#
|
||||
# Set RUN_MIGRATIONS=false to start without touching the database (for example,
|
||||
# a database already migrated by hand, or one managed outside this deployment).
|
||||
set -e
|
||||
|
||||
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||
|
||||
if [ "${RUN_MIGRATIONS:-true}" = "false" ]; then
|
||||
echo "migrate: omitido (RUN_MIGRATIONS=false)"
|
||||
else
|
||||
attempts="${MIGRATE_ATTEMPTS:-30}"
|
||||
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||
i=1
|
||||
|
||||
# The database may still be starting up when this container is already
|
||||
# running, and a deploy usually overlaps a Postgres restart.
|
||||
while [ "$i" -le "$attempts" ]; do
|
||||
if bun run db:deploy; then
|
||||
echo "migrate: listo"
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$i" -eq "$attempts" ]; then
|
||||
echo "migrate: fallo tras $attempts intentos; no se levanta el servidor" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "migrate: intento $i/$attempts fallo; reintento en ${delay}s" >&2
|
||||
i=$((i + 1))
|
||||
sleep "$delay"
|
||||
done
|
||||
fi
|
||||
|
||||
# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
|
||||
# (the server uses it to close Bun.serve and disconnect Prisma).
|
||||
exec "$@"
|
||||
@@ -14,6 +14,7 @@
|
||||
"lint:fix": "biome check . --write",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:deploy": "prisma migrate deploy",
|
||||
"db:push": "prisma db push",
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
@@ -23,10 +24,13 @@
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"better-auth": "1.7.2",
|
||||
"dotenv": "^16.4.5",
|
||||
"hono": "^4.13.3",
|
||||
"nanoid": "^3.3.19",
|
||||
"nodemailer": "^9.0.6",
|
||||
"pino": "^9.5.0",
|
||||
"pino-pretty": "^13.0.0",
|
||||
"prisma": "^7.10.0",
|
||||
"zod": "3.24.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -35,8 +39,6 @@
|
||||
"@types/bun": "^1.4.0",
|
||||
"@types/node": "^20.17.0",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"dotenv": "^16.4.5",
|
||||
"prisma": "^7.10.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "group_pre_registrations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"groupId" TEXT NOT NULL,
|
||||
"fullName" TEXT NOT NULL,
|
||||
"phone" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -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";
|
||||
@@ -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";
|
||||
@@ -8,43 +8,43 @@ enum AttendanceStatus {
|
||||
|
||||
model ClassSession {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
startsAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
groupId String @map("group_id")
|
||||
startsAt DateTime @map("starts_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
|
||||
@@unique([groupId, startsAt])
|
||||
@@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
|
||||
@@map("class_sessions")
|
||||
}
|
||||
|
||||
model Attendance {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String
|
||||
classSessionId String
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
status AttendanceStatus
|
||||
markedAt DateTime @default(now())
|
||||
markedAt DateTime @default(now()) @map("marked_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], 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, map: "attendances_classSessionId_fkey")
|
||||
|
||||
@@unique([attendeeId, classSessionId])
|
||||
@@unique([attendeeId, classSessionId], map: "attendances_attendeeId_classSessionId_key")
|
||||
@@map("attendances")
|
||||
}
|
||||
|
||||
model SlotRelease {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String
|
||||
classSessionId String
|
||||
isClaimed Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
isClaimed Boolean @default(false) @map("is_claimed")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], 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, map: "slot_releases_classSessionId_fkey")
|
||||
|
||||
@@unique([attendeeId, classSessionId])
|
||||
@@unique([attendeeId, classSessionId], map: "slot_releases_attendeeId_classSessionId_key")
|
||||
@@map("slot_releases")
|
||||
}
|
||||
|
||||
@@ -4,11 +4,11 @@ model User {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
email String @unique
|
||||
emailVerified Boolean @default(false)
|
||||
emailVerified Boolean @default(false) @map("email_verified")
|
||||
image String?
|
||||
onboardingCompleted Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
@@ -18,46 +18,46 @@ model User {
|
||||
orgMemberships Member[]
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
waitlist WaitlistEntry[]
|
||||
merchantAccount MerchantAccount?
|
||||
mpAccount MpAccount?
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Account {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
providerId String
|
||||
accountId String
|
||||
userId String @map("user_id")
|
||||
providerId String @map("provider_id")
|
||||
accountId String @map("account_id")
|
||||
issuer String
|
||||
accessToken String?
|
||||
refreshToken String?
|
||||
idToken String?
|
||||
accessTokenExpiresAt DateTime?
|
||||
refreshTokenExpiresAt DateTime?
|
||||
accessToken String? @map("access_token")
|
||||
refreshToken String? @map("refresh_token")
|
||||
idToken String? @map("id_token")
|
||||
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
|
||||
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
|
||||
scope String?
|
||||
password String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "accounts_userId_fkey")
|
||||
|
||||
@@unique([issuer, accountId])
|
||||
@@index([userId])
|
||||
@@unique([issuer, accountId], map: "accounts_issuer_accountId_key")
|
||||
@@index([userId], map: "accounts_userId_idx")
|
||||
@@map("accounts")
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
userId String @map("user_id")
|
||||
token String @unique
|
||||
expiresAt DateTime
|
||||
ipAddress String?
|
||||
userAgent String?
|
||||
activeOrganizationId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime @map("expires_at")
|
||||
ipAddress String? @map("ip_address")
|
||||
userAgent String? @map("user_agent")
|
||||
activeOrganizationId String? @map("active_organization_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "sessions_userId_fkey")
|
||||
|
||||
@@map("sessions")
|
||||
}
|
||||
@@ -66,9 +66,9 @@ model Verification {
|
||||
id String @id @default(cuid())
|
||||
identifier String
|
||||
value String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@unique([identifier, value])
|
||||
@@map("verifications")
|
||||
@@ -81,8 +81,8 @@ model Organization {
|
||||
slug String @unique
|
||||
logo String?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
members Member[]
|
||||
invitations Invitation[]
|
||||
@@ -92,32 +92,32 @@ model Organization {
|
||||
|
||||
model Member {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
userId String
|
||||
organizationId String @map("organization_id")
|
||||
userId String @map("user_id")
|
||||
role String @default("member")
|
||||
createdAt DateTime @default(now())
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "members_organizationId_fkey")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "members_userId_fkey")
|
||||
|
||||
@@unique([organizationId, userId])
|
||||
@@unique([organizationId, userId], map: "members_organizationId_userId_key")
|
||||
@@map("members")
|
||||
}
|
||||
|
||||
model Invitation {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organizationId String @map("organization_id")
|
||||
email String
|
||||
role String
|
||||
status String @default("pending")
|
||||
inviterId String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
inviterId String @map("inviter_id")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "invitations_organizationId_fkey")
|
||||
inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade, map: "invitations_inviterId_fkey")
|
||||
|
||||
@@index([organizationId])
|
||||
@@index([organizationId], map: "invitations_organizationId_idx")
|
||||
@@map("invitations")
|
||||
}
|
||||
|
||||
@@ -125,18 +125,18 @@ model Invitation {
|
||||
model Passkey {
|
||||
id String @id @default(cuid())
|
||||
name String?
|
||||
publicKey String
|
||||
credentialID String @unique
|
||||
userId String
|
||||
publicKey String @map("public_key")
|
||||
credentialID String @unique(map: "passkeys_credentialID_key") @map("credential_id")
|
||||
userId String @map("user_id")
|
||||
counter Int
|
||||
deviceType String
|
||||
backedUp Boolean
|
||||
deviceType String @map("device_type")
|
||||
backedUp Boolean @map("backed_up")
|
||||
transports String?
|
||||
createdAt DateTime @default(now())
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
aaguid String?
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "passkeys_userId_fkey")
|
||||
|
||||
@@index([userId])
|
||||
@@index([userId], map: "passkeys_userId_idx")
|
||||
@@map("passkeys")
|
||||
}
|
||||
@@ -8,18 +8,19 @@ model Group {
|
||||
time String?
|
||||
capacity Int?
|
||||
price Decimal? @db.Decimal(10, 2)
|
||||
billingType BillingType?
|
||||
dueDay Int?
|
||||
inviteToken String? @unique
|
||||
createdById String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
billingType BillingType? @map("billing_type")
|
||||
dueDay Int? @map("due_day")
|
||||
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[]
|
||||
attendees Attendee[]
|
||||
payments Payment[]
|
||||
waitlist GroupWaitlistEntry[]
|
||||
preRegistrations GroupPreRegistration[]
|
||||
classSessions ClassSession[]
|
||||
|
||||
@@map("groups")
|
||||
@@ -42,15 +43,15 @@ enum BillingType {
|
||||
|
||||
model GroupMember {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
userId String
|
||||
groupId String @map("group_id")
|
||||
userId String @map("user_id")
|
||||
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)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_members_groupId_fkey")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "group_members_userId_fkey")
|
||||
|
||||
@@unique([groupId, userId])
|
||||
@@unique([groupId, userId], map: "group_members_groupId_userId_key")
|
||||
@@map("group_members")
|
||||
}
|
||||
|
||||
@@ -68,44 +69,44 @@ enum AttendeeStatus {
|
||||
|
||||
model Attendee {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
email String?
|
||||
phone String?
|
||||
guardianName String?
|
||||
guardianPhone String?
|
||||
guardianName String? @map("guardian_name")
|
||||
guardianPhone String? @map("guardian_phone")
|
||||
notes String?
|
||||
notifyToken String? @unique @default(cuid())
|
||||
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
|
||||
status AttendeeStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
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[]
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
|
||||
@@index([groupId])
|
||||
@@index([groupId], map: "attendees_groupId_idx")
|
||||
@@map("attendees")
|
||||
}
|
||||
|
||||
model Payment {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
attendeeId String
|
||||
groupId String @map("group_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
currency String @default("MXN")
|
||||
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
|
||||
dueDate DateTime
|
||||
paidAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
dueDate DateTime @map("due_date")
|
||||
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)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
|
||||
|
||||
@@index([groupId])
|
||||
@@index([attendeeId])
|
||||
@@index([groupId], map: "payments_groupId_idx")
|
||||
@@index([attendeeId], map: "payments_attendeeId_idx")
|
||||
@@map("payments")
|
||||
}
|
||||
|
||||
@@ -121,12 +122,12 @@ model WaitlistEntry {
|
||||
email String
|
||||
name String?
|
||||
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String? @unique
|
||||
userId String? @unique(map: "waitlist_entries_userId_key") @map("user_id")
|
||||
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull, map: "waitlist_entries_userId_fkey")
|
||||
|
||||
@@unique([email])
|
||||
@@map("waitlist_entries")
|
||||
@@ -134,19 +135,19 @@ model WaitlistEntry {
|
||||
|
||||
model GroupWaitlistEntry {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
notes String?
|
||||
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
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])
|
||||
@@index([groupId])
|
||||
@@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key")
|
||||
@@index([groupId], map: "group_waitlist_entries_groupId_idx")
|
||||
@@map("group_waitlist_entries")
|
||||
}
|
||||
|
||||
@@ -157,22 +158,73 @@ enum WaitlistStatus {
|
||||
DECLINED
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
enum PreRegistrationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model MerchantAccount {
|
||||
model GroupPreRegistration {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique
|
||||
provider PaymentProvider
|
||||
accessToken String?
|
||||
sandbox Boolean @default(true)
|
||||
connectedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
status PreRegistrationStatus @default(PENDING)
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey")
|
||||
|
||||
@@map("merchant_accounts")
|
||||
@@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
|
||||
@@index([groupId], map: "group_pre_registrations_groupId_idx")
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum MpAccountStatus {
|
||||
ACTIVE
|
||||
REQUIRES_REAUTH
|
||||
REVOKED
|
||||
}
|
||||
|
||||
// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
|
||||
// Tokens are stored encrypted (AES-256-GCM); there is a single active account per
|
||||
// teacher and a Mercado Pago user cannot be linked to two teachers.
|
||||
model MpAccount {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
|
||||
mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
|
||||
accessTokenEnc String @map("access_token_enc")
|
||||
refreshTokenEnc String @map("refresh_token_enc")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
scope String?
|
||||
liveMode Boolean @default(false) @map("live_mode")
|
||||
status MpAccountStatus @default(ACTIVE)
|
||||
connectedAt DateTime @default(now()) @map("connected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
|
||||
|
||||
// The daily refresh job looks for ACTIVE accounts expiring within 30 days.
|
||||
@@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx")
|
||||
@@map("mp_accounts")
|
||||
}
|
||||
|
||||
// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE
|
||||
// `code_verifier`. The `state` is the primary key because consuming it (deleting
|
||||
// the row) is what makes it single use.
|
||||
model MpOAuthState {
|
||||
state String @id
|
||||
ownerId String @map("owner_id")
|
||||
codeVerifier String @map("code_verifier")
|
||||
// Constrained to 'onboarding' | 'settings'; decides where the callback lands.
|
||||
returnTo String @map("return_to")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
// Expired rows are swept on every new authorization request.
|
||||
@@index([expiresAt], map: "mp_oauth_states_expiresAt_idx")
|
||||
@@map("mp_oauth_states")
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import { groupsRoutes } from './modules/groups';
|
||||
import { healthCheckRoutes } from './modules/health-check';
|
||||
import { homeRoutes } from './modules/home';
|
||||
import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
@@ -44,6 +45,7 @@ api.route('/invitations', invitationsRoutes);
|
||||
api.route('/groups', groupsRoutes);
|
||||
api.route('/home', homeRoutes);
|
||||
api.route('/onboarding', onboardingRoutes);
|
||||
api.route('/mp', mpRoutes);
|
||||
api.route('/attendees', attendeesRoutes);
|
||||
api.route('/payments', paymentsRoutes);
|
||||
api.route('/waitlist', waitlistRoutes);
|
||||
|
||||
@@ -71,13 +71,49 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl
|
||||
return notFoundProblem(`${resourceName} ${id}`);
|
||||
}
|
||||
|
||||
export function paymentNotSetupProblem(): ProblemDetails {
|
||||
export function mpNotConnectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.',
|
||||
code: 'payment_not_setup',
|
||||
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
|
||||
code: 'mp_not_connected',
|
||||
});
|
||||
}
|
||||
|
||||
export function mpRequiresReauthProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Tu cuenta de Mercado Pago necesita volver a vincularse.',
|
||||
code: 'mp_requires_reauth',
|
||||
});
|
||||
}
|
||||
|
||||
export function mpAccountInUseProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.',
|
||||
code: 'mp_account_in_use',
|
||||
});
|
||||
}
|
||||
|
||||
/** The server is missing MP_CLIENT_ID / MP_CLIENT_SECRET / MP_REDIRECT_URI. */
|
||||
export function mpNotConfiguredProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/mercadopago-not-configured`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'La vinculación con Mercado Pago no está disponible en este momento.',
|
||||
code: 'mp_not_configured',
|
||||
};
|
||||
}
|
||||
|
||||
/** Mercado Pago refused the request, or could not be reached. */
|
||||
export function mpProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/mercadopago-unavailable`,
|
||||
title: 'Bad Gateway',
|
||||
status: 502,
|
||||
detail: 'No pudimos completar la vinculación con Mercado Pago.',
|
||||
code: 'mp_provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
export function onboardingAlreadyCompletedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya completaste el onboarding de Gruperly.',
|
||||
|
||||
@@ -27,7 +27,7 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
|
||||
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') {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -5,14 +5,14 @@ type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
|
||||
// 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 TEXT_STRONG = '#0f172a'
|
||||
const TEXT_MUTED = '#475569'
|
||||
const ON_ACCENT = '#ffffff'
|
||||
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 {
|
||||
try {
|
||||
const base64 = readFileSync(
|
||||
@@ -66,7 +66,7 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
// With no SMTP configured (dev) the flow still doesn't break: it only logs a warning
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
@@ -111,8 +111,8 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||
// Add implementations and switch between them with EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
@@ -33,14 +33,14 @@ export class GetAttendeeHistory {
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { id: true, fullName: true },
|
||||
select: { id: true, fullName: true, createdAt: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
const sessions = await db.classSession.findMany({
|
||||
where: { groupId },
|
||||
where: { groupId, startsAt: { gte: attendee.createdAt } },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
take: HISTORY_SESSIONS_LIMIT,
|
||||
select: { id: true, startsAt: true },
|
||||
|
||||
@@ -4,19 +4,30 @@ import type {
|
||||
GroupRiskLevel,
|
||||
GroupRiskSummary,
|
||||
GroupsRiskOverview,
|
||||
MemberClassSession,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
UrgentMemberSummary,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import {
|
||||
classifyRisk,
|
||||
MIN_RISK_ABSENCE_STREAK,
|
||||
MIN_RISK_MONTHLY_RATE,
|
||||
monthlyAttendanceRate,
|
||||
trailingAbsentStreak,
|
||||
} from '../../lib/risk';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
/* 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 4+4 trend window and for
|
||||
the attendance rate the card shows. */
|
||||
const MEMBER_HISTORY_LIMIT = 20;
|
||||
|
||||
type GetGroupsRiskOverviewDeps = {
|
||||
db?: {
|
||||
group: Prisma.GroupDelegate;
|
||||
@@ -27,18 +38,26 @@ type GetGroupsRiskOverviewDeps = {
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
type GroupRow = { id: string; name: string };
|
||||
type AttendeeRow = { id: string; groupId: string };
|
||||
type SessionRow = { id: string; groupId: string };
|
||||
type GroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
capacity: number | null;
|
||||
/** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
||||
_count: { waitlist: number };
|
||||
};
|
||||
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
||||
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||
type AttendanceRow = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
|
||||
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
|
||||
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
|
||||
// alguno en riesgo moderado y NONE en caso contrario.
|
||||
// Risk status light summary per group for the group listing.
|
||||
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if
|
||||
// any is at medium risk and NONE otherwise. The counters state the reason
|
||||
// (consecutive absences or low attendance) so the listing can name it.
|
||||
export class GetGroupsRiskOverview {
|
||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||
|
||||
@@ -49,30 +68,39 @@ export class GetGroupsRiskOverview {
|
||||
|
||||
const groups = (await db.group.findMany({
|
||||
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
||||
select: { id: true, name: true },
|
||||
})) as GroupRow[];
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
capacity: true,
|
||||
_count: { select: { waitlist: { where: { status: 'PENDING' } } } },
|
||||
},
|
||||
})) as unknown as GroupRow[];
|
||||
|
||||
if (groups.length === 0) {
|
||||
return ok({ items: [] });
|
||||
}
|
||||
|
||||
const groupIds = groups.map((group) => group.id);
|
||||
const attendeeGroup = new Map<string, string>();
|
||||
const sessionCountByGroup = new Map<string, number>();
|
||||
|
||||
const [attendees, sessions, attendances] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true },
|
||||
select: { id: true, groupId: true, fullName: true, createdAt: true },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
db.classSession.findMany({
|
||||
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[]>,
|
||||
/* No date filter, as before: the status light streak counts over the
|
||||
attendee's full history, not over the monthly window. No cap either:
|
||||
the cut to the last 20 classes is done by `memberSessions`, over the
|
||||
group's classes and not over these rows. */
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: {
|
||||
attendeeId: true,
|
||||
classSessionId: true,
|
||||
status: true,
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
@@ -80,18 +108,25 @@ export class GetGroupsRiskOverview {
|
||||
}) as Promise<AttendanceRow[]>,
|
||||
]);
|
||||
|
||||
for (const attendee of attendees) {
|
||||
attendeeGroup.set(attendee.id, attendee.groupId);
|
||||
}
|
||||
const sessionsByGroup = new Map<string, SessionRow[]>();
|
||||
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 worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
||||
// Why there is risk, computed in the same pass: a member with an absence
|
||||
// streak counts in the first counter and only there; the second one
|
||||
// groups the members that don't reach a streak and are still below the
|
||||
// attendance minimum.
|
||||
const absenceStreakCountByGroup = new Map<string, number>();
|
||||
const lowAttendanceCountByGroup = new Map<string, number>();
|
||||
|
||||
for (const attendee of attendees) {
|
||||
const groupId = attendeeGroup.get(attendee.id)!;
|
||||
const groupId = attendee.groupId;
|
||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
||||
status: row.status,
|
||||
occurredAt: row.classSession.startsAt,
|
||||
@@ -99,13 +134,19 @@ export class GetGroupsRiskOverview {
|
||||
const streak = trailingAbsentStreak(stream);
|
||||
const monthlyRate = monthlyAttendanceRate(
|
||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
||||
sessionCountByGroup.get(groupId) ?? 0,
|
||||
sessionsByGroup.get(groupId)?.length ?? 0,
|
||||
);
|
||||
const riskLevel = classifyRisk(streak, monthlyRate);
|
||||
if (!riskLevel) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (streak >= MIN_RISK_ABSENCE_STREAK) {
|
||||
bump(absenceStreakCountByGroup, groupId);
|
||||
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
||||
bump(lowAttendanceCountByGroup, groupId);
|
||||
}
|
||||
|
||||
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
|
||||
if (
|
||||
riskLevel === 'HIGH' ||
|
||||
@@ -119,12 +160,94 @@ export class GetGroupsRiskOverview {
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
|
||||
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
|
||||
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
|
||||
...buildSummaryFields(group, attendees, sessionsByGroup, streamByAttendee, now),
|
||||
}));
|
||||
|
||||
return ok({ items });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-level summary consumed by the listing card and the Home follow-up
|
||||
* section. 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 buildSummaryFields(
|
||||
group: GroupRow,
|
||||
attendees: AttendeeRow[],
|
||||
sessionsByGroup: Map<string, SessionRow[]>,
|
||||
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
||||
now: Date,
|
||||
) {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: group.id,
|
||||
capacity: group.capacity,
|
||||
waitlistCount: group._count.waitlist,
|
||||
now,
|
||||
members: attendees
|
||||
.filter((attendee) => attendee.groupId === group.id)
|
||||
.map((attendee) => {
|
||||
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
|
||||
// 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 = attendeeAttendances.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(
|
||||
sessionsByGroup.get(group.id) ?? [],
|
||||
attendeeAttendances,
|
||||
),
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
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,
|
||||
}));
|
||||
|
||||
return {
|
||||
riesgoAlto: resumen.riesgoAlto,
|
||||
atencion: resumen.atencion,
|
||||
ok: resumen.ok,
|
||||
libres: resumen.libres,
|
||||
enEspera: resumen.enEspera,
|
||||
asistencia: resumen.asistencia,
|
||||
urgentes,
|
||||
};
|
||||
}
|
||||
|
||||
function bump(counter: Map<string, number>, key: string) {
|
||||
counter.set(key, (counter.get(key) ?? 0) + 1);
|
||||
}
|
||||
|
||||
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
||||
const byAttendee = new Map<string, AttendanceRow[]>();
|
||||
for (const row of rows) {
|
||||
@@ -134,3 +257,25 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
||||
}
|
||||
return byAttendee;
|
||||
}
|
||||
|
||||
/* 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: SessionRow[], attendances: AttendanceRow[]): 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,
|
||||
}));
|
||||
}
|
||||
@@ -12,7 +12,7 @@ type GroupWithAccess = {
|
||||
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(
|
||||
db: AnalyticsAccessDb,
|
||||
groupId: string,
|
||||
|
||||
@@ -5,8 +5,14 @@ export type AttendanceStreamEntry = {
|
||||
|
||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
||||
|
||||
// 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.
|
||||
/** Minimum streak of unexcused absences that already triggers risk. */
|
||||
export const MIN_RISK_ABSENCE_STREAK = 2;
|
||||
|
||||
/** Monthly attendance (30-day window) below which there is risk. */
|
||||
export const MIN_RISK_MONTHLY_RATE = 50;
|
||||
|
||||
// Counts the consecutive unexcused absences from the most recent class.
|
||||
// Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
|
||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
let streak = 0;
|
||||
for (const entry of entries) {
|
||||
@@ -18,7 +24,7 @@ export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
return streak;
|
||||
}
|
||||
|
||||
// Fecha de la última clase a la que el alumno asistió (PRESENT), o null.
|
||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.status === 'PRESENT') {
|
||||
@@ -28,8 +34,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Porcentaje de asistencia sobre el total de sesiones del período.
|
||||
// Las sesiones sin registrar cuentan como no asistidas.
|
||||
// Attendance rate over the total number of sessions in the period.
|
||||
// Sessions with no record count as not attended.
|
||||
export function monthlyAttendanceRate(
|
||||
entries: AttendanceStreamEntry[],
|
||||
totalSessions: number,
|
||||
@@ -41,15 +47,15 @@ export function monthlyAttendanceRate(
|
||||
return Math.round((present / totalSessions) * 100);
|
||||
}
|
||||
|
||||
// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 50%.
|
||||
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
|
||||
export function classifyRisk(
|
||||
consecutiveAbsences: number,
|
||||
monthlyRate: number,
|
||||
): RiskLevel | null {
|
||||
if (consecutiveAbsences >= 3) {
|
||||
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
|
||||
return 'HIGH';
|
||||
}
|
||||
if (consecutiveAbsences === 2 || monthlyRate < 50) {
|
||||
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
||||
return 'MEDIUM';
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -41,7 +41,7 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Cargar teléfonos existentes del grupo
|
||||
// Load the group's existing phone numbers
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
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 prisma from '@/lib/prisma';
|
||||
|
||||
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers';
|
||||
import { toAttendeeListItemDto } from '../../lib/helpers';
|
||||
|
||||
type ListAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee'>;
|
||||
@@ -18,17 +18,36 @@ export class ListAttendees {
|
||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
/* Each row's summary travels in the same query instead of being built
|
||||
with one request per member. Both relations are capped on purpose:
|
||||
the payments table grows one row per month forever, and the listing
|
||||
only needs each person's current state. */
|
||||
db.attendee.findMany({
|
||||
...(where ? { where } : {}),
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
select: { status: true },
|
||||
},
|
||||
payments: {
|
||||
where: { status: { not: 'CANCELLED' } },
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 3,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
where ? db.attendee.count({ where }) : db.attendee.count(),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map((r) => toAttendeeDto(r as AttendeeRecord)),
|
||||
data: records.map((record) => toAttendeeListItemDto(record)),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
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 { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
import { toAttendeeDetailDto } from '../../lib/helpers';
|
||||
|
||||
type GetAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export class GetAttendee {
|
||||
@@ -18,7 +19,7 @@ export class GetAttendee {
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
): Promise<Result<AttendeeDetailDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
@@ -26,11 +27,32 @@ export class GetAttendee {
|
||||
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) {
|
||||
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)),
|
||||
};
|
||||
}
|
||||
|
||||
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal 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;
|
||||
@@ -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]),
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AttendeeDto } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
|
||||
export type AttendeeRecord = {
|
||||
id: string;
|
||||
@@ -14,6 +14,19 @@ export type AttendeeRecord = {
|
||||
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 {
|
||||
return {
|
||||
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.
|
||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||
* Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
|
||||
* Keeps a leading '+' for international numbers.
|
||||
*/
|
||||
export function normalizePhone(rawPhone: string): string {
|
||||
const trimmed = rawPhone.trim();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { GetAbsenceDetails } from './use-case';
|
||||
|
||||
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) => {
|
||||
const query = c.req.valid('query') as AbsenceQuery;
|
||||
const useCase = new GetAbsenceDetails();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PublicNotifyAbsenceUseCase } from './use-case';
|
||||
|
||||
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) => {
|
||||
const payload = c.req.valid('json') as PublicNotifyAbsence;
|
||||
const useCase = new PublicNotifyAbsenceUseCase();
|
||||
|
||||
@@ -18,8 +18,8 @@ type PaymentLike = {
|
||||
dueDate: Date;
|
||||
};
|
||||
|
||||
// Estado de cobro calculado en tiempo real (sin columna denormalizada):
|
||||
// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó.
|
||||
// Payment status computed in real time (no denormalized column):
|
||||
// PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed.
|
||||
export function resolvePaymentStatus(
|
||||
payments: PaymentLike[],
|
||||
startOfToday: Date,
|
||||
@@ -52,7 +52,7 @@ type GroupWithAccess = {
|
||||
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(
|
||||
session: ClassSessionRecord & { group: GroupWithAccess },
|
||||
userId: string,
|
||||
|
||||
@@ -17,9 +17,9 @@ type RegisterAbsenceInput = {
|
||||
releaseHours: number;
|
||||
};
|
||||
|
||||
// Núcleo compartido del aviso de ausencia (profesor autenticado y alumno con token):
|
||||
// - Marca la asistencia como EXCUSED (upsert idempotente).
|
||||
// - Si la anticipación alcanza `releaseHours`, crea/conserva un SlotRelease para liberar el cupo.
|
||||
// Shared core of the absence notice (authenticated teacher and attendee with a token):
|
||||
// - Marks the attendance as EXCUSED (idempotent upsert).
|
||||
// - If the notice comes early enough to meet `releaseHours`, creates/keeps a SlotRelease to free the spot.
|
||||
export async function registerAbsence(
|
||||
deps: RegisterAbsenceDeps,
|
||||
input: RegisterAbsenceInput,
|
||||
|
||||
@@ -13,7 +13,7 @@ type ScheduledGroup = {
|
||||
time: string | null;
|
||||
};
|
||||
|
||||
// Calcula qué grupos tienen clase hoy (según days/time y la zona horaria del profesor).
|
||||
// Computes which groups have a class today (from days/time and the teacher's time zone).
|
||||
export function buildTodayCandidates(
|
||||
groups: ScheduledGroup[],
|
||||
now: Date,
|
||||
@@ -37,7 +37,7 @@ export function buildTodayCandidates(
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// Materializa (upsert idempotente) las ClassSession del día y devuelve sus ids.
|
||||
// Materializes (idempotent upsert) today's ClassSession rows and returns their ids.
|
||||
export async function ensureTodaySessions(
|
||||
db: Pick<ClassesDb, 'classSession'>,
|
||||
candidates: TodaySessionCandidate[],
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { ApproveGroupPreRegistration } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/preregistrations/:entryId/approve', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new ApproveGroupPreRegistration();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ApproveGroupPreRegistrationResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
toGroupWaitlistEntryDto,
|
||||
} from '../../../group-waitlist/lib/helpers';
|
||||
import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote';
|
||||
import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
export class ApproveGroupPreRegistration {
|
||||
constructor(private readonly deps: ApproveGroupPreRegistrationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<ApproveGroupPreRegistrationResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const entry = await db.groupPreRegistration.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupPreRegistration', entryId));
|
||||
}
|
||||
if (entry.status !== 'PENDING') {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Esta pre-inscripción ya fue revisada.',
|
||||
code: 'pre_registration_already_reviewed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const record = entry as unknown as GroupPreRegistrationRecord;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx): Promise<Result<ApproveGroupPreRegistrationResult, ProblemDetails>> => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
tx,
|
||||
groupResult.value,
|
||||
{
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
},
|
||||
);
|
||||
|
||||
if (promoteResult.ok) {
|
||||
await tx.groupPreRegistration.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'APPROVED', reviewedAt: new Date() },
|
||||
});
|
||||
return ok({
|
||||
outcome: 'added',
|
||||
attendee: promoteResult.value,
|
||||
waitlistEntry: null,
|
||||
});
|
||||
}
|
||||
|
||||
if (promoteResult.error.code !== 'group_capacity_reached') {
|
||||
return promoteResult;
|
||||
}
|
||||
|
||||
const existingWaitlistEntry = await tx.groupWaitlistEntry.findFirst({
|
||||
where: { groupId: record.groupId, phone: record.phone },
|
||||
});
|
||||
const waitlistEntryRecord = existingWaitlistEntry
|
||||
? (existingWaitlistEntry as unknown as GroupWaitlistEntryRecord)
|
||||
: ((await tx.groupWaitlistEntry.create({
|
||||
data: {
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
},
|
||||
})) as unknown as GroupWaitlistEntryRecord);
|
||||
|
||||
await tx.groupPreRegistration.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'APPROVED', reviewedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({
|
||||
outcome: 'waitlisted',
|
||||
attendee: null,
|
||||
waitlistEntry: toGroupWaitlistEntryDto(waitlistEntryRecord),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
type GroupPreRegistrationQuery,
|
||||
GroupPreRegistrationQuerySchema,
|
||||
} from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListGroupPreRegistrations } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:groupId/preregistrations', validate.query(GroupPreRegistrationQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const query = c.req.valid('query') as GroupPreRegistrationQuery;
|
||||
const useCase = new ListGroupPreRegistrations();
|
||||
const result = await useCase.execute(groupId, user.id, query);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
GroupPreRegistrationList,
|
||||
GroupPreRegistrationQuery,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '../../../group-waitlist/lib/helpers';
|
||||
import {
|
||||
type GroupPreRegistrationRecord,
|
||||
toGroupPreRegistrationDto,
|
||||
} from '../../lib/helpers';
|
||||
|
||||
type ListGroupPreRegistrationsDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export class ListGroupPreRegistrations {
|
||||
constructor(private readonly deps: ListGroupPreRegistrationsDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
userId: string,
|
||||
query: GroupPreRegistrationQuery,
|
||||
): Promise<Result<GroupPreRegistrationList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupForUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const where = { groupId, status: query.status ?? ('PENDING' as const) };
|
||||
const [records, total] = await Promise.all([
|
||||
db.groupPreRegistration.findMany({
|
||||
where,
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
db.groupPreRegistration.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map(
|
||||
(record) => toGroupPreRegistrationDto(record as unknown as GroupPreRegistrationRecord),
|
||||
),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { RejectGroupPreRegistration } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/preregistrations/:entryId/reject', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new RejectGroupPreRegistration();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ProblemDetails,
|
||||
RejectGroupPreRegistrationResult,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '../../../group-waitlist/lib/helpers';
|
||||
import { type GroupPreRegistrationRecord, toGroupPreRegistrationDto } from '../../lib/helpers';
|
||||
|
||||
type RejectGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export class RejectGroupPreRegistration {
|
||||
constructor(private readonly deps: RejectGroupPreRegistrationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<RejectGroupPreRegistrationResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const entry = await db.groupPreRegistration.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupPreRegistration', entryId));
|
||||
}
|
||||
if (entry.status !== 'PENDING') {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Esta pre-inscripción ya fue revisada.',
|
||||
code: 'pre_registration_already_reviewed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const updated = await db.groupPreRegistration.update({
|
||||
where: { id: entry.id },
|
||||
data: { status: 'REJECTED', reviewedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({
|
||||
entry: toGroupPreRegistrationDto(updated as unknown as GroupPreRegistrationRecord),
|
||||
});
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/group-preregistrations/index.ts
Normal file
1
apps/backend/src/modules/group-preregistrations/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as groupPreRegistrationRoutes } from './routes';
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { GroupPreRegistrationDto } from '@gruperly/shared';
|
||||
|
||||
export type GroupPreRegistrationRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
status: GroupPreRegistrationDto['status'];
|
||||
reviewedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export function toGroupPreRegistrationDto(
|
||||
record: GroupPreRegistrationRecord,
|
||||
): GroupPreRegistrationDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
status: record.status,
|
||||
reviewedAt: record.reviewedAt ? record.reviewedAt.toISOString() : null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
12
apps/backend/src/modules/group-preregistrations/routes.ts
Normal file
12
apps/backend/src/modules/group-preregistrations/routes.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import approveRoute from './features/approve/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import rejectRoute from './features/reject/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getAllRoute);
|
||||
routes.route('/', approveRoute);
|
||||
routes.route('/', rejectRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import { Role } from '@generated/prisma/client';
|
||||
import type {
|
||||
CreateFirstGroup as CreateGroupInput,
|
||||
@@ -6,13 +6,11 @@ import type {
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { paymentNotSetupProblem } from '@/http/problem-builders';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { type GroupRecord, toGroupDto } from '../../lib';
|
||||
|
||||
type CreateGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupMember' | 'merchantAccount'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
@@ -23,14 +21,8 @@ export class CreateGroup {
|
||||
data: CreateGroupInput,
|
||||
userId: string,
|
||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (!merchantAccount) {
|
||||
return err(paymentNotSetupProblem());
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const created = await tx.group.create({
|
||||
|
||||
@@ -8,17 +8,30 @@ import type {
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
buildGroupWhereForUser,
|
||||
type GroupDb,
|
||||
type GroupRecord,
|
||||
toGroupDto,
|
||||
type GroupListRecord,
|
||||
toGroupListItemDto,
|
||||
} from '../../lib';
|
||||
|
||||
type ListGroupsDeps = {
|
||||
db?: Pick<GroupDb, 'group'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const OCCUPANCY_COUNT_INCLUDE = {
|
||||
_count: {
|
||||
select: {
|
||||
// Group members. No status filter, same as the detail page counts.
|
||||
attendees: true,
|
||||
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
|
||||
waitlist: { where: { status: 'PENDING' as const } },
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.GroupInclude;
|
||||
|
||||
export class ListGroups {
|
||||
constructor(private readonly deps: ListGroupsDeps = {}) {}
|
||||
|
||||
@@ -27,21 +40,59 @@ export class ListGroups {
|
||||
userId: string,
|
||||
): Promise<Result<GroupList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
db.group.findMany({
|
||||
// We fetch the user's groups with their counters and sort them here: the next
|
||||
// class is derived from days + time, there is no column to sort on in the
|
||||
// database. It's the same engine the home summary uses, with the person's
|
||||
// time zone (or the server's if it doesn't come along).
|
||||
const records: GroupListRecord[] = await db.group.findMany({
|
||||
where,
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
db.group.count({ where }),
|
||||
]);
|
||||
include: OCCUPANCY_COUNT_INCLUDE,
|
||||
});
|
||||
|
||||
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;
|
||||
const withNextClass = records.map((record) => ({
|
||||
record,
|
||||
nextAt: nextOccurrenceAt(record, now, timeZone),
|
||||
}));
|
||||
|
||||
/* A group with no schedule has no class to compare, so it goes last;
|
||||
between groups with the same class (or with no schedule) the newest one
|
||||
breaks the tie, which was the listing's previous criterion. */
|
||||
const ordered = withNextClass.sort((a, b) => {
|
||||
if (a.nextAt !== null && b.nextAt !== null) {
|
||||
return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime();
|
||||
}
|
||||
if (a.nextAt !== null) {
|
||||
return -1;
|
||||
}
|
||||
if (b.nextAt !== null) {
|
||||
return 1;
|
||||
}
|
||||
return b.record.createdAt.getTime() - a.record.createdAt.getTime();
|
||||
});
|
||||
|
||||
const offset = getPaginationOffset(query);
|
||||
const page = ordered.slice(offset, offset + query.pageSize);
|
||||
|
||||
return ok({
|
||||
data: records.map((record: GroupRecord) => toGroupDto(record)),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
data: page.map(({ record }) => toGroupListItemDto(record)),
|
||||
pagination: getPaginationMetadata(query, ordered.length),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function nextOccurrenceAt(record: GroupListRecord, now: Date, timeZone: string): number | null {
|
||||
if (!record.days?.length || !record.time) {
|
||||
return null;
|
||||
}
|
||||
const occurrence = nextClassOccurrence({
|
||||
days: record.days,
|
||||
time: record.time,
|
||||
now,
|
||||
timeZone,
|
||||
});
|
||||
return occurrence ? occurrence.occurrenceAt.getTime() : null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { BillingType, GroupDto, WeekDay } from '@gruperly/shared';
|
||||
import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
||||
|
||||
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
||||
|
||||
@@ -21,6 +21,14 @@ export type GroupRecord = {
|
||||
inviteToken?: string | null;
|
||||
};
|
||||
|
||||
/* The listing adds the occupancy counters to each group so the card can show
|
||||
them without asking for one endpoint per group. They come from the `_count` of
|
||||
the same query: all the members (same as the detail page counts) and only the
|
||||
waitlist entries still waiting for a spot (PENDING). */
|
||||
export type GroupListRecord = GroupRecord & {
|
||||
_count?: { attendees: number; waitlist: number };
|
||||
};
|
||||
|
||||
export function toGroupDto(record: GroupRecord): GroupDto {
|
||||
return {
|
||||
id: record.id,
|
||||
@@ -39,6 +47,14 @@ export function toGroupDto(record: GroupRecord): GroupDto {
|
||||
};
|
||||
}
|
||||
|
||||
export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
|
||||
return {
|
||||
...toGroupDto(record),
|
||||
attendeesCount: record._count?.attendees ?? 0,
|
||||
waitlistCount: record._count?.waitlist ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildGroupWhereForUser(userId: string) {
|
||||
return {
|
||||
OR: [
|
||||
|
||||
@@ -6,6 +6,8 @@ import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createGroupRoute from './features/create/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
@@ -24,8 +26,10 @@ routes.route('/', bulkCreateAttendeesRoute);
|
||||
routes.route('/', getByIdRoute);
|
||||
routes.route('/', addToGroupWaitlistRoute);
|
||||
routes.route('/', groupWaitlistRoutes);
|
||||
routes.route('/', groupPreRegistrationRoutes);
|
||||
routes.route('/', analyticsRoutes);
|
||||
routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', updateAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { WeekDay } from '@gruperly/shared';
|
||||
|
||||
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City';
|
||||
|
||||
// Ventana (en horas) durante la que una clase ya arrancada se muestra como "en curso".
|
||||
// Window (in hours) during which an already started class shows as "in progress".
|
||||
export const CLASS_WINDOW_HOURS = 2;
|
||||
export const CLASS_WINDOW_MS = CLASS_WINDOW_HOURS * 60 * 60 * 1000;
|
||||
|
||||
@@ -21,7 +21,7 @@ export type NextClassOccurrence = {
|
||||
isNow: boolean;
|
||||
};
|
||||
|
||||
// Convierte un tiempo de "pared" (wall clock) expresado en `timeZone` al instante absoluto.
|
||||
// Converts a "wall clock" time expressed in `timeZone` into the absolute instant.
|
||||
export function zonedWallClockToUtc(wall: string, timeZone: string): Date {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall);
|
||||
if (!match) {
|
||||
@@ -145,8 +145,8 @@ function pad(value: number): string {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
// Instante absoluto de la clase de HOY (aunque la hora ya haya pasado), o null si el grupo
|
||||
// no tiene clase programada para el día de `now` en `timeZone`.
|
||||
// Absolute instant of TODAY's class (even if the time has already passed), or null if the
|
||||
// group has no class scheduled for `now`'s day in `timeZone`.
|
||||
export function todayOccurrence(opt: {
|
||||
days: WeekDay[];
|
||||
time: string;
|
||||
@@ -181,7 +181,7 @@ export function todayOccurrence(opt: {
|
||||
return zonedWallClockToUtc(wall, timeZone);
|
||||
}
|
||||
|
||||
// Primer instante del día de `now` en `timeZone` (medianoche local).
|
||||
// First instant of `now`'s day in `timeZone` (local midnight).
|
||||
export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
|
||||
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
type JoinViaInviteDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export type JoinViaInviteResult = {
|
||||
status: 'registered' | 'waitlisted';
|
||||
status: 'pre_registered';
|
||||
message: string;
|
||||
attendee: AttendeeDto | null;
|
||||
attendee: null;
|
||||
};
|
||||
|
||||
export class JoinViaInvite {
|
||||
@@ -53,50 +53,63 @@ export class JoinViaInvite {
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
const email = payload.email?.trim() || null;
|
||||
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
where: { groupId: group.id, status: 'ACTIVE' },
|
||||
});
|
||||
|
||||
if (currentCount >= group.capacity) {
|
||||
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
|
||||
where: { groupId: group.id, phone },
|
||||
});
|
||||
|
||||
if (!existingWaitlistEntry) {
|
||||
await db.groupWaitlistEntry.create({
|
||||
data: {
|
||||
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (existingPreRegistration?.status === 'REJECTED') {
|
||||
await db.groupPreRegistration.update({
|
||||
where: { id: existingPreRegistration.id },
|
||||
data: { status: 'PENDING', fullName, email, reviewedAt: null },
|
||||
});
|
||||
|
||||
return ok({
|
||||
status: 'waitlisted',
|
||||
message:
|
||||
'El grupo está completo. Fuiste agregado a la lista de espera. Te contactaremos cuando haya un lugar disponible.',
|
||||
status: 'pre_registered',
|
||||
attendee: null,
|
||||
message:
|
||||
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||
});
|
||||
}
|
||||
|
||||
if (existingPreRegistration) {
|
||||
const message =
|
||||
existingPreRegistration.status === 'APPROVED'
|
||||
? 'Tu inscripción para este grupo ya fue aprobada.'
|
||||
: 'Ya enviaste una solicitud de inscripción para este grupo. Está pendiente de revisión por el profesor.';
|
||||
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: message,
|
||||
code:
|
||||
existingPreRegistration.status === 'APPROVED'
|
||||
? 'pre_registration_already_approved'
|
||||
: 'pre_registration_already_pending',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const created = await db.attendee.create({
|
||||
await db.groupPreRegistration.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
status: 'registered',
|
||||
attendee: toAttendeeDto(created as unknown as AttendeeRecord),
|
||||
message: 'Inscripción realizada con éxito',
|
||||
status: 'pre_registered',
|
||||
attendee: null,
|
||||
message:
|
||||
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||
});
|
||||
}
|
||||
}
|
||||
58
apps/backend/src/modules/mp/access-token.ts
Normal file
58
apps/backend/src/modules/mp/access-token.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpNotConnectedProblem, mpRequiresReauthProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { RefreshMpAccount } from './jobs';
|
||||
import { openToken } from './lib';
|
||||
|
||||
export type MpTokenAccount = {
|
||||
accountId: string;
|
||||
accessToken: string;
|
||||
expiresAt: Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* Below this, the on-demand path refreshes. The daily job renews much earlier
|
||||
* (30 days out), so hitting this only means the job did not run, which is exactly
|
||||
* when a payment link cannot be allowed to fail.
|
||||
*/
|
||||
const NEAR_EXPIRY_MS = 5 * 60 * 1000;
|
||||
|
||||
type GetMpAccessTokenDeps = {
|
||||
db?: Pick<PrismaClient, 'mpAccount'>;
|
||||
refresh?: RefreshMpAccount;
|
||||
};
|
||||
|
||||
/**
|
||||
* A usable access token for a teacher's Mercado Pago account.
|
||||
*
|
||||
* This is the entry point for payment links and webhook verification, so it fails
|
||||
* explicitly instead of returning something unusable: an unlinked account and an
|
||||
* account that needs re-authorization are different problems and the caller has
|
||||
* to be able to tell them apart.
|
||||
*/
|
||||
export async function getMpAccessToken(
|
||||
ownerId: string,
|
||||
deps: GetMpAccessTokenDeps = {},
|
||||
): Promise<Result<MpTokenAccount, ProblemDetails>> {
|
||||
const db = deps.db ?? prisma;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { ownerId } });
|
||||
if (!account) return err(mpNotConnectedProblem());
|
||||
if (account.status !== 'ACTIVE') return err(mpRequiresReauthProblem());
|
||||
|
||||
if (account.expiresAt.getTime() - Date.now() > NEAR_EXPIRY_MS) {
|
||||
return ok({
|
||||
accountId: account.id,
|
||||
accessToken: openToken(account.accessTokenEnc),
|
||||
expiresAt: account.expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
const refresh = deps.refresh ?? new RefreshMpAccount();
|
||||
const refreshed = await refresh.execute(account.id);
|
||||
if (!refreshed.ok) return refreshed;
|
||||
|
||||
return ok(refreshed.value);
|
||||
}
|
||||
50
apps/backend/src/modules/mp/features/callback/route.ts
Normal file
50
apps/backend/src/modules/mp/features/callback/route.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { MpCallbackQuery, MpCallbackReason, ProblemDetails } from '@gruperly/shared';
|
||||
import { MpCallbackQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { validate } from '@/http/validate';
|
||||
import { logger } from '@/logger';
|
||||
import { buildMpReturnUrl, getWebOrigin } from '../../lib';
|
||||
import { CompleteMpAuthorization, type MpCallbackResult } from './use-case';
|
||||
|
||||
/**
|
||||
* The browser arrives here from Mercado Pago, so this route always answers with
|
||||
* a redirect back to the app and never renders or returns a problem body: there
|
||||
* is nothing on the other side to render a failure into.
|
||||
*/
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
|
||||
const { code, state, error } = c.req.valid('query') as MpCallbackQuery;
|
||||
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
// Without a session there is nobody to credit the tokens to. The state was
|
||||
// issued to whoever was signed in when the flow started, so guessing would
|
||||
// be a way to attach somebody else's Mercado Pago account to this account.
|
||||
logger.warn('Mercado Pago callback arrived without a session');
|
||||
return c.redirect(new URL('/login', getWebOrigin()).toString());
|
||||
}
|
||||
|
||||
const useCase = new CompleteMpAuthorization();
|
||||
const result = await useCase.execute({ code, state, error });
|
||||
|
||||
if (!result.ok) {
|
||||
logger.warn(
|
||||
{ code: result.error.code, status: result.error.status },
|
||||
'Mercado Pago callback failed',
|
||||
);
|
||||
}
|
||||
|
||||
const outcome = result.ok ? result.value.outcome : problemToOutcome(result.error);
|
||||
const returnTo = result.ok ? result.value.returnTo : 'settings';
|
||||
|
||||
return c.redirect(buildMpReturnUrl(getWebOrigin(), returnTo, outcome));
|
||||
});
|
||||
|
||||
/** Reduces an internal problem to a reason code that is safe in a URL. */
|
||||
function problemToOutcome(problem: ProblemDetails): MpCallbackResult['outcome'] {
|
||||
const reason: MpCallbackReason = problem.code === 'mp_account_in_use' ? 'mp_account_in_use' : 'mp_error';
|
||||
return { kind: 'error', reason };
|
||||
}
|
||||
|
||||
export default route;
|
||||
145
apps/backend/src/modules/mp/features/callback/use-case.ts
Normal file
145
apps/backend/src/modules/mp/features/callback/use-case.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { MpCallbackReason, MpReturnTo, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
mpAccountInUseProblem,
|
||||
mpNotConfiguredProblem,
|
||||
mpProviderErrorProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
exchangeAuthorizationCode,
|
||||
getMpOAuthConfig,
|
||||
type MpTokenResponse,
|
||||
sealToken,
|
||||
} from '../../lib';
|
||||
|
||||
type CompleteMpAuthorizationDeps = {
|
||||
db?: Pick<PrismaClient, 'mpOAuthState' | 'mpAccount'>;
|
||||
/** Swapped in tests; defaults to the real Mercado Pago exchange. */
|
||||
exchange?: typeof exchangeAuthorizationCode;
|
||||
};
|
||||
|
||||
export type MpCallbackResult = {
|
||||
returnTo: MpReturnTo;
|
||||
outcome: { kind: 'success' } | { kind: 'error'; reason: MpCallbackReason };
|
||||
};
|
||||
|
||||
/** Prisma's unique-constraint violation on `mp_accounts_mpUserId_key`. */
|
||||
const UNIQUE_VIOLATION = 'P2002';
|
||||
|
||||
/** Where we land if the state is gone and there is nothing to recover. */
|
||||
const DEFAULT_RETURN_TO: MpReturnTo = 'settings';
|
||||
|
||||
export class CompleteMpAuthorization {
|
||||
constructor(private readonly deps: CompleteMpAuthorizationDeps = {}) {}
|
||||
|
||||
async execute(input: {
|
||||
code?: string;
|
||||
state?: string;
|
||||
error?: string;
|
||||
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
|
||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||
try {
|
||||
config = getMpOAuthConfig();
|
||||
} catch (configError) {
|
||||
logger.error({ err: configError }, 'Mercado Pago is not configured');
|
||||
return err(mpNotConfiguredProblem());
|
||||
}
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
// The teacher closed the consent screen. There is nothing to exchange, but
|
||||
// the state is still burned so it cannot be replayed later.
|
||||
if (input.error) {
|
||||
if (input.state) {
|
||||
await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
||||
}
|
||||
return failure('mp_denied');
|
||||
}
|
||||
|
||||
if (!input.code || !input.state) {
|
||||
return failure('invalid_state');
|
||||
}
|
||||
|
||||
const stored = await db.mpOAuthState.findUnique({ where: { state: input.state } });
|
||||
if (!stored || stored.expiresAt.getTime() <= Date.now()) {
|
||||
return failure('invalid_state');
|
||||
}
|
||||
|
||||
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
|
||||
|
||||
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
|
||||
// means someone replayed a state we already consumed.
|
||||
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
||||
if (consumed.count === 0) {
|
||||
return failure('invalid_state', returnTo);
|
||||
}
|
||||
|
||||
const exchange = this.deps.exchange ?? exchangeAuthorizationCode;
|
||||
let tokens: MpTokenResponse;
|
||||
try {
|
||||
tokens = await exchange({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
redirectUri: config.redirectUri,
|
||||
code: input.code,
|
||||
codeVerifier: stored.codeVerifier,
|
||||
});
|
||||
} catch (exchangeError) {
|
||||
// `MpApiError` already logged the status and MP's own error code. Nothing
|
||||
// added here mentions the authorization code or the verifier.
|
||||
logger.error({ err: exchangeError }, 'Mercado Pago authorization could not be completed');
|
||||
return err(mpProviderErrorProblem());
|
||||
}
|
||||
|
||||
const claimed = await db.mpAccount.findUnique({ where: { mpUserId: tokens.mpUserId } });
|
||||
if (claimed && claimed.ownerId !== stored.ownerId) {
|
||||
return err(mpAccountInUseProblem());
|
||||
}
|
||||
|
||||
const encrypted = {
|
||||
accessTokenEnc: sealToken(tokens.accessToken),
|
||||
refreshTokenEnc: sealToken(tokens.refreshToken),
|
||||
expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000),
|
||||
scope: tokens.scope,
|
||||
liveMode: tokens.liveMode,
|
||||
status: 'ACTIVE' as const,
|
||||
};
|
||||
|
||||
try {
|
||||
await db.mpAccount.upsert({
|
||||
where: { ownerId: stored.ownerId },
|
||||
create: { ownerId: stored.ownerId, mpUserId: tokens.mpUserId, ...encrypted },
|
||||
// Re-linking renews the credentials and clears a `requires_reauth`.
|
||||
update: { mpUserId: tokens.mpUserId, ...encrypted, connectedAt: new Date() },
|
||||
});
|
||||
} catch (writeError) {
|
||||
// Two teachers linked the same Mercado Pago id at the same time: the
|
||||
// unique index is the real arbiter, not the read above.
|
||||
if (isUniqueViolation(writeError)) {
|
||||
return err(mpAccountInUseProblem());
|
||||
}
|
||||
throw writeError;
|
||||
}
|
||||
|
||||
return ok({ returnTo, outcome: { kind: 'success' } });
|
||||
}
|
||||
}
|
||||
|
||||
function failure(
|
||||
reason: MpCallbackReason,
|
||||
returnTo: MpReturnTo = DEFAULT_RETURN_TO,
|
||||
): Result<MpCallbackResult, ProblemDetails> {
|
||||
return ok({ returnTo, outcome: { kind: 'error', reason } });
|
||||
}
|
||||
|
||||
function isUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
(error as { code?: unknown }).code === UNIQUE_VIOLATION
|
||||
);
|
||||
}
|
||||
21
apps/backend/src/modules/mp/features/connect/route.ts
Normal file
21
apps/backend/src/modules/mp/features/connect/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { MpConnectQuery, MpReturnTo } from '@gruperly/shared';
|
||||
import { MpConnectQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { StartMpAuthorization } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', validate.query(MpConnectQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const { returnTo } = c.req.valid('query') as MpConnectQuery;
|
||||
|
||||
const useCase = new StartMpAuthorization();
|
||||
const result = await useCase.execute(user.id, returnTo as MpReturnTo);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
71
apps/backend/src/modules/mp/features/connect/use-case.ts
Normal file
71
apps/backend/src/modules/mp/features/connect/use-case.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
MpAuthorizationUrlDto,
|
||||
MpReturnTo,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpNotConfiguredProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
buildAuthorizationUrl,
|
||||
codeChallengeFromVerifier,
|
||||
getMpOAuthConfig,
|
||||
newCodeVerifier,
|
||||
newState,
|
||||
} from '../../lib';
|
||||
|
||||
type StartMpAuthorizationDeps = { db?: Pick<PrismaClient, 'mpOAuthState'> };
|
||||
|
||||
/** The teacher has ten minutes to finish at Mercado Pago before the state dies. */
|
||||
export const STATE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export class StartMpAuthorization {
|
||||
constructor(private readonly deps: StartMpAuthorizationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
ownerId: string,
|
||||
returnTo: MpReturnTo,
|
||||
): Promise<Result<MpAuthorizationUrlDto, ProblemDetails>> {
|
||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||
try {
|
||||
config = getMpOAuthConfig();
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago is not configured');
|
||||
return err(mpNotConfiguredProblem());
|
||||
}
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = new Date();
|
||||
|
||||
// Two jobs in one sweep: drop anything expired, and drop this teacher's
|
||||
// previous attempt so a teacher clicking twice cannot leave rows behind.
|
||||
await db.mpOAuthState.deleteMany({
|
||||
where: { OR: [{ expiresAt: { lt: now } }, { ownerId }] },
|
||||
});
|
||||
|
||||
const state = newState();
|
||||
const codeVerifier = newCodeVerifier();
|
||||
|
||||
await db.mpOAuthState.create({
|
||||
data: {
|
||||
state,
|
||||
ownerId,
|
||||
codeVerifier,
|
||||
returnTo,
|
||||
expiresAt: new Date(now.getTime() + STATE_TTL_MS),
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
authorizationUrl: buildAuthorizationUrl({
|
||||
clientId: config.clientId,
|
||||
redirectUri: config.redirectUri,
|
||||
state,
|
||||
codeChallenge: codeChallengeFromVerifier(codeVerifier),
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/mp/features/disconnect/route.ts
Normal file
16
apps/backend/src/modules/mp/features/disconnect/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { DisconnectMp } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.delete('/', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new DisconnectMp();
|
||||
const result = await useCase.execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
39
apps/backend/src/modules/mp/features/disconnect/use-case.ts
Normal file
39
apps/backend/src/modules/mp/features/disconnect/use-case.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { MpDisconnectResultDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type DisconnectMpDeps = { db?: Pick<PrismaClient, 'mpAccount'> };
|
||||
|
||||
/**
|
||||
* Mercado Pago has no seller-side token revocation endpoint for these grants, so
|
||||
* the tokens are dropped here and the row is kept as `REVOKED`. It is not
|
||||
* deleted on purpose: the Mercado Pago id stays reserved for the same teacher,
|
||||
* which stops someone else from claiming their account later.
|
||||
*/
|
||||
export class DisconnectMp {
|
||||
constructor(private readonly deps: DisconnectMpDeps = {}) {}
|
||||
|
||||
async execute(ownerId: string): Promise<Result<MpDisconnectResultDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { ownerId } });
|
||||
if (!account) {
|
||||
return ok({ disconnected: false });
|
||||
}
|
||||
|
||||
await db.mpAccount.update({
|
||||
where: { ownerId },
|
||||
data: {
|
||||
status: 'REVOKED',
|
||||
// The columns are NOT NULL, so the values are blanked rather than nulled.
|
||||
// Nothing reads them: every consumer filters on `status` first.
|
||||
accessTokenEnc: '',
|
||||
refreshTokenEnc: '',
|
||||
expiresAt: new Date(0),
|
||||
},
|
||||
});
|
||||
|
||||
return ok({ disconnected: true });
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/mp/features/status/route.ts
Normal file
16
apps/backend/src/modules/mp/features/status/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetMpStatus } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new GetMpStatus();
|
||||
const result = await useCase.execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
52
apps/backend/src/modules/mp/features/status/use-case.ts
Normal file
52
apps/backend/src/modules/mp/features/status/use-case.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { MpAccountStatus, MpStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type GetMpStatusDeps = { db?: Pick<PrismaClient, 'mpAccount'> };
|
||||
|
||||
/** How many trailing digits of the Mercado Pago id we show, to confirm the account. */
|
||||
const SUFFIX_LENGTH = 4;
|
||||
|
||||
const NOT_LINKED: MpStatusDto = {
|
||||
status: 'none',
|
||||
liveMode: false,
|
||||
expiresAt: null,
|
||||
connectedAt: null,
|
||||
mpUserIdSuffix: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* An account the teacher unlinked stays in the table (so the Mercado Pago id
|
||||
* stays reserved for them), but from the outside it is simply "not linked".
|
||||
*/
|
||||
function toVisibleStatus(status: 'ACTIVE' | 'REQUIRES_REAUTH' | 'REVOKED'): MpAccountStatus {
|
||||
switch (status) {
|
||||
case 'ACTIVE':
|
||||
return 'active';
|
||||
case 'REQUIRES_REAUTH':
|
||||
return 'requires_reauth';
|
||||
case 'REVOKED':
|
||||
return 'none';
|
||||
}
|
||||
}
|
||||
|
||||
export class GetMpStatus {
|
||||
constructor(private readonly deps: GetMpStatusDeps = {}) {}
|
||||
|
||||
async execute(ownerId: string): Promise<Result<MpStatusDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { ownerId } });
|
||||
if (!account) return ok(NOT_LINKED);
|
||||
|
||||
// Deliberately no tokens and no scope in the response.
|
||||
return ok({
|
||||
status: toVisibleStatus(account.status),
|
||||
liveMode: account.liveMode,
|
||||
expiresAt: account.expiresAt.toISOString(),
|
||||
connectedAt: account.connectedAt.toISOString(),
|
||||
mpUserIdSuffix: account.mpUserId.slice(-SUFFIX_LENGTH),
|
||||
});
|
||||
}
|
||||
}
|
||||
3
apps/backend/src/modules/mp/index.ts
Normal file
3
apps/backend/src/modules/mp/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { getMpAccessToken, type MpTokenAccount } from './access-token';
|
||||
export { startMpJobs } from './jobs';
|
||||
export { default as mpRoutes } from './routes';
|
||||
7
apps/backend/src/modules/mp/jobs/index.ts
Normal file
7
apps/backend/src/modules/mp/jobs/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export {
|
||||
RENEWAL_WINDOW_DAYS,
|
||||
RefreshExpiringMpTokens,
|
||||
type RefreshExpiringMpTokensResult,
|
||||
} from './refresh-expiring-mp-tokens';
|
||||
export { type MpAccountStore, RefreshMpAccount } from './refresh-mp-account';
|
||||
export { startMpJobs } from './schedule';
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { refreshMpTokens } from '../lib';
|
||||
import { RefreshMpAccount } from './refresh-mp-account';
|
||||
|
||||
/**
|
||||
* Mercado Pago hands out access tokens valid for about six months. Renewing at
|
||||
* 30 days leaves room for the job to fail a few times before a token is at risk.
|
||||
*/
|
||||
const RENEWAL_WINDOW_DAYS = 30;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Keeps a bounded batch: the query below holds row locks for the life of the
|
||||
* transaction, which means it holds them across the calls to Mercado Pago.
|
||||
*/
|
||||
const BATCH_LIMIT = 20;
|
||||
const TRANSACTION_TIMEOUT_MS = 120_000;
|
||||
|
||||
export type RefreshExpiringMpTokensResult = {
|
||||
refreshed: number;
|
||||
requiresReauth: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
type RefreshExpiringMpTokensDeps = {
|
||||
db?: PrismaClient;
|
||||
/** Swapped in tests; defaults to the real Mercado Pago renewal. */
|
||||
refresh?: typeof refreshMpTokens;
|
||||
};
|
||||
|
||||
type LockedAccountRow = { id: string };
|
||||
|
||||
export class RefreshExpiringMpTokens {
|
||||
constructor(private readonly deps: RefreshExpiringMpTokensDeps = {}) {}
|
||||
|
||||
async execute(): Promise<RefreshExpiringMpTokensResult> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = new Date();
|
||||
const totals: RefreshExpiringMpTokensResult = { refreshed: 0, requiresReauth: 0, failed: 0 };
|
||||
|
||||
await db.$transaction(
|
||||
async (tx) => {
|
||||
const horizon = new Date(now.getTime() + RENEWAL_WINDOW_DAYS * DAY_MS);
|
||||
|
||||
// FOR UPDATE SKIP LOCKED: two instances of the API never renew the same
|
||||
// account, and a row already claimed by another instance is skipped
|
||||
// instead of blocking the batch. The trade-off is that the lock stays
|
||||
// held across the HTTP calls below; if MP's latency ever became a
|
||||
// problem, this becomes an atomic `updateMany` claim on a
|
||||
// `refresh_claimed_at` column and the rows are released immediately.
|
||||
const rows = await tx.$queryRaw<LockedAccountRow[]>`
|
||||
SELECT "id"
|
||||
FROM "mp_accounts"
|
||||
WHERE "status" = 'ACTIVE' AND "expires_at" < ${horizon}
|
||||
ORDER BY "expires_at" ASC
|
||||
LIMIT ${BATCH_LIMIT}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`;
|
||||
|
||||
for (const row of rows) {
|
||||
// Built per row with the transaction client, so the writes join the
|
||||
// transaction holding the lock. With the shared client the lock would
|
||||
// protect nothing.
|
||||
const result = await new RefreshMpAccount({ db: tx, refresh: this.deps.refresh }).execute(
|
||||
row.id,
|
||||
);
|
||||
|
||||
if (result.ok) {
|
||||
totals.refreshed += 1;
|
||||
} else if (result.error.code === 'mp_requires_reauth') {
|
||||
totals.requiresReauth += 1;
|
||||
} else {
|
||||
totals.failed += 1;
|
||||
}
|
||||
}
|
||||
},
|
||||
{ timeout: TRANSACTION_TIMEOUT_MS },
|
||||
);
|
||||
|
||||
return totals;
|
||||
}
|
||||
}
|
||||
|
||||
export { RENEWAL_WINDOW_DAYS };
|
||||
86
apps/backend/src/modules/mp/jobs/refresh-mp-account.ts
Normal file
86
apps/backend/src/modules/mp/jobs/refresh-mp-account.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpProviderErrorProblem, mpRequiresReauthProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import type { MpTokenAccount } from '../access-token';
|
||||
import {
|
||||
getMpOAuthConfig,
|
||||
isGrantRejected,
|
||||
type MpTokenResponse,
|
||||
openToken,
|
||||
refreshMpTokens,
|
||||
sealToken,
|
||||
} from '../lib';
|
||||
|
||||
/** Either the client or a transaction client: the job runs this inside a transaction. */
|
||||
export type MpAccountStore = { mpAccount: PrismaClient['mpAccount'] };
|
||||
|
||||
export type RefreshMpAccountDeps = {
|
||||
db?: MpAccountStore;
|
||||
refresh?: typeof refreshMpTokens;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renews one account's access token.
|
||||
*
|
||||
* Shared by the daily job and by the on-demand path in `getMpAccessToken`.
|
||||
*
|
||||
* Mercado Pago rotates the refresh token on every renewal, so the new one is
|
||||
* always stored: keeping the old one would make the next renewal fail.
|
||||
*
|
||||
* Only `invalid_grant` marks the account as `REQUIRES_REAUTH`. A 5xx or a network
|
||||
* failure means no decision was taken about the grant, and locking a teacher out
|
||||
* over a bad afternoon at Mercado Pago would be worse than retrying tomorrow.
|
||||
*/
|
||||
export class RefreshMpAccount {
|
||||
constructor(private readonly deps: RefreshMpAccountDeps = {}) {}
|
||||
|
||||
async execute(accountId: string): Promise<Result<MpTokenAccount, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const refresh = this.deps.refresh ?? refreshMpTokens;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { id: accountId } });
|
||||
if (!account) {
|
||||
logger.warn({ accountId }, 'Mercado Pago account vanished mid-renewal');
|
||||
return err(mpRequiresReauthProblem());
|
||||
}
|
||||
|
||||
let tokens: MpTokenResponse;
|
||||
try {
|
||||
const config = getMpOAuthConfig();
|
||||
tokens = await refresh({
|
||||
...config,
|
||||
refreshToken: openToken(account.refreshTokenEnc),
|
||||
});
|
||||
} catch (error) {
|
||||
if (isGrantRejected(error)) {
|
||||
logger.warn({ accountId }, 'Mercado Pago refresh token is no longer valid');
|
||||
await db.mpAccount.update({
|
||||
where: { id: accountId },
|
||||
data: { status: 'REQUIRES_REAUTH' },
|
||||
});
|
||||
return err(mpRequiresReauthProblem());
|
||||
}
|
||||
|
||||
logger.error({ accountId, err: error }, 'Mercado Pago token renewal failed');
|
||||
return err(mpProviderErrorProblem());
|
||||
}
|
||||
|
||||
const expiresAt = new Date(Date.now() + tokens.expiresInSeconds * 1000);
|
||||
|
||||
await db.mpAccount.update({
|
||||
where: { id: accountId },
|
||||
data: {
|
||||
accessTokenEnc: sealToken(tokens.accessToken),
|
||||
refreshTokenEnc: sealToken(tokens.refreshToken),
|
||||
expiresAt,
|
||||
scope: tokens.scope ?? account.scope,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
});
|
||||
|
||||
return ok({ accountId, accessToken: tokens.accessToken, expiresAt });
|
||||
}
|
||||
}
|
||||
33
apps/backend/src/modules/mp/jobs/schedule.ts
Normal file
33
apps/backend/src/modules/mp/jobs/schedule.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { logger } from '@/logger';
|
||||
import { RefreshExpiringMpTokens } from './refresh-expiring-mp-tokens';
|
||||
|
||||
/**
|
||||
* 03:17 UTC. Not on the hour: every instance of the API fires this job at the
|
||||
* same time, and the lock is only there to make the overlap harmless.
|
||||
*/
|
||||
const REFRESH_CRON = '17 3 * * *';
|
||||
|
||||
/**
|
||||
* Registers the background jobs. Called once from `server.ts`.
|
||||
*
|
||||
* Two things are not obvious here:
|
||||
*
|
||||
* - `try/catch` is mandatory. Bun's in-process cron follows `setTimeout` error
|
||||
* semantics: a rejected promise becomes an `unhandledRejection`, and without a
|
||||
* listener the process exits with code 1.
|
||||
* - `unref()` so the job does not keep the process alive on its own.
|
||||
*/
|
||||
export function startMpJobs(): void {
|
||||
Bun.cron(
|
||||
REFRESH_CRON,
|
||||
async () => {
|
||||
try {
|
||||
const totals = await new RefreshExpiringMpTokens().execute();
|
||||
logger.info(totals, 'Mercado Pago token renewal finished');
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago token renewal failed');
|
||||
}
|
||||
},
|
||||
{ tz: 'UTC' },
|
||||
).unref();
|
||||
}
|
||||
51
apps/backend/src/modules/mp/lib/config.ts
Normal file
51
apps/backend/src/modules/mp/lib/config.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
export type MpOAuthConfig = {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
/** Registered as the app's "Redirect URL". Mercado Pago matches it exactly. */
|
||||
redirectUri: string;
|
||||
/** Frontend origin, used to land the teacher back in the app after the callback. */
|
||||
webUrl: string;
|
||||
};
|
||||
|
||||
const DEFAULT_WEB_URL = 'http://localhost:6173';
|
||||
|
||||
export function getWebOrigin(): string {
|
||||
return process.env.WEB_URL?.trim() || DEFAULT_WEB_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the Mercado Pago credentials from the environment.
|
||||
*
|
||||
* Throws instead of returning a `Result`: these are deployment mistakes, not
|
||||
* something the teacher did wrong, so they surface as a 500 with a named
|
||||
* variable in the logs rather than as a problem the UI has to explain. The
|
||||
* names of the missing variables are safe to log; their values never are.
|
||||
*/
|
||||
export function getMpOAuthConfig(): MpOAuthConfig {
|
||||
const missing: string[] = [];
|
||||
const read = (name: string): string => {
|
||||
const value = process.env[name]?.trim();
|
||||
if (!value) {
|
||||
missing.push(name);
|
||||
return '';
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const clientId = read('MP_CLIENT_ID');
|
||||
const clientSecret = read('MP_CLIENT_SECRET');
|
||||
const redirectUri = read('MP_REDIRECT_URI');
|
||||
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing Mercado Pago environment variables: ${missing.join(', ')}. See .env.example.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri,
|
||||
webUrl: getWebOrigin(),
|
||||
};
|
||||
}
|
||||
79
apps/backend/src/modules/mp/lib/crypto.ts
Normal file
79
apps/backend/src/modules/mp/lib/crypto.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
/**
|
||||
* Tokens are encrypted at rest with AES-256-GCM. The payload carries a version
|
||||
* prefix so the scheme can be rotated later without a data migration: an unknown
|
||||
* version fails loudly instead of being decrypted with the wrong assumptions.
|
||||
*
|
||||
* Layout: `v1:<iv>:<tag>:<ciphertext>`, each part base64url. GCM authenticates
|
||||
* the ciphertext, so a tampered payload throws on `openToken` rather than
|
||||
* yielding garbage that would later be sent to Mercado Pago as a token.
|
||||
*/
|
||||
const PAYLOAD_VERSION = 'v1';
|
||||
const KEY_BYTES = 32;
|
||||
const IV_BYTES = 12;
|
||||
|
||||
function getKey(): Buffer {
|
||||
const raw = process.env.TOKEN_ENCRYPTION_KEY;
|
||||
if (!raw) {
|
||||
throw new Error('TOKEN_ENCRYPTION_KEY environment variable is required');
|
||||
}
|
||||
|
||||
const key = Buffer.from(raw, 'base64');
|
||||
if (key.length !== KEY_BYTES) {
|
||||
// Length only, never the value.
|
||||
throw new Error(
|
||||
`TOKEN_ENCRYPTION_KEY must decode to ${KEY_BYTES} bytes in base64, got ${key.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
export function sealToken(plaintext: string): string {
|
||||
const iv = randomBytes(IV_BYTES);
|
||||
const cipher = createCipheriv('aes-256-gcm', getKey(), iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||
|
||||
return [
|
||||
PAYLOAD_VERSION,
|
||||
iv.toString('base64url'),
|
||||
cipher.getAuthTag().toString('base64url'),
|
||||
ciphertext.toString('base64url'),
|
||||
].join(':');
|
||||
}
|
||||
|
||||
export function openToken(payload: string): string {
|
||||
const [version, ivPart, tagPart, ciphertextPart] = payload.split(':');
|
||||
|
||||
if (version !== PAYLOAD_VERSION || !ivPart || !tagPart || ciphertextPart === undefined) {
|
||||
throw new Error('Unsupported token payload');
|
||||
}
|
||||
|
||||
const decipher = createDecipheriv('aes-256-gcm', getKey(), Buffer.from(ivPart, 'base64url'));
|
||||
decipher.setAuthTag(Buffer.from(tagPart, 'base64url'));
|
||||
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(ciphertextPart, 'base64url')),
|
||||
decipher.final(),
|
||||
]).toString('utf8');
|
||||
}
|
||||
|
||||
/** CSRF token echoed back by Mercado Pago. 32 chars of entropy. */
|
||||
export function newState(): string {
|
||||
return nanoid(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCE verifier. Mercado Pago requires 43 to 128 characters, so 32 random bytes
|
||||
* in base64url (43 chars) is the smallest value that fits.
|
||||
*/
|
||||
export function newCodeVerifier(): string {
|
||||
return randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
/** PKCE S256 challenge: base64url(SHA256(verifier)) — RFC 7636 section 4.2. */
|
||||
export function codeChallengeFromVerifier(codeVerifier: string): string {
|
||||
return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');
|
||||
}
|
||||
21
apps/backend/src/modules/mp/lib/index.ts
Normal file
21
apps/backend/src/modules/mp/lib/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
|
||||
export {
|
||||
codeChallengeFromVerifier,
|
||||
newCodeVerifier,
|
||||
newState,
|
||||
openToken,
|
||||
sealToken,
|
||||
} from './crypto';
|
||||
export {
|
||||
buildAuthorizationUrl,
|
||||
exchangeAuthorizationCode,
|
||||
isGrantRejected,
|
||||
MP_AUTHORIZE_URL,
|
||||
MP_SCOPES,
|
||||
MP_TOKEN_URL,
|
||||
MpApiError,
|
||||
type MpAuthorizationUrlInput,
|
||||
type MpTokenResponse,
|
||||
refreshMpTokens,
|
||||
} from './mp-oauth';
|
||||
export { buildMpReturnUrl, type MpCallbackOutcome } from './return-url';
|
||||
170
apps/backend/src/modules/mp/lib/mp-oauth.ts
Normal file
170
apps/backend/src/modules/mp/lib/mp-oauth.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import { logger } from '@/logger';
|
||||
|
||||
export const MP_AUTHORIZE_URL = 'https://auth.mercadopago.com/authorization';
|
||||
export const MP_TOKEN_URL = 'https://api.mercadopago.com/oauth/token';
|
||||
|
||||
/**
|
||||
* `offline_access` is what makes Mercado Pago return a refresh token. Without
|
||||
* it the daily renewal job has nothing to work with.
|
||||
*/
|
||||
export const MP_SCOPES = 'offline_access read write';
|
||||
|
||||
export type MpTokenResponse = {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresInSeconds: number;
|
||||
scope: string | null;
|
||||
mpUserId: string;
|
||||
liveMode: boolean;
|
||||
};
|
||||
|
||||
export type MpAuthorizationUrlInput = {
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
state: string;
|
||||
codeChallenge: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A failure from Mercado Pago's token endpoint.
|
||||
*
|
||||
* `reason` is the safe subset of what MP returned. `error_description` is
|
||||
* deliberately dropped: it echoes back request content, and the request is the
|
||||
* authorization code.
|
||||
*/
|
||||
export class MpApiError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly reason: string | null,
|
||||
) {
|
||||
super(`Mercado Pago token request failed with status ${status}`);
|
||||
this.name = 'MpApiError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Permanent rejection of the grant: the refresh token is dead. */
|
||||
export function isGrantRejected(error: unknown): boolean {
|
||||
return error instanceof MpApiError && error.reason === 'invalid_grant';
|
||||
}
|
||||
|
||||
export function buildAuthorizationUrl({
|
||||
clientId,
|
||||
redirectUri,
|
||||
state,
|
||||
codeChallenge,
|
||||
}: MpAuthorizationUrlInput): string {
|
||||
const url = new URL(MP_AUTHORIZE_URL);
|
||||
url.searchParams.set('client_id', clientId);
|
||||
url.searchParams.set('response_type', 'code');
|
||||
// Declares this as a direct (non-marketplace) integration: the money lands in
|
||||
// the seller's own account, so no platform_id of ours and no fee split.
|
||||
url.searchParams.set('platform_id', 'mp');
|
||||
url.searchParams.set('redirect_uri', redirectUri);
|
||||
url.searchParams.set('state', state);
|
||||
url.searchParams.set('code_challenge', codeChallenge);
|
||||
url.searchParams.set('code_challenge_method', 'S256');
|
||||
url.searchParams.set('scope', MP_SCOPES);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
type TokenRequestInput = {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
};
|
||||
|
||||
export function exchangeAuthorizationCode(
|
||||
input: TokenRequestInput & { code: string; codeVerifier: string },
|
||||
): Promise<MpTokenResponse> {
|
||||
return requestToken({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: input.clientId,
|
||||
client_secret: input.clientSecret,
|
||||
code: input.code,
|
||||
redirect_uri: input.redirectUri,
|
||||
code_verifier: input.codeVerifier,
|
||||
});
|
||||
}
|
||||
|
||||
export function refreshMpTokens(
|
||||
input: TokenRequestInput & { refreshToken: string },
|
||||
): Promise<MpTokenResponse> {
|
||||
return requestToken({
|
||||
grant_type: 'refresh_token',
|
||||
client_id: input.clientId,
|
||||
client_secret: input.clientSecret,
|
||||
refresh_token: input.refreshToken,
|
||||
});
|
||||
}
|
||||
|
||||
async function requestToken(body: Record<string, string>): Promise<MpTokenResponse> {
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
response = await fetch(MP_TOKEN_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (error) {
|
||||
// Network level: no grant decision has been made, so callers must treat the
|
||||
// account as still fine.
|
||||
logger.error({ err: error }, 'Mercado Pago token endpoint unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
|
||||
if (!response.ok) {
|
||||
const reason = typeof payload?.error === 'string' ? payload.error : null;
|
||||
// Only the status and MP's own error code. The body may echo the `code` or
|
||||
// the `code_verifier` back, and neither may reach the logs.
|
||||
logger.error({ status: response.status, reason }, 'Mercado Pago rejected the token request');
|
||||
throw new MpApiError(response.status, reason);
|
||||
}
|
||||
|
||||
return parseTokenResponse(payload);
|
||||
}
|
||||
|
||||
function parseTokenResponse(payload: Record<string, unknown> | null): MpTokenResponse {
|
||||
const accessToken = pickString(payload, 'access_token');
|
||||
const refreshToken = pickString(payload, 'refresh_token');
|
||||
const mpUserId = pickString(payload, 'user_id');
|
||||
const expiresInSeconds = pickNumber(payload, 'expires_in');
|
||||
|
||||
if (!accessToken || !refreshToken || !mpUserId || expiresInSeconds === null) {
|
||||
logger.error(
|
||||
{ received: payload ? Object.keys(payload) : null },
|
||||
'Mercado Pago token response is missing required fields',
|
||||
);
|
||||
throw new MpApiError(200, 'malformed_token_response');
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresInSeconds,
|
||||
// The response omits `scope` when it matches what was requested.
|
||||
scope: pickString(payload, 'scope') ?? null,
|
||||
mpUserId,
|
||||
liveMode: payload?.live_mode === true,
|
||||
};
|
||||
}
|
||||
|
||||
function pickString(payload: Record<string, unknown> | null, key: string): string | null {
|
||||
const value = payload?.[key];
|
||||
if (typeof value === 'string' && value.length > 0) return value;
|
||||
// Mercado Pago sends `user_id` as a number.
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickNumber(payload: Record<string, unknown> | null, key: string): number | null {
|
||||
const value = payload?.[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
25
apps/backend/src/modules/mp/lib/return-url.ts
Normal file
25
apps/backend/src/modules/mp/lib/return-url.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { MpCallbackReason, MpReturnTo } from '@gruperly/shared';
|
||||
|
||||
export type MpCallbackOutcome =
|
||||
| { kind: 'success' }
|
||||
| { kind: 'error'; reason: MpCallbackReason };
|
||||
|
||||
/**
|
||||
* Where the OAuth callback sends the teacher back to.
|
||||
*
|
||||
* Only `mp` and a reason code ever go in the URL: the authorization code and the
|
||||
* PKCE verifier stay on the server. `returnTo` comes from a stored enum, never
|
||||
* from the request, so this cannot be turned into an open redirect.
|
||||
*/
|
||||
export function buildMpReturnUrl(
|
||||
webUrl: string,
|
||||
returnTo: MpReturnTo,
|
||||
outcome: MpCallbackOutcome,
|
||||
): string {
|
||||
const url = new URL(`/${returnTo}`, webUrl);
|
||||
url.searchParams.set('mp', outcome.kind);
|
||||
if (outcome.kind === 'error') {
|
||||
url.searchParams.set('reason', outcome.reason);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
16
apps/backend/src/modules/mp/routes.ts
Normal file
16
apps/backend/src/modules/mp/routes.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import callbackRoute from './features/callback/route';
|
||||
import connectRoute from './features/connect/route';
|
||||
import disconnectRoute from './features/disconnect/route';
|
||||
import statusRoute from './features/status/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
// `disconnectRoute` only declares `DELETE /`, so mounting it at the same path as
|
||||
// `connectRoute` gives the unlink endpoint its RESTful `DELETE /mp/connect`.
|
||||
routes.route('/connect', connectRoute);
|
||||
routes.route('/connect', disconnectRoute);
|
||||
routes.route('/callback', callbackRoute);
|
||||
routes.route('/status', statusRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -7,16 +7,13 @@ import type {
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
onboardingAlreadyCompletedProblem,
|
||||
paymentNotSetupProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import { onboardingAlreadyCompletedProblem } from '@/http/problem-builders';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { toOnboardingGroupDto } from '../../lib';
|
||||
|
||||
type CreateFirstGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'merchantAccount'>;
|
||||
db?: Pick<PrismaClient, 'user'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
@@ -38,11 +35,6 @@ export class CreateFirstGroup {
|
||||
return err(onboardingAlreadyCompletedProblem());
|
||||
}
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (!merchantAccount) {
|
||||
return err(paymentNotSetupProblem());
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const created = await tx.group.create({
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { ConnectPayment } from '@gruperly/shared';
|
||||
import { ConnectPaymentSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { PaymentSetup } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/', validate.json(ConnectPaymentSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const data = c.req.valid('json') as ConnectPayment;
|
||||
const useCase = new PaymentSetup();
|
||||
const result = await useCase.execute(data, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ConnectPayment, ConnectPaymentResult, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type PaymentSetupDeps = { db?: PrismaClient };
|
||||
|
||||
export class PaymentSetup {
|
||||
constructor(private readonly deps: PaymentSetupDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
data: ConnectPayment,
|
||||
userId: string,
|
||||
): Promise<Result<ConnectPaymentResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
await db.merchantAccount.upsert({
|
||||
where: { userId },
|
||||
create: {
|
||||
userId,
|
||||
provider: data.provider,
|
||||
accessToken: data.accessToken,
|
||||
sandbox: data.sandbox,
|
||||
},
|
||||
update: {
|
||||
provider: data.provider,
|
||||
accessToken: data.accessToken,
|
||||
sandbox: data.sandbox,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
provider: data.provider,
|
||||
sandbox: data.sandbox,
|
||||
connected: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type GetOnboardingStatusDeps = { db?: PrismaClient };
|
||||
type GetOnboardingStatusDeps = { db?: Pick<PrismaClient, 'user' | 'mpAccount'> };
|
||||
|
||||
export class GetOnboardingStatus {
|
||||
constructor(private readonly deps: GetOnboardingStatusDeps = {}) {}
|
||||
@@ -28,8 +28,11 @@ export class GetOnboardingStatus {
|
||||
return ok({ step: 'COMPLETED', paymentConnected: true, completed: true });
|
||||
}
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (merchantAccount) {
|
||||
// Linking Mercado Pago is optional, so `paymentConnected` here only resumes
|
||||
// the flow where the teacher left off: with a usable account, they do not
|
||||
// need to see the "Cobros" step again. A `revoked` row is not usable.
|
||||
const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } });
|
||||
if (mpAccount && mpAccount.status === 'ACTIVE') {
|
||||
return ok({ step: 'PAYMENT_CONNECTED', paymentConnected: true, completed: false });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { Hono } from 'hono';
|
||||
import firstGroupRoute from './features/first-group/route';
|
||||
import paymentSetupRoute from './features/payment-setup/route';
|
||||
import statusRoute from './features/status/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/status', statusRoute);
|
||||
routes.route('/payment-setup', paymentSetupRoute);
|
||||
routes.route('/first-group', firstGroupRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -1,6 +1,7 @@
|
||||
import app from '@/app';
|
||||
import { getPrismaClient } from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { startMpJobs } from '@/modules/mp';
|
||||
|
||||
const port = Number(process.env.PORT ?? 4000);
|
||||
|
||||
@@ -11,6 +12,8 @@ const server = Bun.serve({
|
||||
fetch: app.fetch,
|
||||
});
|
||||
|
||||
startMpJobs();
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
server.stop(true);
|
||||
await getPrismaClient().$disconnect();
|
||||
|
||||
@@ -60,39 +60,347 @@ describe('GET /groups-risk/overview', () => {
|
||||
});
|
||||
|
||||
it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => {
|
||||
prismaFetchGroupFindMany([
|
||||
{ id: 'group-1', name: 'Funcional' },
|
||||
{ id: 'group-2', name: 'Yoga' },
|
||||
]);
|
||||
prismaFetchAttendeeFindMany([
|
||||
{ id: 'a-1', groupId: 'group-1' },
|
||||
{ id: 'a-2', groupId: 'group-2' },
|
||||
]);
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
|
||||
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1'), attendee('a-2', 'group-2')]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(-1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(-2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(-3) },
|
||||
{ id: 's4', groupId: 'group-2', startsAt: at(-1) },
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
{ id: 's4', groupId: 'group-2', startsAt: at(1) },
|
||||
]);
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 'ABSENT', at(-1)),
|
||||
attendance('a-1', 'ABSENT', at(-2)),
|
||||
attendance('a-1', 'ABSENT', at(-3)),
|
||||
attendance('a-2', 'PRESENT', at(-1)),
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
attendance('a-2', 's4', 'PRESENT', at(1)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
// `toMatchObject` because the item now also carries the per-level summary
|
||||
// the card consumes; here we are testing the usual status light.
|
||||
expect(await res.json()).toMatchObject({
|
||||
items: [
|
||||
{ groupId: 'group-1', groupName: 'Funcional', riskLevel: 'HIGH' },
|
||||
{ groupId: 'group-2', groupName: 'Yoga', riskLevel: 'NONE' },
|
||||
{
|
||||
groupId: 'group-1',
|
||||
groupName: 'Funcional',
|
||||
riskLevel: 'HIGH',
|
||||
absenceStreakCount: 1,
|
||||
lowAttendanceCount: 0,
|
||||
},
|
||||
{
|
||||
groupId: 'group-2',
|
||||
groupName: 'Yoga',
|
||||
riskLevel: 'NONE',
|
||||
absenceStreakCount: 0,
|
||||
lowAttendanceCount: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('cuenta el motivo: faltas seguidas y asistencia baja, sin repetir alumnos', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
|
||||
prismaFetchAttendeeFindMany([
|
||||
attendee('a-1', 'group-1'),
|
||||
attendee('a-2', 'group-1'),
|
||||
attendee('a-3', 'group-1'),
|
||||
attendee('b-1', 'group-2'),
|
||||
]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
|
||||
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
|
||||
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
||||
]);
|
||||
prismaFetchAttendanceFindMany([
|
||||
// Two consecutive absences: counts toward the absence reason.
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'PRESENT', at(3)),
|
||||
// No streak, but attends less than half of the month's classes.
|
||||
attendance('a-2', 's1', 'PRESENT', at(1)),
|
||||
attendance('a-2', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-2', 's3', 'ABSENT', at(3)),
|
||||
attendance('a-2', 's4', 'ABSENT', at(4)),
|
||||
// Ok.
|
||||
attendance('a-3', 's1', 'PRESENT', at(1)),
|
||||
attendance('a-3', 's2', 'PRESENT', at(2)),
|
||||
attendance('a-3', 's3', 'PRESENT', at(3)),
|
||||
attendance('a-3', 's4', 'PRESENT', at(4)),
|
||||
// Again via streak, in the other group.
|
||||
attendance('b-1', 's5', 'ABSENT', at(1)),
|
||||
attendance('b-1', 's6', 'ABSENT', at(2)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({
|
||||
items: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
groupName: 'Funcional',
|
||||
riskLevel: 'MEDIUM',
|
||||
absenceStreakCount: 1,
|
||||
lowAttendanceCount: 1,
|
||||
},
|
||||
{
|
||||
groupId: 'group-2',
|
||||
groupName: 'Yoga',
|
||||
riskLevel: 'MEDIUM',
|
||||
absenceStreakCount: 1,
|
||||
lowAttendanceCount: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/* What the listing card consumes. The status light above already had its
|
||||
tests; what was missing was pinning the new payload against the same
|
||||
endpoint, because that is the contract the frontend reads. */
|
||||
it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]);
|
||||
prismaFetchAttendeeFindMany([
|
||||
attendee('a-1', 'group-1', 'Sofía Díaz'),
|
||||
attendee('a-2', 'group-1', 'Diego Soto'),
|
||||
attendee('a-3', 'group-1', 'Ana Ruiz'),
|
||||
]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// The mock ignores `orderBy`, so the rows come most recent first, as Prisma
|
||||
// would return them: the streak depends on that order.
|
||||
// `at(n)` is n days back; the summary drops what has not happened yet, so
|
||||
// the dates have to be in the past, not in the future.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
attendance('a-2', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-2', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-2', 's3', 'PRESENT', at(3)),
|
||||
attendance('a-3', 's1', 'PRESENT', at(1)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||
expect(items[0]).toMatchObject({
|
||||
riesgoAlto: 1,
|
||||
atencion: 1,
|
||||
ok: 1,
|
||||
// Capacity is 5 and there are 3 members, not 2: free spots are computed
|
||||
// against capacity, not as "the ones with no signal at all".
|
||||
libres: 2,
|
||||
enEspera: 2,
|
||||
// Average of the already-rounded per-person rates: 0, 33 and 100 → 44.
|
||||
asistencia: 44,
|
||||
});
|
||||
expect(items[0].urgentes).toEqual([
|
||||
{
|
||||
attendeeId: 'a-1',
|
||||
fullName: 'Sofía Díaz',
|
||||
level: 'riesgo_alto',
|
||||
consecutiveAbsences: 3,
|
||||
daysSinceLastAttendance: 1,
|
||||
attendanceRate: 0,
|
||||
},
|
||||
{
|
||||
attendeeId: 'a-2',
|
||||
fullName: 'Diego Soto',
|
||||
level: 'atencion',
|
||||
consecutiveAbsences: 2,
|
||||
// Counted from their last class they attended, not from the group's
|
||||
// most recent one: theirs was 3 days ago.
|
||||
daysSinceLastAttendance: 3,
|
||||
attendanceRate: 33,
|
||||
},
|
||||
{
|
||||
attendeeId: 'a-3',
|
||||
fullName: 'Ana Ruiz',
|
||||
level: 'ok',
|
||||
consecutiveAbsences: 0,
|
||||
daysSinceLastAttendance: 1,
|
||||
attendanceRate: 100,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('un grupo sin capacidad declarada no inventa lugares libres', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Sin cupo', null)]);
|
||||
prismaFetchAttendeeFindMany([]);
|
||||
prismaFetchClassSessionFindMany([]);
|
||||
prismaFetchAttendanceFindMany([]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({
|
||||
items: [
|
||||
{
|
||||
riskLevel: 'NONE',
|
||||
riesgoAlto: 0,
|
||||
atencion: 0,
|
||||
ok: 0,
|
||||
libres: 0,
|
||||
enEspera: 0,
|
||||
asistencia: null,
|
||||
urgentes: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('una clase sin registro corta la racha: no son faltas seguidas', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
|
||||
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// Absence, unmarked class, absence. Reading only the `Attendance` rows this
|
||||
// would look like a streak of 2 and the group would land in attention; the
|
||||
// middle class happened and has no record, so the real streak is 1.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||
expect(items[0].riesgoAlto).toBe(0);
|
||||
expect(items[0].atencion).toBe(0);
|
||||
expect(items[0].ok).toBe(1);
|
||||
expect(items[0].urgentes).toEqual([
|
||||
{
|
||||
attendeeId: 'a-1',
|
||||
fullName: 'Sofía Díaz',
|
||||
level: 'ok',
|
||||
consecutiveAbsences: 1,
|
||||
daysSinceLastAttendance: 1,
|
||||
// Both marked classes were absences; the middle one does not go into the average.
|
||||
attendanceRate: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('las faltas pegadas hasta la última clase sí cuentan como racha', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
|
||||
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// The streak is counted backwards from the most recent class, so they reach
|
||||
// exactly the end: s1 and s2 back to back, and the one 3 days ago is
|
||||
// unmarked, which falls before the streak and does not touch it.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||
expect(items[0].atencion).toBe(1);
|
||||
expect(items[0].urgentes).toEqual([
|
||||
{
|
||||
attendeeId: 'a-1',
|
||||
fullName: 'Sofía Díaz',
|
||||
level: 'atencion',
|
||||
consecutiveAbsences: 2,
|
||||
daysSinceLastAttendance: 1,
|
||||
attendanceRate: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('una clase sin registrar después de las faltas las borra: la racha mira hasta la última clase', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
|
||||
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// The same two back-to-back absences as the previous case, but the most
|
||||
// recent class (s1) is the one with no record. Since the streak is counted
|
||||
// from the end and "no record" is not an absence, there is no streak: the
|
||||
// asymmetry is there on purpose, because it is the same thing that already
|
||||
// happens with an excused class.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||
expect(items[0].atencion).toBe(0);
|
||||
expect(items[0].riesgoAlto).toBe(0);
|
||||
expect(items[0].ok).toBe(1);
|
||||
expect(items[0].urgentes).toEqual([
|
||||
{
|
||||
attendeeId: 'a-1',
|
||||
fullName: 'Sofía Díaz',
|
||||
level: 'ok',
|
||||
consecutiveAbsences: 0,
|
||||
daysSinceLastAttendance: 1,
|
||||
attendanceRate: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]);
|
||||
// The attendee was created today (offset 0), but has 3 absences in classes 7, 3 and 1 days ago.
|
||||
prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(3) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(7) },
|
||||
]);
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(3)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(7)),
|
||||
]);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||
expect(items[0].riesgoAlto).toBe(1);
|
||||
expect(items[0].riskLevel).toBe('HIGH');
|
||||
expect(items[0].absenceStreakCount).toBe(1);
|
||||
});
|
||||
|
||||
/* The use-case asks for `capacity` and the waitlist count to compute the
|
||||
free spots, and `fullName` + `createdAt` of every attendee for the per-level
|
||||
summary. The fixtures provide them so the older tests don't have to know
|
||||
about that. */
|
||||
function group(id: string, name: string, capacity: number | null = 10, waiting = 0) {
|
||||
return { id, name, capacity, _count: { waitlist: waiting } };
|
||||
}
|
||||
|
||||
function attendee(id: string, groupId: string, fullName = id) {
|
||||
return { id, groupId, fullName, createdAt: at(90) };
|
||||
}
|
||||
|
||||
function prismaFetchGroupFindMany(rows: unknown[]) {
|
||||
db.group.findMany.mockResolvedValue(rows);
|
||||
}
|
||||
@@ -109,6 +417,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) {
|
||||
db.attendance.findMany.mockResolvedValue(rows);
|
||||
}
|
||||
|
||||
function attendance(attendeeId: string, status: string, startsAt: string) {
|
||||
return { attendeeId, status, classSession: { startsAt } };
|
||||
/* The `classSessionId` matters: the summary is built by cross-referencing the
|
||||
group's class sessions with the attendance rows, and without that join every
|
||||
class would have no record for everyone. */
|
||||
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
|
||||
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
|
||||
}
|
||||
@@ -202,7 +202,11 @@ describe('analytics routes', () => {
|
||||
describe('GET /groups/:groupId/attendees/:attendeeId/history', () => {
|
||||
it('devuelve el historial de presentismo con su porcentaje', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||
prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1', fullName: 'Ana Pérez' });
|
||||
prisma.attendee.findFirst.mockResolvedValue({
|
||||
id: 'a-1',
|
||||
fullName: 'Ana Pérez',
|
||||
createdAt: new Date('2026-09-29T00:00:00.000Z'),
|
||||
});
|
||||
prisma.classSession.findMany.mockResolvedValue([
|
||||
{ id: 's-2', startsAt: new Date(at(7)) },
|
||||
{ id: 's-1', startsAt: new Date(at(0)) },
|
||||
@@ -228,6 +232,15 @@ describe('analytics routes', () => {
|
||||
{ classSessionId: 's-2', startsAt: at(7), status: 'ABSENT' },
|
||||
],
|
||||
});
|
||||
expect(prisma.classSession.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
groupId: 'group-1',
|
||||
startsAt: { gte: new Date('2026-09-29T00:00:00.000Z') },
|
||||
},
|
||||
orderBy: { startsAt: 'desc' },
|
||||
take: 20,
|
||||
select: { id: true, startsAt: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('devuelve 404 si el alumno no pertenece al grupo', async () => {
|
||||
|
||||
305
apps/backend/test/attendance-risk.test.ts
Normal file
305
apps/backend/test/attendance-risk.test.ts
Normal file
@@ -0,0 +1,305 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
ATTENDANCE_RISK_RULES,
|
||||
getGroupAttendanceSummary,
|
||||
getMemberAttendanceRisk,
|
||||
type MemberAttendance,
|
||||
type MemberClassSession,
|
||||
summarizeMemberAttendance,
|
||||
} from '@gruperly/shared';
|
||||
|
||||
/* The risk rule is business logic, not a screen concern: these tests pin it so
|
||||
that changing a threshold or refactoring the class filter doesn't quietly
|
||||
move the status light of the group list.
|
||||
|
||||
Two test-scaffold helpers:
|
||||
|
||||
- `dense` puts the classes on consecutive days, so that "how long since we
|
||||
saw them" is always close by and the case isolates the rule it claims to
|
||||
test (one class a week would trip the inactivity threshold almost always).
|
||||
- `series` honors the offsets it is given, for the cases that do need gaps.
|
||||
|
||||
All dates hang off a fixed `NOW`: the function takes the moment as an
|
||||
argument precisely so it can be tested without a clock. */
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const NOW = new Date('2026-09-30T20:00:00.000Z');
|
||||
|
||||
/** Days back from `NOW`, in ISO. Negative = future class. */
|
||||
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
|
||||
|
||||
type Status = MemberClassSession['status'];
|
||||
|
||||
/** Classes on consecutive days, oldest first. */
|
||||
function dense(statuses: Status[]): MemberClassSession[] {
|
||||
return statuses.map((status, index) => ({
|
||||
sessionId: `ses_${statuses.length - index}`,
|
||||
startsAt: daysAgo(statuses.length - index),
|
||||
status,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Classes with the offsets given, in any order. */
|
||||
function series(rows: [Status, number][]): MemberClassSession[] {
|
||||
return rows.map(([status, offsetDays], index) => ({
|
||||
sessionId: `ses_${index}`,
|
||||
startsAt: daysAgo(offsetDays),
|
||||
status,
|
||||
}));
|
||||
}
|
||||
|
||||
function member(sessions: MemberClassSession[], enrolledDaysAgo = 365): MemberAttendance {
|
||||
return {
|
||||
attendeeId: 'at_1',
|
||||
fullName: 'Sofía Ramírez',
|
||||
enrolledAt: daysAgo(enrolledDaysAgo),
|
||||
sessions,
|
||||
};
|
||||
}
|
||||
|
||||
describe('getMemberAttendanceRisk', () => {
|
||||
it('un alumno nuevo sin clases no genera ninguna alerta', () => {
|
||||
expect(getMemberAttendanceRisk(member([]), NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('no lo penaliza por clases anteriores a su alta en el grupo', () => {
|
||||
const rejo = member(series([['ABSENT', 28], ['ABSENT', 21], ['ABSENT', 14]]), 2);
|
||||
expect(getMemberAttendanceRisk(rejo, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('no cuenta clases que todavía no ocurrieron', () => {
|
||||
// Attended the last three and is absent for the next three: nobody is drifting away.
|
||||
const alumno = member(series([['PRESENT', 7], ['PRESENT', 14], ['PRESENT', 21], ['ABSENT', -7], ['ABSENT', -14]]));
|
||||
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('tres o más faltas consecutivas dan riesgo alto', () => {
|
||||
const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(3);
|
||||
// 4 days since last showing up: the level comes from the streak, not from the
|
||||
// time since they last came.
|
||||
expect(señales.daysSinceLastAttendance).toBe(4);
|
||||
expect(señales.level).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('una racha larguísima sin ninguna clase con presencia igual es riesgo alto', () => {
|
||||
// Never attended an eligible class: the reference for "how long since we saw
|
||||
// them" is the last class, so it doesn't stay green forever.
|
||||
const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT']));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(5);
|
||||
expect(señales.daysSinceLastAttendance).toBe(1);
|
||||
expect(señales.level).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('dos faltas consecutivas dan atención y una sola no da nada', () => {
|
||||
expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])), NOW)).toBe('atencion');
|
||||
expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])), NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => {
|
||||
// A single absence, the most recent one: the streak doesn't reach. What drives
|
||||
// the level is the time since they last showed up.
|
||||
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
expect(señales.daysSinceLastAttendance).toBe(30);
|
||||
expect(señales.level).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
|
||||
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
|
||||
// Two streak absences: attention comes from the streak, and exactly 10 days
|
||||
// does not move the level.
|
||||
expect(
|
||||
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
|
||||
).toBe('atencion');
|
||||
expect(
|
||||
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW),
|
||||
).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('una tendencia a la baja da atención', () => {
|
||||
// 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
|
||||
// most recent is a PRESENT: streak 0 and recent attendance, so the trend is
|
||||
// the only thing that can raise the alert.
|
||||
const candidato = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
|
||||
]));
|
||||
const señales = summarizeMemberAttendance(candidato, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(0);
|
||||
expect(señales.daysSinceLastAttendance).toBe(1);
|
||||
expect(señales.level).toBe('atencion');
|
||||
});
|
||||
|
||||
it('perder una sola clase no es tendencia', () => {
|
||||
// Same case as the previous one with one class fewer missed in the recent
|
||||
// window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
|
||||
const estable = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
|
||||
]));
|
||||
expect(getMemberAttendanceRisk(estable, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('la tendencia necesita historia para las dos ventanas', () => {
|
||||
// 5 marked classes: the previous window would be left with a single one, so
|
||||
// there is nothing to compare against.
|
||||
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
|
||||
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('la racha manda sobre la tendencia', () => {
|
||||
// 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
|
||||
// absences and one attended class. The trend alone would give attention;
|
||||
// the 3 trailing absences give high risk, which is what has to win.
|
||||
const alumno = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
|
||||
]));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(3);
|
||||
expect(señales.attendanceRate).toBe(81);
|
||||
expect(señales.level).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('una clase sin registro corta la racha: sin dato no hay ausencia', () => {
|
||||
// Absent, the middle one has no record, absent again. The real streak
|
||||
// is one, not two.
|
||||
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
|
||||
const señales = summarizeMemberAttendance(conHueco, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
expect(señales.markedClasses).toBe(2);
|
||||
expect(señales.attendanceRate).toBe(0);
|
||||
expect(señales.level).toBe('ok');
|
||||
});
|
||||
|
||||
it('una clase justificada es la clase que no cuenta', () => {
|
||||
// Absent, notified, absent again: the streak is one, and the average ignores
|
||||
// the excused class instead of counting it as attendance or as an absence.
|
||||
const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]]));
|
||||
const señales = summarizeMemberAttendance(justificada, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
expect(señales.markedClasses).toBe(2);
|
||||
expect(señales.attendanceRate).toBe(0);
|
||||
expect(señales.level).toBe('ok');
|
||||
});
|
||||
|
||||
it('avisar de la falta tampoco encadena las de alrededor', () => {
|
||||
const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]]));
|
||||
expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0);
|
||||
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('no le importa el orden en que llegan las clases', () => {
|
||||
const desordenado = member(series([['ABSENT', 1], ['PRESENT', 4], ['ABSENT', 2], ['ABSENT', 3]]));
|
||||
expect(summarizeMemberAttendance(desordenado, NOW).consecutiveAbsences).toBe(3);
|
||||
expect(getMemberAttendanceRisk(desordenado, NOW)).toBe('riesgo_alto');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGroupAttendanceSummary', () => {
|
||||
const conNivel = (attendeeId: string, level: 'riesgo_alto' | 'atencion' | 'ok') => ({
|
||||
attendeeId,
|
||||
fullName: attendeeId,
|
||||
enrolledAt: daysAgo(365),
|
||||
sessions:
|
||||
level === 'riesgo_alto'
|
||||
? dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT'])
|
||||
: level === 'atencion'
|
||||
? dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])
|
||||
: dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT']),
|
||||
});
|
||||
|
||||
it('cuenta por nivel y calcula los lugares libres', () => {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: 'grp_1',
|
||||
capacity: 10,
|
||||
waitlistCount: 2,
|
||||
members: [
|
||||
conNivel('a', 'riesgo_alto'),
|
||||
conNivel('b', 'riesgo_alto'),
|
||||
conNivel('c', 'atencion'),
|
||||
conNivel('d', 'ok'),
|
||||
conNivel('e', 'ok'),
|
||||
],
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(resumen).toMatchObject({ riesgoAlto: 2, atencion: 1, ok: 2, libres: 5, enEspera: 2 });
|
||||
expect(resumen.peorNivel).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('un grupo vacío no inventa niveles', () => {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: 'grp_vacio',
|
||||
capacity: 5,
|
||||
waitlistCount: 0,
|
||||
members: [],
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(resumen).toMatchObject({ riesgoAlto: 0, atencion: 0, ok: 0, libres: 5, enEspera: 0 });
|
||||
expect(resumen.peorNivel).toBeNull();
|
||||
expect(resumen.urgentes).toEqual([]);
|
||||
expect(resumen.asistencia).toBeNull();
|
||||
});
|
||||
|
||||
it('más miembros que lugares da 0 libres, nunca negativos', () => {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: 'grp_lleno',
|
||||
capacity: 2,
|
||||
waitlistCount: 3,
|
||||
members: [conNivel('a', 'ok'), conNivel('b', 'ok'), conNivel('c', 'ok')],
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(resumen.libres).toBe(0);
|
||||
expect(resumen.enEspera).toBe(3);
|
||||
expect(resumen.ok).toBe(3);
|
||||
});
|
||||
|
||||
it('sin cupo definido tampoco hay lugares libres que mostrar', () => {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: 'grp_sin_cupo',
|
||||
capacity: null,
|
||||
waitlistCount: 0,
|
||||
members: [conNivel('a', 'ok')],
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(resumen.libres).toBe(0);
|
||||
});
|
||||
|
||||
it('ordena los urgentes de peor a mejor', () => {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: 'grp_1',
|
||||
capacity: 4,
|
||||
waitlistCount: 0,
|
||||
members: [conNivel('ok_1', 'ok'), conNivel('alto_1', 'riesgo_alto'), conNivel('aten_1', 'atencion'), conNivel('ok_2', 'ok')],
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(resumen.urgentes.map((urgente) => urgente.attendeeId)).toEqual(['alto_1', 'aten_1', 'ok_1', 'ok_2']);
|
||||
});
|
||||
|
||||
it('la asistencia del grupo promedia solo a los que tienen clases con dato', () => {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: 'grp_1',
|
||||
capacity: 4,
|
||||
waitlistCount: 0,
|
||||
members: [
|
||||
conNivel('a', 'ok'),
|
||||
{ attendeeId: 'b', fullName: 'b', enrolledAt: daysAgo(365), sessions: series([['PRESENT', 1], ['ABSENT', 2]]) },
|
||||
// Just joined Chess: no marked classes, so they don't move the average.
|
||||
{ attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] },
|
||||
],
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(resumen.asistencia).toBe(75);
|
||||
expect(resumen.ok).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -47,6 +47,9 @@ const attendee = {
|
||||
notifyToken: 'token-1',
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
payments: [
|
||||
{ status: 'PENDING', dueDate: new Date('2026-10-10T00:00:00.000Z') },
|
||||
],
|
||||
};
|
||||
|
||||
describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
@@ -73,6 +76,21 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
notifyToken: 'token-1',
|
||||
createdAt: '2026-08-01T10:00:00.000Z',
|
||||
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
|
||||
});
|
||||
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1', groupId: 'group-1' },
|
||||
include: {
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
dueDate: { gte: expect.any(Date), lt: expect.any(Date) },
|
||||
},
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 1,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
99
apps/backend/test/attendee-update.test.ts
Normal file
99
apps/backend/test/attendee-update.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
const db = {
|
||||
group: { findUnique: mock() },
|
||||
attendee: { findFirst: mock(), update: mock() },
|
||||
}
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}))
|
||||
|
||||
import updateAttendeeRoute from '@/modules/attendees/features/update/route'
|
||||
|
||||
const userId = 'user-1'
|
||||
const attendee = {
|
||||
id: 'a-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: null,
|
||||
phone: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: 'Llega temprano',
|
||||
notifyToken: 'token-1',
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-01T12:00:00.000Z'),
|
||||
}
|
||||
|
||||
function makeApp() {
|
||||
const app = new Hono()
|
||||
app.use('*', async (context, next) => {
|
||||
context.set('user', { id: userId } as never)
|
||||
await next()
|
||||
})
|
||||
app.route('/groups', updateAttendeeRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
db.group.findUnique.mockResolvedValue({
|
||||
id: 'group-1',
|
||||
name: 'Funcional',
|
||||
createdById: userId,
|
||||
members: [],
|
||||
})
|
||||
db.attendee.findFirst.mockResolvedValue(attendee)
|
||||
})
|
||||
|
||||
it('actualiza contacto y conserva los campos vacíos como null', async () => {
|
||||
db.attendee.update.mockResolvedValue({
|
||||
...attendee,
|
||||
email: 'ana@example.com',
|
||||
phone: null,
|
||||
})
|
||||
|
||||
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: 'ana@example.com', phone: '' }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(db.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1' },
|
||||
data: { email: 'ana@example.com', phone: null },
|
||||
})
|
||||
})
|
||||
|
||||
it('actualiza una única nota', async () => {
|
||||
db.attendee.update.mockResolvedValue({ ...attendee, notes: 'Traer colchoneta' })
|
||||
|
||||
await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notes: 'Traer colchoneta' }),
|
||||
})
|
||||
|
||||
expect(db.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1' },
|
||||
data: { notes: 'Traer colchoneta' },
|
||||
})
|
||||
})
|
||||
|
||||
it('rechaza un email inválido', async () => {
|
||||
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: 'sin-arroba' }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(db.attendee.update).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
@@ -411,7 +412,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
|
||||
it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
// Simular que ya existe un alumno con teléfono '11111111'
|
||||
// Simulate that an attendee with phone '11111111' already exists
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ phone: '11111111' },
|
||||
] as never);
|
||||
@@ -433,8 +434,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
attendees: [
|
||||
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
|
||||
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Ya existe en BD
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicado dentro del lote
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
|
||||
],
|
||||
}),
|
||||
});
|
||||
@@ -463,6 +464,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
notes: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
attendances: [],
|
||||
payments: [],
|
||||
},
|
||||
] as never);
|
||||
prisma.attendee.count.mockResolvedValue(1);
|
||||
@@ -474,11 +477,28 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
const data = await res.json();
|
||||
expect(data.data.length).toBe(1);
|
||||
expect(data.data[0].fullName).toBe('Ana García');
|
||||
expect(data.data[0].recentAttendance).toEqual([]);
|
||||
expect(data.data[0].payment).toBeNull();
|
||||
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
// The row summary is requested in the same query: one request per
|
||||
// member would be N+1 over a listing of up to 100.
|
||||
include: {
|
||||
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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
98
apps/backend/test/attendees-list-item.test.ts
Normal file
98
apps/backend/test/attendees-list-item.test.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers';
|
||||
import { toAttendeeListItemDto } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
/* The row summary is built in memory: which class counts as recent and
|
||||
which payment is shown. Those are the two decisions the row reads. */
|
||||
|
||||
function record(
|
||||
overrides: Partial<AttendeeListItemRecord> = {},
|
||||
): AttendeeListItemRecord {
|
||||
return {
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: null,
|
||||
phone: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
notifyToken: null,
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
attendances: [],
|
||||
payments: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
|
||||
|
||||
describe('toAttendeeListItemDto', () => {
|
||||
it('invierte la asistencia para que la clase más reciente quede a la derecha', () => {
|
||||
const dto = toAttendeeListItemDto(
|
||||
record({
|
||||
// It arrives from most recent to oldest.
|
||||
attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(dto.recentAttendance).toEqual(['ABSENT', 'EXCUSED', 'PRESENT']);
|
||||
});
|
||||
|
||||
it('deja la lista vacía cuando no hay ninguna clase registrada', () => {
|
||||
expect(toAttendeeListItemDto(record()).recentAttendance).toEqual([]);
|
||||
});
|
||||
|
||||
it('no inventa cobro cuando no hay pagos', () => {
|
||||
expect(toAttendeeListItemDto(record()).payment).toBeNull();
|
||||
});
|
||||
|
||||
it('arranca en cero los pagos impagos y descarta los cancelados', () => {
|
||||
const dto = toAttendeeListItemDto(
|
||||
record({
|
||||
payments: [
|
||||
{ status: 'CANCELLED', dueDate: day('2026-01-05') },
|
||||
{ status: 'PAID', dueDate: day('2026-08-10') },
|
||||
{ status: 'PENDING', dueDate: day('2026-09-10') },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(dto.payment).toEqual({ status: 'PENDING', dueDate: '2026-09-10T00:00:00.000Z' });
|
||||
});
|
||||
|
||||
it('manda el impago más antiguo: los días de atraso son los que hay que ver', () => {
|
||||
const dto = toAttendeeListItemDto(
|
||||
record({
|
||||
payments: [
|
||||
{ status: 'PENDING', dueDate: day('2026-09-10') },
|
||||
{ status: 'OVERDUE', dueDate: day('2026-04-10') },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(dto.payment).toEqual({ status: 'OVERDUE', dueDate: '2026-04-10T00:00:00.000Z' });
|
||||
});
|
||||
|
||||
it('cae al último pago cerrado cuando no queda nada impago', () => {
|
||||
const dto = toAttendeeListItemDto(
|
||||
record({
|
||||
payments: [
|
||||
{ status: 'PAID', dueDate: day('2026-08-10') },
|
||||
{ status: 'PAID', dueDate: day('2026-09-10') },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(dto.payment).toEqual({ status: 'PAID', dueDate: '2026-09-10T00:00:00.000Z' });
|
||||
});
|
||||
|
||||
it('conserva los campos del DTO plano', () => {
|
||||
const dto = toAttendeeListItemDto(record({ phone: '22222222' }));
|
||||
|
||||
expect(dto.fullName).toBe('Ana Pérez');
|
||||
expect(dto.phone).toBe('22222222');
|
||||
expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
@@ -18,7 +19,7 @@ import { attendeesRoutes } from '@/modules/attendees';
|
||||
const app = new Hono();
|
||||
app.route('/attendees', attendeesRoutes);
|
||||
|
||||
const attendee = {
|
||||
const attendeeRow = {
|
||||
id: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana Pérez',
|
||||
@@ -32,6 +33,13 @@ const attendee = {
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
};
|
||||
|
||||
// What the Prisma mock returns: the row plus the summary relations.
|
||||
const attendee = {
|
||||
...attendeeRow,
|
||||
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
|
||||
payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }],
|
||||
};
|
||||
|
||||
describe('attendees routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -47,9 +55,13 @@ describe('attendees routes', () => {
|
||||
expect(await res.json()).toEqual({
|
||||
data: [
|
||||
{
|
||||
...attendee,
|
||||
createdAt: attendee.createdAt.toISOString(),
|
||||
updatedAt: attendee.updatedAt.toISOString(),
|
||||
...attendeeRow,
|
||||
createdAt: attendeeRow.createdAt.toISOString(),
|
||||
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||
// The query comes most recent first; the row shows them
|
||||
// the other way around, with the most recent class on the right.
|
||||
recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'],
|
||||
payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' },
|
||||
},
|
||||
],
|
||||
pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 },
|
||||
@@ -58,6 +70,19 @@ describe('attendees routes', () => {
|
||||
skip: 10,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
select: { status: true },
|
||||
},
|
||||
payments: {
|
||||
where: { status: { not: 'CANCELLED' } },
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 3,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(prisma.attendee.count).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
@@ -77,7 +77,7 @@ function makeSession(overrides: Record<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// Fecha "hoy" a las 19:00 UTC, del día real del runner.
|
||||
// "Today" at 19:00 UTC, on the runner's real day.
|
||||
function todayAtUtc() {
|
||||
const date = new Date();
|
||||
date.setUTCHours(19, 0, 0, 0);
|
||||
|
||||
@@ -10,9 +10,6 @@ const db = {
|
||||
groupMember: {
|
||||
create: mock(),
|
||||
},
|
||||
merchantAccount: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
@@ -26,6 +23,7 @@ mock.module('@/lib/prisma', () => ({
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
import { ListGroups } from '@/modules/groups/features/get-all/use-case';
|
||||
|
||||
const userId = 'user-1';
|
||||
const group = {
|
||||
@@ -60,7 +58,9 @@ describe('groups routes', () => {
|
||||
});
|
||||
|
||||
it('lists groups scoped to the current user', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([group]);
|
||||
prisma.group.findMany.mockResolvedValue([
|
||||
{ ...group, _count: { attendees: 4, waitlist: 1 } },
|
||||
]);
|
||||
prisma.group.count.mockResolvedValue(1);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups');
|
||||
@@ -72,6 +72,8 @@ describe('groups routes', () => {
|
||||
...group,
|
||||
createdAt: group.createdAt.toISOString(),
|
||||
updatedAt: group.updatedAt.toISOString(),
|
||||
attendeesCount: 4,
|
||||
waitlistCount: 1,
|
||||
},
|
||||
],
|
||||
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
||||
@@ -79,13 +81,16 @@ describe('groups routes', () => {
|
||||
const where = {
|
||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||
};
|
||||
// The occupancy counters ride along in the same query; the waitlist
|
||||
// counts only PENDING, the ones still waiting for a spot.
|
||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||
where,
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
_count: {
|
||||
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(prisma.group.count).toHaveBeenCalledWith({ where });
|
||||
});
|
||||
|
||||
it('rejects listing groups without a session', async () => {
|
||||
@@ -101,8 +106,68 @@ describe('groups routes', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects an invalid time zone', async () => {
|
||||
const res = await makeApp({ id: userId }).request('/groups?timeZone=Marte/Olympus');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('ordena los grupos por la clase más cercana y deja al final los sin horario', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([
|
||||
{ ...group, id: 'sin-horario', name: 'Sin horario' },
|
||||
{ ...group, id: 'proxima-semana', name: 'Próxima semana', days: ['MONDAY'], time: '08:00' },
|
||||
{ ...group, id: 'manana', name: 'Mañana', days: ['TUESDAY'], time: '09:00' },
|
||||
{ ...group, id: 'hoy-tarde', name: 'Hoy a la tarde', days: ['MONDAY'], time: '18:00' },
|
||||
{
|
||||
...group,
|
||||
id: 'hoy-tarde-viejo',
|
||||
name: 'Hoy a la tarde (viejo)',
|
||||
days: ['MONDAY'],
|
||||
time: '18:00',
|
||||
createdAt: new Date('2026-07-01T10:00:00.000Z'),
|
||||
},
|
||||
]);
|
||||
|
||||
// Monday 2026-01-05 at noon in Mexico City: the 18:00 class
|
||||
// hasn't started yet, so that group goes first.
|
||||
const result = await new ListGroups({
|
||||
db,
|
||||
now: new Date('2026-01-05T18:00:00.000Z'),
|
||||
}).execute({ page: 1, pageSize: 10, timeZone: 'America/Mexico_City' }, userId);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
// On a tie the newest one goes first, which was the previous criterion.
|
||||
expect(result.value.data.map((item) => item.id)).toEqual([
|
||||
'hoy-tarde',
|
||||
'hoy-tarde-viejo',
|
||||
'manana',
|
||||
'proxima-semana',
|
||||
'sin-horario',
|
||||
]);
|
||||
expect(result.value.pagination).toEqual({ page: 1, pageSize: 10, total: 5, totalPages: 1 });
|
||||
});
|
||||
|
||||
it('pagina la lista ya ordenada por próxima clase', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([
|
||||
{ ...group, id: 'a', name: 'A', days: ['MONDAY'], time: '10:00' },
|
||||
{ ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// Monday at noon: A's 10:00 class already happened, so its
|
||||
// next occurrence is next Monday and B (Wednesday) goes first.
|
||||
const result = await new ListGroups({
|
||||
db,
|
||||
now: new Date('2026-01-05T18:00:00.000Z'),
|
||||
}).execute({ page: 2, pageSize: 1, timeZone: 'UTC' }, userId);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.data.map((item) => item.id)).toEqual(['a']);
|
||||
expect(result.value.pagination).toEqual({ page: 2, pageSize: 1, total: 2, totalPages: 2 });
|
||||
});
|
||||
|
||||
it('creates a group with billing configuration', async () => {
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId });
|
||||
prisma.group.create.mockResolvedValue({
|
||||
...group,
|
||||
days: ['MONDAY'],
|
||||
@@ -158,8 +223,16 @@ describe('groups routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects creating a group without a linked merchant account', async () => {
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue(null);
|
||||
it('creates a group without Mercado Pago linked, since linking is optional', async () => {
|
||||
prisma.group.create.mockResolvedValue({
|
||||
...group,
|
||||
days: ['MONDAY'],
|
||||
time: '09:00',
|
||||
capacity: 20,
|
||||
price: 500,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 5,
|
||||
});
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups', {
|
||||
method: 'POST',
|
||||
@@ -175,9 +248,8 @@ describe('groups routes', () => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: 'payment_not_setup' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
expect(res.status).toBe(201);
|
||||
expect(prisma.group.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects creating a group with an invalid payload', async () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ const TZ = 'America/Mexico_City';
|
||||
|
||||
describe('nextClassOccurrence', () => {
|
||||
it('devuelve la próxima clase de hoy cuando aún no arrancó', () => {
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // miércoles 12:00 hora CDMX
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -21,7 +21,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('marca en curso si la clase arrancó hace menos de la ventana', () => {
|
||||
const now = new Date('2026-09-24T01:00:00.000Z'); // miércoles 19:00 hora CDMX (1 h tras la clase)
|
||||
const now = new Date('2026-09-24T01:00:00.000Z'); // Wednesday 19:00 CDMX time (1 h after the class)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -37,7 +37,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('salta a la próxima semana si la clase ya pasó la ventana', () => {
|
||||
const now = new Date('2026-09-24T03:00:00.000Z'); // miércoles 21:00 hora CDMX (3 h tras la clase)
|
||||
const now = new Date('2026-09-24T03:00:00.000Z'); // Wednesday 21:00 CDMX time (3 h after the class)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -53,7 +53,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('elige la ocurrencia más próxima entre varios días', () => {
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // miércoles 12:00 hora CDMX
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
|
||||
@@ -69,7 +69,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('cruza de mes sin problema', () => {
|
||||
const now = new Date('2026-09-29T18:00:00.000Z'); // martes 12:00 hora CDMX (último día de septiembre es miércoles 30)
|
||||
const now = new Date('2026-09-29T18:00:00.000Z'); // Tuesday 12:00 CDMX time (September's last day is Wednesday the 30th)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['THURSDAY'],
|
||||
|
||||
@@ -193,7 +193,7 @@ describe('GetHomeSummary', () => {
|
||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// 10:23 en Buenos Aires (UTC-3). La clase de las 10:00 ya arrancó.
|
||||
// 10:23 in Buenos Aires (UTC-3). The 10:00 class already started.
|
||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||
const result = await useCase.execute(userId, { timeZone: 'America/Argentina/Buenos_Aires' });
|
||||
|
||||
@@ -212,7 +212,7 @@ describe('GetHomeSummary', () => {
|
||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// 10:23 en Buenos Aires, pero la zona por defecto es CDMX → las 07:23 CDMX (aún no empieza).
|
||||
// 10:23 in Buenos Aires, but the default zone is CDMX → 07:23 CDMX (not started yet).
|
||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||
const result = await useCase.execute(userId);
|
||||
|
||||
|
||||
@@ -10,9 +10,10 @@ const db = {
|
||||
create: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
groupPreRegistration: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -83,18 +84,18 @@ describe('public invitations routes', () => {
|
||||
});
|
||||
|
||||
describe('POST /invitations/:token/join', () => {
|
||||
it('registers a new attendee successfully', async () => {
|
||||
it('creates a pending pre-registration instead of an attendee', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue({
|
||||
id: 'att-1',
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.create.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
email: 'lucia@test.com',
|
||||
phone: '+5491122334455',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
reviewedAt: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
} as never);
|
||||
@@ -112,9 +113,11 @@ describe('public invitations routes', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.message).toBe('Inscripción realizada con éxito');
|
||||
expect(body.attendee.fullName).toBe('Lucía Méndez');
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
expect(body.status).toBe('pre_registered');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(body.message).toContain('solicitud de inscripción');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
@@ -141,7 +144,7 @@ describe('public invitations routes', () => {
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid inputs (missing required name/phone)', async () => {
|
||||
@@ -157,21 +160,67 @@ describe('public invitations routes', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('adds to the waitlist when the group is full', async () => {
|
||||
it('returns 409 when a pre-registration is already pending', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.count.mockResolvedValue(15); // capacity full
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
prisma.groupWaitlistEntry.create.mockResolvedValue({
|
||||
id: 'wl-1',
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
status: 'PENDING',
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: 'Lucía',
|
||||
lastName: 'Méndez',
|
||||
phone: '+54 9 11 2233-4455',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_pending');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already approved', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
status: 'APPROVED',
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: 'Lucía',
|
||||
lastName: 'Méndez',
|
||||
phone: '+54 9 11 2233-4455',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_approved');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reactivates a rejected pre-registration back to pending', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
phone: '+5491122334455',
|
||||
email: 'lucia@test.com',
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
status: 'REJECTED',
|
||||
reviewedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
@@ -187,15 +236,15 @@ describe('public invitations routes', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.status).toBe('waitlisted');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
||||
expect(body.status).toBe('pre_registered');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
status: 'PENDING',
|
||||
fullName: 'Lucía Méndez',
|
||||
phone: '+5491122334455',
|
||||
email: 'lucia@test.com',
|
||||
reviewedAt: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
1042
apps/backend/test/mp.test.ts
Normal file
1042
apps/backend/test/mp.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -6,9 +6,8 @@ const db = {
|
||||
findUnique: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
merchantAccount: {
|
||||
mpAccount: {
|
||||
findUnique: mock(),
|
||||
upsert: mock(),
|
||||
},
|
||||
group: {
|
||||
create: mock(),
|
||||
@@ -75,7 +74,7 @@ describe('onboarding routes', () => {
|
||||
describe('GET /onboarding/status', () => {
|
||||
it('returns NOT_STARTED for a user that has not started', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
@@ -87,9 +86,9 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns PAYMENT_CONNECTED when the merchant account exists', async () => {
|
||||
it('returns PAYMENT_CONNECTED when Mercado Pago is linked and active', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId });
|
||||
prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId: userId, status: 'ACTIVE' });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
@@ -101,6 +100,24 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns NOT_STARTED when the account needs to be linked again', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.mpAccount.findUnique.mockResolvedValue({
|
||||
id: 'mp-1',
|
||||
ownerId: userId,
|
||||
status: 'REQUIRES_REAUTH',
|
||||
});
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
step: 'NOT_STARTED',
|
||||
paymentConnected: false,
|
||||
completed: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns COMPLETED when onboarding is already done', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true });
|
||||
|
||||
@@ -122,54 +139,9 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /onboarding/payment-setup', () => {
|
||||
it('connects a merchant account in sandbox mode', async () => {
|
||||
prisma.merchantAccount.upsert.mockResolvedValue({ id: 'ma-1', userId });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ provider: 'MERCADO_PAGO', sandbox: true }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
provider: 'MERCADO_PAGO',
|
||||
sandbox: true,
|
||||
connected: true,
|
||||
});
|
||||
expect(prisma.merchantAccount.upsert).toHaveBeenCalledWith({
|
||||
where: { userId },
|
||||
create: { userId, provider: 'MERCADO_PAGO', accessToken: undefined, sandbox: true },
|
||||
update: { provider: 'MERCADO_PAGO', accessToken: undefined, sandbox: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an unknown provider', async () => {
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ provider: 'PAYPAL' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects without a session', async () => {
|
||||
const res = await makeApp(null).request('/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ provider: 'STRIPE', sandbox: true }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /onboarding/first-group', () => {
|
||||
it('creates the first group and completes onboarding', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId });
|
||||
prisma.group.create.mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
@@ -217,9 +189,10 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects when the payment has not been set up', async () => {
|
||||
it('creates the group without Mercado Pago linked, since that step is skippable', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.group.create.mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
method: 'POST',
|
||||
@@ -227,9 +200,8 @@ describe('onboarding routes', () => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: 'payment_not_setup' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
expect(res.status).toBe(201);
|
||||
expect(prisma.group.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects when onboarding is already completed', async () => {
|
||||
@@ -248,7 +220,6 @@ describe('onboarding routes', () => {
|
||||
|
||||
it('rejects invalid payloads', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
method: 'POST',
|
||||
|
||||
365
apps/backend/test/preregistrations.test.ts
Normal file
365
apps/backend/test/preregistrations.test.ts
Normal file
@@ -0,0 +1,365 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
groupPreRegistration: {
|
||||
findMany: mock(),
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {
|
||||
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
|
||||
const teacherId = 'teacher-1';
|
||||
const mockGroup = {
|
||||
id: 'group-1',
|
||||
name: 'Taller de Pintura',
|
||||
description: null,
|
||||
createdById: teacherId,
|
||||
inviteToken: 'valid-token-123',
|
||||
createdAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
days: ['MONDAY'],
|
||||
time: '18:00',
|
||||
capacity: 20,
|
||||
price: 1500,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 10,
|
||||
members: [],
|
||||
};
|
||||
|
||||
const preRegistration = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
status: 'PENDING',
|
||||
reviewedAt: null,
|
||||
createdAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
notifyToken: 'notify-1',
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'wl-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
createdAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('group pre-registrations', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/preregistrations', () => {
|
||||
it('lists pending pre-registrations in FIFO order with pagination', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findMany.mockResolvedValue([
|
||||
preRegistration({ id: 'pre-1', fullName: 'Ana García', createdAt: new Date('2026-09-08T10:00:00.000Z') }),
|
||||
preRegistration({ id: 'pre-2', fullName: 'Pedro López', createdAt: new Date('2026-09-09T10:00:00.000Z') }),
|
||||
] as never);
|
||||
prisma.groupPreRegistration.count.mockResolvedValue(2);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/preregistrations');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.data).toHaveLength(2);
|
||||
expect(data.data[0].fullName).toBe('Ana García');
|
||||
expect(data.data[0].status).toBe('PENDING');
|
||||
expect(data.pagination).toEqual({ page: 1, pageSize: 10, total: 2, totalPages: 1 });
|
||||
expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'PENDING' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('filters by status when provided', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findMany.mockResolvedValue([] as never);
|
||||
prisma.groupPreRegistration.count.mockResolvedValue(0);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations?status=REJECTED',
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'REJECTED' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects user without access to the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/preregistrations');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/preregistrations/:entryId/approve', () => {
|
||||
it('adds the person to the group when there is free capacity', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue(attendee() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.outcome).toBe('added');
|
||||
expect(body.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(body.waitlistEntry).toBeNull();
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
},
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'APPROVED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('moves the person to the waitlist when the group is full', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(20); // capacity full
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
prisma.groupWaitlistEntry.create.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.outcome).toBe('waitlisted');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(body.waitlistEntry.fullName).toBe('Martín Gómez');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
},
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'APPROVED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('reuses an existing waitlist entry instead of duplicating it', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(20);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the phone already belongs to a member', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already reviewed', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_reviewed');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the pre-registration does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/missing/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('rejects approval from a user who is not the owner', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/preregistrations/:entryId/reject', () => {
|
||||
it('marks the pre-registration as rejected', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'REJECTED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.entry.status).toBe('REJECTED');
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'REJECTED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already reviewed', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(
|
||||
preRegistration({ status: 'REJECTED' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_reviewed');
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects rejection from a user who is not the owner', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,7 @@ describe('session auth', () => {
|
||||
it('classifies absence notification endpoints as public (token-based)', () => {
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/classes/notify-absence')).toBe(true);
|
||||
// Las rutas autenticadas de clases siguen protegidas.
|
||||
// The authenticated class routes stay protected.
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/today')).toBe(false);
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false);
|
||||
|
||||
@@ -2,16 +2,19 @@
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<!-- viewport-fit=cover enables env(safe-area-inset-*) in iOS standalone. -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<title>Gruperly</title>
|
||||
<meta name="description" content="Gestión de cobros grupales" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<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@400;500;600;700;800;900&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180.png" />
|
||||
|
||||
<!-- iOS standalone: without this the app opens in a Safari tab. -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="Gruperly" />
|
||||
|
||||
<meta name="theme-color" id="theme-color" content="#ffffff" />
|
||||
<script>
|
||||
(function () {
|
||||
try {
|
||||
@@ -19,7 +22,11 @@
|
||||
var isDark =
|
||||
stored === 'dark' ||
|
||||
(stored !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
if (isDark) document.documentElement.classList.add('dark');
|
||||
if (isDark) {
|
||||
document.documentElement.classList.add('dark');
|
||||
var meta = document.getElementById('theme-color');
|
||||
if (meta) meta.setAttribute('content', '#020617');
|
||||
}
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
|
||||
70
apps/web/nginx.conf
Normal file
70
apps/web/nginx.conf
Normal file
@@ -0,0 +1,70 @@
|
||||
# Nginx para el build de @gruperly/web.
|
||||
# Sirve los assets estáticos y hace de proxy de /api hacia el servicio `api`.
|
||||
# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión
|
||||
# es first-party y el CORS del backend queda como red de seguridad.
|
||||
|
||||
# DNS interno de Docker: resuelve `api` en cada request, así el proxy sobrevive
|
||||
# a un recreate del contenedor (que cambia la IP).
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
client_max_body_size 10m;
|
||||
|
||||
# ── API ────────────────────────────────────────────────────────────────────
|
||||
location /api/ {
|
||||
set $api http://api:4000;
|
||||
proxy_pass $api$request_uri;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
# ── Assets con hash en el nombre ───────────────────────────────────────────
|
||||
# Solo `add_header`: `expires` agregaría un segundo Cache-Control.
|
||||
location /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ── Service worker y manifest ─────────────────────────────────────────────
|
||||
# Nunca se cachean: el navegador tiene que ver la versión nueva en el próximo
|
||||
# load. `=404` y no el fallback del SPA, porque un 404 del SW debe ser un 404.
|
||||
location = /manifest.webmanifest {
|
||||
# `mime.types` de alpine no conoce `webmanifest` y lo sirve como
|
||||
# octet-stream. Un `types` acá reemplaza el mapa heredado, pero esta location
|
||||
# solo sirve un archivo, así que no puede romper nada más.
|
||||
types { application/manifest+json webmanifest; }
|
||||
default_type application/manifest+json;
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~ ^/(sw\.js|workbox-[^/]+\.js)$ {
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ── SPA ────────────────────────────────────────────────────────────────────
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user