Compare commits
35 Commits
feat/atten
...
e03f510874
| Author | SHA1 | Date | |
|---|---|---|---|
| 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
|
||||
41
.env.example
Normal file
41
.env.example
Normal file
@@ -0,0 +1,41 @@
|
||||
# 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>"
|
||||
|
||||
# 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.
|
||||
14
AGENTS.md
14
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,8 +31,8 @@ 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: `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).
|
||||
|
||||
@@ -40,19 +41,24 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
||||
- **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;"]
|
||||
85
README.md
85
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,92 @@ 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).
|
||||
|
||||
## 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`) |
|
||||
| `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
|
||||
```
|
||||
|
||||
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";
|
||||
@@ -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[]
|
||||
@@ -25,39 +25,39 @@ model User {
|
||||
|
||||
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,6 +158,30 @@ enum WaitlistStatus {
|
||||
DECLINED
|
||||
}
|
||||
|
||||
enum PreRegistrationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model GroupPreRegistration {
|
||||
id String @id @default(cuid())
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
status PreRegistrationStatus @default(PENDING)
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey")
|
||||
|
||||
@@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
|
||||
@@index([groupId], map: "group_pre_registrations_groupId_idx")
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
@@ -164,15 +189,15 @@ enum PaymentProvider {
|
||||
|
||||
model MerchantAccount {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique
|
||||
userId String @unique(map: "merchant_accounts_userId_key") @map("user_id")
|
||||
provider PaymentProvider
|
||||
accessToken String?
|
||||
accessToken String? @map("access_token")
|
||||
sandbox Boolean @default(true)
|
||||
connectedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
connectedAt DateTime @default(now()) @map("connected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "merchant_accounts_userId_fkey")
|
||||
|
||||
@@map("merchant_accounts")
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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.',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -26,6 +26,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 +61,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 +75,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 +84,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,6 +109,67 @@ 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({
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,13 @@
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"icons": "bun run scripts/generate-icons.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "^1.7.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@gruperly/shared": "workspace:*",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
@@ -31,8 +34,11 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.0",
|
||||
"sharp": "^0.35.4",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^6.0.0"
|
||||
"vite": "^6.0.0",
|
||||
"vite-plugin-pwa": "^1.3.0",
|
||||
"workbox-window": "^7.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
apps/web/public/apple-touch-icon-180.png
Normal file
BIN
apps/web/public/apple-touch-icon-180.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 16 KiB |
BIN
apps/web/public/pwa-192x192.png
Normal file
BIN
apps/web/public/pwa-192x192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.0 KiB |
BIN
apps/web/public/pwa-512x512.png
Normal file
BIN
apps/web/public/pwa-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
BIN
apps/web/public/pwa-maskable-512x512.png
Normal file
BIN
apps/web/public/pwa-maskable-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
66
apps/web/scripts/generate-icons.ts
Normal file
66
apps/web/scripts/generate-icons.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Generates the PWA icon set from the brand isotype SVG.
|
||||
*
|
||||
* Usage: bun --filter @gruperly/web icons
|
||||
*
|
||||
* The outputs are versioned in `public/`; the Vite build does not regenerate
|
||||
* them (sharp is a devDependency and must not end up in the Docker image).
|
||||
* Re-run only when `src/assets/brand/isotipo-y-organica.svg` changes.
|
||||
*/
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import sharp from 'sharp'
|
||||
|
||||
const webDir = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const source = join(webDir, 'src/assets/brand/isotipo-y-organica.svg')
|
||||
const publicDir = join(webDir, 'public')
|
||||
|
||||
/** Light theme background; it also serves as the canvas for opaque icons. */
|
||||
const BACKGROUND = '#ffffff'
|
||||
const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const
|
||||
|
||||
type IconTarget = {
|
||||
file: string
|
||||
size: number
|
||||
/** Fills the canvas with `BACKGROUND` instead of leaving it transparent. */
|
||||
opaque: boolean
|
||||
/** Fraction of the side the logo takes up. 1 = no padding. */
|
||||
contentRatio: number
|
||||
}
|
||||
|
||||
const targets: IconTarget[] = [
|
||||
{ file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 },
|
||||
{ file: 'pwa-512x512.png', size: 512, opaque: false, contentRatio: 0.9 },
|
||||
// Android crops adaptive icons in a circle: the useful content lives in the
|
||||
// central 80% of the canvas, so the logo goes on white and scaled.
|
||||
{ file: 'pwa-maskable-512x512.png', size: 512, opaque: true, contentRatio: 0.8 },
|
||||
{ file: 'apple-touch-icon-180.png', size: 180, opaque: true, contentRatio: 0.82 },
|
||||
]
|
||||
|
||||
// The isotype viewBox does not start at 0 and leaves air around the glyph:
|
||||
// `trim` crops that margin so the framing uses the drawing's real area.
|
||||
const logo = await sharp(await readFile(source), { density: 512 })
|
||||
.trim({ threshold: 1 })
|
||||
.png()
|
||||
.toBuffer()
|
||||
|
||||
await mkdir(publicDir, { recursive: true })
|
||||
|
||||
for (const { file, size, opaque, contentRatio } of targets) {
|
||||
const box = Math.round(size * contentRatio)
|
||||
const layer = await sharp(logo)
|
||||
.resize(box, box, { fit: 'inside' })
|
||||
.png()
|
||||
.toBuffer()
|
||||
|
||||
const output = await sharp({
|
||||
create: { width: size, height: size, channels: 4, background: opaque ? BACKGROUND : TRANSPARENT },
|
||||
})
|
||||
.composite([{ input: layer, gravity: 'center' }])
|
||||
.png({ compressionLevel: 9 })
|
||||
.toBuffer()
|
||||
|
||||
await writeFile(join(publicDir, file), output)
|
||||
console.log(`${file.padEnd(28)} ${size}x${size} ${(output.byteLength / 1024).toFixed(1)} KB`)
|
||||
}
|
||||
@@ -1,29 +1,36 @@
|
||||
import { Link, useLocation } from '@tanstack/react-router'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { NAV_ITEMS } from './nav-items'
|
||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||
|
||||
export function BottomNav() {
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 backdrop-blur lg:hidden">
|
||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
|
||||
<div className="mx-auto grid max-w-md grid-cols-4">
|
||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||
const isActive = location.pathname === to
|
||||
const isActive = isNavItemActive(location.pathname, to)
|
||||
return (
|
||||
<Link
|
||||
key={to}
|
||||
to={to}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
className={cn(
|
||||
'flex flex-col items-center gap-0.5 py-2.5 text-[11px] font-medium transition-colors',
|
||||
isActive ? 'text-accent-fg' : 'text-foreground/50 hover:text-primary',
|
||||
'flex min-h-14 flex-col items-center justify-center gap-1 py-2 text-[11px] font-medium transition-colors',
|
||||
isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary',
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
className={cn('size-6', isActive && 'fill-accent/15 stroke-accent')}
|
||||
strokeWidth={isActive ? 2.2 : 2}
|
||||
/>
|
||||
{label}
|
||||
{/* Soft pill behind the icon: the active state is read by
|
||||
color + background, not only by the text tone. */}
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-8 items-center justify-center rounded-lg transition-colors duration-150',
|
||||
isActive && 'bg-accent-soft',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
||||
</span>
|
||||
<span className="leading-none">{label}</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { Logo } from '../brand'
|
||||
import { Breadcrumb } from './Breadcrumb'
|
||||
import { ThemeToggle } from './ThemeToggle'
|
||||
@@ -8,9 +9,12 @@ export function Header() {
|
||||
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
|
||||
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
|
||||
<div className="flex min-w-0 items-center">
|
||||
<a href="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
||||
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the
|
||||
home screen and an anchor would reload the whole document, losing
|
||||
the in-memory state (React Query cache, install event). */}
|
||||
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
||||
<Logo className="h-8" />
|
||||
</a>
|
||||
</Link>
|
||||
<Breadcrumb />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
116
apps/web/src/components/layout/LargeTitle.tsx
Normal file
116
apps/web/src/components/layout/LargeTitle.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
||||
import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse'
|
||||
|
||||
type LargeTitleProps = {
|
||||
/** Title text. It's the same in the large title and in the bar's copy: the
|
||||
* real `h1` is the large one, the bar's is a visual duplicate. */
|
||||
title: string
|
||||
/** Action to the left of the bar. On desktop it's the "Volver" link that
|
||||
* used to live in the screen body; on mobile it's hidden. */
|
||||
leading?: ReactNode
|
||||
/** Context shown in the center before the large title collapses. */
|
||||
barContext?: ReactNode
|
||||
/** Visual identity beside the large title, such as an avatar. */
|
||||
titleLeading?: ReactNode
|
||||
/** Context that can't disappear on scroll (e.g. the present counter). It
|
||||
* travels to the bar and blends with the title. */
|
||||
barTrailing?: ReactNode
|
||||
/** Metadata under the large title: badges, description. It goes away when
|
||||
* the title collapses. */
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Screen header with Large Title (the iOS pattern): the title starts large and
|
||||
* slides under the bar as you scroll, while the bar goes opaque and takes the
|
||||
* title in its small version.
|
||||
*
|
||||
* The large title is a normal block in the flow; the bar lives in a sticky box
|
||||
* that the layout mounts above `<main>` (see `ImmersiveBarHost`), so the content
|
||||
* slides under it without negative margins or a `fixed` we'd have to compensate
|
||||
* for on desktop.
|
||||
*
|
||||
* The scroll state lives in here on purpose: `children` arrives as an already
|
||||
* built prop, so React reuses the elements and the subtree below doesn't
|
||||
* re-render on every scroll frame.
|
||||
*/
|
||||
export function LargeTitle({
|
||||
title,
|
||||
leading,
|
||||
barContext,
|
||||
titleLeading,
|
||||
barTrailing,
|
||||
children,
|
||||
}: LargeTitleProps) {
|
||||
const { titleRef, progress } = useLargeTitleCollapse()
|
||||
const barHost = useImmersiveBarHost()
|
||||
|
||||
return (
|
||||
<>
|
||||
{barHost
|
||||
? createPortal(
|
||||
<div className="relative flex h-full items-center gap-3 px-4 lg:px-0">
|
||||
{/* The background goes on its own layer: it goes opaque with the
|
||||
scroll while the title slides in, and `leading` (the "Volver"
|
||||
link) can't blend with it because it always exists. */}
|
||||
<div
|
||||
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
|
||||
style={{ opacity: progress }}
|
||||
/>
|
||||
{leading}
|
||||
{barContext ? (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-14 right-14 flex items-center justify-center overflow-hidden text-center">
|
||||
<span
|
||||
className="truncate text-sm font-medium text-secondary"
|
||||
style={{ opacity: 1 - progress }}
|
||||
>
|
||||
{barContext}
|
||||
</span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute inset-x-0 truncate text-base font-semibold text-primary"
|
||||
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="relative min-w-0 flex-1 truncate text-base font-semibold text-primary"
|
||||
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
)}
|
||||
{barContext ? <span className="min-w-0 flex-1" aria-hidden="true" /> : null}
|
||||
{barTrailing ? (
|
||||
<span
|
||||
aria-hidden={barContext ? undefined : true}
|
||||
className="relative flex shrink-0 items-center"
|
||||
style={{ opacity: barContext ? 1 : progress }}
|
||||
>
|
||||
{barTrailing}
|
||||
</span>
|
||||
) : null}
|
||||
</div>,
|
||||
barHost,
|
||||
)
|
||||
: null}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{titleLeading}
|
||||
<h1
|
||||
ref={titleRef}
|
||||
className="min-w-0 text-balance text-[2.125rem] font-bold leading-[1.1] tracking-tight text-primary sm:text-[2.5rem]"
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,39 @@
|
||||
import { useLocation } from '@tanstack/react-router'
|
||||
import type { ReactNode } from 'react'
|
||||
import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider'
|
||||
import { isImmersiveRoute } from '../../lib/immersive-routes'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { Header } from './Header'
|
||||
import { Sidebar } from './Sidebar'
|
||||
import { BottomNav } from './BottomNav'
|
||||
|
||||
export function RootLayout({ children }: { children: ReactNode }) {
|
||||
const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) })
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh w-full">
|
||||
<Header />
|
||||
<div className="min-h-dvh w-full overflow-x-clip">
|
||||
{/* On immersive routes the screen brings its own bar (LargeTitle) with
|
||||
the logo and the group name: the global header with logo + theme +
|
||||
avatar would be a second bar competing for the same pixels. */}
|
||||
{immersive ? null : <Header />}
|
||||
|
||||
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
||||
<Sidebar />
|
||||
<Sidebar immersive={immersive} />
|
||||
|
||||
<main className="min-w-0 flex-1 px-4 pb-24 pt-4 lg:px-0 lg:pb-8 lg:pt-8">{children}</main>
|
||||
<ImmersiveBarProvider>
|
||||
{/* pt-0 on immersive: the bar's box provides the top padding,
|
||||
otherwise the large title would start 16px below the bottom of the
|
||||
bar and the collapse would be measured off. */}
|
||||
<main
|
||||
className={cn(
|
||||
'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8',
|
||||
immersive ? 'pt-0' : 'pt-4 lg:pt-8',
|
||||
)}
|
||||
>
|
||||
{immersive ? <ImmersiveBarHost /> : null}
|
||||
{children}
|
||||
</main>
|
||||
</ImmersiveBarProvider>
|
||||
</div>
|
||||
|
||||
<BottomNav />
|
||||
|
||||
@@ -1,29 +1,40 @@
|
||||
import { Link, useLocation } from '@tanstack/react-router'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { Logo } from '../brand'
|
||||
import { NAV_ITEMS } from './nav-items'
|
||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||
|
||||
export function Sidebar() {
|
||||
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<aside className="sticky top-16 hidden h-[calc(100dvh-4rem)] w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex">
|
||||
<a href="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
||||
// Without the global header there's nothing to clear above: the sidebar
|
||||
// column takes over the whole window and lines up with the height of the
|
||||
// LargeTitle bar.
|
||||
<aside
|
||||
className={cn(
|
||||
'sticky hidden w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex',
|
||||
immersive ? 'top-0 h-dvh' : 'top-16 h-[calc(100dvh-4rem)]',
|
||||
)}
|
||||
>
|
||||
{/* `Link` and not `<a>`: an anchor would reload the document and lose the
|
||||
in-memory state (React Query cache, install event). */}
|
||||
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
||||
<Logo className="h-10" />
|
||||
</a>
|
||||
</Link>
|
||||
|
||||
<nav className="flex flex-col gap-1">
|
||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||
const isActive = location.pathname === to
|
||||
const isActive = isNavItemActive(location.pathname, to)
|
||||
return (
|
||||
<Link
|
||||
key={to}
|
||||
to={to}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
className={cn(
|
||||
'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
|
||||
isActive
|
||||
? 'bg-accent-soft text-accent-fg'
|
||||
: 'text-foreground/60 hover:bg-primary-soft hover:text-primary',
|
||||
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export { RootLayout } from './RootLayout'
|
||||
export { Header } from './Header'
|
||||
export { LargeTitle } from './LargeTitle'
|
||||
export { ThemeToggle } from './ThemeToggle'
|
||||
export { PublicHeader } from './PublicHeader'
|
||||
export { PublicFooter } from './PublicFooter'
|
||||
|
||||
@@ -12,3 +12,12 @@ export const NAV_ITEMS: NavItem[] = [
|
||||
{ label: 'Cobros', to: '/payments', icon: Wallet },
|
||||
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
||||
]
|
||||
|
||||
/** A section stays active within its subroutes: on `/groups/abc` the active
|
||||
* item is "Grupos", not none. The prefix is cut at the separator so
|
||||
* `/groupsomething` isn't taken for "/groups". The root is exact: the home has
|
||||
* no subroutes that should mark it. */
|
||||
export function isNavItemActive(pathname: string, to: string): boolean {
|
||||
if (to === '/') return pathname === '/'
|
||||
return pathname === to || pathname.startsWith(`${to}/`)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { forwardRef, type HTMLAttributes } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral'
|
||||
export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' | 'info'
|
||||
|
||||
export type BadgeProps = HTMLAttributes<HTMLSpanElement> & {
|
||||
variant?: BadgeVariant
|
||||
@@ -12,6 +12,11 @@ const variants: Record<BadgeVariant, string> = {
|
||||
warning: 'bg-warning-soft text-warning',
|
||||
danger: 'bg-danger-soft text-danger',
|
||||
neutral: 'bg-primary-soft text-primary',
|
||||
/* Informational state, not an alert: waitlist, free spots. Uses the legible
|
||||
accent ink (`accent-fg` is the light blue in the dark theme, 7.1:1 on the
|
||||
card) and not the plain `accent`, which in dark scores 2.2:1 and misses the
|
||||
3:1 minimum for non-text content. */
|
||||
info: 'bg-accent-soft text-accent-fg',
|
||||
}
|
||||
|
||||
export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
||||
@@ -20,7 +25,7 @@ export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
||||
<span
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
|
||||
'inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-medium',
|
||||
variants[variant],
|
||||
className,
|
||||
)}
|
||||
|
||||
@@ -28,7 +28,10 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
ref={ref}
|
||||
type={type}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center gap-2 rounded-xl font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50',
|
||||
// Explicit `transition-*` instead of `transition-all`: only color,
|
||||
// background, border and transform are animated. Press feedback is
|
||||
// cancelled with `motion-reduce` to respect prefers-reduced-motion.
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-medium transition-[color,background-color,border-color,fill,stroke,transform] duration-150 ease-out active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50',
|
||||
variants[variant],
|
||||
sizes[size],
|
||||
className,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
export { Avatar, type AvatarProps } from './avatar'
|
||||
export { Button, type ButtonProps, type ButtonVariant, type ButtonSize } from './button'
|
||||
export { Badge, type BadgeProps, type BadgeVariant } from './badge'
|
||||
export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './button'
|
||||
export { Input, type InputProps } from './input'
|
||||
export { Label, type LabelProps } from './label'
|
||||
export { Modal, type ModalProps } from './modal'
|
||||
export { ToastProvider, useToast, type ToastType, type Toast } from './toast'
|
||||
export { type Toast, ToastProvider, type ToastType, useToast } from './toast'
|
||||
export { Tooltip, type TooltipProps } from './tooltip'
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
<input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
// text-base (16px) on mobile: iOS auto-zooms when focusing controls
|
||||
// with font-size < 16px and doesn't restore the scale on keyboard close.
|
||||
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base sm:text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
invalid && 'border-danger focus:border-danger focus:ring-danger/30',
|
||||
className,
|
||||
)}
|
||||
|
||||
68
apps/web/src/components/ui/tooltip.tsx
Normal file
68
apps/web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import { type ReactNode, useId, useState } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
export type TooltipProps = {
|
||||
/** Explanatory text shown on hover, keyboard focus or tap. */
|
||||
content: ReactNode
|
||||
/** Trigger content. It sits inside a <button> to stay accessible. */
|
||||
children: ReactNode
|
||||
className?: string
|
||||
/** Alternate positioning for the bubble (default: below, anchored right on sm+). */
|
||||
tooltipClassName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessible tooltip with no dependencies: hover (mouse), focus (keyboard) and
|
||||
* tap (touch, via focus). It closes on Escape, when the pointer leaves or when
|
||||
* it loses focus. The bubble is anchored below the trigger so it doesn't cover
|
||||
* the content.
|
||||
*/
|
||||
export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const id = useId()
|
||||
|
||||
const show = () => setOpen(true)
|
||||
const hide = () => setOpen(false)
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
aria-describedby={open ? id : undefined}
|
||||
// Hover only applies to mouse pointers: on touch there is no
|
||||
// "persistent hover" and tap is handled with focus + click.
|
||||
onPointerEnter={(e) => {
|
||||
if (e.pointerType === 'mouse') show()
|
||||
}}
|
||||
onPointerLeave={(e) => {
|
||||
if (e.pointerType === 'mouse') hide()
|
||||
}}
|
||||
onFocus={show}
|
||||
onBlur={hide}
|
||||
onClick={show}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') hide()
|
||||
}}
|
||||
className={cn(
|
||||
'inline-flex cursor-help rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<span
|
||||
id={id}
|
||||
role="tooltip"
|
||||
className={cn(
|
||||
'absolute top-full left-0 z-50 mt-1.5 w-max max-w-[min(16rem,calc(100vw_-_2rem))] rounded-lg border border-border bg-surface px-2.5 py-2 text-xs leading-snug text-foreground shadow-sm animate-fade-in sm:left-auto sm:right-0',
|
||||
tooltipClassName,
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
42
apps/web/src/context/ImmersiveBarProvider.tsx
Normal file
42
apps/web/src/context/ImmersiveBarProvider.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'
|
||||
|
||||
/* "Immersive" screens (group detail and attendance) build their own title bar
|
||||
instead of using the global header, but the bar has to be a direct child of
|
||||
`<main>`: a `sticky` only sticks while its parent box is on screen, and the
|
||||
bar's natural parent (the feature block) is short, so it would detach at
|
||||
around ~200px of scroll.
|
||||
|
||||
This provider exposes a fixed 56px box pinned to the top of `<main>` where
|
||||
the screen mounts its bar. The layout draws the box (so it holds its place
|
||||
from the first render) and the screen supplies its content. */
|
||||
|
||||
type ImmersiveBarValue = {
|
||||
host: HTMLElement | null
|
||||
hostRef: (element: HTMLElement | null) => void
|
||||
}
|
||||
|
||||
const ImmersiveBarContext = createContext<ImmersiveBarValue>({
|
||||
host: null,
|
||||
hostRef: () => undefined,
|
||||
})
|
||||
|
||||
export function ImmersiveBarProvider({ children }: { children: ReactNode }) {
|
||||
const [host, setHost] = useState<HTMLElement | null>(null)
|
||||
const hostRef = useCallback((element: HTMLElement | null) => setHost(element), [])
|
||||
|
||||
return (
|
||||
<ImmersiveBarContext.Provider value={{ host, hostRef }}>{children}</ImmersiveBarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** The bar's box: first child of `<main>`, on immersive routes. */
|
||||
export function ImmersiveBarHost() {
|
||||
const { hostRef } = useContext(ImmersiveBarContext)
|
||||
|
||||
return <div ref={hostRef} className="sticky top-0 z-40 -mx-4 h-14 lg:mx-0" />
|
||||
}
|
||||
|
||||
/** Portal target for `LargeTitle`; `null` if the screen is not immersive. */
|
||||
export function useImmersiveBarHost() {
|
||||
return useContext(ImmersiveBarContext).host
|
||||
}
|
||||
@@ -18,6 +18,10 @@ type ThemeContextValue = {
|
||||
|
||||
const STORAGE_KEY = 'theme'
|
||||
|
||||
/** Status bar colors in standalone mode. Must match index.css. */
|
||||
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
|
||||
const THEME_COLOR_META_ID = 'theme-color'
|
||||
|
||||
function readStoredTheme(): Theme {
|
||||
const value = localStorage.getItem(STORAGE_KEY)
|
||||
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
||||
@@ -41,9 +45,16 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
document.documentElement.classList.toggle('dark', resolveDark(theme))
|
||||
setIsDark(document.documentElement.classList.contains('dark'))
|
||||
const dark = resolveDark(theme)
|
||||
document.documentElement.classList.toggle('dark', dark)
|
||||
setIsDark(dark)
|
||||
localStorage.setItem(STORAGE_KEY, theme)
|
||||
|
||||
// In standalone the status bar is painted with theme-color; without this
|
||||
// it stays frozen at the value the inline script in index.html set.
|
||||
document
|
||||
.getElementById(THEME_COLOR_META_ID)
|
||||
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)
|
||||
}
|
||||
update()
|
||||
|
||||
|
||||
75
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
75
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { useId, useState } from 'react'
|
||||
import { Check, Copy, MessageCircle } from 'lucide-react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||
import { Section } from './Section'
|
||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||
|
||||
export function AbsenceLinkSection() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const { copied, copy } = useCopyToClipboard()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const panelId = useId()
|
||||
|
||||
const token = attendee?.notifyToken
|
||||
const url = token ? `${window.location.origin}/report-absence/${token}` : null
|
||||
if (!attendee || !url) return null
|
||||
|
||||
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
|
||||
const shareUrl = phoneDigits
|
||||
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
|
||||
`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${url}`,
|
||||
)}`
|
||||
: null
|
||||
|
||||
return (
|
||||
<Section
|
||||
title="Link de ausencias"
|
||||
description="Para que avise si no puede venir"
|
||||
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
|
||||
>
|
||||
{/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
|
||||
the "Link copied" text is not lost on collapse/expand. */}
|
||||
<div id={panelId} hidden={!isOpen}>
|
||||
{/* Stacked and full width: at 50% the labels ("Enviar por WhatsApp")
|
||||
wrapped onto two lines and fell below the minimum touch target.
|
||||
Copy stays on top, glued to its confirmation, and the primary action
|
||||
is told apart by the accent fill. */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(url)}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
||||
>
|
||||
<Copy className="size-4" aria-hidden="true" />
|
||||
Copiar link
|
||||
</button>
|
||||
{shareUrl ? (
|
||||
<a
|
||||
href={shareUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
|
||||
className={PRIMARY_ACTION_CLASS}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
Enviar por WhatsApp
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
<p
|
||||
aria-live="polite"
|
||||
className="flex min-h-5 items-center gap-1.5 px-3 pt-2 text-xs font-medium text-success"
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="size-3.5" aria-hidden="true" />
|
||||
Link copiado
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
159
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
159
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import type { KeyboardEvent, RefObject } from 'react'
|
||||
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus } from 'lucide-react'
|
||||
import { useToast } from '../../components/ui'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
const ITEM_CLASS =
|
||||
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||
|
||||
/** Accessible "⋯" menu for member-level actions. */
|
||||
export function AttendeeActionsMenu({
|
||||
triggerRef,
|
||||
}: {
|
||||
/** The screen passes it in so the confirmation dialog can give focus back
|
||||
* when it closes. */
|
||||
triggerRef: RefObject<HTMLButtonElement | null>
|
||||
}) {
|
||||
const { beginContactEdit, openRemoveDialog } = useAttendeeDetail()
|
||||
const toast = useToast()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const itemRef = useRef<HTMLButtonElement>(null)
|
||||
const menuId = useId()
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) itemRef.current?.focus()
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
const target = event.target as Node
|
||||
if (menuRef.current?.contains(target) || triggerRef.current?.contains(target)) return
|
||||
setIsOpen(false)
|
||||
}
|
||||
document.addEventListener('pointerdown', handlePointerDown)
|
||||
return () => document.removeEventListener('pointerdown', handlePointerDown)
|
||||
}, [isOpen, triggerRef])
|
||||
|
||||
const close = (restoreFocus = false) => {
|
||||
setIsOpen(false)
|
||||
if (restoreFocus) triggerRef.current?.focus()
|
||||
}
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.stopPropagation()
|
||||
close(true)
|
||||
return
|
||||
}
|
||||
if (event.key === 'Tab') {
|
||||
close()
|
||||
return
|
||||
}
|
||||
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return
|
||||
|
||||
event.preventDefault()
|
||||
const items = Array.from(
|
||||
menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [],
|
||||
)
|
||||
if (items.length === 0) return
|
||||
const current = items.indexOf(document.activeElement as HTMLElement)
|
||||
const next =
|
||||
event.key === 'Home'
|
||||
? 0
|
||||
: event.key === 'End'
|
||||
? items.length - 1
|
||||
: (current + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length
|
||||
items[next]?.focus()
|
||||
}
|
||||
|
||||
const showPendingChangeGroup = () => {
|
||||
close()
|
||||
// TODO(miembros): navegar al selector cuando se confirmen las reglas y exista el endpoint.
|
||||
toast.info('Cambiar de grupo estará disponible cuando se confirme el flujo de traspaso.')
|
||||
}
|
||||
|
||||
const showPendingPause = () => {
|
||||
close()
|
||||
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
|
||||
toast.info('Pausar la membresía estará disponible cuando se confirme su lógica de negocio.')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative shrink-0">
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
onClick={() => setIsOpen((value) => !value)}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={isOpen ? menuId : undefined}
|
||||
aria-label="Más acciones"
|
||||
className="inline-flex size-11 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
<Ellipsis className="size-5" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
{isOpen ? (
|
||||
<div
|
||||
ref={menuRef}
|
||||
id={menuId}
|
||||
role="menu"
|
||||
aria-label="Acciones del miembro"
|
||||
onKeyDown={handleKeyDown}
|
||||
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
|
||||
>
|
||||
<button
|
||||
ref={itemRef}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={showPendingChangeGroup}
|
||||
>
|
||||
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Cambiar de grupo
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={() => {
|
||||
close()
|
||||
beginContactEdit()
|
||||
requestAnimationFrame(() => {
|
||||
document.getElementById('attendee-contact')?.scrollIntoView({ behavior: 'smooth' })
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Pencil className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Editar contacto
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={showPendingPause}
|
||||
>
|
||||
<Pause className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Pausar membresía
|
||||
</button>
|
||||
<div className="my-1 border-t border-border/70" aria-hidden="true" />
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={`${ITEM_CLASS} text-danger-fg hover:bg-danger-soft`}
|
||||
onClick={() => {
|
||||
close()
|
||||
openRemoveDialog()
|
||||
}}
|
||||
>
|
||||
<UserMinus className="size-4 shrink-0" aria-hidden="true" />
|
||||
Quitar del grupo
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useState } from 'react'
|
||||
import type { AttendanceStatus } from '@gruperly/shared'
|
||||
import { Check, ChevronDown, Loader2, Megaphone, Minus, X } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { cn } from '../../lib/utils'
|
||||
import {
|
||||
attendanceStatusClass,
|
||||
attendanceStatusLabel,
|
||||
attendanceSummary,
|
||||
formatSessionShortDate,
|
||||
HISTORY_LIMIT,
|
||||
HISTORY_PREVIEW,
|
||||
visibleSessions,
|
||||
type AttendanceSession,
|
||||
} from './attendance'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
|
||||
PRESENT: Check,
|
||||
ABSENT: X,
|
||||
EXCUSED: Megaphone,
|
||||
UNMARKED: Minus,
|
||||
}
|
||||
|
||||
function iconFor(status: AttendanceSession['status']): LucideIcon {
|
||||
return STATUS_ICONS[status ?? 'UNMARKED']
|
||||
}
|
||||
|
||||
export function AttendeeAttendanceSection() {
|
||||
const { history, historyPending, historyFailed } = useAttendeeDetail()
|
||||
const [showAll, setShowAll] = useState(false)
|
||||
|
||||
if (historyPending) {
|
||||
return (
|
||||
<Section title="Asistencia" trailing="—">
|
||||
<div className="flex items-center justify-center py-5">
|
||||
<Loader2 className="size-5 animate-spin text-accent" />
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
if (historyFailed) {
|
||||
return (
|
||||
<Section title="Asistencia">
|
||||
<p className="py-3 text-sm text-foreground">
|
||||
No pudimos cargar la asistencia de este miembro.
|
||||
</p>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
const sessions = history?.sessions ?? []
|
||||
|
||||
if (sessions.length === 0) {
|
||||
return (
|
||||
<Section title="Asistencia">
|
||||
<p className="py-3 text-sm text-foreground">
|
||||
Todavía no hay clases registradas.
|
||||
</p>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
const visible = visibleSessions(sessions, showAll)
|
||||
const hasMore = sessions.length > HISTORY_PREVIEW
|
||||
const isCapped = sessions.length >= HISTORY_LIMIT
|
||||
const summary = attendanceSummary(visible)
|
||||
|
||||
return (
|
||||
<Section title="Asistencia" trailing={summary.label}>
|
||||
<ul className="divide-y divide-border/60">
|
||||
{visible.map((session) => {
|
||||
const Icon = iconFor(session.status)
|
||||
return (
|
||||
<li
|
||||
key={session.classSessionId}
|
||||
className="flex items-center justify-between gap-3 px-3 py-2"
|
||||
>
|
||||
<span className="truncate text-sm text-primary">
|
||||
{formatSessionShortDate(session.startsAt)}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'flex shrink-0 items-center gap-1.5 text-xs font-semibold',
|
||||
attendanceStatusClass(session.status),
|
||||
)}
|
||||
>
|
||||
<Icon className="size-3.5" aria-hidden="true" />
|
||||
{attendanceStatusLabel(session.status)}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{showAll && isCapped ? (
|
||||
<p className="px-3 pt-2 text-xs text-foreground">
|
||||
El historial guarda las últimas {HISTORY_LIMIT} clases.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{hasMore ? (
|
||||
<div className="mt-1 flex justify-end">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setShowAll((value) => !value)}
|
||||
aria-expanded={showAll}
|
||||
className="h-11 gap-1 px-3 text-sm text-accent-fg hover:text-primary"
|
||||
>
|
||||
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
|
||||
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { MessageCircle, Phone } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeeContactActions() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
|
||||
const phone = attendee?.phone
|
||||
const digits = phone?.replace(/\D/g, '') ?? ''
|
||||
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? 'el miembro'
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="grid grid-cols-[1.4fr_1fr] gap-2.5">
|
||||
{phone ? (
|
||||
<a
|
||||
href={`https://wa.me/${digits}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Abrir WhatsApp con ${label}`}
|
||||
className={PRIMARY_ACTION_CLASS}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
WhatsApp
|
||||
</a>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
aria-describedby="missing-phone-feedback"
|
||||
className={cn(PRIMARY_ACTION_CLASS, 'cursor-not-allowed opacity-45')}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
WhatsApp
|
||||
</button>
|
||||
)}
|
||||
{phone ? (
|
||||
<a
|
||||
href={`tel:${digits}`}
|
||||
aria-label={`Llamar a ${label}`}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
||||
>
|
||||
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
|
||||
Llamar
|
||||
</a>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
aria-describedby="missing-phone-feedback"
|
||||
className={cn(ACTION_BUTTON_CLASS, 'w-full cursor-not-allowed opacity-45')}
|
||||
>
|
||||
<Phone className="size-4 text-secondary" aria-hidden="true" />
|
||||
Llamar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{!phone ? (
|
||||
<p id="missing-phone-feedback" className="mt-2 text-xs text-secondary">
|
||||
Agregá un teléfono para usar estas acciones
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Loader2, Mail, Phone } from 'lucide-react'
|
||||
import { Button, Input } from '../../components/ui'
|
||||
|
||||
type AttendeeContactFormProps = {
|
||||
phone: string
|
||||
email: string
|
||||
error: string | null
|
||||
isSaving: boolean
|
||||
onPhoneChange: (value: string) => void
|
||||
onEmailChange: (value: string) => void
|
||||
onCancel: () => void
|
||||
onSave: () => void
|
||||
}
|
||||
|
||||
export function AttendeeContactForm({
|
||||
phone,
|
||||
email,
|
||||
error,
|
||||
isSaving,
|
||||
onPhoneChange,
|
||||
onEmailChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: AttendeeContactFormProps) {
|
||||
return (
|
||||
<div className="space-y-3 px-3 pb-1">
|
||||
<ContactInput icon={Phone} label="Teléfono">
|
||||
<Input
|
||||
type="tel"
|
||||
value={phone}
|
||||
onChange={(event) => onPhoneChange(event.target.value)}
|
||||
autoComplete="tel"
|
||||
autoFocus
|
||||
aria-label="Teléfono"
|
||||
/>
|
||||
</ContactInput>
|
||||
<ContactInput icon={Mail} label="Email">
|
||||
<Input
|
||||
type="email"
|
||||
value={email}
|
||||
invalid={error === 'Ingresá un email válido'}
|
||||
onChange={(event) => onEmailChange(event.target.value)}
|
||||
autoComplete="email"
|
||||
aria-label="Email"
|
||||
aria-describedby={error ? 'contact-error' : undefined}
|
||||
/>
|
||||
</ContactInput>
|
||||
{error ? (
|
||||
<p id="contact-error" role="alert" className="text-sm text-danger-fg">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
Guardar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type ContactInputProps = {
|
||||
icon: typeof Phone
|
||||
label: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function ContactInput({ icon: Icon, label, children }: ContactInputProps) {
|
||||
return (
|
||||
<label className="grid grid-cols-[1.25rem_1fr] items-center gap-x-3 gap-y-1">
|
||||
<Icon className="size-4 text-secondary" aria-hidden="true" />
|
||||
<span className="text-xs font-medium text-secondary">{label}</span>
|
||||
<span className="col-start-2">{children}</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
135
apps/web/src/features/attendee-detail/AttendeeContactSection.tsx
Normal file
135
apps/web/src/features/attendee-detail/AttendeeContactSection.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Mail, Phone } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { AttendeeContactForm } from './AttendeeContactForm'
|
||||
import { contactEmailError } from './detail'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeeContactSection() {
|
||||
const {
|
||||
attendee,
|
||||
isEditingContact,
|
||||
beginContactEdit,
|
||||
endContactEdit,
|
||||
saveAttendee,
|
||||
isUpdatingAttendee,
|
||||
} = useAttendeeDetail()
|
||||
const [phone, setPhone] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEditingContact || !attendee) return
|
||||
setPhone(attendee.phone ?? '')
|
||||
setEmail(attendee.email ?? '')
|
||||
setError(null)
|
||||
}, [attendee, isEditingContact])
|
||||
|
||||
if (!attendee) return null
|
||||
|
||||
const cancel = () => {
|
||||
setError(null)
|
||||
endContactEdit()
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const emailError = contactEmailError(email)
|
||||
if (emailError) {
|
||||
setError(emailError)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await saveAttendee({ phone, email })
|
||||
endContactEdit()
|
||||
} catch {
|
||||
setError('No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Section
|
||||
id="attendee-contact"
|
||||
title="Contacto"
|
||||
trailing={
|
||||
!isEditingContact ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={beginContactEdit}
|
||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
Editar
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{isEditingContact ? (
|
||||
<AttendeeContactForm
|
||||
phone={phone}
|
||||
email={email}
|
||||
error={error}
|
||||
isSaving={isUpdatingAttendee}
|
||||
onPhoneChange={(value) => {
|
||||
setPhone(value)
|
||||
setError(null)
|
||||
}}
|
||||
onEmailChange={(value) => {
|
||||
setEmail(value)
|
||||
setError(null)
|
||||
}}
|
||||
onCancel={cancel}
|
||||
onSave={() => void save()}
|
||||
/>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
<ContactRow
|
||||
icon={Phone}
|
||||
label="Teléfono"
|
||||
value={formatPhoneDisplay(attendee.phone) ?? 'Agregar teléfono'}
|
||||
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
|
||||
placeholder={!attendee.phone}
|
||||
/>
|
||||
<ContactRow
|
||||
icon={Mail}
|
||||
label="Email"
|
||||
value={attendee.email ?? 'Agregar email'}
|
||||
href={attendee.email ? `mailto:${attendee.email}` : undefined}
|
||||
placeholder={!attendee.email}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
type ContactRowProps = {
|
||||
icon: typeof Phone
|
||||
label: string
|
||||
value: string
|
||||
href?: string
|
||||
placeholder: boolean
|
||||
}
|
||||
|
||||
function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowProps) {
|
||||
const content = (
|
||||
<>
|
||||
<Icon className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
<span className="min-w-0">
|
||||
<span className="block text-xs font-medium text-secondary">{label}</span>
|
||||
<span className={cn('block truncate text-sm text-primary', placeholder && 'text-secondary')}>
|
||||
{value}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
|
||||
const className = 'flex min-h-14 items-center gap-3 rounded-lg px-3 py-2'
|
||||
return href ? (
|
||||
<a href={href} className={cn(className, 'transition-colors hover:bg-primary-soft')}>
|
||||
{content}
|
||||
</a>
|
||||
) : (
|
||||
<div className={className}>{content}</div>
|
||||
)
|
||||
}
|
||||
@@ -1,30 +1,44 @@
|
||||
import { createContext, useContext, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||
import { useToast } from '../../../components/ui'
|
||||
import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api'
|
||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||
import type {
|
||||
AttendeeDetailDto,
|
||||
AttendeeHistory,
|
||||
GroupWaitlistEntryDto,
|
||||
UpdateAttendee,
|
||||
} from '@gruperly/shared'
|
||||
import {
|
||||
getAttendeeHistory,
|
||||
getGroup,
|
||||
getGroupAttendee,
|
||||
getGroupWaitlist,
|
||||
updateGroupAttendee,
|
||||
} from '../../lib/api'
|
||||
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
||||
|
||||
type AttendeeDetailContextValue = {
|
||||
groupId: string
|
||||
groupName: string | undefined
|
||||
attendee: AttendeeDto | undefined
|
||||
attendee: AttendeeDetailDto | undefined
|
||||
attendeePending: boolean
|
||||
attendeeFailed: boolean
|
||||
attendeeStats: AttendeeStats | undefined
|
||||
attendeeStatsPending: boolean
|
||||
attendeeStatsFailed: boolean
|
||||
history: AttendeeHistory | undefined
|
||||
historyPending: boolean
|
||||
historyFailed: boolean
|
||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
waitlistTotal: number
|
||||
waitlistPending: boolean
|
||||
isRemoveModalOpen: boolean
|
||||
openRemoveModal: () => void
|
||||
closeRemoveModal: () => void
|
||||
isEditingContact: boolean
|
||||
beginContactEdit: () => void
|
||||
endContactEdit: () => void
|
||||
saveAttendee: (input: UpdateAttendee) => Promise<void>
|
||||
isUpdatingAttendee: boolean
|
||||
isRemoveDialogOpen: boolean
|
||||
openRemoveDialog: () => void
|
||||
closeRemoveDialog: () => void
|
||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||
isSubmittingRemoval: boolean
|
||||
copyAbsenceNotifyUrl: (url: string) => void
|
||||
}
|
||||
|
||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||
@@ -38,9 +52,10 @@ export function AttendeeDetailProvider({
|
||||
attendeeId: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const toast = useToast()
|
||||
const navigate = useNavigate()
|
||||
const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false)
|
||||
const queryClient = useQueryClient()
|
||||
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||
const [isEditingContact, setIsEditingContact] = useState(false)
|
||||
|
||||
const groupQuery = useQuery({
|
||||
queryKey: ['group', groupId],
|
||||
@@ -54,16 +69,31 @@ export function AttendeeDetailProvider({
|
||||
enabled: Boolean(groupId && attendeeId),
|
||||
})
|
||||
|
||||
const attendeeStatsQuery = useQuery({
|
||||
queryKey: ['attendee-stats', groupId, attendeeId],
|
||||
queryFn: () => getAttendeeStats(groupId, attendeeId),
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (input: UpdateAttendee) => updateGroupAttendee(groupId, attendeeId, input),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.setQueryData<AttendeeDetailDto>(
|
||||
['group-attendee', groupId, attendeeId],
|
||||
(current) => (current ? { ...current, ...updated } : current),
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
},
|
||||
})
|
||||
|
||||
// Same key the analytics screen uses: both read the same history and do not
|
||||
// clobber each other's cache.
|
||||
const historyQuery = useQuery({
|
||||
queryKey: ['attendee-history', groupId, attendeeId],
|
||||
queryFn: () => getAttendeeHistory(groupId, attendeeId),
|
||||
enabled: Boolean(groupId && attendeeId),
|
||||
})
|
||||
|
||||
// The waitlist is only needed for the remove dialog, so it is not fetched
|
||||
// until the user opens it.
|
||||
const waitlistQuery = useQuery({
|
||||
queryKey: ['group-waitlist', groupId],
|
||||
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
||||
enabled: Boolean(groupId && isRemoveModalOpen),
|
||||
enabled: Boolean(groupId && isRemoveDialogOpen),
|
||||
})
|
||||
|
||||
const waitlistEntries = waitlistQuery.data?.data ?? []
|
||||
@@ -73,38 +103,38 @@ export function AttendeeDetailProvider({
|
||||
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
||||
groupId,
|
||||
onRemoved: () => {
|
||||
setIsRemoveModalOpen(false)
|
||||
setIsRemoveDialogOpen(false)
|
||||
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
||||
},
|
||||
})
|
||||
|
||||
const copyAbsenceNotifyUrl = (url: string) => {
|
||||
void navigator.clipboard.writeText(url).then(() => {
|
||||
toast.success('Link copiado al portapapeles.')
|
||||
})
|
||||
}
|
||||
|
||||
const value: AttendeeDetailContextValue = {
|
||||
groupId,
|
||||
groupName: groupQuery.data?.name,
|
||||
attendee: attendeeQuery.data,
|
||||
attendeePending: attendeeQuery.isPending,
|
||||
attendeeFailed: attendeeQuery.isError,
|
||||
attendeeStats: attendeeStatsQuery.data,
|
||||
attendeeStatsPending: attendeeStatsQuery.isPending,
|
||||
attendeeStatsFailed: attendeeStatsQuery.isError,
|
||||
history: historyQuery.data,
|
||||
historyPending: historyQuery.isPending,
|
||||
historyFailed: historyQuery.isError,
|
||||
firstWaitlistEntry,
|
||||
waitlistTotal,
|
||||
waitlistPending: waitlistQuery.isPending,
|
||||
isRemoveModalOpen,
|
||||
openRemoveModal: () => setIsRemoveModalOpen(true),
|
||||
closeRemoveModal: () => setIsRemoveModalOpen(false),
|
||||
isEditingContact,
|
||||
beginContactEdit: () => setIsEditingContact(true),
|
||||
endContactEdit: () => setIsEditingContact(false),
|
||||
saveAttendee: async (input) => {
|
||||
await updateMutation.mutateAsync(input)
|
||||
},
|
||||
isUpdatingAttendee: updateMutation.isPending,
|
||||
isRemoveDialogOpen,
|
||||
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
||||
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
||||
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||
if (!attendeeQuery.data) return
|
||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||
},
|
||||
isSubmittingRemoval: isRemovingAttendee,
|
||||
copyAbsenceNotifyUrl,
|
||||
}
|
||||
|
||||
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||
100
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
100
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { useRef } from 'react'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||
import { LargeTitle } from '../../components/layout/LargeTitle'
|
||||
import { Avatar, Badge, Button } from '../../components/ui'
|
||||
import { AbsenceLinkSection } from './AbsenceLinkSection'
|
||||
import { AttendeeActionsMenu } from './AttendeeActionsMenu'
|
||||
import { AttendeeAttendanceSection } from './AttendeeAttendanceSection'
|
||||
import { AttendeeContactActions } from './AttendeeContactActions'
|
||||
import { AttendeeContactSection } from './AttendeeContactSection'
|
||||
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
||||
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||
import { formatMemberSince } from './attendance'
|
||||
import { paymentPresentation } from './detail'
|
||||
|
||||
export function AttendeeDetailView() {
|
||||
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
|
||||
const navigate = useNavigate()
|
||||
const menuTriggerRef = useRef<HTMLButtonElement>(null)
|
||||
const payment = attendee ? paymentPresentation(attendee.payment) : null
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-md animate-fade-in lg:max-w-2xl">
|
||||
<LargeTitle
|
||||
title={attendee?.fullName ?? 'Miembro'}
|
||||
barContext={groupName ?? 'Grupo'}
|
||||
leading={
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId }}
|
||||
aria-label="Volver al grupo"
|
||||
className="relative z-10 inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
<ArrowLeft className="size-5" aria-hidden="true" />
|
||||
</Link>
|
||||
}
|
||||
barTrailing={<AttendeeActionsMenu triggerRef={menuTriggerRef} />}
|
||||
titleLeading={
|
||||
attendee ? (
|
||||
<Avatar
|
||||
name={attendee.fullName}
|
||||
className="size-14 rounded-full bg-accent-soft text-base text-accent-fg ring-1 ring-border"
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{attendee && payment ? (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2 text-sm text-secondary">
|
||||
<Badge variant={payment.isDue ? 'warning' : 'success'} className="text-[11px]">
|
||||
{payment.chipLabel}
|
||||
</Badge>
|
||||
<span>Desde {formatMemberSince(attendee.createdAt)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</LargeTitle>
|
||||
|
||||
{attendeePending ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{attendeeFailed || (!attendeePending && !attendee) ? (
|
||||
<div className="mt-6 rounded-2xl bg-danger-soft p-6">
|
||||
<h2 className="text-lg font-bold text-danger-fg">Miembro no encontrado</h2>
|
||||
<p className="mt-2 text-sm text-primary">
|
||||
No se pudo cargar la información de este miembro.
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
|
||||
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||
>
|
||||
Volver al grupo
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{attendee ? (
|
||||
<>
|
||||
<div className="mt-5">
|
||||
<AttendeeContactActions />
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<AttendeeContactSection />
|
||||
<AttendeePaymentsSection />
|
||||
<AttendeeAttendanceSection />
|
||||
<AttendeeNotesSection />
|
||||
<AbsenceLinkSection />
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
47
apps/web/src/features/attendee-detail/AttendeeNotesForm.tsx
Normal file
47
apps/web/src/features/attendee-detail/AttendeeNotesForm.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
|
||||
type AttendeeNotesFormProps = {
|
||||
draft: string
|
||||
error: string | null
|
||||
isSaving: boolean
|
||||
onDraftChange: (value: string) => void
|
||||
onCancel: () => void
|
||||
onSave: () => void
|
||||
}
|
||||
|
||||
export function AttendeeNotesForm({
|
||||
draft,
|
||||
error,
|
||||
isSaving,
|
||||
onDraftChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: AttendeeNotesFormProps) {
|
||||
return (
|
||||
<div className="space-y-3 px-3 pb-1">
|
||||
<textarea
|
||||
value={draft}
|
||||
onChange={(event) => onDraftChange(event.target.value)}
|
||||
rows={4}
|
||||
autoFocus
|
||||
aria-label="Notas del miembro"
|
||||
className="w-full resize-y rounded-xl border border-border bg-surface px-3 py-2.5 text-base leading-relaxed text-primary placeholder:text-secondary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 sm:text-sm"
|
||||
/>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-danger-fg">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
Guardar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react'
|
||||
import { AttendeeNotesForm } from './AttendeeNotesForm'
|
||||
import { formatNotesUpdatedAt } from './detail'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeeNotesSection() {
|
||||
const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail()
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
if (!attendee) return null
|
||||
|
||||
const beginEditing = () => {
|
||||
setDraft(attendee.notes ?? '')
|
||||
setError(null)
|
||||
setIsEditing(true)
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
try {
|
||||
await saveAttendee({ notes: draft })
|
||||
setIsEditing(false)
|
||||
} catch {
|
||||
setError('No pudimos guardar la nota. Revisá tu conexión e intentá de nuevo.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Section
|
||||
title="Notas"
|
||||
trailing={
|
||||
!isEditing ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={beginEditing}
|
||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
Editar
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{isEditing ? (
|
||||
<AttendeeNotesForm
|
||||
draft={draft}
|
||||
error={error}
|
||||
isSaving={isUpdatingAttendee}
|
||||
onDraftChange={(value) => {
|
||||
setDraft(value)
|
||||
setError(null)
|
||||
}}
|
||||
onCancel={() => {
|
||||
setIsEditing(false)
|
||||
setError(null)
|
||||
}}
|
||||
onSave={() => void save()}
|
||||
/>
|
||||
) : (
|
||||
<div className="px-3 pb-1">
|
||||
<p className="whitespace-pre-line text-sm leading-relaxed text-primary">
|
||||
{attendee.notes || 'Sin notas todavía.'}
|
||||
</p>
|
||||
<p className="mt-1.5 text-xs text-secondary">{formatNotesUpdatedAt(attendee.updatedAt)}</p>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Badge, useToast } from '../../components/ui'
|
||||
import { paymentPresentation } from './detail'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeePaymentsSection() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const toast = useToast()
|
||||
if (!attendee) return null
|
||||
|
||||
const payment = paymentPresentation(attendee.payment)
|
||||
|
||||
const registerPayment = () => {
|
||||
// TODO(cobros): conectar esta acción cuando se confirme el flujo y el endpoint de pagos.
|
||||
toast.info('Registrar pagos estará disponible cuando se defina el flujo de cobros.')
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title="Cobros">
|
||||
<div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-primary">
|
||||
{payment.periodLabel} · {payment.statusLabel}
|
||||
</p>
|
||||
<Badge variant={payment.isDue ? 'warning' : 'success'} className="mt-1.5 text-[11px]">
|
||||
{payment.chipLabel}
|
||||
</Badge>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={registerPayment}
|
||||
className="min-h-11 shrink-0 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
Registrar pago
|
||||
</button>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
45
apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx
Normal file
45
apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||
|
||||
/** The phone as the subtitle's second line.
|
||||
*
|
||||
* It used to live in a "Contacto" section with a single row that repeated the
|
||||
* number already visible behind the WhatsApp and Llamar buttons. Here it sits
|
||||
* next to "Miembro desde…", copies on one tap and is 44px tall even though the
|
||||
* text is 14px: it is a control, not decorative data. */
|
||||
export function AttendeePhoneLine() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const { copied, copy } = useCopyToClipboard()
|
||||
|
||||
const phone = attendee?.phone
|
||||
const label = formatPhoneDisplay(phone)
|
||||
if (!phone || !label) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(phone)}
|
||||
className="flex min-h-11 max-w-fit items-center gap-2 rounded-lg text-left transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
<span className="truncate text-sm text-foreground">{label}</span>
|
||||
{/* `aria-hidden`: the confirmation is announced from the live region
|
||||
below, so it does not sneak into the button's name. */}
|
||||
{copied ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="flex shrink-0 items-center gap-1 text-xs font-medium text-accent-fg"
|
||||
>
|
||||
<Check className="size-3.5" />
|
||||
Número copiado
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
<span aria-live="polite" className="sr-only">
|
||||
{copied ? 'Número copiado al portapapeles' : ''}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user