Compare commits
29 Commits
feat/atten
...
a93450579a
| Author | SHA1 | Date | |
|---|---|---|---|
| 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
|
||||||
38
.env.example
Normal file
38
.env.example
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# Plantilla de variables para `docker compose`.
|
||||||
|
#
|
||||||
|
# Local: copiá este archivo a `.env` en la raíz y completá los valores.
|
||||||
|
# Dokploy: no hace falta el archivo; definí las mismas variables en la pestaña
|
||||||
|
# Environment del servicio Compose (Dokploy las escribe en un `.env` al lado del
|
||||||
|
# compose, que es de donde salen los `${...}`).
|
||||||
|
|
||||||
|
# Origen público de la app, sin barra final. El mismo valor alimenta WEB_URL y
|
||||||
|
# BETTER_AUTH_URL porque nginx hace de proxy de /api: la web y la API comparten
|
||||||
|
# dominio y por lo tanto la cookie de sesión es first-party.
|
||||||
|
WEB_URL="http://localhost:8080"
|
||||||
|
|
||||||
|
# PostgreSQL de producción.
|
||||||
|
# La password va percent-encoded: si tiene #, @, :, /, ?, % o espacio, escapala
|
||||||
|
# (%23, %40, %3A, %2F, %3F, %25, %20). Sin eso Prisma corta la URL donde empieza
|
||||||
|
# el fragmento y falla con P1013 "invalid port number in database URL".
|
||||||
|
DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
|
||||||
|
|
||||||
|
# Generalo con: openssl rand -base64 32
|
||||||
|
BETTER_AUTH_SECRET=""
|
||||||
|
|
||||||
|
# ── Opcionales ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# Login social con Google. Sin client id/secret no se registra el provider.
|
||||||
|
# GOOGLE_CLIENT_ID=""
|
||||||
|
# GOOGLE_CLIENT_SECRET=""
|
||||||
|
|
||||||
|
# Envío de emails (mismas variables que 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>"
|
||||||
|
|
||||||
|
# Solo si querés la API en otro dominio: se hornea en el bundle de Vite y obliga
|
||||||
|
# a sacar el proxy /api de apps/web/nginx.conf. Vacío = mismo origen (recomendado).
|
||||||
|
# VITE_API_URL=""
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -90,6 +90,8 @@ out
|
|||||||
# Nuxt.js build / generate output
|
# Nuxt.js build / generate output
|
||||||
.nuxt
|
.nuxt
|
||||||
dist
|
dist
|
||||||
|
# Service worker que vite-plugin-pwa escribe al serving en dev
|
||||||
|
dev-dist
|
||||||
|
|
||||||
# Gatsby files
|
# Gatsby files
|
||||||
.cache/
|
.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.
|
||||||
11
AGENTS.md
11
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 typecheck # verificación de un solo paquete
|
||||||
bun --filter @gruperly/backend test # bun test (backend)
|
bun --filter @gruperly/backend test # bun test (backend)
|
||||||
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
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
|
## 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/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `src/logger.ts` — pino + pino-pretty.
|
||||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`).
|
- 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`).
|
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||||
|
|
||||||
@@ -40,7 +41,9 @@ 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`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||||
- `.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
|
## Convenciones repo-específicas
|
||||||
|
|
||||||
@@ -51,8 +54,10 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
|||||||
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
|
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
|
||||||
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
|
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
|
||||||
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
||||||
|
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
|
||||||
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
||||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||||
|
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
|
||||||
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
||||||
|
|
||||||
## Fuentes de contexto
|
## Fuentes de contexto
|
||||||
|
|||||||
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
|
||||||
|
|
||||||
|
# ─── Dependencias ────────────────────────────────────────────────────────────
|
||||||
|
# Solo los package.json:bun no necesita el código fuente para resolver el 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/
|
||||||
|
# El cache global de bun pesa ~370MB: se borra en la misma capa.
|
||||||
|
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# ─── Prisma Client ───────────────────────────────────────────────────────────
|
||||||
|
# El generator "prisma-client" emite TypeScript, así que el cliente generado se
|
||||||
|
# ejecuta con Bun sin compilar nada. La URL es un placeholder: `generate` no
|
||||||
|
# necesita conexión, solo leer el schema.
|
||||||
|
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
|
||||||
|
|
||||||
|
# ─── Imagen de la API ────────────────────────────────────────────────────────
|
||||||
|
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` y `dotenv` son dependencies (no dev) porque el entrypoint corre
|
||||||
|
# `prisma migrate deploy` en cada arranque. Con `--production` no entra el resto
|
||||||
|
# del tooling: biome, typescript, turbo.
|
||||||
|
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# El CLI de Prisma carga prisma.config.ts, que apunta al 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 se consume como fuente TS; @gruperly/config aporta el
|
||||||
|
# tsconfig base del que extiende el tsconfig del backend.
|
||||||
|
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
|
||||||
|
# Sin `${...}`: el CMD corre bajo /bin/sh (ash), donde eso es un error de sintaxis.
|
||||||
|
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 ejecuta el TypeScript directamente y resuelve `@/*` con el tsconfig.json,
|
||||||
|
# igual que `bun start` en local.
|
||||||
|
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
|
||||||
|
|
||||||
|
# ─── Dependencias ────────────────────────────────────────────────────────────
|
||||||
|
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/
|
||||||
|
# El cache global de bun pesa ~370MB: se borra en la misma capa.
|
||||||
|
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# ─── Build de Vite ───────────────────────────────────────────────────────────
|
||||||
|
FROM deps AS build
|
||||||
|
# Vite reemplaza import.meta.env.* en tiempo de build, no de runtime.
|
||||||
|
# Vacío = mismo origen: el proxy /api de nginx hace de 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
|
||||||
|
|
||||||
|
# ─── Imagen final ────────────────────────────────────────────────────────────
|
||||||
|
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;"]
|
||||||
87
README.md
87
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
|
- Package manager: [Bun](https://bun.sh/) 1.4
|
||||||
- Monorepo: bun workspaces + Turborepo
|
- Monorepo: bun workspaces + Turborepo
|
||||||
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
- 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
|
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
||||||
|
|
||||||
## Estructura
|
## 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 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:push # Aplica el esquema de Prisma a la base de datos
|
||||||
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
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
|
## Setup de base de datos
|
||||||
|
|
||||||
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
||||||
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
||||||
|
|
||||||
|
## 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
|
||||||
|
# Entrypoint de producción del backend: aplica las migraciones y levanta el
|
||||||
|
# servidor en el mismo contenedor.
|
||||||
|
#
|
||||||
|
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo
|
||||||
|
# serían ~10MB por un shebang).
|
||||||
|
#
|
||||||
|
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una
|
||||||
|
# base ya migrada a mano o una que se gestiona fuera de este despliegue).
|
||||||
|
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
|
||||||
|
|
||||||
|
# La base puede seguir arrancando cuando este contenedor ya empezó, y un
|
||||||
|
# deploy suele convivir con un reinicio de Postgres.
|
||||||
|
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 para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop`
|
||||||
|
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma).
|
||||||
|
exec "$@"
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
"lint:fix": "biome check . --write",
|
"lint:fix": "biome check . --write",
|
||||||
"db:generate": "prisma generate",
|
"db:generate": "prisma generate",
|
||||||
"db:migrate": "prisma migrate dev",
|
"db:migrate": "prisma migrate dev",
|
||||||
|
"db:deploy": "prisma migrate deploy",
|
||||||
"db:push": "prisma db push",
|
"db:push": "prisma db push",
|
||||||
"db:studio": "prisma studio"
|
"db:studio": "prisma studio"
|
||||||
},
|
},
|
||||||
@@ -23,10 +24,13 @@
|
|||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
"better-auth": "1.7.2",
|
"better-auth": "1.7.2",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
"hono": "^4.13.3",
|
"hono": "^4.13.3",
|
||||||
|
"nanoid": "^3.3.19",
|
||||||
"nodemailer": "^9.0.6",
|
"nodemailer": "^9.0.6",
|
||||||
"pino": "^9.5.0",
|
"pino": "^9.5.0",
|
||||||
"pino-pretty": "^13.0.0",
|
"pino-pretty": "^13.0.0",
|
||||||
|
"prisma": "^7.10.0",
|
||||||
"zod": "3.24.2"
|
"zod": "3.24.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -35,8 +39,6 @@
|
|||||||
"@types/bun": "^1.4.0",
|
"@types/bun": "^1.4.0",
|
||||||
"@types/node": "^20.17.0",
|
"@types/node": "^20.17.0",
|
||||||
"@types/nodemailer": "^8.0.1",
|
"@types/nodemailer": "^8.0.1",
|
||||||
"dotenv": "^16.4.5",
|
|
||||||
"prisma": "^7.10.0",
|
|
||||||
"typescript": "^5.7.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;
|
||||||
@@ -20,6 +20,7 @@ model Group {
|
|||||||
attendees Attendee[]
|
attendees Attendee[]
|
||||||
payments Payment[]
|
payments Payment[]
|
||||||
waitlist GroupWaitlistEntry[]
|
waitlist GroupWaitlistEntry[]
|
||||||
|
preRegistrations GroupPreRegistration[]
|
||||||
classSessions ClassSession[]
|
classSessions ClassSession[]
|
||||||
|
|
||||||
@@map("groups")
|
@@map("groups")
|
||||||
@@ -157,6 +158,30 @@ enum WaitlistStatus {
|
|||||||
DECLINED
|
DECLINED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum PreRegistrationStatus {
|
||||||
|
PENDING
|
||||||
|
APPROVED
|
||||||
|
REJECTED
|
||||||
|
}
|
||||||
|
|
||||||
|
model GroupPreRegistration {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
groupId String
|
||||||
|
fullName String
|
||||||
|
phone String
|
||||||
|
email String?
|
||||||
|
status PreRegistrationStatus @default(PENDING)
|
||||||
|
reviewedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([groupId, phone])
|
||||||
|
@@index([groupId])
|
||||||
|
@@map("group_pre_registrations")
|
||||||
|
}
|
||||||
|
|
||||||
enum PaymentProvider {
|
enum PaymentProvider {
|
||||||
MERCADO_PAGO
|
MERCADO_PAGO
|
||||||
STRIPE
|
STRIPE
|
||||||
|
|||||||
@@ -4,19 +4,30 @@ import type {
|
|||||||
GroupRiskLevel,
|
GroupRiskLevel,
|
||||||
GroupRiskSummary,
|
GroupRiskSummary,
|
||||||
GroupsRiskOverview,
|
GroupsRiskOverview,
|
||||||
|
MemberClassSession,
|
||||||
ProblemDetails,
|
ProblemDetails,
|
||||||
Result,
|
Result,
|
||||||
|
UrgentMemberSummary,
|
||||||
} from '@gruperly/shared';
|
} from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
import {
|
import {
|
||||||
classifyRisk,
|
classifyRisk,
|
||||||
|
MIN_RISK_ABSENCE_STREAK,
|
||||||
|
MIN_RISK_MONTHLY_RATE,
|
||||||
monthlyAttendanceRate,
|
monthlyAttendanceRate,
|
||||||
trailingAbsentStreak,
|
trailingAbsentStreak,
|
||||||
} from '../../lib/risk';
|
} from '../../lib/risk';
|
||||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||||
|
|
||||||
|
/* Cuántas clases se miran hacia atrás por alumno. Es el techo real del modelo:
|
||||||
|
los `class_sessions` no se crean solos, se materializan cuando alguien entra
|
||||||
|
a "clases de hoy", así que no tiene sentido traer años de filas. Con 20
|
||||||
|
clases alcanza para la racha, para la ventana de tendencia de 4+4 y para el
|
||||||
|
porcentaje de asistencia que muestra la tarjeta. */
|
||||||
|
const MEMBER_HISTORY_LIMIT = 20;
|
||||||
|
|
||||||
type GetGroupsRiskOverviewDeps = {
|
type GetGroupsRiskOverviewDeps = {
|
||||||
db?: {
|
db?: {
|
||||||
group: Prisma.GroupDelegate;
|
group: Prisma.GroupDelegate;
|
||||||
@@ -27,18 +38,26 @@ type GetGroupsRiskOverviewDeps = {
|
|||||||
now?: Date;
|
now?: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
type GroupRow = { id: string; name: string };
|
type GroupRow = {
|
||||||
type AttendeeRow = { id: string; groupId: string };
|
id: string;
|
||||||
type SessionRow = { id: string; groupId: string };
|
name: string;
|
||||||
|
capacity: number | null;
|
||||||
|
/** Los que todavía esperan cupo (`GroupWaitlistEntry` en PENDING). */
|
||||||
|
_count: { waitlist: number };
|
||||||
|
};
|
||||||
|
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
||||||
|
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||||
type AttendanceRow = {
|
type AttendanceRow = {
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
|
classSessionId: string;
|
||||||
status: AttendanceStatus;
|
status: AttendanceStatus;
|
||||||
classSession: { startsAt: Date };
|
classSession: { startsAt: Date };
|
||||||
};
|
};
|
||||||
|
|
||||||
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
|
// 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
|
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
|
||||||
// alguno en riesgo moderado y NONE en caso contrario.
|
// alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
|
||||||
|
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
|
||||||
export class GetGroupsRiskOverview {
|
export class GetGroupsRiskOverview {
|
||||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||||
|
|
||||||
@@ -49,30 +68,39 @@ export class GetGroupsRiskOverview {
|
|||||||
|
|
||||||
const groups = (await db.group.findMany({
|
const groups = (await db.group.findMany({
|
||||||
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
||||||
select: { id: true, name: true },
|
select: {
|
||||||
})) as GroupRow[];
|
id: true,
|
||||||
|
name: true,
|
||||||
|
capacity: true,
|
||||||
|
_count: { select: { waitlist: { where: { status: 'PENDING' } } } },
|
||||||
|
},
|
||||||
|
})) as unknown as GroupRow[];
|
||||||
|
|
||||||
if (groups.length === 0) {
|
if (groups.length === 0) {
|
||||||
return ok({ items: [] });
|
return ok({ items: [] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupIds = groups.map((group) => group.id);
|
const groupIds = groups.map((group) => group.id);
|
||||||
const attendeeGroup = new Map<string, string>();
|
|
||||||
const sessionCountByGroup = new Map<string, number>();
|
|
||||||
|
|
||||||
const [attendees, sessions, attendances] = await Promise.all([
|
const [attendees, sessions, attendances] = await Promise.all([
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||||
select: { id: true, groupId: true },
|
select: { id: true, groupId: true, fullName: true, createdAt: true },
|
||||||
}) as Promise<AttendeeRow[]>,
|
}) as Promise<AttendeeRow[]>,
|
||||||
db.classSession.findMany({
|
db.classSession.findMany({
|
||||||
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
|
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
|
||||||
select: { id: true, groupId: true },
|
select: { id: true, groupId: true, startsAt: true },
|
||||||
|
orderBy: { startsAt: 'desc' },
|
||||||
}) as Promise<SessionRow[]>,
|
}) as Promise<SessionRow[]>,
|
||||||
|
/* Sin filtro de fecha, como antes: la racha del semáforo cuenta sobre el
|
||||||
|
historial completo del alumno, no sobre la ventana mensual. Sin recorte
|
||||||
|
tampoco: el corte a las últimas 20 clases lo hace `memberSessions`,
|
||||||
|
sobre las clases del grupo y no sobre estas filas. */
|
||||||
db.attendance.findMany({
|
db.attendance.findMany({
|
||||||
where: { attendee: { groupId: { in: groupIds } } },
|
where: { attendee: { groupId: { in: groupIds } } },
|
||||||
select: {
|
select: {
|
||||||
attendeeId: true,
|
attendeeId: true,
|
||||||
|
classSessionId: true,
|
||||||
status: true,
|
status: true,
|
||||||
classSession: { select: { startsAt: true } },
|
classSession: { select: { startsAt: true } },
|
||||||
},
|
},
|
||||||
@@ -80,18 +108,24 @@ export class GetGroupsRiskOverview {
|
|||||||
}) as Promise<AttendanceRow[]>,
|
}) as Promise<AttendanceRow[]>,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (const attendee of attendees) {
|
const sessionsByGroup = new Map<string, SessionRow[]>();
|
||||||
attendeeGroup.set(attendee.id, attendee.groupId);
|
|
||||||
}
|
|
||||||
for (const session of sessions) {
|
for (const session of sessions) {
|
||||||
sessionCountByGroup.set(session.groupId, (sessionCountByGroup.get(session.groupId) ?? 0) + 1);
|
const list = sessionsByGroup.get(session.groupId) ?? [];
|
||||||
|
list.push(session);
|
||||||
|
sessionsByGroup.set(session.groupId, list);
|
||||||
}
|
}
|
||||||
|
|
||||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||||
|
|
||||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
||||||
|
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
|
||||||
|
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
|
||||||
|
// a racha y aun así quedan por debajo del mínimo de asistencia.
|
||||||
|
const absenceStreakCountByGroup = new Map<string, number>();
|
||||||
|
const lowAttendanceCountByGroup = new Map<string, number>();
|
||||||
|
|
||||||
for (const attendee of attendees) {
|
for (const attendee of attendees) {
|
||||||
const groupId = attendeeGroup.get(attendee.id)!;
|
const groupId = attendee.groupId;
|
||||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
||||||
status: row.status,
|
status: row.status,
|
||||||
occurredAt: row.classSession.startsAt,
|
occurredAt: row.classSession.startsAt,
|
||||||
@@ -99,13 +133,19 @@ export class GetGroupsRiskOverview {
|
|||||||
const streak = trailingAbsentStreak(stream);
|
const streak = trailingAbsentStreak(stream);
|
||||||
const monthlyRate = monthlyAttendanceRate(
|
const monthlyRate = monthlyAttendanceRate(
|
||||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
||||||
sessionCountByGroup.get(groupId) ?? 0,
|
sessionsByGroup.get(groupId)?.length ?? 0,
|
||||||
);
|
);
|
||||||
const riskLevel = classifyRisk(streak, monthlyRate);
|
const riskLevel = classifyRisk(streak, monthlyRate);
|
||||||
if (!riskLevel) {
|
if (!riskLevel) {
|
||||||
continue;
|
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';
|
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
|
||||||
if (
|
if (
|
||||||
riskLevel === 'HIGH' ||
|
riskLevel === 'HIGH' ||
|
||||||
@@ -119,12 +159,94 @@ export class GetGroupsRiskOverview {
|
|||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
groupName: group.name,
|
groupName: group.name,
|
||||||
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
|
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 });
|
return ok({ items });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El resumen por nivel que consumen la tarjeta del listado y la sección de
|
||||||
|
* seguimiento del Inicio. Sale de `getGroupAttendanceSummary`, la misma función
|
||||||
|
* de dominio que se prueba en `test/attendance-risk.test.ts`, para que la regla
|
||||||
|
* no tenga dos copias: una acá y otra en el cliente.
|
||||||
|
*
|
||||||
|
* `libres` y `enEspera` salen de acá y no del conteo de `Attendee`: el resumen
|
||||||
|
* cuenta los miembros del grupo y la tarjeta necesita los lugares del cupo
|
||||||
|
* para pintar el indicador.
|
||||||
|
*/
|
||||||
|
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) ?? [];
|
||||||
|
// Si el alumno tiene asistencias previas a su fecha de alta en la BD (ej.
|
||||||
|
// creado hoy pero con clases pasadas registradas), su fecha efectiva de
|
||||||
|
// incorporación es la de la primera clase a la que se le tomó asistencia.
|
||||||
|
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[]> {
|
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
||||||
const byAttendee = new Map<string, AttendanceRow[]>();
|
const byAttendee = new Map<string, AttendanceRow[]>();
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
@@ -133,4 +255,26 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
|||||||
byAttendee.set(row.attendeeId, list);
|
byAttendee.set(row.attendeeId, list);
|
||||||
}
|
}
|
||||||
return byAttendee;
|
return byAttendee;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* El universo de clases es el del grupo, no el de las filas de `Attendance`.
|
||||||
|
La asistencia se carga alumno por alumno y solo cuando alguien la marca, así
|
||||||
|
que "esta clase pasó y no hay registro de este alumno" es un estado real y
|
||||||
|
frecuente, no una falta. Si la lista se armara desde las filas de asistencia
|
||||||
|
esas clases no existirían y la racha no se cortaría: dos faltas separadas por
|
||||||
|
una clase sin marcar se contarían como tres seguidas.
|
||||||
|
El dominio ya las trata como neutras (`status: null`), así que acá solo hay
|
||||||
|
que elegir bien el universo y dejar el criterio en un solo lado.
|
||||||
|
`sessions` viene de más reciente a más antigua, así que quedarse con las
|
||||||
|
primeras `MEMBER_HISTORY_LIMIT` es quedarse con las clases recientes. El
|
||||||
|
recorte va por alumno y no global para que un grupo con mucha historia no le
|
||||||
|
robe ventana a los grupos que se listan después. */
|
||||||
|
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,
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,12 @@ export type AttendanceStreamEntry = {
|
|||||||
|
|
||||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
||||||
|
|
||||||
|
/** Racha mínima de faltas sin justificar que ya dispara riesgo. */
|
||||||
|
export const MIN_RISK_ABSENCE_STREAK = 2;
|
||||||
|
|
||||||
|
/** Asistencia mensual (ventana de 30 días) por debajo de la cual hay riesgo. */
|
||||||
|
export const MIN_RISK_MONTHLY_RATE = 50;
|
||||||
|
|
||||||
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
|
// 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.
|
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
|
||||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||||
@@ -46,10 +52,10 @@ export function classifyRisk(
|
|||||||
consecutiveAbsences: number,
|
consecutiveAbsences: number,
|
||||||
monthlyRate: number,
|
monthlyRate: number,
|
||||||
): RiskLevel | null {
|
): RiskLevel | null {
|
||||||
if (consecutiveAbsences >= 3) {
|
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
|
||||||
return 'HIGH';
|
return 'HIGH';
|
||||||
}
|
}
|
||||||
if (consecutiveAbsences === 2 || monthlyRate < 50) {
|
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
||||||
return 'MEDIUM';
|
return 'MEDIUM';
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
|
import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
|
||||||
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers';
|
import { toAttendeeListItemDto } from '../../lib/helpers';
|
||||||
|
|
||||||
type ListAttendeesDeps = {
|
type ListAttendeesDeps = {
|
||||||
db?: Pick<PrismaClient, 'attendee'>;
|
db?: Pick<PrismaClient, 'attendee'>;
|
||||||
@@ -18,18 +18,37 @@ export class ListAttendees {
|
|||||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||||
|
|
||||||
const [records, total] = await Promise.all([
|
const [records, total] = await Promise.all([
|
||||||
|
/* El resumen de cada fila viaja en la misma consulta en vez de armarse con
|
||||||
|
una petición por miembro. Ambas relaciones vienen acotadas a propósito:
|
||||||
|
la tabla de pagos crece un renglón por mes y para siempre, y el listado
|
||||||
|
solo necesita el estado actual de cada persona. */
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
...(where ? { where } : {}),
|
...(where ? { where } : {}),
|
||||||
skip: getPaginationOffset(query),
|
skip: getPaginationOffset(query),
|
||||||
take: query.pageSize,
|
take: query.pageSize,
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
|
include: {
|
||||||
|
// Por fecha de la clase, no por `markedAt`: marcar la asistencia
|
||||||
|
// tarde no debe cambiar qué clase cuenta como reciente.
|
||||||
|
attendances: {
|
||||||
|
orderBy: { classSession: { startsAt: 'desc' } },
|
||||||
|
take: RECENT_ATTENDANCE_LIMIT,
|
||||||
|
select: { status: true },
|
||||||
|
},
|
||||||
|
payments: {
|
||||||
|
where: { status: { not: 'CANCELLED' } },
|
||||||
|
orderBy: { dueDate: 'desc' },
|
||||||
|
take: 3,
|
||||||
|
select: { status: true, dueDate: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
where ? db.attendee.count({ where }) : db.attendee.count(),
|
where ? db.attendee.count({ where }) : db.attendee.count(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
data: records.map((r) => toAttendeeDto(r as AttendeeRecord)),
|
data: records.map((record) => toAttendeeListItemDto(record)),
|
||||||
pagination: getPaginationMetadata(query, total),
|
pagination: getPaginationMetadata(query, total),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { AttendeeDto } from '@gruperly/shared';
|
import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||||
|
|
||||||
export type AttendeeRecord = {
|
export type AttendeeRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -14,6 +14,15 @@ export type AttendeeRecord = {
|
|||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Item del listado con el resumen de asistencia y cobro ya resuelto. */
|
||||||
|
export type AttendeeListItemRecord = AttendeeRecord & {
|
||||||
|
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
|
||||||
|
payments: {
|
||||||
|
status: NonNullable<AttendeeListItem['payment']>['status'];
|
||||||
|
dueDate: Date;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||||
return {
|
return {
|
||||||
id: record.id,
|
id: record.id,
|
||||||
@@ -30,6 +39,37 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* El renglón que resume el cobro vigente. Si hay algo impago manda el de
|
||||||
|
vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos
|
||||||
|
días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada
|
||||||
|
impago, el último pago cerrado sirve para marcar la fila como al día. */
|
||||||
|
function pickRelevantPayment(
|
||||||
|
payments: AttendeeListItemRecord['payments'],
|
||||||
|
): AttendeeListItem['payment'] {
|
||||||
|
// CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos
|
||||||
|
// acá también evita que un cargo anulado gane la fila por ser el más antiguo.
|
||||||
|
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() };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* La consulta viene en orden descendente; la fila los muestra de más antigua a
|
||||||
|
más reciente para que el punto de la derecha sea el último hecho. */
|
||||||
|
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.
|
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
|
||||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||||
|
|||||||
@@ -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 { ok } from '@gruperly/shared';
|
||||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler';
|
||||||
import {
|
import {
|
||||||
buildGroupWhereForUser,
|
buildGroupWhereForUser,
|
||||||
type GroupDb,
|
type GroupDb,
|
||||||
type GroupRecord,
|
type GroupListRecord,
|
||||||
toGroupDto,
|
toGroupListItemDto,
|
||||||
} from '../../lib';
|
} from '../../lib';
|
||||||
|
|
||||||
type ListGroupsDeps = {
|
type ListGroupsDeps = {
|
||||||
db?: Pick<GroupDb, 'group'>;
|
db?: Pick<GroupDb, 'group'>;
|
||||||
|
now?: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const OCCUPANCY_COUNT_INCLUDE = {
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
// Miembros del grupo. Sin filtro de estado, igual que cuenta el detalle.
|
||||||
|
attendees: true,
|
||||||
|
// Lista de espera: los que todavía esperan cupo (los revisados salen).
|
||||||
|
waitlist: { where: { status: 'PENDING' as const } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies Prisma.GroupInclude;
|
||||||
|
|
||||||
export class ListGroups {
|
export class ListGroups {
|
||||||
constructor(private readonly deps: ListGroupsDeps = {}) {}
|
constructor(private readonly deps: ListGroupsDeps = {}) {}
|
||||||
|
|
||||||
@@ -27,21 +40,59 @@ export class ListGroups {
|
|||||||
userId: string,
|
userId: string,
|
||||||
): Promise<Result<GroupList, ProblemDetails>> {
|
): Promise<Result<GroupList, ProblemDetails>> {
|
||||||
const db = this.deps.db ?? prisma;
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
|
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
|
||||||
|
|
||||||
const [records, total] = await Promise.all([
|
// Traemos los grupos del usuario con sus contadores y los ordenamos acá:
|
||||||
db.group.findMany({
|
// la próxima clase se deriva de días + hora, no hay columna por la que
|
||||||
where,
|
// ordenar en la base. Es el mismo motor que usa el resumen de home, con la
|
||||||
skip: getPaginationOffset(query),
|
// zona horaria de la persona (o la del servidor si no viaja).
|
||||||
take: query.pageSize,
|
const records: GroupListRecord[] = await db.group.findMany({
|
||||||
orderBy: { createdAt: 'desc' },
|
where,
|
||||||
}),
|
include: OCCUPANCY_COUNT_INCLUDE,
|
||||||
db.group.count({ where }),
|
});
|
||||||
]);
|
|
||||||
|
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;
|
||||||
|
const withNextClass = records.map((record) => ({
|
||||||
|
record,
|
||||||
|
nextAt: nextOccurrenceAt(record, now, timeZone),
|
||||||
|
}));
|
||||||
|
|
||||||
|
/* Un grupo sin horario no tiene clase que comparar, así que va al final;
|
||||||
|
entre grupos con la misma clase (o sin horario) desempata el más nuevo,
|
||||||
|
que era el criterio anterior de la lista. */
|
||||||
|
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({
|
return ok({
|
||||||
data: records.map((record: GroupRecord) => toGroupDto(record)),
|
data: page.map(({ record }) => toGroupListItemDto(record)),
|
||||||
pagination: getPaginationMetadata(query, total),
|
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 { 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'>;
|
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
||||||
|
|
||||||
@@ -21,6 +21,14 @@ export type GroupRecord = {
|
|||||||
inviteToken?: string | null;
|
inviteToken?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* El listado suma los contadores de ocupación a cada grupo para que la card los
|
||||||
|
muestre sin pedir un endpoint por grupo. Los trae el `_count` de la misma
|
||||||
|
consulta: los miembros van todos (igual que cuenta el detalle) y la lista de
|
||||||
|
espera solo los que siguen esperando cupo (PENDING). */
|
||||||
|
export type GroupListRecord = GroupRecord & {
|
||||||
|
_count?: { attendees: number; waitlist: number };
|
||||||
|
};
|
||||||
|
|
||||||
export function toGroupDto(record: GroupRecord): GroupDto {
|
export function toGroupDto(record: GroupRecord): GroupDto {
|
||||||
return {
|
return {
|
||||||
id: record.id,
|
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) {
|
export function buildGroupWhereForUser(userId: string) {
|
||||||
return {
|
return {
|
||||||
OR: [
|
OR: [
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import createAttendeeRoute from '../attendees/features/create/route';
|
|||||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||||
|
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||||
import createGroupRoute from './features/create/route';
|
import createGroupRoute from './features/create/route';
|
||||||
import getAllRoute from './features/get-all/route';
|
import getAllRoute from './features/get-all/route';
|
||||||
@@ -24,6 +25,7 @@ routes.route('/', bulkCreateAttendeesRoute);
|
|||||||
routes.route('/', getByIdRoute);
|
routes.route('/', getByIdRoute);
|
||||||
routes.route('/', addToGroupWaitlistRoute);
|
routes.route('/', addToGroupWaitlistRoute);
|
||||||
routes.route('/', groupWaitlistRoutes);
|
routes.route('/', groupWaitlistRoutes);
|
||||||
|
routes.route('/', groupPreRegistrationRoutes);
|
||||||
routes.route('/', analyticsRoutes);
|
routes.route('/', analyticsRoutes);
|
||||||
routes.route('/', getAttendeeRoute);
|
routes.route('/', getAttendeeRoute);
|
||||||
routes.route('/', getAttendeeStatsRoute);
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
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 { err, ok } from '@gruperly/shared';
|
||||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||||
|
|
||||||
type JoinViaInviteDeps = {
|
type JoinViaInviteDeps = {
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type JoinViaInviteResult = {
|
export type JoinViaInviteResult = {
|
||||||
status: 'registered' | 'waitlisted';
|
status: 'pre_registered';
|
||||||
message: string;
|
message: string;
|
||||||
attendee: AttendeeDto | null;
|
attendee: null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class JoinViaInvite {
|
export class JoinViaInvite {
|
||||||
@@ -53,50 +53,63 @@ export class JoinViaInvite {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||||
|
const email = payload.email?.trim() || null;
|
||||||
|
|
||||||
if (group.capacity !== null) {
|
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||||
const currentCount = await db.attendee.count({
|
where: {
|
||||||
where: { groupId: group.id, status: 'ACTIVE' },
|
groupId: group.id,
|
||||||
|
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 },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (currentCount >= group.capacity) {
|
return ok({
|
||||||
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
|
status: 'pre_registered',
|
||||||
where: { groupId: group.id, phone },
|
attendee: null,
|
||||||
});
|
message:
|
||||||
|
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||||
if (!existingWaitlistEntry) {
|
});
|
||||||
await db.groupWaitlistEntry.create({
|
|
||||||
data: {
|
|
||||||
groupId: group.id,
|
|
||||||
fullName,
|
|
||||||
phone,
|
|
||||||
email: payload.email?.trim() || null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return ok({
|
|
||||||
status: 'waitlisted',
|
|
||||||
message:
|
|
||||||
'El grupo está completo. Fuiste agregado a la lista de espera. Te contactaremos cuando haya un lugar disponible.',
|
|
||||||
attendee: null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const created = await db.attendee.create({
|
if (existingPreRegistration) {
|
||||||
|
const message =
|
||||||
|
existingPreRegistration.status === 'APPROVED'
|
||||||
|
? 'Tu inscripción para este grupo ya fue aprobada.'
|
||||||
|
: 'Ya enviaste una solicitud de inscripción para este grupo. Está pendiente de revisión por el profesor.';
|
||||||
|
|
||||||
|
return err(
|
||||||
|
conflictProblem({
|
||||||
|
detail: message,
|
||||||
|
code:
|
||||||
|
existingPreRegistration.status === 'APPROVED'
|
||||||
|
? 'pre_registration_already_approved'
|
||||||
|
: 'pre_registration_already_pending',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.groupPreRegistration.create({
|
||||||
data: {
|
data: {
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
fullName,
|
fullName,
|
||||||
phone,
|
phone,
|
||||||
email: payload.email?.trim() || null,
|
email,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
status: 'registered',
|
status: 'pre_registered',
|
||||||
attendee: toAttendeeDto(created as unknown as AttendeeRecord),
|
attendee: null,
|
||||||
message: 'Inscripción realizada con éxito',
|
message:
|
||||||
|
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,39 +60,346 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => {
|
it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => {
|
||||||
prismaFetchGroupFindMany([
|
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
|
||||||
{ id: 'group-1', name: 'Funcional' },
|
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1'), attendee('a-2', 'group-2')]);
|
||||||
{ id: 'group-2', name: 'Yoga' },
|
|
||||||
]);
|
|
||||||
prismaFetchAttendeeFindMany([
|
|
||||||
{ id: 'a-1', groupId: 'group-1' },
|
|
||||||
{ id: 'a-2', groupId: 'group-2' },
|
|
||||||
]);
|
|
||||||
prismaFetchClassSessionFindMany([
|
prismaFetchClassSessionFindMany([
|
||||||
{ id: 's1', groupId: 'group-1', startsAt: at(-1) },
|
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||||
{ id: 's2', groupId: 'group-1', startsAt: at(-2) },
|
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||||
{ id: 's3', groupId: 'group-1', startsAt: at(-3) },
|
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||||
{ id: 's4', groupId: 'group-2', startsAt: at(-1) },
|
{ id: 's4', groupId: 'group-2', startsAt: at(1) },
|
||||||
]);
|
]);
|
||||||
prismaFetchAttendanceFindMany([
|
prismaFetchAttendanceFindMany([
|
||||||
attendance('a-1', 'ABSENT', at(-1)),
|
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||||
attendance('a-1', 'ABSENT', at(-2)),
|
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||||
attendance('a-1', 'ABSENT', at(-3)),
|
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||||
attendance('a-2', 'PRESENT', at(-1)),
|
attendance('a-2', 's4', 'PRESENT', at(1)),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(await res.json()).toEqual({
|
// `toMatchObject` porque el item ahora arrastra también el resumen por nivel
|
||||||
|
// que consume la tarjeta; acá se está probando el semáforo de siempre.
|
||||||
|
expect(await res.json()).toMatchObject({
|
||||||
items: [
|
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([
|
||||||
|
// Dos faltas seguidas: cuenta en el motivo de faltas.
|
||||||
|
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||||
|
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||||
|
attendance('a-1', 's3', 'PRESENT', at(3)),
|
||||||
|
// Sin racha, pero asiste menos de la mitad de las clases del mes.
|
||||||
|
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)),
|
||||||
|
// Al día.
|
||||||
|
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)),
|
||||||
|
// Otra vez por racha, en el otro grupo.
|
||||||
|
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,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/* Lo que consume la tarjeta del listado. El semáforo de arriba ya tenía sus
|
||||||
|
tests; lo que faltaba era fijar el payload nuevo contra el mismo endpoint,
|
||||||
|
porque es el contrato que el frontend lee. */
|
||||||
|
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) },
|
||||||
|
]);
|
||||||
|
// El mock ignora el `orderBy`, así que las filas van de la más reciente a la
|
||||||
|
// más antigua como las devolvería Prisma: de ese orden depende la racha.
|
||||||
|
// `at(n)` son n días hacia atrás; el resumen descarta lo que no ocurrió, así
|
||||||
|
// que las fechas tienen que estar en el pasado y no en el futuro.
|
||||||
|
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,
|
||||||
|
// El cupo es de 5 y hay 3 miembros, no 2: los lugares libres se calculan
|
||||||
|
// contra el cupo y no como "los que no tienen ninguna señal".
|
||||||
|
libres: 2,
|
||||||
|
enEspera: 2,
|
||||||
|
// Promedio de las tasas ya redondeadas por persona: 0, 33 y 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,
|
||||||
|
// Cuenta desde su última clase con presencia, no desde la más
|
||||||
|
// reciente del grupo: la suya fue hace 3 días.
|
||||||
|
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) },
|
||||||
|
]);
|
||||||
|
// Falta, clase sin marcar, falta. Leyendo solo las filas de `Attendance` esto
|
||||||
|
// parecería una racha de 2 y el grupo saldría en atención; la clase del medio
|
||||||
|
// pasó y no tiene registro, así que la racha real es de 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,
|
||||||
|
// Las dos clases con dato fueron falta; la del medio no entra al promedio.
|
||||||
|
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) },
|
||||||
|
]);
|
||||||
|
// La racha se cuenta hacia atrás desde la clase más reciente, así que llegan
|
||||||
|
// justo hasta el final: s1 y s2 pegadas, y la de hace 3 días sin registrar,
|
||||||
|
// que queda antes de la racha y no la toca.
|
||||||
|
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) },
|
||||||
|
]);
|
||||||
|
// Mismas dos faltas pegadas del caso anterior, pero la clase más reciente
|
||||||
|
// (s1) es la que no tiene registro. Como la racha se cuenta desde el final y
|
||||||
|
// "sin dato" no es ausencia, no hay racha: se ve la asimetría a propósito,
|
||||||
|
// porque es lo mismo que ya pasa con una clase justificada.
|
||||||
|
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)]);
|
||||||
|
// El alumno fue creado hoy (offset 0), pero tiene 3 faltas en clases de hace 7, 3 y 1 días.
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* El use-case pide `capacity` y el conteo de lista de espera para poder calcular
|
||||||
|
los lugares libres, y `fullName` + `createdAt` de cada alumno para el resumen
|
||||||
|
por nivel. Los fixtures los dan para que los tests viejos no tengan que
|
||||||
|
saber de eso. */
|
||||||
|
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[]) {
|
function prismaFetchGroupFindMany(rows: unknown[]) {
|
||||||
db.group.findMany.mockResolvedValue(rows);
|
db.group.findMany.mockResolvedValue(rows);
|
||||||
}
|
}
|
||||||
@@ -109,6 +416,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) {
|
|||||||
db.attendance.findMany.mockResolvedValue(rows);
|
db.attendance.findMany.mockResolvedValue(rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
function attendance(attendeeId: string, status: string, startsAt: string) {
|
/* El `classSessionId` importa: el resumen se arma cruzando las clases del grupo
|
||||||
return { attendeeId, status, classSession: { startsAt } };
|
con las filas de asistencia, y sin ese cruce toda clase quedaría sin registro
|
||||||
|
para todo el mundo. */
|
||||||
|
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
|
||||||
|
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
|
||||||
}
|
}
|
||||||
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';
|
||||||
|
|
||||||
|
/* La regla de riesgo es de negocio, no de pantalla: estos tests la fijan para
|
||||||
|
que cambiar un umbral o refactorizar el filtro de clases no mueva el
|
||||||
|
semáforo de la lista de grupos en silencio.
|
||||||
|
|
||||||
|
Dos helpers de armazón:
|
||||||
|
|
||||||
|
- `dense` mete las clases en días consecutivos, para que "hace cuánto no lo
|
||||||
|
vemos" quede siempre cerca y el caso aísle la regla que dice probar (una
|
||||||
|
clase por semana haría saltar el umbral de inactividad en casi todo).
|
||||||
|
- `series` respeta los offsets que se le pasan, para los casos que sí
|
||||||
|
necesitan huecos.
|
||||||
|
|
||||||
|
Todas las fechas se cuelgan de un `NOW` fijo: la función recibe el momento
|
||||||
|
como argumento justamente para poder testear sin reloj. */
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const NOW = new Date('2026-09-30T20:00:00.000Z');
|
||||||
|
|
||||||
|
/** Días hacia atrás desde `NOW`, en ISO. Negativo = clase futura. */
|
||||||
|
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
|
||||||
|
|
||||||
|
type Status = MemberClassSession['status'];
|
||||||
|
|
||||||
|
/** Clases en días consecutivos, de la más antigua a la más reciente. */
|
||||||
|
function dense(statuses: Status[]): MemberClassSession[] {
|
||||||
|
return statuses.map((status, index) => ({
|
||||||
|
sessionId: `ses_${statuses.length - index}`,
|
||||||
|
startsAt: daysAgo(statuses.length - index),
|
||||||
|
status,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clases con los offsets que se le pasen, en cualquier orden. */
|
||||||
|
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', () => {
|
||||||
|
// Asistió a las tres últimas y falta a las tres siguientes: nadie se está yendo.
|
||||||
|
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 días sin aparecer: el nivel viene de la racha, no del tiempo sin venir.
|
||||||
|
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', () => {
|
||||||
|
// Nunca asistió a una clase elegible: la referencia para "hace cuánto no lo
|
||||||
|
// vemos" es la última clase, así que no queda en verde para siempre.
|
||||||
|
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', () => {
|
||||||
|
// Una sola falta, la más reciente: la racha no llega. El nivel lo dispara
|
||||||
|
// el tiempo sin aparecer.
|
||||||
|
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;
|
||||||
|
// Dos faltas de racha: la atención le llega por la racha, y los 10 días
|
||||||
|
// justos no mueven el nivel.
|
||||||
|
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 clases con dato. Las 4 anteriores al 100%, las 4 últimas al 50%, y la
|
||||||
|
// más reciente es un PRESENT: racha 0 y asistencia reciente, así que la
|
||||||
|
// tendencia es lo único que puede disparar la alerta.
|
||||||
|
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', () => {
|
||||||
|
// Mismo caso que el anterior con una clase menos perdida en la ventana
|
||||||
|
// reciente: 3 de 4 contra 4 de 4. Es ruido, no una caída.
|
||||||
|
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 clases con dato: la ventana anterior quedaría con una sola, así que no
|
||||||
|
// hay contra qué comparar.
|
||||||
|
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
|
||||||
|
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la racha manda sobre la tendencia', () => {
|
||||||
|
// 16 clases: 4 anteriores al 100%, y las 4 últimas con 3 faltas seguidas
|
||||||
|
// una clase con presencia. La tendencia sola daría atención; las 3 faltas
|
||||||
|
// seguidas de punta dan riesgo alto, que es lo que tiene que ganar.
|
||||||
|
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', () => {
|
||||||
|
// Faltó, la de en medio no tiene registro, volvió a faltar. La racha real
|
||||||
|
// es de una, no de dos.
|
||||||
|
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', () => {
|
||||||
|
// Faltó, avisó, volvió a faltar: la racha es de una, y el promedio ignora la
|
||||||
|
// clase justificada en vez de contarla como asistencia o como falta.
|
||||||
|
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]]) },
|
||||||
|
// Recién Chess: sin clases con dato, no mueve el promedio.
|
||||||
|
{ attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] },
|
||||||
|
],
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(resumen.asistencia).toBe(75);
|
||||||
|
expect(resumen.ok).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||||
|
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
const db = {
|
const db = {
|
||||||
@@ -463,6 +464,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
|||||||
notes: null,
|
notes: null,
|
||||||
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
|
||||||
|
attendances: [],
|
||||||
|
payments: [],
|
||||||
},
|
},
|
||||||
] as never);
|
] as never);
|
||||||
prisma.attendee.count.mockResolvedValue(1);
|
prisma.attendee.count.mockResolvedValue(1);
|
||||||
@@ -474,11 +477,28 @@ describe('attendee incorporation & invite-token in groups', () => {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
expect(data.data.length).toBe(1);
|
expect(data.data.length).toBe(1);
|
||||||
expect(data.data[0].fullName).toBe('Ana García');
|
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({
|
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
|
||||||
where: { groupId: 'group-1' },
|
where: { groupId: 'group-1' },
|
||||||
skip: 0,
|
skip: 0,
|
||||||
take: 10,
|
take: 10,
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
|
// El resumen de la fila se pide en la misma consulta: una petición por
|
||||||
|
// miembro sería N+1 sobre un listado de hasta 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';
|
||||||
|
|
||||||
|
/* El resumen de la fila se arma en memoria: qué clase cuenta como reciente y
|
||||||
|
qué cobro se muestra. Son las dos decisiones que la fila leen. */
|
||||||
|
|
||||||
|
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({
|
||||||
|
// Llega de más reciente a más antigua.
|
||||||
|
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 { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||||
|
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
mock.module('@/lib/prisma', () => ({
|
mock.module('@/lib/prisma', () => ({
|
||||||
@@ -18,7 +19,7 @@ import { attendeesRoutes } from '@/modules/attendees';
|
|||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
app.route('/attendees', attendeesRoutes);
|
app.route('/attendees', attendeesRoutes);
|
||||||
|
|
||||||
const attendee = {
|
const attendeeRow = {
|
||||||
id: 'attendee-1',
|
id: 'attendee-1',
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
fullName: 'Ana Pérez',
|
fullName: 'Ana Pérez',
|
||||||
@@ -32,6 +33,13 @@ const attendee = {
|
|||||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Lo que devuelve el mock de Prisma: la fila más las relaciones del resumen.
|
||||||
|
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', () => {
|
describe('attendees routes', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
@@ -47,9 +55,13 @@ describe('attendees routes', () => {
|
|||||||
expect(await res.json()).toEqual({
|
expect(await res.json()).toEqual({
|
||||||
data: [
|
data: [
|
||||||
{
|
{
|
||||||
...attendee,
|
...attendeeRow,
|
||||||
createdAt: attendee.createdAt.toISOString(),
|
createdAt: attendeeRow.createdAt.toISOString(),
|
||||||
updatedAt: attendee.updatedAt.toISOString(),
|
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||||
|
// La consulta viene de más reciente a más antigua; la fila los
|
||||||
|
// muestra al revés, con la clase más reciente a la derecha.
|
||||||
|
recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'],
|
||||||
|
payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 },
|
pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 },
|
||||||
@@ -58,6 +70,19 @@ describe('attendees routes', () => {
|
|||||||
skip: 10,
|
skip: 10,
|
||||||
take: 10,
|
take: 10,
|
||||||
orderBy: { createdAt: 'desc' },
|
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();
|
expect(prisma.attendee.count).toHaveBeenCalledWith();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ mock.module('@/lib/prisma', () => ({
|
|||||||
|
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { groupsRoutes } from '@/modules/groups';
|
import { groupsRoutes } from '@/modules/groups';
|
||||||
|
import { ListGroups } from '@/modules/groups/features/get-all/use-case';
|
||||||
|
|
||||||
const userId = 'user-1';
|
const userId = 'user-1';
|
||||||
const group = {
|
const group = {
|
||||||
@@ -60,7 +61,9 @@ describe('groups routes', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('lists groups scoped to the current user', async () => {
|
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);
|
prisma.group.count.mockResolvedValue(1);
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups');
|
const res = await makeApp({ id: userId }).request('/groups');
|
||||||
@@ -72,6 +75,8 @@ describe('groups routes', () => {
|
|||||||
...group,
|
...group,
|
||||||
createdAt: group.createdAt.toISOString(),
|
createdAt: group.createdAt.toISOString(),
|
||||||
updatedAt: group.updatedAt.toISOString(),
|
updatedAt: group.updatedAt.toISOString(),
|
||||||
|
attendeesCount: 4,
|
||||||
|
waitlistCount: 1,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
||||||
@@ -79,13 +84,16 @@ describe('groups routes', () => {
|
|||||||
const where = {
|
const where = {
|
||||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||||
};
|
};
|
||||||
|
// Los contadores de ocupación viajan en la misma consulta; la lista de
|
||||||
|
// espera cuenta solo los PENDING, los que siguen esperando cupo.
|
||||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||||
where,
|
where,
|
||||||
skip: 0,
|
include: {
|
||||||
take: 10,
|
_count: {
|
||||||
orderBy: { createdAt: 'desc' },
|
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
expect(prisma.group.count).toHaveBeenCalledWith({ where });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects listing groups without a session', async () => {
|
it('rejects listing groups without a session', async () => {
|
||||||
@@ -101,6 +109,67 @@ describe('groups routes', () => {
|
|||||||
expect(res.status).toBe(400);
|
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'),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Lunes 2026-01-05 al mediodía en Ciudad de México: la clase de las 18:00
|
||||||
|
// todavía no empieza, así que ese grupo va primero.
|
||||||
|
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;
|
||||||
|
// A igual clase se pone delante el más nuevo, que era el criterio anterior.
|
||||||
|
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' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Lunes al mediodía: la clase de las 10:00 de A ya pasó, así que su
|
||||||
|
// próxima ocurrencia es el lunes que viene y B (miércoles) va primero.
|
||||||
|
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 () => {
|
it('creates a group with billing configuration', async () => {
|
||||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId });
|
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId });
|
||||||
prisma.group.create.mockResolvedValue({
|
prisma.group.create.mockResolvedValue({
|
||||||
|
|||||||
@@ -10,9 +10,10 @@ const db = {
|
|||||||
create: mock(),
|
create: mock(),
|
||||||
count: mock(),
|
count: mock(),
|
||||||
},
|
},
|
||||||
groupWaitlistEntry: {
|
groupPreRegistration: {
|
||||||
findFirst: mock(),
|
findFirst: mock(),
|
||||||
create: mock(),
|
create: mock(),
|
||||||
|
update: mock(),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,18 +84,18 @@ describe('public invitations routes', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('POST /invitations/:token/join', () => {
|
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.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
prisma.attendee.create.mockResolvedValue({
|
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||||
id: 'att-1',
|
prisma.groupPreRegistration.create.mockResolvedValue({
|
||||||
|
id: 'pre-1',
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
email: 'lucia@test.com',
|
email: 'lucia@test.com',
|
||||||
phone: '+5491122334455',
|
phone: '+5491122334455',
|
||||||
guardianName: null,
|
status: 'PENDING',
|
||||||
guardianPhone: null,
|
reviewedAt: null,
|
||||||
notes: null,
|
|
||||||
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
|
||||||
} as never);
|
} as never);
|
||||||
@@ -112,9 +113,11 @@ describe('public invitations routes', () => {
|
|||||||
|
|
||||||
expect(res.status).toBe(201);
|
expect(res.status).toBe(201);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.message).toBe('Inscripción realizada con éxito');
|
expect(body.status).toBe('pre_registered');
|
||||||
expect(body.attendee.fullName).toBe('Lucía Méndez');
|
expect(body.attendee).toBeNull();
|
||||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
expect(body.message).toContain('solicitud de inscripción');
|
||||||
|
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||||
|
expect(prisma.groupPreRegistration.create).toHaveBeenCalledWith({
|
||||||
data: {
|
data: {
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
@@ -141,7 +144,7 @@ describe('public invitations routes', () => {
|
|||||||
expect(res.status).toBe(409);
|
expect(res.status).toBe(409);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.code).toBe('attendee_already_registered');
|
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 () => {
|
it('rejects invalid inputs (missing required name/phone)', async () => {
|
||||||
@@ -157,21 +160,67 @@ describe('public invitations routes', () => {
|
|||||||
expect(res.status).toBe(400);
|
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.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
prisma.attendee.count.mockResolvedValue(15); // capacity full
|
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
id: 'pre-1',
|
||||||
prisma.groupWaitlistEntry.create.mockResolvedValue({
|
status: 'PENDING',
|
||||||
id: 'wl-1',
|
} 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',
|
groupId: 'group-1',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
phone: '+5491122334455',
|
phone: '+5491122334455',
|
||||||
email: 'lucia@test.com',
|
status: 'REJECTED',
|
||||||
notes: null,
|
reviewedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||||
status: 'PENDING',
|
|
||||||
createdAt: new Date('2026-09-18T10: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);
|
} as never);
|
||||||
|
|
||||||
const res = await app.request('/invitations/valid-token-123/join', {
|
const res = await app.request('/invitations/valid-token-123/join', {
|
||||||
@@ -187,15 +236,15 @@ describe('public invitations routes', () => {
|
|||||||
|
|
||||||
expect(res.status).toBe(201);
|
expect(res.status).toBe(201);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.status).toBe('waitlisted');
|
expect(body.status).toBe('pre_registered');
|
||||||
expect(body.attendee).toBeNull();
|
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
where: { id: 'pre-1' },
|
||||||
data: {
|
data: {
|
||||||
groupId: 'group-1',
|
status: 'PENDING',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
phone: '+5491122334455',
|
|
||||||
email: 'lucia@test.com',
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,16 +2,19 @@
|
|||||||
<html lang="es">
|
<html lang="es">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<!-- viewport-fit=cover habilita env(safe-area-inset-*) en iOS standalone. -->
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
<title>Gruperly</title>
|
<title>Gruperly</title>
|
||||||
|
<meta name="description" content="Gestión de cobros grupales" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180.png" />
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
<!-- iOS standalone: sin esto la app abre en un pestaña de Safari. -->
|
||||||
<link
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
rel="stylesheet"
|
<meta name="apple-mobile-web-app-title" content="Gruperly" />
|
||||||
/>
|
|
||||||
|
<meta name="theme-color" id="theme-color" content="#ffffff" />
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
try {
|
try {
|
||||||
@@ -19,7 +22,11 @@
|
|||||||
var isDark =
|
var isDark =
|
||||||
stored === 'dark' ||
|
stored === 'dark' ||
|
||||||
(stored !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
(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) {}
|
} catch (e) {}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
@@ -28,4 +35,4 @@
|
|||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
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",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit"
|
"icons": "bun run scripts/generate-icons.ts",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@better-auth/passkey": "^1.7.2",
|
"@better-auth/passkey": "^1.7.2",
|
||||||
|
"@fontsource-variable/inter": "^5.3.0",
|
||||||
"@gruperly/shared": "workspace:*",
|
"@gruperly/shared": "workspace:*",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@tanstack/react-query": "^5.62.0",
|
"@tanstack/react-query": "^5.62.0",
|
||||||
@@ -31,8 +34,11 @@
|
|||||||
"@types/react": "^19.0.0",
|
"@types/react": "^19.0.0",
|
||||||
"@types/react-dom": "^19.0.0",
|
"@types/react-dom": "^19.0.0",
|
||||||
"@vitejs/plugin-react": "^4.3.0",
|
"@vitejs/plugin-react": "^4.3.0",
|
||||||
|
"sharp": "^0.35.4",
|
||||||
"tailwindcss": "^4.0.0",
|
"tailwindcss": "^4.0.0",
|
||||||
"typescript": "^5.7.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 @@
|
|||||||
|
/**
|
||||||
|
* Genera el set de iconos PWA desde el isotipo SVG de marca.
|
||||||
|
*
|
||||||
|
* Uso: bun --filter @gruperly/web icons
|
||||||
|
*
|
||||||
|
* Las salidas se versionan en `public/`; el build de Vite no las regenera
|
||||||
|
* (sharp es una devDependency y no debe entrar en la imagen de Docker).
|
||||||
|
* Re-correr solo cuando cambia `src/assets/brand/isotipo-y-organica.svg`.
|
||||||
|
*/
|
||||||
|
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')
|
||||||
|
|
||||||
|
/** Fondo del tema claro; también sirve de lienzo para los iconos opacos. */
|
||||||
|
const BACKGROUND = '#ffffff'
|
||||||
|
const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const
|
||||||
|
|
||||||
|
type IconTarget = {
|
||||||
|
file: string
|
||||||
|
size: number
|
||||||
|
/** Rellena el lienzo con `BACKGROUND` en vez de dejar transparencia. */
|
||||||
|
opaque: boolean
|
||||||
|
/** Fracción del lado que ocupa el logo. 1 = sin 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 recorta los iconos adaptativos en círculo: el contenido útil
|
||||||
|
// vive en el 80% central del canvas, así que el logo va over white y escalado.
|
||||||
|
{ 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 },
|
||||||
|
]
|
||||||
|
|
||||||
|
// El viewBox del isotipo no arranca en 0 y deja aire alrededor del glifo:
|
||||||
|
// `trim` recorta ese margen para que el encuadre use el área real del dibujo.
|
||||||
|
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 { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function BottomNav() {
|
export function BottomNav() {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
|
|
||||||
return (
|
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">
|
<div className="mx-auto grid max-w-md grid-cols-4">
|
||||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||||
const isActive = location.pathname === to
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={to}
|
key={to}
|
||||||
to={to}
|
to={to}
|
||||||
|
aria-current={isActive ? 'page' : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex flex-col items-center gap-0.5 py-2.5 text-[11px] font-medium transition-colors',
|
'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/50 hover:text-primary',
|
isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon
|
{/* Pastilla suave detrás del ícono: el estado activo se lee por
|
||||||
className={cn('size-6', isActive && 'fill-accent/15 stroke-accent')}
|
color + fondo, no solo por el tono del texto. */}
|
||||||
strokeWidth={isActive ? 2.2 : 2}
|
<span
|
||||||
/>
|
className={cn(
|
||||||
{label}
|
'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>
|
</Link>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
import { Breadcrumb } from './Breadcrumb'
|
import { Breadcrumb } from './Breadcrumb'
|
||||||
import { ThemeToggle } from './ThemeToggle'
|
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">
|
<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="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">
|
<div className="flex min-w-0 items-center">
|
||||||
<a href="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
{/* `Link` y no `<a>`: en mobile el logo es la única forma de volver al
|
||||||
|
inicio y un anchor recargaría el documento entero, perdiendo el
|
||||||
|
estado en memoria (cache de React Query, evento de instalación). */}
|
||||||
|
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
||||||
<Logo className="h-8" />
|
<Logo className="h-8" />
|
||||||
</a>
|
</Link>
|
||||||
<Breadcrumb />
|
<Breadcrumb />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
|||||||
82
apps/web/src/components/layout/LargeTitle.tsx
Normal file
82
apps/web/src/components/layout/LargeTitle.tsx
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { createPortal } from 'react-dom'
|
||||||
|
import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
||||||
|
import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse'
|
||||||
|
|
||||||
|
type LargeTitleProps = {
|
||||||
|
/** Texto del título. Es el mismo en el grande y en el de la barra: el `h1`
|
||||||
|
* real es el grande, el de la barra es un duplicado visual. */
|
||||||
|
title: string
|
||||||
|
/** Acción a la izquierda de la barra. En desktop es el link "volver" que
|
||||||
|
* antes vivía en el cuerpo de la pantalla; en mobile se oculta. */
|
||||||
|
leading?: ReactNode
|
||||||
|
/** Contexto que no puede desaparecer al scrollear (ej. el contador de
|
||||||
|
* presentes). Viaja a la barra y se funde con el título. */
|
||||||
|
barTrailing?: ReactNode
|
||||||
|
/** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */
|
||||||
|
children?: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encabezado de pantalla con Large Title (patrón de iOS): el título arranca
|
||||||
|
* grande y al scrollear se desliza debajo de la barra, que se opaca y recibe
|
||||||
|
* el título en versión chica.
|
||||||
|
*
|
||||||
|
* El título grande es un bloque normal en el flujo; la barra vive en una caja
|
||||||
|
* sticky que el layout monta arriba de `<main>` (ver `ImmersiveBarHost`), así
|
||||||
|
* el contenido se desliza por debajo sin márgenes negativos ni `fixed` que
|
||||||
|
* haya que compensar en desktop.
|
||||||
|
*
|
||||||
|
* El estado del scroll vive acá adentro a propósito: `children` llega como prop
|
||||||
|
* ya construido, así React reutiliza los elementos y el subtree de abajo no se
|
||||||
|
* re-renderiza en cada frame de scroll.
|
||||||
|
*/
|
||||||
|
export function LargeTitle({ title, leading, 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">
|
||||||
|
{/* El fondo va en una capa propia: se opaca con el scroll mientras
|
||||||
|
el título entra, y `leading` (el link "volver") no puede
|
||||||
|
fundirse con él porque existe siempre. */}
|
||||||
|
<div
|
||||||
|
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
|
||||||
|
style={{ opacity: progress }}
|
||||||
|
/>
|
||||||
|
{leading}
|
||||||
|
<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>
|
||||||
|
{barTrailing ? (
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="relative flex shrink-0 items-center"
|
||||||
|
style={{ opacity: progress }}
|
||||||
|
>
|
||||||
|
{barTrailing}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>,
|
||||||
|
barHost,
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
<h1
|
||||||
|
ref={titleRef}
|
||||||
|
className="text-balance text-[2.125rem] font-bold leading-[1.1] tracking-tight text-primary sm:text-[2.5rem]"
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,17 +1,39 @@
|
|||||||
|
import { useLocation } from '@tanstack/react-router'
|
||||||
import type { ReactNode } from 'react'
|
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 { Header } from './Header'
|
||||||
import { Sidebar } from './Sidebar'
|
import { Sidebar } from './Sidebar'
|
||||||
import { BottomNav } from './BottomNav'
|
import { BottomNav } from './BottomNav'
|
||||||
|
|
||||||
export function RootLayout({ children }: { children: ReactNode }) {
|
export function RootLayout({ children }: { children: ReactNode }) {
|
||||||
|
const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) })
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh w-full">
|
<div className="min-h-dvh w-full">
|
||||||
<Header />
|
{/* En las rutas immersive la pantalla trae su propia barra (LargeTitle),
|
||||||
|
con el logo y el nombre del grupo: el header global con logo + tema +
|
||||||
|
avatar sería una segunda barra compitiendo por los mismos píxeles. */}
|
||||||
|
{immersive ? null : <Header />}
|
||||||
|
|
||||||
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
<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 en immersive: el padding superior lo aporta la caja de la
|
||||||
|
barra, y si no el título grande arrancaría 16px más abajo de la
|
||||||
|
base de la barra y el colapso se mediría corrido. */}
|
||||||
|
<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>
|
</div>
|
||||||
|
|
||||||
<BottomNav />
|
<BottomNav />
|
||||||
|
|||||||
@@ -1,29 +1,40 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { Logo } from '../brand'
|
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()
|
const location = useLocation()
|
||||||
|
|
||||||
return (
|
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">
|
// Sin header global no hay nada que esquive arriba: la columna del sidebar
|
||||||
<a href="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
// pasa a ocupar la ventana completa y queda a la altura de la barra de
|
||||||
|
// LargeTitle.
|
||||||
|
<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` y no `<a>`: un anchor recargaría el documento y perdería el
|
||||||
|
estado en memoria (cache de React Query, evento de instalación). */}
|
||||||
|
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
||||||
<Logo className="h-10" />
|
<Logo className="h-10" />
|
||||||
</a>
|
</Link>
|
||||||
|
|
||||||
<nav className="flex flex-col gap-1">
|
<nav className="flex flex-col gap-1">
|
||||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||||
const isActive = location.pathname === to
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={to}
|
key={to}
|
||||||
to={to}
|
to={to}
|
||||||
|
aria-current={isActive ? 'page' : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
|
'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
|
||||||
isActive
|
isActive
|
||||||
? 'bg-accent-soft text-accent-fg'
|
? '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} />
|
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
export { RootLayout } from './RootLayout'
|
export { RootLayout } from './RootLayout'
|
||||||
export { Header } from './Header'
|
export { Header } from './Header'
|
||||||
|
export { LargeTitle } from './LargeTitle'
|
||||||
export { ThemeToggle } from './ThemeToggle'
|
export { ThemeToggle } from './ThemeToggle'
|
||||||
export { PublicHeader } from './PublicHeader'
|
export { PublicHeader } from './PublicHeader'
|
||||||
export { PublicFooter } from './PublicFooter'
|
export { PublicFooter } from './PublicFooter'
|
||||||
|
|||||||
@@ -12,3 +12,12 @@ export const NAV_ITEMS: NavItem[] = [
|
|||||||
{ label: 'Cobros', to: '/payments', icon: Wallet },
|
{ label: 'Cobros', to: '/payments', icon: Wallet },
|
||||||
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/** Una sección sigue activa dentro de sus subrutas: en `/groups/abc` el ítem
|
||||||
|
* activo es "Grupos", no ninguno. El prefijo se corta en el separador para
|
||||||
|
* que `/groupsomething` no se considere "/groups". La raíz es exacta: no hay
|
||||||
|
* subrutas del home que deban marcarla. */
|
||||||
|
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 { forwardRef, type HTMLAttributes } from 'react'
|
||||||
import { cn } from '../../lib/utils'
|
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> & {
|
export type BadgeProps = HTMLAttributes<HTMLSpanElement> & {
|
||||||
variant?: BadgeVariant
|
variant?: BadgeVariant
|
||||||
@@ -12,6 +12,11 @@ const variants: Record<BadgeVariant, string> = {
|
|||||||
warning: 'bg-warning-soft text-warning',
|
warning: 'bg-warning-soft text-warning',
|
||||||
danger: 'bg-danger-soft text-danger',
|
danger: 'bg-danger-soft text-danger',
|
||||||
neutral: 'bg-primary-soft text-primary',
|
neutral: 'bg-primary-soft text-primary',
|
||||||
|
/* Estado informativo que no es alerta: lista de espera, cupos libres. Usa la
|
||||||
|
tinta de acento legible (`accent-fg` es el azul claro en tema oscuro,
|
||||||
|
7.1:1 sobre la tarjeta) y no el `accent` directo, que en oscuro da 2.2:1
|
||||||
|
y no alcanza el mínimo de 3:1 para contenido no textual. */
|
||||||
|
info: 'bg-accent-soft text-accent-fg',
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
||||||
@@ -20,7 +25,7 @@ export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
|||||||
<span
|
<span
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
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],
|
variants[variant],
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -28,7 +28,10 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
type={type}
|
type={type}
|
||||||
className={cn(
|
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',
|
// `transition-*` explícito en vez de `transition-all`: solo se animan
|
||||||
|
// color, fondo, borde y transform. El feedback de presión se anula
|
||||||
|
// con `motion-reduce` para respetar 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],
|
variants[variant],
|
||||||
sizes[size],
|
sizes[size],
|
||||||
className,
|
className,
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
export { Avatar, type AvatarProps } from './avatar'
|
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 { Badge, type BadgeProps, type BadgeVariant } from './badge'
|
||||||
|
export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './button'
|
||||||
export { Input, type InputProps } from './input'
|
export { Input, type InputProps } from './input'
|
||||||
export { Label, type LabelProps } from './label'
|
export { Label, type LabelProps } from './label'
|
||||||
export { Modal, type ModalProps } from './modal'
|
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
|
<input
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
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) en mobile: iOS auto-zoomea al enfocar controles con
|
||||||
|
// font-size < 16px y, al cerrar el teclado, no restaura el scale.
|
||||||
|
'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',
|
invalid && 'border-danger focus:border-danger focus:ring-danger/30',
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
|
|||||||
67
apps/web/src/components/ui/tooltip.tsx
Normal file
67
apps/web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { type ReactNode, useId, useState } from 'react'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
|
export type TooltipProps = {
|
||||||
|
/** Texto explicativo que se muestra al hacer hover, foco de teclado o tap. */
|
||||||
|
content: ReactNode
|
||||||
|
/** Contenido del disparador. Queda dentro de un <button> para ser accesible. */
|
||||||
|
children: ReactNode
|
||||||
|
className?: string
|
||||||
|
/** Posicionamiento alternativo del globo (por defecto: abajo, anclado a la derecha en sm+). */
|
||||||
|
tooltipClassName?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tooltip accesible sin dependencias: hover (ratón), foco (teclado) y tap
|
||||||
|
* (táctil, vía focus). Se cierra con Escape, al salir el puntero o al perder
|
||||||
|
* el foco. El globo se ancla abajo del disparador para no tapar el contenido.
|
||||||
|
*/
|
||||||
|
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}
|
||||||
|
// El hover solo aplica a punteros de ratón: en táctil no hay "hover
|
||||||
|
// persistente" y el tap se resuelve con 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'
|
||||||
|
|
||||||
|
/* Las pantallas "immersive" (ficha de grupo y asistencia) arman su propia barra
|
||||||
|
de título en vez de usar el header global, pero la barra tiene que ser hija
|
||||||
|
directa de `<main>`: un `sticky` solo se pega mientras su caja padre esté en
|
||||||
|
pantalla, y el padre natural de la barra (el bloque del feature) es corto, así
|
||||||
|
que se despegaría a los ~200px de scroll.
|
||||||
|
|
||||||
|
Este provider expone una caja fija de 56px clavada arriba de `<main>` donde la
|
||||||
|
pantalla monta su barra. La caja la dibuja el layout (para que ocupe su lugar
|
||||||
|
desde el primer render) y su contenido lo aporta la pantalla. */
|
||||||
|
|
||||||
|
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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Caja de la barra: primer hijo de `<main>`, en las rutas immersive. */
|
||||||
|
export function ImmersiveBarHost() {
|
||||||
|
const { hostRef } = useContext(ImmersiveBarContext)
|
||||||
|
|
||||||
|
return <div ref={hostRef} className="sticky top-0 z-40 -mx-4 h-14 lg:mx-0" />
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Destino del portal de `LargeTitle`; `null` si la pantalla no es immersive. */
|
||||||
|
export function useImmersiveBarHost() {
|
||||||
|
return useContext(ImmersiveBarContext).host
|
||||||
|
}
|
||||||
@@ -18,6 +18,10 @@ type ThemeContextValue = {
|
|||||||
|
|
||||||
const STORAGE_KEY = 'theme'
|
const STORAGE_KEY = 'theme'
|
||||||
|
|
||||||
|
/** Colores de la barra de estado en modo standalone. Debe matchear index.css. */
|
||||||
|
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
|
||||||
|
const THEME_COLOR_META_ID = 'theme-color'
|
||||||
|
|
||||||
function readStoredTheme(): Theme {
|
function readStoredTheme(): Theme {
|
||||||
const value = localStorage.getItem(STORAGE_KEY)
|
const value = localStorage.getItem(STORAGE_KEY)
|
||||||
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
||||||
@@ -41,9 +45,16 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const update = () => {
|
const update = () => {
|
||||||
document.documentElement.classList.toggle('dark', resolveDark(theme))
|
const dark = resolveDark(theme)
|
||||||
setIsDark(document.documentElement.classList.contains('dark'))
|
document.documentElement.classList.toggle('dark', dark)
|
||||||
|
setIsDark(dark)
|
||||||
localStorage.setItem(STORAGE_KEY, theme)
|
localStorage.setItem(STORAGE_KEY, theme)
|
||||||
|
|
||||||
|
// En standalone la barra de estado se pinta con theme-color; sin esto
|
||||||
|
// queda congelada en el valor que puso el script inline de index.html.
|
||||||
|
document
|
||||||
|
.getElementById(THEME_COLOR_META_ID)
|
||||||
|
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)
|
||||||
}
|
}
|
||||||
update()
|
update()
|
||||||
|
|
||||||
|
|||||||
77
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
77
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
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"
|
||||||
|
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
|
||||||
|
>
|
||||||
|
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y
|
||||||
|
el texto de "Link copiado" no se pierde al plegar y desplegar. */}
|
||||||
|
<div id={panelId} hidden={!isOpen}>
|
||||||
|
<p className="px-3 text-sm text-foreground">
|
||||||
|
Mandales este link para que avisen cuando no puedan venir.
|
||||||
|
</p>
|
||||||
|
{/* Apiladas y a ancho completo: al 50% los rótulos ("Enviar por WhatsApp")
|
||||||
|
se partían en dos líneas y quedaban por debajo del mínimo táctil.
|
||||||
|
Copiar queda arriba, pegado a su confirmación, y la acción principal
|
||||||
|
se distingue por el relleno de acento. */}
|
||||||
|
<div className="mt-2.5 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
120
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
120
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
import { useEffect, useId, useRef, useState } from 'react'
|
||||||
|
import type { KeyboardEvent, RefObject } from 'react'
|
||||||
|
import { Ellipsis, UserMinus } from 'lucide-react'
|
||||||
|
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-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
|
|
||||||
|
/** Menú "⋯" de la ficha del miembro.
|
||||||
|
*
|
||||||
|
* Por ahora solo guarda "Quitar del grupo": el backend no tiene forma de
|
||||||
|
* regenerar el token de ausencias, así que la opción no se muestra antes que
|
||||||
|
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo
|
||||||
|
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la
|
||||||
|
* lista de abajo.
|
||||||
|
*
|
||||||
|
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo
|
||||||
|
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */
|
||||||
|
export function AttendeeActionsMenu({
|
||||||
|
triggerRef,
|
||||||
|
}: {
|
||||||
|
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el
|
||||||
|
* foco cuando se cierra. */
|
||||||
|
triggerRef: RefObject<HTMLButtonElement | null>
|
||||||
|
}) {
|
||||||
|
const { openRemoveDialog } = useAttendeeDetail()
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
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={() => {
|
||||||
|
close()
|
||||||
|
openRemoveDialog()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<UserMinus className="size-4 shrink-0 text-danger" aria-hidden="true" />
|
||||||
|
Quitar del grupo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
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>
|
||||||
|
|
||||||
|
{/* Las clases sin registro no son ausencias: se avisa aparte y en voz baja
|
||||||
|
para que el "1 de 1" de arriba no se lea como un fallo. */}
|
||||||
|
{summary.unmarkedLabel ? (
|
||||||
|
<p className="px-3 pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{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,42 @@
|
|||||||
|
import { MessageCircle, Phone } from 'lucide-react'
|
||||||
|
import { formatPhoneDisplay } from '../../lib/format'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import { ACTION_BUTTON_CLASS } from './actionButton'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
export function AttendeeContactActions() {
|
||||||
|
const { attendee } = useAttendeeDetail()
|
||||||
|
|
||||||
|
const phone = attendee?.phone
|
||||||
|
if (!phone) return null
|
||||||
|
|
||||||
|
// Los links van con los dígitos crudos: wa.me y tel: no entienden formatos.
|
||||||
|
const digits = phone.replace(/\D/g, '')
|
||||||
|
const label = formatPhoneDisplay(phone) ?? phone
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex gap-2.5">
|
||||||
|
{/* Los íconos van con `accent-fg` y no con `accent`: el azul de `accent` es
|
||||||
|
el mismo en los dos temas y sobre `primary-soft` oscuro queda en 2.2:1.
|
||||||
|
`accent-fg` da 6.2:1 en claro y 7.1:1 en oscuro. */}
|
||||||
|
<a
|
||||||
|
href={`https://wa.me/${digits}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
aria-label={`Abrir WhatsApp con ${label}`}
|
||||||
|
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-4 text-accent-fg" aria-hidden="true" />
|
||||||
|
WhatsApp
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={`tel:${digits}`}
|
||||||
|
aria-label={`Llamar a ${label}`}
|
||||||
|
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||||
|
>
|
||||||
|
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
|
||||||
|
Llamar
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { Mail } from 'lucide-react'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { Section } from './Section'
|
||||||
|
|
||||||
|
/* `px-3` interno: la banda de hover sigue a sangre hasta el borde de la sección
|
||||||
|
(la separa del texto, no al revés) y las notas de abajo suman el mismo para
|
||||||
|
que el email y ellas caigan en la misma columna. */
|
||||||
|
const ROW_CLASS =
|
||||||
|
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
|
|
||||||
|
/** Email y notas del miembro. El teléfono no va acá: ya está en el subtítulo y
|
||||||
|
* detrás de los botones de WhatsApp y Llamar, y repetirlo llenaba la pantalla
|
||||||
|
* de un dato que ya estaba a la vista.
|
||||||
|
*
|
||||||
|
* Sin datos no se dibuja la sección: no hay filas con "Sin email"/"Sin notas".
|
||||||
|
* Aparece sola en cuanto el miembro tenga alguno (hoy el email puede llegar al
|
||||||
|
* aprobar una preinscripción; las notas, cuando exista la edición). */
|
||||||
|
export function AttendeeContactSection() {
|
||||||
|
const { attendee } = useAttendeeDetail()
|
||||||
|
|
||||||
|
if (!attendee) return null
|
||||||
|
|
||||||
|
const { email, notes } = attendee
|
||||||
|
if (!email && !notes) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="Contacto">
|
||||||
|
<div className="divide-y divide-border/60">
|
||||||
|
{email ? (
|
||||||
|
<a href={`mailto:${email}`} className={ROW_CLASS}>
|
||||||
|
<span className="truncate text-sm text-primary">{email}</span>
|
||||||
|
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{notes ? (
|
||||||
|
<p className="whitespace-pre-line px-3 py-2 text-sm leading-relaxed text-primary">{notes}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,10 +2,9 @@ import { createContext, useContext, useState } from 'react'
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared'
|
import type { AttendeeDto, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||||
import { useToast } from '../../../components/ui'
|
import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api'
|
||||||
import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api'
|
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
||||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
|
||||||
|
|
||||||
type AttendeeDetailContextValue = {
|
type AttendeeDetailContextValue = {
|
||||||
groupId: string
|
groupId: string
|
||||||
@@ -13,18 +12,17 @@ type AttendeeDetailContextValue = {
|
|||||||
attendee: AttendeeDto | undefined
|
attendee: AttendeeDto | undefined
|
||||||
attendeePending: boolean
|
attendeePending: boolean
|
||||||
attendeeFailed: boolean
|
attendeeFailed: boolean
|
||||||
attendeeStats: AttendeeStats | undefined
|
history: AttendeeHistory | undefined
|
||||||
attendeeStatsPending: boolean
|
historyPending: boolean
|
||||||
attendeeStatsFailed: boolean
|
historyFailed: boolean
|
||||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
waitlistTotal: number
|
waitlistTotal: number
|
||||||
waitlistPending: boolean
|
waitlistPending: boolean
|
||||||
isRemoveModalOpen: boolean
|
isRemoveDialogOpen: boolean
|
||||||
openRemoveModal: () => void
|
openRemoveDialog: () => void
|
||||||
closeRemoveModal: () => void
|
closeRemoveDialog: () => void
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||||
isSubmittingRemoval: boolean
|
isSubmittingRemoval: boolean
|
||||||
copyAbsenceNotifyUrl: (url: string) => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||||
@@ -38,9 +36,8 @@ export function AttendeeDetailProvider({
|
|||||||
attendeeId: string
|
attendeeId: string
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
}) {
|
}) {
|
||||||
const toast = useToast()
|
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false)
|
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
const groupQuery = useQuery({
|
||||||
queryKey: ['group', groupId],
|
queryKey: ['group', groupId],
|
||||||
@@ -54,16 +51,20 @@ export function AttendeeDetailProvider({
|
|||||||
enabled: Boolean(groupId && attendeeId),
|
enabled: Boolean(groupId && attendeeId),
|
||||||
})
|
})
|
||||||
|
|
||||||
const attendeeStatsQuery = useQuery({
|
// Misma clave que usa la pantalla de estadísticas: las dos leen el mismo
|
||||||
queryKey: ['attendee-stats', groupId, attendeeId],
|
// historial y no se pisan la caché.
|
||||||
queryFn: () => getAttendeeStats(groupId, attendeeId),
|
const historyQuery = useQuery({
|
||||||
|
queryKey: ['attendee-history', groupId, attendeeId],
|
||||||
|
queryFn: () => getAttendeeHistory(groupId, attendeeId),
|
||||||
enabled: Boolean(groupId && attendeeId),
|
enabled: Boolean(groupId && attendeeId),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// La lista de espera solo hace falta para el diálogo de quitar, así que no se
|
||||||
|
// pide hasta que el usuario lo abre.
|
||||||
const waitlistQuery = useQuery({
|
const waitlistQuery = useQuery({
|
||||||
queryKey: ['group-waitlist', groupId],
|
queryKey: ['group-waitlist', groupId],
|
||||||
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
||||||
enabled: Boolean(groupId && isRemoveModalOpen),
|
enabled: Boolean(groupId && isRemoveDialogOpen),
|
||||||
})
|
})
|
||||||
|
|
||||||
const waitlistEntries = waitlistQuery.data?.data ?? []
|
const waitlistEntries = waitlistQuery.data?.data ?? []
|
||||||
@@ -73,38 +74,31 @@ export function AttendeeDetailProvider({
|
|||||||
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
||||||
groupId,
|
groupId,
|
||||||
onRemoved: () => {
|
onRemoved: () => {
|
||||||
setIsRemoveModalOpen(false)
|
setIsRemoveDialogOpen(false)
|
||||||
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
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 = {
|
const value: AttendeeDetailContextValue = {
|
||||||
groupId,
|
groupId,
|
||||||
groupName: groupQuery.data?.name,
|
groupName: groupQuery.data?.name,
|
||||||
attendee: attendeeQuery.data,
|
attendee: attendeeQuery.data,
|
||||||
attendeePending: attendeeQuery.isPending,
|
attendeePending: attendeeQuery.isPending,
|
||||||
attendeeFailed: attendeeQuery.isError,
|
attendeeFailed: attendeeQuery.isError,
|
||||||
attendeeStats: attendeeStatsQuery.data,
|
history: historyQuery.data,
|
||||||
attendeeStatsPending: attendeeStatsQuery.isPending,
|
historyPending: historyQuery.isPending,
|
||||||
attendeeStatsFailed: attendeeStatsQuery.isError,
|
historyFailed: historyQuery.isError,
|
||||||
firstWaitlistEntry,
|
firstWaitlistEntry,
|
||||||
waitlistTotal,
|
waitlistTotal,
|
||||||
waitlistPending: waitlistQuery.isPending,
|
waitlistPending: waitlistQuery.isPending,
|
||||||
isRemoveModalOpen,
|
isRemoveDialogOpen,
|
||||||
openRemoveModal: () => setIsRemoveModalOpen(true),
|
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
||||||
closeRemoveModal: () => setIsRemoveModalOpen(false),
|
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||||
if (!attendeeQuery.data) return
|
if (!attendeeQuery.data) return
|
||||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||||
},
|
},
|
||||||
isSubmittingRemoval: isRemovingAttendee,
|
isSubmittingRemoval: isRemovingAttendee,
|
||||||
copyAbsenceNotifyUrl,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||||
90
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
90
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import { useRef } from 'react'
|
||||||
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { 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 { AttendeePhoneLine } from './AttendeePhoneLine'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||||
|
import { formatMemberSince } from './attendance'
|
||||||
|
|
||||||
|
export function AttendeeDetailView() {
|
||||||
|
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const menuTriggerRef = useRef<HTMLButtonElement>(null)
|
||||||
|
|
||||||
|
if (attendeePending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-20">
|
||||||
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attendeeFailed || !attendee) {
|
||||||
|
return (
|
||||||
|
<div className="animate-fade-in rounded-2xl bg-danger-soft p-6">
|
||||||
|
{/* El título lleva el rojo (a 18px ya cuenta como texto grande y llega a
|
||||||
|
los 3:1) y el cuerpo usa `text-primary`: en `danger-soft` el rojo no
|
||||||
|
pasa los 4.5:1 que necesita un `text-sm`. */}
|
||||||
|
<h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1>
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="animate-fade-in">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="flex min-h-11 min-w-0 items-center gap-1.5 rounded-lg py-2 text-sm text-foreground transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4 shrink-0" aria-hidden="true" />
|
||||||
|
<span className="truncate">{groupName ?? 'Grupo'}</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<AttendeeActionsMenu triggerRef={menuTriggerRef} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-1">
|
||||||
|
<h1 className="text-balance text-2xl font-bold leading-tight tracking-tight text-primary">
|
||||||
|
{attendee.fullName}
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 whitespace-nowrap text-sm text-foreground">
|
||||||
|
Miembro desde {formatMemberSince(attendee.createdAt)}
|
||||||
|
</p>
|
||||||
|
<AttendeePhoneLine />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3">
|
||||||
|
<AttendeeContactActions />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
|
||||||
|
arriba de Asistencia; cada sección lleva su propio aire, así que el
|
||||||
|
layout no se toca. */}
|
||||||
|
<div className="mt-5">
|
||||||
|
<AttendeeAttendanceSection />
|
||||||
|
<AttendeeContactSection />
|
||||||
|
<AbsenceLinkSection />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
|
||||||
|
</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'
|
||||||
|
|
||||||
|
/** Teléfono como segunda línea del subtítulo.
|
||||||
|
*
|
||||||
|
* Vivía en una sección "Contacto" con una sola fila que repetía el número que
|
||||||
|
* ya está a la vista detrás de los botones de WhatsApp y Llamar. Acá acompaña
|
||||||
|
* al "Miembro desde…", se copia con un toque y tiene 44px de alto aunque el
|
||||||
|
* texto sea de 14px: es un control, no un dato decorativo. */
|
||||||
|
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`: la confirmación se anuncia desde la región viva de
|
||||||
|
abajo, así no se cuela en el nombre del botón. */}
|
||||||
|
{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>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import type { RefObject } from 'react'
|
||||||
|
import type { LucideIcon } from 'lucide-react'
|
||||||
|
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
|
||||||
|
import { Button, Modal } from '../../components/ui'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
type Consequence = { key: string; icon: LucideIcon; text: string }
|
||||||
|
|
||||||
|
export function ConfirmRemoveAttendeeDialog({
|
||||||
|
returnFocusRef,
|
||||||
|
}: {
|
||||||
|
/** Elemento al que vuelve el foco al cerrarse (el botón "⋯"). */
|
||||||
|
returnFocusRef: RefObject<HTMLButtonElement | null>
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
attendee,
|
||||||
|
groupName,
|
||||||
|
firstWaitlistEntry,
|
||||||
|
waitlistTotal,
|
||||||
|
waitlistPending,
|
||||||
|
isSubmittingRemoval,
|
||||||
|
isRemoveDialogOpen,
|
||||||
|
closeRemoveDialog,
|
||||||
|
confirmRemoveAttendee,
|
||||||
|
} = useAttendeeDetail()
|
||||||
|
|
||||||
|
const wasOpen = useRef(false)
|
||||||
|
const contentRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isRemoveDialogOpen) {
|
||||||
|
wasOpen.current = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!wasOpen.current) return
|
||||||
|
wasOpen.current = false
|
||||||
|
returnFocusRef.current?.focus()
|
||||||
|
}, [isRemoveDialogOpen, returnFocusRef])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isRemoveDialogOpen) return
|
||||||
|
return trapTabWithin(contentRef)
|
||||||
|
}, [isRemoveDialogOpen])
|
||||||
|
|
||||||
|
if (!attendee) return null
|
||||||
|
|
||||||
|
const waiting = waitlistTotal > 0
|
||||||
|
const canPromote = !waitlistPending && firstWaitlistEntry !== null
|
||||||
|
|
||||||
|
const consequences: Consequence[] = [
|
||||||
|
{
|
||||||
|
key: 'historial',
|
||||||
|
icon: History,
|
||||||
|
text: 'Se borra su historial: las clases registradas y las ausencias que avisó dejan de existir.',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
if (attendee.notifyToken) {
|
||||||
|
consequences.push({ key: 'link', icon: Link2, text: 'El link de ausencias deja de funcionar.' })
|
||||||
|
}
|
||||||
|
consequences.push({
|
||||||
|
key: 'lugar',
|
||||||
|
icon: Users,
|
||||||
|
text: waiting
|
||||||
|
? `Se libera 1 lugar. Hay ${waitlistTotal} ${
|
||||||
|
waitlistTotal === 1 ? 'persona' : 'personas'
|
||||||
|
} en lista de espera.`
|
||||||
|
: 'Se libera 1 lugar en el grupo.',
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={isRemoveDialogOpen}
|
||||||
|
onClose={closeRemoveDialog}
|
||||||
|
title="Quitar del grupo"
|
||||||
|
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
||||||
|
maxWidth="sm"
|
||||||
|
>
|
||||||
|
<div ref={contentRef} className="space-y-4">
|
||||||
|
<ul className="space-y-2.5">
|
||||||
|
{consequences.map(({ icon: Icon, key, text }) => (
|
||||||
|
<li key={key} className="flex items-start gap-2.5 text-sm text-foreground">
|
||||||
|
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||||
|
<span>{text}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p className="text-xs text-foreground">
|
||||||
|
Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{canPromote && firstWaitlistEntry ? (
|
||||||
|
<div className="rounded-xl bg-accent-soft p-3.5">
|
||||||
|
<p className="text-sm text-foreground">
|
||||||
|
Si lo quitás, podés darle el lugar a{' '}
|
||||||
|
<strong className="text-primary">{firstWaitlistEntry.fullName}</strong>, el primero
|
||||||
|
de la lista de espera.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={() => confirmRemoveAttendee(true)}
|
||||||
|
disabled={isSubmittingRemoval}
|
||||||
|
className="mt-2.5 w-full gap-2"
|
||||||
|
>
|
||||||
|
{isSubmittingRemoval ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<UserPlus className="size-4" />
|
||||||
|
)}
|
||||||
|
<span>Pasar a {firstWaitlistEntry.fullName} al grupo</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
||||||
|
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
{/* Etiqueta en negro sobre el relleno `danger`: es la única forma de
|
||||||
|
llegar a AA con el mismo rojo en los dos temas (4.9:1 claro,
|
||||||
|
6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */}
|
||||||
|
<Button
|
||||||
|
onClick={() => confirmRemoveAttendee(false)}
|
||||||
|
disabled={isSubmittingRemoval}
|
||||||
|
className="gap-2 bg-danger text-black hover:bg-danger/90"
|
||||||
|
>
|
||||||
|
{isSubmittingRemoval ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Trash2 className="size-4" />
|
||||||
|
)}
|
||||||
|
<span>Quitar del grupo</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** El `Modal` de la app no atrapa el foco; este diálogo sí, para que el Tab no
|
||||||
|
* se vaya detrás del overlay. Solo cicla entre los controles del contenido: si
|
||||||
|
* el foco está en otro lado (la X del `Modal`, que se sigue cerrando con
|
||||||
|
* Escape) lo deja seguir su curso normal. */
|
||||||
|
function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) {
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key !== 'Tab') return
|
||||||
|
|
||||||
|
const container = contentRef.current
|
||||||
|
if (!container?.contains(document.activeElement)) return
|
||||||
|
|
||||||
|
const focusable = Array.from(container.querySelectorAll<HTMLElement>('button:not([disabled])'))
|
||||||
|
if (focusable.length === 0) return
|
||||||
|
|
||||||
|
const first = focusable[0]
|
||||||
|
const last = focusable[focusable.length - 1]
|
||||||
|
const active = document.activeElement
|
||||||
|
|
||||||
|
if (event.shiftKey && active === first) {
|
||||||
|
event.preventDefault()
|
||||||
|
last.focus()
|
||||||
|
} else if (!event.shiftKey && active === last) {
|
||||||
|
event.preventDefault()
|
||||||
|
first.focus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('keydown', handleKeyDown)
|
||||||
|
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||||
|
}
|
||||||
86
apps/web/src/features/attendee-detail/Section.tsx
Normal file
86
apps/web/src/features/attendee-detail/Section.tsx
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import { useId } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { ChevronDown } from 'lucide-react'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
|
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a
|
||||||
|
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */
|
||||||
|
export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground'
|
||||||
|
|
||||||
|
/* La fila que despliega la sección es un botón, no un título: por eso lleva
|
||||||
|
superficie de hover y presión, se pinta en `primary` para que se lea
|
||||||
|
distinta de los títulos fijos, y el chevron cae al borde derecho de la fila
|
||||||
|
en vez de pegado al texto.
|
||||||
|
|
||||||
|
El `px-3` es interno: la banda de hover sigue a sangre hasta el borde de la
|
||||||
|
sección y lo que se separa del borde es el contenido (el `px-3` del `h2` y
|
||||||
|
del `trailing` de abajo alinea rótulo y resumen con esta fila). */
|
||||||
|
const TOGGLE_ROW_CLASS = cn(
|
||||||
|
SECTION_TITLE_CLASS,
|
||||||
|
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-left text-primary',
|
||||||
|
'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',
|
||||||
|
)
|
||||||
|
|
||||||
|
type SectionProps = {
|
||||||
|
/** Título de la sección. Un string por lo general. */
|
||||||
|
title: ReactNode
|
||||||
|
/** A la derecha del título: el resumen de asistencia, por ejemplo. */
|
||||||
|
trailing?: ReactNode
|
||||||
|
/** Cuando está, el título entero es el disparador del contenido y `title` es
|
||||||
|
* solo su rótulo: el `<h2>` sigue siendo el encabezado de la sección y el
|
||||||
|
* botón ocupa la fila completa. */
|
||||||
|
toggle?: { isOpen: boolean; panelId: string; onToggle: () => void }
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bloque de sección: separador fino sobre el fondo, título chico en
|
||||||
|
* mayúsculas y contenido sin padding propio (el de la pantalla).
|
||||||
|
*
|
||||||
|
* El aire vive acá y no en la pantalla: cada sección cierra con su propio
|
||||||
|
* padding, así que el separador queda siempre a la misma distancia del
|
||||||
|
* contenido de arriba. Sumar otra sección (Pagos, por ejemplo) es insertar
|
||||||
|
* otro bloque y nada más. */
|
||||||
|
export function Section({ title, trailing, toggle, children }: SectionProps) {
|
||||||
|
const headingId = useId()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section aria-labelledby={headingId} className="border-t border-border/70 py-4">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
{toggle ? (
|
||||||
|
// El botón vive dentro del `<h2>`: el encabezado no se pierde y el
|
||||||
|
// disparador sigue siendo un control de verdad (Enter, Espacio y foco
|
||||||
|
// visible por teclado).
|
||||||
|
<h2 id={headingId} className="min-w-0 flex-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-expanded={toggle.isOpen}
|
||||||
|
aria-controls={toggle.panelId}
|
||||||
|
onClick={toggle.onToggle}
|
||||||
|
className={TOGGLE_ROW_CLASS}
|
||||||
|
>
|
||||||
|
<span className="truncate">{title}</span>
|
||||||
|
<ChevronDown
|
||||||
|
className={cn(
|
||||||
|
'size-4 shrink-0 transition-transform',
|
||||||
|
toggle.isOpen && 'rotate-180',
|
||||||
|
)}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</h2>
|
||||||
|
) : (
|
||||||
|
<h2 id={headingId} className={cn(SECTION_TITLE_CLASS, 'px-3')}>
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
)}
|
||||||
|
{trailing ? (
|
||||||
|
<div className="shrink-0 px-3 text-xs font-semibold tabular-nums text-foreground">
|
||||||
|
{trailing}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2">{children}</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
15
apps/web/src/features/attendee-detail/actionButton.ts
Normal file
15
apps/web/src/features/attendee-detail/actionButton.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/** Botón de acción de la pantalla (WhatsApp, Llamar, Copiar link).
|
||||||
|
*
|
||||||
|
* Relleno `primary-soft`, que es la misma superficie rellena que usa el detalle
|
||||||
|
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque
|
||||||
|
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y
|
||||||
|
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
|
||||||
|
export const ACTION_BUTTON_CLASS =
|
||||||
|
'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
|
|
||||||
|
/** Acción principal de un panel (Enviar por WhatsApp). Misma superficie que el
|
||||||
|
* `Button` `primary` de la app —relleno `accent` con texto `on-accent`, que
|
||||||
|
* da 6.8:1 en los dos temas— pero a ancho completo porque sola en la columna:
|
||||||
|
* al lado de la secundaria al 50% los rótulos largos se parten en dos líneas. */
|
||||||
|
export const PRIMARY_ACTION_CLASS =
|
||||||
|
'inline-flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-accent px-4 text-sm font-medium text-on-accent transition-colors hover:bg-accent-strong active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
103
apps/web/src/features/attendee-detail/attendance.ts
Normal file
103
apps/web/src/features/attendee-detail/attendance.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import type { AttendanceHistoryItem } from '@gruperly/shared'
|
||||||
|
|
||||||
|
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el
|
||||||
|
backend). Es el techo real de lo que esta pantalla puede mostrar, así que
|
||||||
|
"Ver todas" no promete más de lo que hay. */
|
||||||
|
export const HISTORY_PREVIEW = 5
|
||||||
|
export const HISTORY_LIMIT = 20
|
||||||
|
|
||||||
|
export type AttendanceSession = AttendanceHistoryItem
|
||||||
|
|
||||||
|
export function formatSessionShortDate(iso: string): string {
|
||||||
|
const date = new Date(iso)
|
||||||
|
const weekday = date.toLocaleDateString('es-MX', { weekday: 'short' })
|
||||||
|
const day = date.toLocaleDateString('es-MX', { day: 'numeric' })
|
||||||
|
const month = date.toLocaleDateString('es-MX', { month: 'short' })
|
||||||
|
return `${weekday} ${day} ${month}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'PRESENT':
|
||||||
|
return 'Asistió'
|
||||||
|
case 'ABSENT':
|
||||||
|
return 'Faltó'
|
||||||
|
case 'EXCUSED':
|
||||||
|
return 'Faltó (avisó)'
|
||||||
|
default:
|
||||||
|
return 'Sin registrar'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* El estado se lee por texto e ícono, no solo por color: los tokens de estado
|
||||||
|
están pensados como texto sobre superficies oscuras y el verde sobre blanco
|
||||||
|
queda justo por debajo de AA, así que la fila lleva las tres señales. */
|
||||||
|
export function attendanceStatusClass(status: AttendanceSession['status']): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'PRESENT':
|
||||||
|
return 'text-success'
|
||||||
|
case 'ABSENT':
|
||||||
|
return 'text-danger'
|
||||||
|
case 'EXCUSED':
|
||||||
|
return 'text-warning'
|
||||||
|
default:
|
||||||
|
return 'text-foreground'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "28 sep 2026". Es la fecha corta de siempre: entra en una línea en móvil. */
|
||||||
|
export function formatMemberSince(iso: string): string {
|
||||||
|
return new Date(iso).toLocaleDateString('es-MX', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
year: 'numeric',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1 clase" / "2 clases". */
|
||||||
|
export function classCountLabel(count: number): string {
|
||||||
|
return count === 1 ? '1 clase' : `${count} clases`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas
|
||||||
|
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden
|
||||||
|
* contrario (más antigua → más reciente). */
|
||||||
|
export function visibleSessions(
|
||||||
|
sessions: AttendanceSession[],
|
||||||
|
showAll: boolean,
|
||||||
|
): AttendanceSession[] {
|
||||||
|
const ordered = [...sessions].reverse()
|
||||||
|
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clases con asistencia registrada: asistió, faltó o faltó con aviso. Las
|
||||||
|
* "Sin registrar" no cuentan: sin dato no hay ni asistencia ni ausencia, y
|
||||||
|
* meterlas en el denominador hacía que "1 de 3" se leyera como dos ausencias. */
|
||||||
|
function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
|
||||||
|
return sessions.filter((session) => session.status != null)
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AttendanceSummary = {
|
||||||
|
/** "1 de 1 clase", o "Sin clases registradas" si no hay ninguna con dato. */
|
||||||
|
label: string
|
||||||
|
/** "2 sin registrar", o `null` si no hay clases sin registro. */
|
||||||
|
unmarkedLabel: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resumen de las filas que se están mostrando: cuántas clases registró la
|
||||||
|
* persona sobre cuántas hay con dato, y cuántas quedaron sin registrar.
|
||||||
|
*
|
||||||
|
* El texto de las "sin registrar" se apaga cuando no hay ninguna clase
|
||||||
|
* registrada: el resumen ya dice que no hay datos y los dos textos dirían lo
|
||||||
|
* mismo dos veces. */
|
||||||
|
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
|
||||||
|
const marked = markedSessions(sessions)
|
||||||
|
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }
|
||||||
|
|
||||||
|
const present = marked.filter((session) => session.status === 'PRESENT').length
|
||||||
|
const unmarked = sessions.length - marked.length
|
||||||
|
return {
|
||||||
|
label: `${present} de ${classCountLabel(marked.length)}`,
|
||||||
|
unmarkedLabel: unmarked > 0 ? `${unmarked} sin registrar` : null,
|
||||||
|
}
|
||||||
|
}
|
||||||
33
apps/web/src/features/attendee-detail/useCopyToClipboard.ts
Normal file
33
apps/web/src/features/attendee-detail/useCopyToClipboard.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
const FEEDBACK_MS = 1800
|
||||||
|
|
||||||
|
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es
|
||||||
|
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */
|
||||||
|
export function useCopyToClipboard() {
|
||||||
|
const [copied, setCopied] = useState(false)
|
||||||
|
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
if (timeoutRef.current) clearTimeout(timeoutRef.current)
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
const copy = (text: string) => {
|
||||||
|
if (!navigator.clipboard) return
|
||||||
|
void navigator.clipboard
|
||||||
|
.writeText(text)
|
||||||
|
.then(() => {
|
||||||
|
setCopied(true)
|
||||||
|
if (timeoutRef.current) clearTimeout(timeoutRef.current)
|
||||||
|
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
|
||||||
|
})
|
||||||
|
// Si el navegador rechaza la escritura no hay nada que confirmar: se
|
||||||
|
// deja el control como estaba en vez de dejar la promesa sin manejar.
|
||||||
|
.catch(() => setCopied(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
return { copied, copy }
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { LargeTitle } from '../../components/layout/LargeTitle'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge, Button } from '../../components/ui'
|
||||||
import { useAttendance } from './AttendanceProvider'
|
import { useAttendance } from './AttendanceProvider'
|
||||||
import { StudentRow } from './StudentRow'
|
import { StudentRow } from './StudentRow'
|
||||||
@@ -16,15 +17,43 @@ export function ClassAttendanceView() {
|
|||||||
isSaving,
|
isSaving,
|
||||||
} = useAttendance()
|
} = useAttendance()
|
||||||
|
|
||||||
|
const total = sessionInfo?.students.length ?? 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
<Link
|
{/* El título grande va siempre, incluso mientras carga la sesión: es lo
|
||||||
to="/"
|
que orienta y da altura de anclaje a la barra. El contador de
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
presentes, en cambio, solo aparece cuando ya hay alumnos en pantalla. */}
|
||||||
|
<LargeTitle
|
||||||
|
title={sessionInfo?.groupName ?? 'Asistencia'}
|
||||||
|
leading={
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver al inicio</span>
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
|
barTrailing={
|
||||||
|
total > 0 ? (
|
||||||
|
<Badge variant="success" className="text-[11px] tabular-nums">
|
||||||
|
{presentCount}/{total}
|
||||||
|
</Badge>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
{sessionInfo ? (
|
||||||
<span>Volver al inicio</span>
|
<div className="mt-2 flex items-center justify-between gap-3">
|
||||||
</Link>
|
<p className="text-sm text-foreground/60">
|
||||||
|
{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}
|
||||||
|
</p>
|
||||||
|
<Badge variant="success" className="shrink-0 text-xs tabular-nums">
|
||||||
|
{presentCount}/{total} presentes
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</LargeTitle>
|
||||||
|
|
||||||
{studentsPending ? (
|
{studentsPending ? (
|
||||||
<div className="flex items-center justify-center py-16">
|
<div className="flex items-center justify-center py-16">
|
||||||
@@ -43,19 +72,7 @@ export function ClassAttendanceView() {
|
|||||||
|
|
||||||
{sessionInfo ? (
|
{sessionInfo ? (
|
||||||
<>
|
<>
|
||||||
<header className="sticky top-16 z-30 -mx-4 border-b border-border bg-background/95 px-4 py-3 backdrop-blur lg:mx-0 lg:rounded-xl lg:border lg:px-4">
|
{total === 0 ? (
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<div className="min-w-0">
|
|
||||||
<h1 className="truncate text-lg font-bold text-primary">{sessionInfo.groupName}</h1>
|
|
||||||
<p className="text-xs text-foreground/60">{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}</p>
|
|
||||||
</div>
|
|
||||||
<Badge variant="success" className="shrink-0 text-sm">
|
|
||||||
{presentCount}/{sessionInfo.students.length} presentes
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{sessionInfo.students.length === 0 ? (
|
|
||||||
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||||
<p className="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
<p className="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
@@ -70,7 +87,7 @@ export function ClassAttendanceView() {
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{sessionInfo.students.length > 0 ? (
|
{total > 0 ? (
|
||||||
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -87,4 +104,4 @@ export function ClassAttendanceView() {
|
|||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
185
apps/web/src/features/groups/AttendanceCapacityIndicator.tsx
Normal file
185
apps/web/src/features/groups/AttendanceCapacityIndicator.tsx
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
import type { CapacityCounts, RiskTone } from './card'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicador único de cupo y asistencia: una barra que junta "cuánta gente hay"
|
||||||
|
* con "cómo viene esa gente". Reemplaza al badge de baja asistencia y a la
|
||||||
|
* barrita de ocupación, que contaban dos cosas distintas y competían por el
|
||||||
|
* mismo lugar en la tarjeta.
|
||||||
|
*
|
||||||
|
* ── Qué se está midiendo ───────────────────────────────────────────────────
|
||||||
|
* `capacity` es el total contra el que se reparten los bloques, y `places` dice
|
||||||
|
* si ese total son lugares del cupo o la matrícula. Sin cupo declarado el
|
||||||
|
* grupo no tiene lugares, pero sí tiene gente en riesgo, así que la barra
|
||||||
|
* mide a los miembros (`places: false`) en vez de desaparecer.
|
||||||
|
*
|
||||||
|
* ── Dos modos ──────────────────────────────────────────────────────────────
|
||||||
|
* Con total chico (<= `SEGMENTED_CAPACITY_MAX`) hay un segmento por unidad y se
|
||||||
|
* ve exactamente qué posiciones están ocupadas y de qué color. Con total grande
|
||||||
|
* eso ya no se distingue, así que se pasa a bloques proporcionales. Ambos modos
|
||||||
|
* conservan la misma medida visual para que la lista se pueda escanear en
|
||||||
|
* vertical; importa la proporción, no que los grupos chicos queden diminutos.
|
||||||
|
*
|
||||||
|
* ── Lectura ────────────────────────────────────────────────────────────────
|
||||||
|
* El color solo no alcanza. El bloque va con `role="img"` y un `aria-label` que
|
||||||
|
* dice todo ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención"), que es
|
||||||
|
* lo que lee el lector de pantalla; y la tarjeta repite lo esencial en texto
|
||||||
|
* ("3 en riesgo alto · 4 en atención") abajo. Los tres niveles van siempre en el
|
||||||
|
* mismo orden, de peor a mejor, para que la barra se lea igual en todas las
|
||||||
|
* tarjetas y el ojo aprenda a escanearlas.
|
||||||
|
*
|
||||||
|
* ── Contraste ──────────────────────────────────────────────────────────────
|
||||||
|
* Todo sale de tokens, nada hardcodeado. Los rellenos miden 5.74:1 (rojo),
|
||||||
|
* 4.58:1 (ámbar) y 6.20:1 (azul) contra la tarjeta en tema claro, y 5.44, 10.15
|
||||||
|
* y 7.10:1 en oscuro: los tres pasan el 3:1 que pide WCAG para contenido no
|
||||||
|
* textual y el 4.5:1 que necesita la línea de texto que los acompaña. El rojo
|
||||||
|
* usa `danger-fg` y no `danger` justamente por eso: `danger` en tema claro da
|
||||||
|
* 3.35:1 y no alcanzaría como texto.
|
||||||
|
*
|
||||||
|
* El contorno de los lugares libres NO puede usar `border`, que en tema oscuro
|
||||||
|
* vale lo mismo que la tarjeta (1.00:1 y no se ve); usa `foreground` al 70%,
|
||||||
|
* que da 3.42:1 en claro y 3.55:1 en oscuro.
|
||||||
|
*/
|
||||||
|
|
||||||
|
type Level = keyof Pick<CapacityCounts, 'riesgoAlto' | 'atencion' | 'ok' | 'libres'>
|
||||||
|
|
||||||
|
/* De peor a mejor. Es el orden fijo de la barra: si mañana se agrega un nivel
|
||||||
|
entra en esta lista y no hay que tocar el componente. */
|
||||||
|
const LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok', 'libres']
|
||||||
|
const OCCUPIED_LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok']
|
||||||
|
|
||||||
|
/* El lugar libre no es un estado de la persona: es ausencia de gente. Por eso
|
||||||
|
es el único que no lleva relleno. */
|
||||||
|
const FILL: Record<Level, string> = {
|
||||||
|
riesgoAlto: 'bg-attendance-high',
|
||||||
|
atencion: 'bg-attendance-attention',
|
||||||
|
ok: 'bg-attendance-ok',
|
||||||
|
libres: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
const OUTLINE = 'border-[1.5px] border-border dark:border-foreground/50'
|
||||||
|
|
||||||
|
/** Frase larga del `aria-label`: toda la información del bloque en una línea. */
|
||||||
|
export function capacityIndicatorLabel(
|
||||||
|
counts: CapacityCounts,
|
||||||
|
capacity: number,
|
||||||
|
places = true,
|
||||||
|
): string {
|
||||||
|
const { riesgoAlto, atencion, ok, libres } = counts
|
||||||
|
const ocupados = riesgoAlto + atencion + ok
|
||||||
|
|
||||||
|
const niveles = [
|
||||||
|
`${riesgoAlto} en riesgo alto`,
|
||||||
|
`${atencion} en atención`,
|
||||||
|
`${ok} en ok`,
|
||||||
|
].filter((parte, index) => {
|
||||||
|
const valor = [riesgoAlto, atencion, ok][index]
|
||||||
|
return valor > 0
|
||||||
|
})
|
||||||
|
|
||||||
|
const detalle = niveles.length > 0 ? `: ${niveles.join(', ')}` : ''
|
||||||
|
|
||||||
|
/* Sin cupo declarado no hay lugares que ocupar ni libres que contar: la
|
||||||
|
barra es un reparto de la matrícula y decirlo con esas palabras sería
|
||||||
|
inventar un cupo que el grupo no tiene. */
|
||||||
|
if (!places) {
|
||||||
|
return `${ocupados} ${ocupados === 1 ? 'miembro' : 'miembros'}${detalle}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const libresTexto = libres > 0 ? `, ${libres} libre${libres === 1 ? '' : 's'}` : ''
|
||||||
|
|
||||||
|
return `${ocupados} de ${capacity} lugares ocupados${detalle}${libresTexto}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AttendanceCapacityIndicator({
|
||||||
|
counts,
|
||||||
|
capacity,
|
||||||
|
segmented,
|
||||||
|
places = true,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
counts: CapacityCounts
|
||||||
|
/** Total contra el que se reparte la barra: el cupo, o la matrícula si el
|
||||||
|
* grupo no tiene cupo declarado. */
|
||||||
|
capacity: number
|
||||||
|
/** `true` cuando el total es chico y va un segmento por unidad. */
|
||||||
|
segmented: boolean
|
||||||
|
/** `false` cuando `capacity` son miembros y no lugares del cupo. */
|
||||||
|
places?: boolean
|
||||||
|
className?: string
|
||||||
|
}) {
|
||||||
|
const label = capacityIndicatorLabel(counts, capacity, places)
|
||||||
|
|
||||||
|
if (segmented) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
role="img"
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
className={cn('flex h-3.5 min-w-0 items-center gap-1.5', className)}
|
||||||
|
>
|
||||||
|
{Array.from({ length: capacity }, (_, index) => (
|
||||||
|
<LevelSegment
|
||||||
|
key={index}
|
||||||
|
level={levelAt(counts, index)}
|
||||||
|
className="h-3.5 w-[50px] shrink-0"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
role="img"
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
className={cn(
|
||||||
|
'flex h-3.5 min-w-0 flex-1 items-stretch overflow-hidden rounded-full bg-surface',
|
||||||
|
OUTLINE,
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{OCCUPIED_LEVELS.map((level) =>
|
||||||
|
counts[level] > 0 ? (
|
||||||
|
<span
|
||||||
|
key={level}
|
||||||
|
className={cn('h-full min-w-1.5', FILL[level])}
|
||||||
|
style={{ width: capacitySegmentWidth(counts[level], capacity) }}
|
||||||
|
/>
|
||||||
|
) : null,
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function capacitySegmentWidth(count: number, capacity: number): string {
|
||||||
|
if (capacity <= 0) return '0%'
|
||||||
|
return `${((count / capacity) * 100).toFixed(4)}%`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un segmento es una persona: el color es el del nivel de ese lugar. */
|
||||||
|
function LevelSegment({ level, className }: { level: Level; className?: string }) {
|
||||||
|
if (level === 'libres') return <span className={cn(OUTLINE, 'rounded-full', className)} />
|
||||||
|
return <span className={cn('rounded-full', FILL[level], className)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
/** El lugar `index` lo ocupa la persona de peor nivel que todavía entra. */
|
||||||
|
function levelAt(counts: CapacityCounts, index: number): Level {
|
||||||
|
let restante = index
|
||||||
|
for (const level of LEVELS) {
|
||||||
|
if (restante < counts[level]) return level
|
||||||
|
restante -= counts[level]
|
||||||
|
}
|
||||||
|
return 'libres'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Color del texto según el peor nivel: la línea de estado no puede quedar
|
||||||
|
* desalineada con la barra. `danger-fg` y no `danger` porque el primero es la
|
||||||
|
* versión legible (5.7:1 en claro, 5.4:1 en oscuro) y el segundo se queda en
|
||||||
|
* 3.35:1 como texto. */
|
||||||
|
export const TONE_TEXT: Record<RiskTone, string> = {
|
||||||
|
riesgo_alto: 'text-danger-fg',
|
||||||
|
atencion: 'text-warning',
|
||||||
|
ok: 'text-secondary',
|
||||||
|
}
|
||||||
@@ -1,78 +1,95 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
import type { GroupListItem, GroupRiskSummary } from '@gruperly/shared'
|
||||||
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { CalendarClock, Users } from 'lucide-react'
|
import { TriangleAlert } from 'lucide-react'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { AttendanceCapacityIndicator } from './AttendanceCapacityIndicator'
|
||||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format'
|
import {
|
||||||
import { cn } from '../../lib/utils'
|
SEGMENTED_CAPACITY_MAX,
|
||||||
import { RISK_LABELS } from './constants'
|
alertTextFromMembers,
|
||||||
|
capacityCountsFromMembers,
|
||||||
|
membersFromGroupAndRisk,
|
||||||
|
type GroupMember,
|
||||||
|
} from './card'
|
||||||
|
|
||||||
export function GroupCard({
|
const CARD_CLASS_NAME =
|
||||||
group,
|
'block rounded-2xl border border-border/80 bg-surface px-7 py-5 shadow-none transition-[border-color,background-color,transform] duration-150 ease-out hover:border-accent/35 hover:bg-primary-soft/35 focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none active:scale-[0.995] active:bg-primary-soft/55'
|
||||||
riskLevel,
|
|
||||||
}: {
|
export type GroupCardProps = {
|
||||||
group: GroupDto
|
id?: string
|
||||||
riskLevel: GroupRiskLevel
|
name?: string
|
||||||
}) {
|
capacity?: number
|
||||||
const navigate = useNavigate()
|
members?: GroupMember[]
|
||||||
const hasSchedule = (group.days?.length ?? 0) > 0
|
group?: GroupListItem
|
||||||
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
|
risk?: GroupRiskSummary | undefined
|
||||||
|
link?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GroupCard({ link = true, ...props }: GroupCardProps) {
|
||||||
|
const linkId = props.id ?? props.group?.id
|
||||||
|
|
||||||
|
if (link && linkId) {
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId: linkId }}
|
||||||
|
className={CARD_CLASS_NAME}
|
||||||
|
>
|
||||||
|
<GroupCardContent {...props} />
|
||||||
|
</Link>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article className="rounded-xl border border-border bg-surface p-5 transition-all hover:border-accent/40">
|
<div className={CARD_CLASS_NAME}>
|
||||||
<div className="flex items-start justify-between gap-3">
|
<GroupCardContent {...props} />
|
||||||
<div className="min-w-0">
|
</div>
|
||||||
<h3 className="truncate text-base font-semibold text-primary">{group.name}</h3>
|
|
||||||
{group.description ? (
|
|
||||||
<p className="mt-0.5 truncate text-sm text-foreground/60">{group.description}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col items-end gap-1.5">
|
|
||||||
{hasRisk ? (
|
|
||||||
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'size-2 rounded-full',
|
|
||||||
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
|
|
||||||
)}
|
|
||||||
aria-hidden="true"
|
|
||||||
/>
|
|
||||||
{RISK_LABELS[riskLevel]}
|
|
||||||
</Badge>
|
|
||||||
) : null}
|
|
||||||
<Badge variant="success">Activo</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{hasSchedule ? (
|
|
||||||
<dl className="mt-4 space-y-2 text-sm">
|
|
||||||
<div className="flex items-center gap-2 text-foreground/70">
|
|
||||||
<CalendarClock className="size-4 shrink-0 text-accent" />
|
|
||||||
<span>{formatSchedule(group.days ?? [], group.time)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 text-foreground/70">
|
|
||||||
<Users className="size-4 shrink-0 text-accent" />
|
|
||||||
<span>
|
|
||||||
Cupo {group.capacity ?? '—'} miembros
|
|
||||||
{group.price != null
|
|
||||||
? ` · ${formatPrice(group.price)}${group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}`
|
|
||||||
: ''}
|
|
||||||
{group.dueDay != null ? ` · vence el día ${group.dueDay}` : ''}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</dl>
|
|
||||||
) : (
|
|
||||||
<p className="mt-4 text-sm text-foreground/50">Aún sin plan de cobro configurado.</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="mt-4 flex items-center justify-end gap-2 border-t border-border pt-3">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => void navigate({ to: `/groups/${group.id}` })}
|
|
||||||
>
|
|
||||||
Gestionar Miembros
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GroupCardContent(props: GroupCardProps) {
|
||||||
|
const name = props.name ?? props.group?.name ?? ''
|
||||||
|
const members =
|
||||||
|
props.members ??
|
||||||
|
(props.group ? membersFromGroupAndRisk(props.group, props.risk) : [])
|
||||||
|
const capacity =
|
||||||
|
props.capacity ??
|
||||||
|
props.group?.capacity ??
|
||||||
|
props.group?.attendeesCount ??
|
||||||
|
members.length
|
||||||
|
|
||||||
|
const counts = capacityCountsFromMembers(members, capacity)
|
||||||
|
const alertText = alertTextFromMembers(members)
|
||||||
|
const segmented = capacity <= SEGMENTED_CAPACITY_MAX
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<h3 className="min-w-0 text-2xl leading-tight font-semibold tracking-tight text-primary">
|
||||||
|
{name}
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="mt-5 flex min-w-0 items-center gap-3">
|
||||||
|
<AttendanceCapacityIndicator
|
||||||
|
counts={counts}
|
||||||
|
capacity={capacity}
|
||||||
|
segmented={segmented}
|
||||||
|
places={true}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<span className="shrink-0 whitespace-nowrap text-lg tabular-nums text-secondary">
|
||||||
|
{members.length}/{capacity} {capacity === 1 ? 'miembro' : 'miembros'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{alertText ? (
|
||||||
|
<p className="mt-3 flex min-w-0 items-center gap-2.5 text-base leading-6 font-medium text-[#8B1A1A] dark:text-[#f87171]">
|
||||||
|
<TriangleAlert
|
||||||
|
className="size-4 shrink-0 text-[#8B1A1A] dark:text-[#f87171]"
|
||||||
|
strokeWidth={2}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<span className="min-w-0">{alertText}</span>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ export function GroupForm({
|
|||||||
<div>
|
<div>
|
||||||
<Label htmlFor="price">Precio</Label>
|
<Label htmlFor="price">Precio</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-foreground/50">
|
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-base text-foreground/50 sm:text-sm">
|
||||||
$
|
$
|
||||||
</span>
|
</span>
|
||||||
<Input
|
<Input
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { Loader2, Plus } from 'lucide-react'
|
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { getGroups, getGroupsRiskOverview } from '../../lib/api'
|
import { getGroups, getGroupsRiskOverview } from '../../lib/api'
|
||||||
import { GroupCard } from './GroupCard'
|
import { GroupCard } from './GroupCard'
|
||||||
|
import { MOCK_TEST_CASES } from './card'
|
||||||
|
|
||||||
export function GroupsView() {
|
export function GroupsView() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
@@ -16,26 +18,49 @@ export function GroupsView() {
|
|||||||
queryFn: getGroupsRiskOverview,
|
queryFn: getGroupsRiskOverview,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const [showExamples, setShowExamples] = useState(() => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
return new URLSearchParams(window.location.search).get('mock') === 'true'
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
|
||||||
const riskByGroup = new Map(
|
const riskByGroup = new Map(
|
||||||
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]),
|
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item]),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const hasGroups = groupsQuery.isSuccess && groupsQuery.data.data.length > 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<div>
|
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
||||||
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
<div className="flex items-center gap-2">
|
||||||
<p className="mt-2 text-sm text-foreground/60">Tus grupos de cobranza.</p>
|
{!hasGroups && groupsQuery.isSuccess ? (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-11"
|
||||||
|
onClick={() => setShowExamples((prev) => !prev)}
|
||||||
|
>
|
||||||
|
{showExamples ? 'Ocultar ejemplos' : 'Ver ejemplos'}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
className="h-11"
|
||||||
|
onClick={() => void navigate({ to: '/groups/new' })}
|
||||||
|
>
|
||||||
|
<Plus className="size-4" />
|
||||||
|
Nuevo grupo
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="primary" onClick={() => void navigate({ to: '/groups/new' })}>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Crear
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{groupsQuery.isPending ? (
|
{groupsQuery.isPending ? (
|
||||||
<div className="mt-8 flex items-center justify-center py-16">
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
<Loader2 className="size-6 animate-spin text-foreground/40" />
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
|
<span className="sr-only">Cargando grupos</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -48,34 +73,57 @@ export function GroupsView() {
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? (
|
{showExamples ? (
|
||||||
<div className="mt-8 rounded-xl border border-dashed border-border bg-surface px-4 py-12 text-center">
|
<div className="mt-6 grid gap-4">
|
||||||
<p className="font-medium text-primary">Todavía no tenés grupos</p>
|
{MOCK_TEST_CASES.map((group) => (
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<GroupCard key={group.id} {...group} />
|
||||||
Crea tu primer grupo para empezar a cobrar.
|
))}
|
||||||
</p>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
className="mt-5"
|
|
||||||
onClick={() => void navigate({ to: '/groups/new' })}
|
|
||||||
>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Crear tu primer grupo
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? (
|
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? (
|
||||||
|
/* Un ícono solo, con un punto focal, y el texto en secundario: la
|
||||||
|
pantalla vacía compite con la acción y no puede ganar. */
|
||||||
|
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
|
||||||
|
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
|
||||||
|
<CalendarPlus className="size-7" aria-hidden="true" />
|
||||||
|
</span>
|
||||||
|
<p className="mt-4 text-base font-semibold text-primary">Todavía no tenés grupos</p>
|
||||||
|
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
|
||||||
|
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
|
||||||
|
</p>
|
||||||
|
<div className="mt-6 flex items-center justify-center gap-3">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="h-11"
|
||||||
|
onClick={() => setShowExamples(true)}
|
||||||
|
>
|
||||||
|
Ver tarjetas de ejemplo
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
className="h-11"
|
||||||
|
onClick={() => void navigate({ to: '/groups/new' })}
|
||||||
|
>
|
||||||
|
<Plus className="size-4" />
|
||||||
|
Crear primer grupo
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{hasGroups && !showExamples ? (
|
||||||
<div className="mt-6 grid gap-4">
|
<div className="mt-6 grid gap-4">
|
||||||
{groupsQuery.data.data.map((group) => (
|
{groupsQuery.data.data.map((group) => (
|
||||||
<GroupCard
|
<GroupCard
|
||||||
key={group.id}
|
key={group.id}
|
||||||
group={group}
|
group={group}
|
||||||
riskLevel={riskByGroup.get(group.id) ?? 'NONE'}
|
risk={riskByGroup.get(group.id)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
83
apps/web/src/features/groups/add/AddAttendeePage.tsx
Normal file
83
apps/web/src/features/groups/add/AddAttendeePage.tsx
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
import { BulkCapacityModal } from './BulkCapacityModal'
|
||||||
|
import { BulkImportPanel } from './BulkImportPanel'
|
||||||
|
import { CapacityModal } from './CapacityModal'
|
||||||
|
import { QuickAddForm } from './QuickAddForm'
|
||||||
|
|
||||||
|
const TABS = [
|
||||||
|
{ value: 'quick' as const, label: 'Carga Rápida (Individual)' },
|
||||||
|
{ value: 'bulk' as const, label: 'Carga Masiva (CSV / Excel)' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function AddAttendeePage() {
|
||||||
|
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
||||||
|
useAddAttendee()
|
||||||
|
|
||||||
|
if (groupPending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-20">
|
||||||
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="mx-auto w-full max-w-2xl animate-fade-in space-y-5">
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver al grupo</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<header className="space-y-1">
|
||||||
|
<h1 className="text-2xl font-bold text-primary">Agregar miembros</h1>
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
{groupName ? (
|
||||||
|
<>
|
||||||
|
Sumá miembros a <span className="font-medium text-primary">{groupName}</span> de forma
|
||||||
|
individual o masiva desde una lista.
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Sumá miembros de forma individual o masiva desde una lista.'
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
{capacity != null ? (
|
||||||
|
<p className="text-xs text-foreground/50">
|
||||||
|
{attendeesTotal} de {capacity} lugares ocupados.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="rounded-xl border border-border bg-surface p-4 sm:p-5">
|
||||||
|
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
||||||
|
{TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setActiveTab(tab.value)}
|
||||||
|
className={cn(
|
||||||
|
'flex-1 rounded-lg px-1 py-2 text-xs font-semibold transition-all',
|
||||||
|
activeTab === tab.value
|
||||||
|
? 'bg-surface text-primary shadow-xs'
|
||||||
|
: 'text-foreground/60 hover:text-primary',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CapacityModal />
|
||||||
|
<BulkCapacityModal />
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
302
apps/web/src/features/groups/add/AddAttendeeProvider.tsx
Normal file
302
apps/web/src/features/groups/add/AddAttendeeProvider.tsx
Normal file
@@ -0,0 +1,302 @@
|
|||||||
|
import { createContext, useContext, useMemo, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type {
|
||||||
|
CreateAttendee,
|
||||||
|
CreateAttendeeResult,
|
||||||
|
CreateGroupWaitlistEntry,
|
||||||
|
GroupWaitlistEntryDto,
|
||||||
|
GroupWaitlistList,
|
||||||
|
} from '@gruperly/shared'
|
||||||
|
import { useToast } from '../../../components/ui'
|
||||||
|
import {
|
||||||
|
addToGroupWaitlist,
|
||||||
|
ApiError,
|
||||||
|
bulkCreateAttendees,
|
||||||
|
createAttendee,
|
||||||
|
getGroup,
|
||||||
|
getGroupAttendees,
|
||||||
|
} from '../../../lib/api'
|
||||||
|
import type { ParsedContactRow } from '../../../lib/file-parser'
|
||||||
|
|
||||||
|
export type BulkAttendeeRow = {
|
||||||
|
firstName: string
|
||||||
|
lastName: string
|
||||||
|
fullName: string
|
||||||
|
phone: string
|
||||||
|
email?: string
|
||||||
|
notes?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AddAttendeeTab = 'quick' | 'bulk'
|
||||||
|
|
||||||
|
type AddAttendeeContextValue = {
|
||||||
|
groupId: string
|
||||||
|
groupName: string | undefined
|
||||||
|
groupPending: boolean
|
||||||
|
attendeesTotal: number
|
||||||
|
capacity: number | null
|
||||||
|
activeTab: AddAttendeeTab
|
||||||
|
setActiveTab: (value: AddAttendeeTab) => void
|
||||||
|
cancelAddAttendee: () => void
|
||||||
|
isCapacityModalOpen: boolean
|
||||||
|
capacityPayload: CreateAttendee | null
|
||||||
|
closeCapacityModal: () => void
|
||||||
|
isBulkCapacityModalOpen: boolean
|
||||||
|
closeBulkCapacityModal: () => void
|
||||||
|
parsedContacts: ParsedContactRow[]
|
||||||
|
setParsedContacts: (contacts: ParsedContactRow[]) => void
|
||||||
|
removeParsedContact: (id: string) => void
|
||||||
|
fileName: string | null
|
||||||
|
setFileName: (name: string | null) => void
|
||||||
|
isParsingFile: boolean
|
||||||
|
setIsParsingFile: (value: boolean) => void
|
||||||
|
isDragging: boolean
|
||||||
|
setIsDragging: (value: boolean) => void
|
||||||
|
validRowsCount: number
|
||||||
|
invalidRowsCount: number
|
||||||
|
isSubmittingAttendee: boolean
|
||||||
|
isSubmittingForcedAttendee: boolean
|
||||||
|
isSubmittingWaitlistEntry: boolean
|
||||||
|
isSubmittingBulkImport: boolean
|
||||||
|
submitQuickAttendee: (payload: CreateAttendee) => void
|
||||||
|
submitForcedAttendee: () => void
|
||||||
|
submitWaitlistEntry: () => void
|
||||||
|
requestBulkImport: () => void
|
||||||
|
confirmBulkImportOverCapacity: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const AddAttendeeContext = createContext<AddAttendeeContextValue | null>(null)
|
||||||
|
|
||||||
|
export function AddAttendeeProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const toast = useToast()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
||||||
|
const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false)
|
||||||
|
const [pendingCapacityPayload, setPendingCapacityPayload] = useState<CreateAttendee | null>(null)
|
||||||
|
const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false)
|
||||||
|
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([])
|
||||||
|
const [fileName, setFileName] = useState<string | null>(null)
|
||||||
|
const [isParsingFile, setIsParsingFile] = useState(false)
|
||||||
|
const [isDragging, setIsDragging] = useState(false)
|
||||||
|
|
||||||
|
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar,
|
||||||
|
// así que la página se monta sin spinner ni fetch duplicado.
|
||||||
|
const groupQuery = useQuery({
|
||||||
|
queryKey: ['group', groupId],
|
||||||
|
queryFn: () => getGroup(groupId),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const attendeesQuery = useQuery({
|
||||||
|
queryKey: ['group-attendees', groupId],
|
||||||
|
queryFn: () => getGroupAttendees(groupId, 1, 100),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const group = groupQuery.data
|
||||||
|
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? 0
|
||||||
|
const capacity = group?.capacity ?? null
|
||||||
|
|
||||||
|
const goBackToGroup = () => {
|
||||||
|
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeCapacityFlow = () => {
|
||||||
|
setPendingCapacityPayload(null)
|
||||||
|
setIsCapacityModalOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const invalidateGroupQueries = () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
||||||
|
if (result.outcome === 'created') {
|
||||||
|
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
||||||
|
} else {
|
||||||
|
toast.info(result.message)
|
||||||
|
}
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
goBackToGroup()
|
||||||
|
}
|
||||||
|
|
||||||
|
const createAttendeeMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
||||||
|
onMutate: (payload) => setPendingCapacityPayload(payload),
|
||||||
|
onSuccess: handleCreateSuccess,
|
||||||
|
onError: (err: Error) => {
|
||||||
|
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
||||||
|
setIsCapacityModalOpen(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toast.error(err.message || 'Error al agregar miembro.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const createAttendeeForceMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
||||||
|
onSuccess: handleCreateSuccess,
|
||||||
|
onError: (err: Error) => {
|
||||||
|
toast.error(err.message || 'Error al agregar miembro.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const addToWaitlistMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload),
|
||||||
|
onMutate: async (payload: CreateGroupWaitlistEntry) => {
|
||||||
|
await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
const previousWaitlist = queryClient.getQueryData<GroupWaitlistList>(['group-waitlist', groupId])
|
||||||
|
|
||||||
|
if (previousWaitlist) {
|
||||||
|
const optimisticEntry: GroupWaitlistEntryDto = {
|
||||||
|
id: `temp-${Date.now()}`,
|
||||||
|
groupId,
|
||||||
|
fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(),
|
||||||
|
phone: payload.phone,
|
||||||
|
email: payload.email || null,
|
||||||
|
notes: payload.notes ?? null,
|
||||||
|
status: 'PENDING',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], {
|
||||||
|
data: [optimisticEntry, ...previousWaitlist.data],
|
||||||
|
pagination: {
|
||||||
|
...previousWaitlist.pagination,
|
||||||
|
total: previousWaitlist.pagination.total + 1,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return { previousWaitlist }
|
||||||
|
},
|
||||||
|
onSuccess: (entry) => {
|
||||||
|
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
||||||
|
invalidateGroupQueries()
|
||||||
|
goBackToGroup()
|
||||||
|
},
|
||||||
|
onError: (err: Error, _payload, context) => {
|
||||||
|
if (context?.previousWaitlist) {
|
||||||
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
||||||
|
}
|
||||||
|
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
||||||
|
toast.info('Este número ya está en la lista de espera del grupo.')
|
||||||
|
} else {
|
||||||
|
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
||||||
|
}
|
||||||
|
closeCapacityFlow()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const bulkImportMutation = useMutation({
|
||||||
|
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
||||||
|
onSuccess: (res) => {
|
||||||
|
toast.success(res.message)
|
||||||
|
setParsedContacts([])
|
||||||
|
setFileName(null)
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
goBackToGroup()
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
toast.error(err.message || 'Error al importar miembros.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const validRows: BulkAttendeeRow[] = useMemo(
|
||||||
|
() =>
|
||||||
|
parsedContacts
|
||||||
|
.filter((contact) => contact.isValid)
|
||||||
|
.map((contact) => ({
|
||||||
|
firstName: contact.firstName,
|
||||||
|
lastName: contact.lastName,
|
||||||
|
fullName: contact.fullName,
|
||||||
|
phone: contact.phone,
|
||||||
|
email: contact.email || undefined,
|
||||||
|
notes: contact.notes || undefined,
|
||||||
|
})),
|
||||||
|
[parsedContacts],
|
||||||
|
)
|
||||||
|
|
||||||
|
const runBulkImport = () => {
|
||||||
|
if (validRows.length === 0) {
|
||||||
|
toast.error('No hay miembros válidos para importar.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bulkImportMutation.mutate(validRows)
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestBulkImport = () => {
|
||||||
|
if (validRows.length === 0) {
|
||||||
|
toast.error('No hay miembros válidos para importar.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (capacity != null && attendeesTotal + validRows.length > capacity) {
|
||||||
|
setIsBulkCapacityModalOpen(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
runBulkImport()
|
||||||
|
}
|
||||||
|
|
||||||
|
const value: AddAttendeeContextValue = {
|
||||||
|
groupId,
|
||||||
|
groupName: group?.name,
|
||||||
|
groupPending: groupQuery.isPending,
|
||||||
|
attendeesTotal,
|
||||||
|
capacity,
|
||||||
|
activeTab,
|
||||||
|
setActiveTab,
|
||||||
|
cancelAddAttendee: goBackToGroup,
|
||||||
|
isCapacityModalOpen,
|
||||||
|
capacityPayload: pendingCapacityPayload,
|
||||||
|
closeCapacityModal: closeCapacityFlow,
|
||||||
|
isBulkCapacityModalOpen,
|
||||||
|
closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false),
|
||||||
|
parsedContacts,
|
||||||
|
setParsedContacts,
|
||||||
|
removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)),
|
||||||
|
fileName,
|
||||||
|
setFileName,
|
||||||
|
isParsingFile,
|
||||||
|
setIsParsingFile,
|
||||||
|
isDragging,
|
||||||
|
setIsDragging,
|
||||||
|
validRowsCount: validRows.length,
|
||||||
|
invalidRowsCount: parsedContacts.length - validRows.length,
|
||||||
|
isSubmittingAttendee: createAttendeeMutation.isPending,
|
||||||
|
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
||||||
|
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
||||||
|
isSubmittingBulkImport: bulkImportMutation.isPending,
|
||||||
|
submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload),
|
||||||
|
submitForcedAttendee: () => {
|
||||||
|
if (pendingCapacityPayload) {
|
||||||
|
createAttendeeForceMutation.mutate({ ...pendingCapacityPayload })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
submitWaitlistEntry: () => {
|
||||||
|
if (pendingCapacityPayload) {
|
||||||
|
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
requestBulkImport,
|
||||||
|
confirmBulkImportOverCapacity: () => {
|
||||||
|
setIsBulkCapacityModalOpen(false)
|
||||||
|
runBulkImport()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AddAttendeeContext.Provider value={value}>{children}</AddAttendeeContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAddAttendee() {
|
||||||
|
const context = useContext(AddAttendeeContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAddAttendee debe usarse dentro de <AddAttendeeProvider>')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Check } from 'lucide-react'
|
import { Check } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function BulkCapacityModal() {
|
export function BulkCapacityModal() {
|
||||||
const {
|
const {
|
||||||
@@ -9,8 +9,9 @@ export function BulkCapacityModal() {
|
|||||||
confirmBulkImportOverCapacity,
|
confirmBulkImportOverCapacity,
|
||||||
validRowsCount,
|
validRowsCount,
|
||||||
attendeesTotal,
|
attendeesTotal,
|
||||||
group,
|
groupName,
|
||||||
} = useGroupDetail()
|
capacity,
|
||||||
|
} = useAddAttendee()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
@@ -24,13 +25,17 @@ export function BulkCapacityModal() {
|
|||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
Estás por importar <strong className="text-primary">{validRowsCount}</strong> miembro(s), pero el
|
Estás por importar <strong className="text-primary">{validRowsCount}</strong> miembro(s), pero el
|
||||||
grupo ya tiene <strong className="text-primary">{attendeesTotal}</strong> inscrito(s) y su cupo es
|
grupo ya tiene <strong className="text-primary">{attendeesTotal}</strong> inscrito(s) y su cupo es
|
||||||
de <strong className="text-primary">{group?.capacity}</strong>. ¿Deseas importarlos de todos modos?
|
de <strong className="text-primary">{capacity}</strong>. ¿Deseas importarlos de todos modos?
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center justify-end gap-2.5 pt-2">
|
<div className="flex flex-col-reverse gap-2.5 pt-2 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeBulkCapacityModal}>
|
<Button variant="ghost" onClick={closeBulkCapacityModal} className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" onClick={confirmBulkImportOverCapacity} className="gap-2">
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={confirmBulkImportOverCapacity}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
|
>
|
||||||
<Check className="size-4" />
|
<Check className="size-4" />
|
||||||
Importar de todos modos
|
Importar de todos modos
|
||||||
</Button>
|
</Button>
|
||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
parseXlsxContent,
|
parseXlsxContent,
|
||||||
} from '../../../lib/file-parser'
|
} from '../../../lib/file-parser'
|
||||||
import { cn } from '../../../lib/utils'
|
import { cn } from '../../../lib/utils'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function BulkImportPanel() {
|
export function BulkImportPanel() {
|
||||||
const {
|
const {
|
||||||
@@ -24,9 +24,9 @@ export function BulkImportPanel() {
|
|||||||
validRowsCount,
|
validRowsCount,
|
||||||
invalidRowsCount,
|
invalidRowsCount,
|
||||||
isSubmittingBulkImport,
|
isSubmittingBulkImport,
|
||||||
closeAddAttendeeModal,
|
cancelAddAttendee,
|
||||||
requestBulkImport,
|
requestBulkImport,
|
||||||
} = useGroupDetail()
|
} = useAddAttendee()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
@@ -115,12 +115,12 @@ export function BulkImportPanel() {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between px-1 text-xs">
|
<div className="flex flex-col items-start gap-1 px-1 text-xs sm:flex-row sm:items-center sm:justify-between">
|
||||||
<span className="text-foreground/60">¿No tienes el archivo listo? Usa nuestra plantilla.</span>
|
<span className="text-foreground/60">¿No tienes el archivo listo? Usa nuestra plantilla.</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={downloadAttendeeTemplateCsv}
|
onClick={downloadAttendeeTemplateCsv}
|
||||||
className="inline-flex items-center gap-1 font-medium text-accent transition-colors hover:text-accent-strong"
|
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-accent transition-colors hover:text-accent-strong"
|
||||||
>
|
>
|
||||||
<Download className="size-3.5" />
|
<Download className="size-3.5" />
|
||||||
<span>Descargar plantilla CSV</span>
|
<span>Descargar plantilla CSV</span>
|
||||||
@@ -207,15 +207,15 @@ export function BulkImportPanel() {
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-end gap-2.5 border-t border-border pt-3">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeAddAttendeeModal}>
|
<Button variant="ghost" onClick={cancelAddAttendee} className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={requestBulkImport}
|
onClick={requestBulkImport}
|
||||||
disabled={isSubmittingBulkImport || validRowsCount === 0}
|
disabled={isSubmittingBulkImport || validRowsCount === 0}
|
||||||
className="gap-2"
|
className="w-full sm:w-auto"
|
||||||
>
|
>
|
||||||
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
<span>Confirmar e Importar ({validRowsCount})</span>
|
<span>Confirmar e Importar ({validRowsCount})</span>
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function CapacityModal() {
|
export function CapacityModal() {
|
||||||
const {
|
const {
|
||||||
isCapacityModalOpen,
|
isCapacityModalOpen,
|
||||||
closeCapacityModal,
|
closeCapacityModal,
|
||||||
capacityPayload,
|
capacityPayload,
|
||||||
group,
|
groupName,
|
||||||
|
capacity,
|
||||||
submitForcedAttendee,
|
submitForcedAttendee,
|
||||||
submitWaitlistEntry,
|
submitWaitlistEntry,
|
||||||
isSubmittingForcedAttendee,
|
isSubmittingForcedAttendee,
|
||||||
isSubmittingWaitlistEntry,
|
isSubmittingWaitlistEntry,
|
||||||
} = useGroupDetail()
|
} = useAddAttendee()
|
||||||
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -26,15 +27,20 @@ export function CapacityModal() {
|
|||||||
{capacityPayload ? (
|
{capacityPayload ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
El grupo <strong className="text-primary">{group?.name}</strong> ya alcanzó su cupo de{' '}
|
El grupo <strong className="text-primary">{groupName}</strong> ya alcanzó su cupo de{' '}
|
||||||
<strong className="text-primary">{group?.capacity}</strong> miembros. ¿Qué deseas hacer con{' '}
|
<strong className="text-primary">{capacity}</strong> miembros. ¿Qué deseas hacer con{' '}
|
||||||
<strong className="text-primary">
|
<strong className="text-primary">
|
||||||
{`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()}
|
{`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()}
|
||||||
</strong>
|
</strong>
|
||||||
?
|
?
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-col gap-2.5">
|
<div className="flex flex-col gap-2.5">
|
||||||
<Button variant="primary" onClick={submitForcedAttendee} disabled={isBusy} className="gap-2">
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={submitForcedAttendee}
|
||||||
|
disabled={isBusy}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
{isSubmittingForcedAttendee ? (
|
{isSubmittingForcedAttendee ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
@@ -42,7 +48,12 @@ export function CapacityModal() {
|
|||||||
)}
|
)}
|
||||||
<span>Agregar de todos modos</span>
|
<span>Agregar de todos modos</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" onClick={submitWaitlistEntry} disabled={isBusy} className="gap-2">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={submitWaitlistEntry}
|
||||||
|
disabled={isBusy}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
{isSubmittingWaitlistEntry ? (
|
{isSubmittingWaitlistEntry ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Check, Loader2 } from 'lucide-react'
|
import { Check, Loader2 } from 'lucide-react'
|
||||||
import { Button, Input, Label, useToast } from '../../../components/ui'
|
import { Button, Input, Label, useToast } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function QuickAddForm() {
|
export function QuickAddForm() {
|
||||||
const { submitQuickAttendee, isSubmittingAttendee, closeAddAttendeeModal } = useGroupDetail()
|
const { submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const [firstName, setFirstName] = useState('')
|
const [firstName, setFirstName] = useState('')
|
||||||
const [lastName, setLastName] = useState('')
|
const [lastName, setLastName] = useState('')
|
||||||
@@ -34,7 +34,6 @@ export function QuickAddForm() {
|
|||||||
setEmail('')
|
setEmail('')
|
||||||
setNotes('')
|
setNotes('')
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
@@ -104,17 +103,23 @@ export function QuickAddForm() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-end gap-2.5 border-t border-border pt-3">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
resetForm()
|
resetForm()
|
||||||
closeAddAttendeeModal()
|
cancelAddAttendee()
|
||||||
}}
|
}}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
>
|
>
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" type="submit" disabled={isSubmittingAttendee} className="gap-2">
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
type="submit"
|
||||||
|
disabled={isSubmittingAttendee}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
|
>
|
||||||
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
<span>Guardar Miembro</span>
|
<span>Guardar Miembro</span>
|
||||||
</Button>
|
</Button>
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { Link, useParams } from '@tanstack/react-router'
|
import { Link, useParams } from '@tanstack/react-router'
|
||||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
import type { GroupDto, StudentAtRiskDto } from '@gruperly/shared'
|
||||||
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
||||||
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
import { Badge, Button, useToast } from '../../../components/ui'
|
import { Badge, Button, useToast } from '../../../components/ui'
|
||||||
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
||||||
import { KpiCard } from './KpiCard'
|
import { KpiCard } from './KpiCard'
|
||||||
@@ -77,124 +78,144 @@ export function AnalyticsView() {
|
|||||||
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupName = riskQuery.data?.groupName
|
// El nombre suele estar en caché porque se llega desde la ficha del grupo: así
|
||||||
|
// el título grande aparece de entrada y no hay salto cuando cargan las queries.
|
||||||
if (analyticsQuery.isPending || riskQuery.isPending) {
|
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
|
||||||
return (
|
const groupName = riskQuery.data?.groupName ?? cachedGroupName
|
||||||
<div className="flex items-center justify-center py-20">
|
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
|
||||||
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
|
||||||
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="mt-4"
|
|
||||||
onClick={() => {
|
|
||||||
void analyticsQuery.refetch()
|
|
||||||
void riskQuery.refetch()
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Reintentar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const analytics = analyticsQuery.data
|
const analytics = analyticsQuery.data
|
||||||
const atRisk = riskQuery.data?.data ?? []
|
const atRisk = riskQuery.data?.data ?? []
|
||||||
|
|
||||||
|
const isPending = analyticsQuery.isPending || riskQuery.isPending
|
||||||
|
const hasFailed = analyticsQuery.isError || riskQuery.isError
|
||||||
|
// El contenido necesita los dos queries: sin `riskQuery` no hay ni el nombre
|
||||||
|
// del grupo ni la lista de alumnos en riesgo.
|
||||||
|
const showContent = !isPending && !hasFailed && Boolean(analytics)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
||||||
<Link
|
{/* El título grande va siempre, incluso cargando: es lo que da altura a
|
||||||
to="/groups/$groupId"
|
la barra y evita que el layout salte cuando llegan los datos. */}
|
||||||
params={{ groupId }}
|
<LargeTitle
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
title={groupName ?? 'Grupo'}
|
||||||
|
leading={
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
Volver al grupo
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
{/* "Estadísticas" es el subtítulo de la pantalla, no el título: el
|
||||||
Volver a {groupName ?? 'el grupo'}
|
título grande identifica el grupo y la barra colapsada lo muestra
|
||||||
</Link>
|
para saber siempre sobre qué se está mirando. */}
|
||||||
|
<div className="mt-2 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="min-w-0">
|
||||||
<div>
|
<p className="text-[14px] font-semibold uppercase tracking-wide text-foreground/70">
|
||||||
<h1 className="text-2xl font-bold text-primary">Estadísticas</h1>
|
Estadísticas
|
||||||
<p className="mt-2 text-sm text-foreground/60">
|
</p>
|
||||||
Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}.
|
<p className="mt-0.5 text-pretty text-sm text-foreground/80">
|
||||||
</p>
|
Asistencia y gestión de riesgo
|
||||||
</div>
|
|
||||||
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
|
||||||
Últimos 30 días
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
|
||||||
<KpiCard
|
|
||||||
icon={<Percent className="size-5" />}
|
|
||||||
label="Asistencia promedio"
|
|
||||||
value={`${analytics.attendanceRate}%`}
|
|
||||||
hint="últimos 30 días"
|
|
||||||
/>
|
|
||||||
<KpiCard
|
|
||||||
icon={<CalendarCheck className="size-5" />}
|
|
||||||
label="Asistencias del mes"
|
|
||||||
value={analytics.totalPresent.toLocaleString('es-MX')}
|
|
||||||
hint={`${analytics.totalClasses} clases dictadas`}
|
|
||||||
/>
|
|
||||||
<KpiCard
|
|
||||||
icon={<DoorOpen className="size-5" />}
|
|
||||||
label="Cupos recuperados"
|
|
||||||
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
|
||||||
hint="por ausencias avisadas"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-8">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Users className="size-5 text-accent" />
|
|
||||||
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
|
||||||
{atRisk.length > 0 ? (
|
|
||||||
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
|
||||||
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
|
||||||
</Badge>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
|
||||||
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{atRisk.length === 0 ? (
|
|
||||||
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
|
||||||
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
|
||||||
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
||||||
<ul className="mt-4 space-y-3">
|
Últimos 30 días
|
||||||
{atRisk.map((student) => (
|
</span>
|
||||||
<AtRiskStudentCard
|
</div>
|
||||||
key={student.attendeeId}
|
</LargeTitle>
|
||||||
student={student}
|
|
||||||
menuOpen={menuOpenFor === student.attendeeId}
|
{isPending ? (
|
||||||
onToggleMenu={() =>
|
<div className="flex items-center justify-center py-20">
|
||||||
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
}
|
</div>
|
||||||
onViewHistory={() => setHistoryStudent(student)}
|
) : null}
|
||||||
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
|
||||||
onRequestStatusAction={(action) => {
|
{hasFailed ? (
|
||||||
setStatusAction(action)
|
<div className="mt-6 rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||||
setMenuOpenFor(null)
|
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
||||||
}}
|
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
||||||
/>
|
<Button
|
||||||
))}
|
variant="outline"
|
||||||
</ul>
|
className="mt-4"
|
||||||
)}
|
onClick={() => {
|
||||||
</div>
|
void analyticsQuery.refetch()
|
||||||
|
void riskQuery.refetch()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{showContent && analytics ? (
|
||||||
|
<>
|
||||||
|
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
|
<KpiCard
|
||||||
|
icon={<Percent className="size-5" />}
|
||||||
|
label="Asistencia promedio"
|
||||||
|
value={`${analytics.attendanceRate}%`}
|
||||||
|
hint="últimos 30 días"
|
||||||
|
/>
|
||||||
|
<KpiCard
|
||||||
|
icon={<CalendarCheck className="size-5" />}
|
||||||
|
label="Asistencias del mes"
|
||||||
|
value={analytics.totalPresent.toLocaleString('es-MX')}
|
||||||
|
hint={`${analytics.totalClasses} clases dictadas`}
|
||||||
|
/>
|
||||||
|
<KpiCard
|
||||||
|
icon={<DoorOpen className="size-5" />}
|
||||||
|
label="Cupos recuperados"
|
||||||
|
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
||||||
|
hint="por ausencias avisadas"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-8">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Users className="size-5 text-accent" />
|
||||||
|
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
||||||
|
{atRisk.length > 0 ? (
|
||||||
|
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
||||||
|
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
|
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{atRisk.length === 0 ? (
|
||||||
|
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||||
|
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
||||||
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
|
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="mt-4 space-y-3">
|
||||||
|
{atRisk.map((student) => (
|
||||||
|
<AtRiskStudentCard
|
||||||
|
key={student.attendeeId}
|
||||||
|
student={student}
|
||||||
|
menuOpen={menuOpenFor === student.attendeeId}
|
||||||
|
onToggleMenu={() =>
|
||||||
|
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
||||||
|
}
|
||||||
|
onViewHistory={() => setHistoryStudent(student)}
|
||||||
|
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
||||||
|
onRequestStatusAction={(action) => {
|
||||||
|
setStatusAction(action)
|
||||||
|
setMenuOpenFor(null)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<AttendeeHistoryModal
|
<AttendeeHistoryModal
|
||||||
student={historyStudent}
|
student={historyStudent}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
import type { StudentAtRiskDto } from '@gruperly/shared'
|
||||||
import { MessageCircle, MoreVertical, Pause, UserMinus } from 'lucide-react'
|
import { MessageCircle, MoreVertical, Pause, UserMinus } from 'lucide-react'
|
||||||
import { Avatar, Badge, Button } from '../../../components/ui'
|
import { Avatar, Badge, Button } from '../../../components/ui'
|
||||||
import { cn } from '../../../lib/utils'
|
import { formatPhoneDisplay } from '../../../lib/format'
|
||||||
|
|
||||||
export type StatusAction = { student: StudentAtRiskDto; status: 'PAUSED' | 'DROPPED' } | null
|
export type StatusAction = { student: StudentAtRiskDto; status: 'PAUSED' | 'DROPPED' } | null
|
||||||
|
|
||||||
@@ -32,8 +32,10 @@ export function AtRiskStudentCard({
|
|||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
{student.phone ?? 'Sin teléfono'} · {student.monthlyAttendanceRate}% de asistencia
|
{student.phone
|
||||||
mensual
|
? `${formatPhoneDisplay(student.phone)} · `
|
||||||
|
: 'Sin teléfono · '}
|
||||||
|
{student.monthlyAttendanceRate}% de asistencia mensual
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
341
apps/web/src/features/groups/card.ts
Normal file
341
apps/web/src/features/groups/card.ts
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
import type { GroupListItem, GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
|
||||||
|
|
||||||
|
/* Derivaciones de la tarjeta del listado de grupos. La tarjeta no consulta
|
||||||
|
nada: decide acá qué se ve, con qué tono y con qué peso visual, para que el
|
||||||
|
JSX solo arme el layout y las reglas se puedan testear sueltas.
|
||||||
|
|
||||||
|
Los conteos por nivel y los miembros urgentes no se calculan en el cliente:
|
||||||
|
los trae `GET /groups-risk/overview`, que corre la misma función de dominio
|
||||||
|
(`getGroupAttendanceSummary` en packages/shared) que va a usar la sección de
|
||||||
|
seguimiento del Inicio. Acá solo se adapta esa respuesta a lo que la
|
||||||
|
tarjeta necesita pintar, y se decide cómo se lee. */
|
||||||
|
|
||||||
|
export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'>
|
||||||
|
|
||||||
|
/** A partir de este cupo el indicador deja de ser un segmento por lugar: con
|
||||||
|
* más de diez segmentos no se distinguen entre sí y pasan a ser bloques
|
||||||
|
* proporcionales. */
|
||||||
|
export const SEGMENTED_CAPACITY_MAX = 10
|
||||||
|
|
||||||
|
export type MemberStatus = 'high_risk' | 'attention' | 'ok'
|
||||||
|
|
||||||
|
export type GroupMember = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
status: MemberStatus
|
||||||
|
absences: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CapacityCounts = {
|
||||||
|
riesgoAlto: number
|
||||||
|
atencion: number
|
||||||
|
ok: number
|
||||||
|
libres: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Conteos derivados directamente de una lista de miembros y el cupo.
|
||||||
|
*/
|
||||||
|
export function capacityCountsFromMembers(
|
||||||
|
members: GroupMember[],
|
||||||
|
capacity: number,
|
||||||
|
): CapacityCounts {
|
||||||
|
let riesgoAlto = 0
|
||||||
|
let atencion = 0
|
||||||
|
let ok = 0
|
||||||
|
|
||||||
|
for (const m of members) {
|
||||||
|
if (m.status === 'high_risk') riesgoAlto++
|
||||||
|
else if (m.status === 'attention') atencion++
|
||||||
|
else ok++
|
||||||
|
}
|
||||||
|
|
||||||
|
const libres = Math.max(capacity - members.length, 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
riesgoAlto,
|
||||||
|
atencion,
|
||||||
|
ok,
|
||||||
|
libres,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reglas de texto de alerta a partir de los miembros:
|
||||||
|
* - 1 en riesgo alto: "{Nombre}: {N} faltas" + (si hay atención > 0) " · {K} en atención"
|
||||||
|
* - 2 o más en riesgo alto: "{N} en riesgo alto" + (si hay atención > 0) " · {K} en atención"
|
||||||
|
* - 0 en riesgo alto pero atención > 0: "{K} en atención"
|
||||||
|
* - Ninguno: null
|
||||||
|
*/
|
||||||
|
export function alertTextFromMembers(members: GroupMember[]): string | null {
|
||||||
|
const highRisk = members.filter((m) => m.status === 'high_risk')
|
||||||
|
const attention = members.filter((m) => m.status === 'attention')
|
||||||
|
|
||||||
|
const kAtencion = attention.length > 0 ? ` · ${attention.length} en atención` : ''
|
||||||
|
|
||||||
|
if (highRisk.length === 1) {
|
||||||
|
const first = highRisk[0]
|
||||||
|
const nombre = firstName(first.name)
|
||||||
|
const faltas = `${first.absences} ${first.absences === 1 ? 'falta' : 'faltas'}`
|
||||||
|
return `${nombre}: ${faltas}${kAtencion}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (highRisk.length >= 2) {
|
||||||
|
return `${highRisk.length} en riesgo alto${kAtencion}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attention.length > 0) {
|
||||||
|
return `${attention.length} en atención`
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convierte un GroupListItem y GroupRiskSummary en una lista de GroupMember
|
||||||
|
* para unificar la representación interna.
|
||||||
|
*/
|
||||||
|
export function membersFromGroupAndRisk(
|
||||||
|
group: Pick<GroupListItem, 'attendeesCount' | 'capacity'>,
|
||||||
|
risk: GroupRiskSummary | undefined,
|
||||||
|
): GroupMember[] {
|
||||||
|
const members: GroupMember[] = []
|
||||||
|
const urgentes = risk?.urgentes ?? []
|
||||||
|
|
||||||
|
for (const u of urgentes) {
|
||||||
|
if (u.level === 'riesgo_alto') {
|
||||||
|
members.push({
|
||||||
|
id: u.attendeeId,
|
||||||
|
name: u.fullName,
|
||||||
|
status: 'high_risk',
|
||||||
|
absences: u.consecutiveAbsences,
|
||||||
|
})
|
||||||
|
} else if (u.level === 'atencion') {
|
||||||
|
members.push({
|
||||||
|
id: u.attendeeId,
|
||||||
|
name: u.fullName,
|
||||||
|
status: 'attention',
|
||||||
|
absences: u.consecutiveAbsences,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentHigh = members.filter((m) => m.status === 'high_risk').length
|
||||||
|
const remainingHigh = Math.max((risk?.riesgoAlto ?? 0) - currentHigh, 0)
|
||||||
|
for (let i = 0; i < remainingHigh; i++) {
|
||||||
|
members.push({
|
||||||
|
id: `high-risk-extra-${i}`,
|
||||||
|
name: `Alumno ${members.length + 1}`,
|
||||||
|
status: 'high_risk',
|
||||||
|
absences: 1,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentAttention = members.filter((m) => m.status === 'attention').length
|
||||||
|
const remainingAttention = Math.max((risk?.atencion ?? 0) - currentAttention, 0)
|
||||||
|
for (let i = 0; i < remainingAttention; i++) {
|
||||||
|
members.push({
|
||||||
|
id: `attention-extra-${i}`,
|
||||||
|
name: `Alumno ${members.length + 1}`,
|
||||||
|
status: 'attention',
|
||||||
|
absences: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainingOk = Math.max(group.attendeesCount - members.length, 0)
|
||||||
|
for (let i = 0; i < remainingOk; i++) {
|
||||||
|
members.push({
|
||||||
|
id: `ok-${i}`,
|
||||||
|
name: `Alumno ${members.length + 1}`,
|
||||||
|
status: 'ok',
|
||||||
|
absences: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return members
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Conteos que consume el indicador de cupo y asistencia.
|
||||||
|
*
|
||||||
|
* `ok` es la diferencia, no un número de la API: el resumen de riesgo solo
|
||||||
|
* nombra a los que hay que mirar, y el resto de la matrícula es lo que queda
|
||||||
|
* bien. Se acota a 0 porque el resumen cuenta los miembros activos y la tarjeta
|
||||||
|
* muestra todos.
|
||||||
|
*
|
||||||
|
* Sin resumen todavía (o si la consulta falla) todos los miembros caen en `ok`.
|
||||||
|
* Es el estado en calma: el resumen puede seguir cargando y la tarjeta tiene
|
||||||
|
* que poder pintar igual.
|
||||||
|
*/
|
||||||
|
export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts {
|
||||||
|
const riesgoAlto = risk?.riesgoAlto ?? 0
|
||||||
|
const atencion = risk?.atencion ?? 0
|
||||||
|
const libres = group.capacity === null ? 0 : Math.max(group.capacity - group.attendeesCount, 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
riesgoAlto,
|
||||||
|
atencion,
|
||||||
|
ok: Math.max(group.attendeesCount - riesgoAlto - atencion, 0),
|
||||||
|
libres,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tono de la línea de estado y del indicador: el peor nivel presente. */
|
||||||
|
export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok'
|
||||||
|
|
||||||
|
export function riskTone(counts: CapacityCounts): RiskTone {
|
||||||
|
if (counts.riesgoAlto > 0) return 'riesgo_alto'
|
||||||
|
if (counts.atencion > 0) return 'atencion'
|
||||||
|
return 'ok'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StatusLine = {
|
||||||
|
text: string
|
||||||
|
tone: RiskTone
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* La cuarta fila de la tarjeta: qué está pasando con la asistencia.
|
||||||
|
*
|
||||||
|
* Con una sola persona en riesgo alto se muestra su nombre y cantidad de
|
||||||
|
* faltas. Con dos o más se resume por nivel. Cuando no hay nada que reportar,
|
||||||
|
* el componente omite esta línea por completo.
|
||||||
|
*/
|
||||||
|
export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine {
|
||||||
|
const counts = capacityCounts(group, risk)
|
||||||
|
const tone = riskTone(counts)
|
||||||
|
const urgentes = risk?.urgentes.filter((miembro) => miembro.level !== 'ok') ?? []
|
||||||
|
|
||||||
|
if (tone !== 'ok') {
|
||||||
|
const conNombre = counts.riesgoAlto === 1 ? namedHighRiskMember(urgentes, counts) : ''
|
||||||
|
return { text: conNombre || countedLevels(counts), tone }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (risk?.asistencia != null) return { text: `Asistencia ${risk.asistencia}%`, tone: 'ok' }
|
||||||
|
return { text: 'Sin clases registradas', tone: 'ok' }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El total con el que se mide el indicador.
|
||||||
|
*
|
||||||
|
* Cuando el grupo no tiene cupo declarado la barra no desaparece: pasa a
|
||||||
|
* medir a la matrícula, un segmento (o bloque) por miembro, con los lugares
|
||||||
|
* libres en cero. Un grupo sin cupo no tiene "lugares libres" que mostrar, pero
|
||||||
|
* sí tiene gente en riesgo, y esa es justo la señal que la barra existe para
|
||||||
|
* comunicar. Lo que sí desaparece es la barra de un grupo vacío: sin miembros no
|
||||||
|
* hay nada que repartir.
|
||||||
|
*/
|
||||||
|
export function barCapacity(group: GroupLike): number {
|
||||||
|
return group.capacity ?? group.attendeesCount
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ¿El indicador va con un segmento por lugar, o con bloques proporcionales? */
|
||||||
|
export function isSegmentedCapacity(capacity: number): boolean {
|
||||||
|
return capacity > 0 && capacity <= SEGMENTED_CAPACITY_MAX
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "5/10 miembros", o "5 miembros" cuando el grupo no tiene cupo definido. */
|
||||||
|
export function occupancyLabel(group: GroupLike): string {
|
||||||
|
if (group.capacity === null) return membersLabel(group.attendeesCount)
|
||||||
|
return `${group.attendeesCount}/${group.capacity} ${group.capacity === 1 ? 'miembro' : 'miembros'}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombra a la única persona en riesgo alto y agrega el total en atención. */
|
||||||
|
function namedHighRiskMember(
|
||||||
|
urgentes: UrgentMemberSummary[],
|
||||||
|
counts: CapacityCounts,
|
||||||
|
): string {
|
||||||
|
const urgente = urgentes.find((miembro) => miembro.level === 'riesgo_alto')
|
||||||
|
if (!urgente) return ''
|
||||||
|
|
||||||
|
const motivo = absenceReason(urgente)
|
||||||
|
if (!motivo) return ''
|
||||||
|
|
||||||
|
const nombre = `${firstName(urgente.fullName)}: ${motivo}`
|
||||||
|
return counts.atencion > 0 ? `${nombre} · ${counts.atencion} en atención` : nombre
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Grupo grande: los conteos por nivel, y solo de los que hay algo que decir. */
|
||||||
|
function countedLevels(counts: CapacityCounts): string {
|
||||||
|
const partes: string[] = []
|
||||||
|
if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`)
|
||||||
|
if (counts.atencion > 0) partes.push(`${counts.atencion} en atención`)
|
||||||
|
return partes.join(' · ')
|
||||||
|
}
|
||||||
|
|
||||||
|
/* El motivo que mejor explica por qué alguien está en la línea de estado, en el
|
||||||
|
orden en que la regla los considera: primero la racha de faltas (algo que se
|
||||||
|
está yendo), después el tiempo sin aparecer, y por último la asistencia. Con
|
||||||
|
una sola falta y al día se devuelve null: no alcanza para nombrar a nadie. */
|
||||||
|
function absenceReason(miembro: UrgentMemberSummary): string | null {
|
||||||
|
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
|
||||||
|
|
||||||
|
if (faltas > 0) return `${faltas} ${faltas === 1 ? 'falta' : 'faltas'}`
|
||||||
|
if (dias != null && dias > 0) return `${dias} ${dias === 1 ? 'día' : 'días'} sin venir`
|
||||||
|
if (asistencia != null && asistencia < 100) return `asistencia ${asistencia}%`
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Solo el primer nombre: en una línea de 360px "Sofía Ramírez: 4 faltas" no
|
||||||
|
entra, y entre dos personas con el mismo nombre la ficha las distingue. */
|
||||||
|
function firstName(fullName: string): string {
|
||||||
|
return fullName.trim().split(/\s+/)[0] || fullName
|
||||||
|
}
|
||||||
|
|
||||||
|
function membersLabel(count: number): string {
|
||||||
|
return count === 1 ? '1 miembro' : `${count} miembros`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Casos de prueba solicitados para verificación contra la imagen de referencia.
|
||||||
|
*/
|
||||||
|
export const MOCK_TEST_CASES = [
|
||||||
|
{
|
||||||
|
id: 'mock-tai-chi',
|
||||||
|
name: 'Tai Chi Martes',
|
||||||
|
capacity: 5,
|
||||||
|
members: [
|
||||||
|
{ id: 'tc-1', name: 'Sofía Ramírez', status: 'high_risk' as const, absences: 4 },
|
||||||
|
{ id: 'tc-2', name: 'Lucas Rossi', status: 'attention' as const, absences: 1 },
|
||||||
|
{ id: 'tc-3', name: 'Martín Paz', status: 'ok' as const, absences: 0 },
|
||||||
|
{ id: 'tc-4', name: 'Elena Gómez', status: 'ok' as const, absences: 0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mock-pilates',
|
||||||
|
name: 'Pilates Sábado',
|
||||||
|
capacity: 15,
|
||||||
|
members: [
|
||||||
|
{ id: 'p-1', name: 'Sofía Ramírez', status: 'high_risk' as const, absences: 4 },
|
||||||
|
{ id: 'p-2', name: 'Lucas Rossi', status: 'attention' as const, absences: 1 },
|
||||||
|
{ id: 'p-3', name: 'Mateo Díaz', status: 'attention' as const, absences: 1 },
|
||||||
|
...Array.from({ length: 9 }, (_, i) => ({
|
||||||
|
id: `p-ok-${i}`,
|
||||||
|
name: `Alumno ${i + 1}`,
|
||||||
|
status: 'ok' as const,
|
||||||
|
absences: 0,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mock-natacion',
|
||||||
|
name: 'Natación Adultos',
|
||||||
|
capacity: 30,
|
||||||
|
members: [
|
||||||
|
{ id: 'n-1', name: 'Alumno 1', status: 'high_risk' as const, absences: 3 },
|
||||||
|
{ id: 'n-2', name: 'Alumno 2', status: 'high_risk' as const, absences: 2 },
|
||||||
|
{ id: 'n-3', name: 'Alumno 3', status: 'high_risk' as const, absences: 4 },
|
||||||
|
{ id: 'n-4', name: 'Alumno 4', status: 'attention' as const, absences: 1 },
|
||||||
|
{ id: 'n-5', name: 'Alumno 5', status: 'attention' as const, absences: 1 },
|
||||||
|
{ id: 'n-6', name: 'Alumno 6', status: 'attention' as const, absences: 2 },
|
||||||
|
{ id: 'n-7', name: 'Alumno 7', status: 'attention' as const, absences: 1 },
|
||||||
|
...Array.from({ length: 15 }, (_, i) => ({
|
||||||
|
id: `n-ok-${i}`,
|
||||||
|
name: `Alumno ${i + 8}`,
|
||||||
|
status: 'ok' as const,
|
||||||
|
absences: 0,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
@@ -3,4 +3,13 @@ import type { GroupRiskLevel } from '@gruperly/shared'
|
|||||||
export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
|
export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
|
||||||
HIGH: 'Riesgo alto',
|
HIGH: 'Riesgo alto',
|
||||||
MEDIUM: 'Riesgo moderado',
|
MEDIUM: 'Riesgo moderado',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* El badge solo dice "Riesgo moderado"; esta frase explica de qué habla
|
||||||
|
(abandono de un miembro, no fraude ni cobranza) y vive en el tooltip. */
|
||||||
|
export const RISK_HINT =
|
||||||
|
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
|
||||||
|
|
||||||
|
/* El motivo concreto ("4 miembros con faltas seguidas") ya no se calcula acá:
|
||||||
|
vive en `card.ts`, que además decide el peso visual del badge. Esto quedó
|
||||||
|
con la copia estática de la ficha del grupo. */
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import { Modal } from '../../../components/ui'
|
|
||||||
import { cn } from '../../../lib/utils'
|
|
||||||
import { BulkImportPanel } from './BulkImportPanel'
|
|
||||||
import { QuickAddForm } from './QuickAddForm'
|
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
|
||||||
|
|
||||||
export function AddAttendeeModal() {
|
|
||||||
const { isAddAttendeeModalOpen, closeAddAttendeeModal, activeTab, setActiveTab } = useGroupDetail()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
isOpen={isAddAttendeeModalOpen}
|
|
||||||
onClose={closeAddAttendeeModal}
|
|
||||||
title="Agregar Miembros al Grupo"
|
|
||||||
description="Agrega miembros rápidamente completando sus datos o importa una lista de contactos."
|
|
||||||
maxWidth="lg"
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setActiveTab('quick')}
|
|
||||||
className={cn(
|
|
||||||
'flex-1 rounded-lg py-2 text-xs font-semibold transition-all',
|
|
||||||
activeTab === 'quick' ? 'bg-surface text-primary shadow-xs' : 'text-foreground/60 hover:text-primary',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Carga Rápida (Individual)
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setActiveTab('bulk')}
|
|
||||||
className={cn(
|
|
||||||
'flex-1 rounded-lg py-2 text-xs font-semibold transition-all',
|
|
||||||
activeTab === 'bulk' ? 'bg-surface text-primary shadow-xs' : 'text-foreground/60 hover:text-primary',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Carga Masiva (CSV / Excel)
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
|
||||||
</div>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
import { Loader2 } from 'lucide-react'
|
|
||||||
import { cn } from '../../../lib/utils'
|
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
|
||||||
|
|
||||||
type RateTone = 'good' | 'mid' | 'low' | 'none'
|
|
||||||
|
|
||||||
function rateTone(rate: number, totalMarked: number): RateTone {
|
|
||||||
if (totalMarked === 0) return 'none'
|
|
||||||
if (rate >= 75) return 'good'
|
|
||||||
if (rate >= 50) return 'mid'
|
|
||||||
return 'low'
|
|
||||||
}
|
|
||||||
|
|
||||||
const barTone: Record<RateTone, string> = {
|
|
||||||
good: 'bg-success',
|
|
||||||
mid: 'bg-warning',
|
|
||||||
low: 'bg-danger',
|
|
||||||
none: 'bg-border',
|
|
||||||
}
|
|
||||||
|
|
||||||
const valueTone: Record<RateTone, string> = {
|
|
||||||
good: 'text-success',
|
|
||||||
mid: 'text-warning',
|
|
||||||
low: 'text-danger',
|
|
||||||
none: 'text-foreground/40',
|
|
||||||
}
|
|
||||||
|
|
||||||
export function AttendeeAttendanceStats() {
|
|
||||||
const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail()
|
|
||||||
|
|
||||||
if (attendeeStatsPending) {
|
|
||||||
return (
|
|
||||||
<div className="flex items-center justify-center rounded-xl border border-border bg-primary-soft/30 py-8">
|
|
||||||
<Loader2 className="size-5 animate-spin text-accent" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (attendeeStatsFailed || !attendeeStats) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
|
||||||
No pudimos cargar la asistencia de este participante.
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats
|
|
||||||
const tone = rateTone(attendanceRate, totalMarked)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-3 rounded-xl border border-border bg-primary-soft/30 p-3 sm:p-4">
|
|
||||||
<div className="flex items-end justify-between gap-3">
|
|
||||||
<div className="min-w-0">
|
|
||||||
<p className="text-[11px] font-medium uppercase tracking-wide text-foreground/50">
|
|
||||||
Asistencia
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-foreground/50">
|
|
||||||
{totalMarked > 0
|
|
||||||
? `Sobre ${totalMarked} clases registradas`
|
|
||||||
: 'Sin clases registradas todavía'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<p className={cn('text-2xl font-bold tabular-nums', valueTone[tone])}>
|
|
||||||
{totalMarked > 0 ? `${attendanceRate}%` : '—'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className="h-1.5 overflow-hidden rounded-full bg-border"
|
|
||||||
role="presentation"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'h-full rounded-full transition-[width] duration-500 ease-out',
|
|
||||||
barTone[tone],
|
|
||||||
)}
|
|
||||||
style={{ width: `${attendanceRate}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<dl className="grid grid-cols-3 gap-1.5 sm:gap-2">
|
|
||||||
<StatCounter value={presentCount} label="Clases asistidas" valueClass="text-success" />
|
|
||||||
<StatCounter value={absentCount} label="Clases ausentes" valueClass="text-danger" />
|
|
||||||
<StatCounter value={excusedCount} label="Avisó ausencia" valueClass="text-warning" />
|
|
||||||
</dl>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function StatCounter({
|
|
||||||
value,
|
|
||||||
label,
|
|
||||||
valueClass,
|
|
||||||
}: {
|
|
||||||
value: number
|
|
||||||
label: string
|
|
||||||
valueClass: string
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="min-w-0 rounded-lg bg-surface px-2 py-2">
|
|
||||||
<dt className="text-[11px] font-medium uppercase leading-tight text-foreground/50">{label}</dt>
|
|
||||||
<dd className={cn('text-lg font-bold tabular-nums', valueClass)}>{value}</dd>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,212 +0,0 @@
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
|
||||||
import {
|
|
||||||
ArrowLeft,
|
|
||||||
Copy,
|
|
||||||
Loader2,
|
|
||||||
Mail,
|
|
||||||
MessageCircle,
|
|
||||||
Phone,
|
|
||||||
ShieldCheck,
|
|
||||||
StickyNote,
|
|
||||||
UserMinus,
|
|
||||||
} from 'lucide-react'
|
|
||||||
import { Button } from '../../../components/ui'
|
|
||||||
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
|
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
|
||||||
import { DetailRow } from './DetailRow'
|
|
||||||
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
|
||||||
|
|
||||||
export function AttendeeDetailPage() {
|
|
||||||
const {
|
|
||||||
groupId,
|
|
||||||
groupName,
|
|
||||||
attendee,
|
|
||||||
attendeePending,
|
|
||||||
attendeeFailed,
|
|
||||||
openRemoveModal,
|
|
||||||
isRemoveModalOpen,
|
|
||||||
closeRemoveModal,
|
|
||||||
confirmRemoveAttendee,
|
|
||||||
firstWaitlistEntry,
|
|
||||||
waitlistTotal,
|
|
||||||
waitlistPending,
|
|
||||||
isSubmittingRemoval,
|
|
||||||
copyAbsenceNotifyUrl,
|
|
||||||
} = useAttendeeDetail()
|
|
||||||
const navigate = useNavigate()
|
|
||||||
|
|
||||||
if (attendeePending) {
|
|
||||||
return (
|
|
||||||
<div className="flex items-center justify-center py-20">
|
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (attendeeFailed || !attendee) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
|
||||||
<h2 className="text-lg font-semibold">Participante no encontrado</h2>
|
|
||||||
<p className="mt-2 text-sm">No se pudo cargar la información de este participante.</p>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="mt-4"
|
|
||||||
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
|
||||||
>
|
|
||||||
Volver al grupo
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const absenceNotifyUrl = attendee.notifyToken
|
|
||||||
? `${window.location.origin}/report-absence/${attendee.notifyToken}`
|
|
||||||
: null
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className="animate-fade-in space-y-5">
|
|
||||||
<Link
|
|
||||||
to="/groups/$groupId"
|
|
||||||
params={{ groupId }}
|
|
||||||
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
|
||||||
>
|
|
||||||
<ArrowLeft className="size-4" />
|
|
||||||
<span>Volver al grupo</span>
|
|
||||||
</Link>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="flex size-14 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xl font-bold text-accent">
|
|
||||||
{attendee.fullName.charAt(0).toUpperCase()}
|
|
||||||
</div>
|
|
||||||
<div className="min-w-0">
|
|
||||||
<h1 className="truncate text-xl font-bold text-primary">{attendee.fullName}</h1>
|
|
||||||
<p className="text-xs text-foreground/50">
|
|
||||||
{groupName ? `${groupName} · ` : ''}Incorporado el{' '}
|
|
||||||
{new Date(attendee.createdAt).toLocaleDateString('es-ES', {
|
|
||||||
day: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
year: 'numeric',
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<AttendeeAttendanceStats />
|
|
||||||
|
|
||||||
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
|
|
||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
|
||||||
{attendee.phone ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-primary">{attendee.phone}</span>
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-3.5" />
|
|
||||||
<span>WhatsApp</span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-foreground/40">Sin teléfono</span>
|
|
||||||
)}
|
|
||||||
</DetailRow>
|
|
||||||
|
|
||||||
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
|
|
||||||
{attendee.email ? (
|
|
||||||
<a
|
|
||||||
href={`mailto:${attendee.email}`}
|
|
||||||
className="text-primary transition-colors hover:text-accent"
|
|
||||||
>
|
|
||||||
{attendee.email}
|
|
||||||
</a>
|
|
||||||
) : (
|
|
||||||
<span className="text-foreground/40">Sin email</span>
|
|
||||||
)}
|
|
||||||
</DetailRow>
|
|
||||||
|
|
||||||
{attendee.guardianName || attendee.guardianPhone ? (
|
|
||||||
<>
|
|
||||||
<DetailRow icon={<ShieldCheck className="size-4 text-accent" />} label="Responsable">
|
|
||||||
<span className="text-primary">
|
|
||||||
{attendee.guardianName || <span className="text-foreground/40">—</span>}
|
|
||||||
</span>
|
|
||||||
</DetailRow>
|
|
||||||
{attendee.guardianPhone ? (
|
|
||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-primary">{attendee.guardianPhone}</span>
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-3.5" />
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</DetailRow>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<DetailRow icon={<StickyNote className="size-4 text-accent" />} label="Notas">
|
|
||||||
{attendee.notes ? (
|
|
||||||
<span className="text-xs leading-relaxed text-primary">{attendee.notes}</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-foreground/40">Sin notas</span>
|
|
||||||
)}
|
|
||||||
</DetailRow>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{absenceNotifyUrl ? (
|
|
||||||
<div className="space-y-2 rounded-xl border border-border p-4">
|
|
||||||
<p className="text-xs font-medium text-foreground/60">Link para avisar ausencias</p>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<code className="min-w-0 flex-1 truncate rounded-lg bg-primary-soft px-2 py-1.5 text-xs text-primary">
|
|
||||||
{absenceNotifyUrl}
|
|
||||||
</code>
|
|
||||||
<Button variant="outline" size="sm" onClick={() => copyAbsenceNotifyUrl(absenceNotifyUrl)}>
|
|
||||||
<Copy className="size-3.5" />
|
|
||||||
Copiar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{attendee.phone ? (
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}?text=${encodeURIComponent(`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${absenceNotifyUrl}`)}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-3.5" />
|
|
||||||
<span>Enviar por WhatsApp</span>
|
|
||||||
</a>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<div className="border-t border-border pt-2">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
onClick={openRemoveModal}
|
|
||||||
className="w-full gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
|
|
||||||
>
|
|
||||||
<UserMinus className="size-4" />
|
|
||||||
Quitar del grupo
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<RemoveAttendeeModal
|
|
||||||
attendee={isRemoveModalOpen ? attendee : null}
|
|
||||||
groupName={groupName}
|
|
||||||
firstWaitlistEntry={firstWaitlistEntry}
|
|
||||||
waitlistTotal={waitlistTotal}
|
|
||||||
isResolvingWaitlist={isRemoveModalOpen && waitlistPending}
|
|
||||||
isSubmitting={isSubmittingRemoval}
|
|
||||||
onCancel={closeRemoveModal}
|
|
||||||
onConfirm={confirmRemoveAttendee}
|
|
||||||
/>
|
|
||||||
</section>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -3,108 +3,79 @@ import type { ReactNode } from 'react'
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import type {
|
import type {
|
||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
CreateAttendee,
|
AttendeeListItem,
|
||||||
CreateAttendeeResult,
|
|
||||||
CreateGroupWaitlistEntry,
|
|
||||||
GroupDto,
|
GroupDto,
|
||||||
|
GroupPreRegistrationDto,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
GroupWaitlistList,
|
|
||||||
GroupRiskLevel,
|
GroupRiskLevel,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import { useToast } from '../../../components/ui'
|
import { useToast } from '../../../components/ui'
|
||||||
import type { ParsedContactRow } from '../../../lib/file-parser'
|
|
||||||
import {
|
import {
|
||||||
addToGroupWaitlist,
|
|
||||||
ApiError,
|
ApiError,
|
||||||
bulkCreateAttendees,
|
approveGroupPreRegistration,
|
||||||
createAttendee,
|
|
||||||
getGroup,
|
getGroup,
|
||||||
getGroupAttendees,
|
getGroupAttendees,
|
||||||
|
getGroupPreRegistrations,
|
||||||
getGroupsRiskOverview,
|
getGroupsRiskOverview,
|
||||||
getGroupWaitlist,
|
getGroupWaitlist,
|
||||||
getInviteToken,
|
getInviteToken,
|
||||||
promoteGroupWaitlistEntry,
|
promoteGroupWaitlistEntry,
|
||||||
|
rejectGroupPreRegistration,
|
||||||
removeGroupWaitlistEntry,
|
removeGroupWaitlistEntry,
|
||||||
} from '../../../lib/api'
|
} from '../../../lib/api'
|
||||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||||
|
|
||||||
export type BulkAttendeeRow = {
|
export type ListSection = 'members' | 'pending'
|
||||||
firstName: string
|
|
||||||
lastName: string
|
|
||||||
fullName: string
|
|
||||||
phone: string
|
|
||||||
email?: string
|
|
||||||
notes?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ListSection = 'members' | 'waitlist'
|
|
||||||
export type AddAttendeeTab = 'quick' | 'bulk'
|
|
||||||
|
|
||||||
type GroupDetailContextValue = {
|
type GroupDetailContextValue = {
|
||||||
groupId: string
|
groupId: string
|
||||||
group: GroupDto | undefined
|
group: GroupDto | undefined
|
||||||
|
/** Nombre para el título grande: dato real, caché o "Grupo" mientras carga. */
|
||||||
|
groupTitle: string
|
||||||
groupQueryPending: boolean
|
groupQueryPending: boolean
|
||||||
riskLevel: GroupRiskLevel
|
riskLevel: GroupRiskLevel
|
||||||
attendees: AttendeeDto[]
|
attendees: AttendeeListItem[]
|
||||||
attendeesTotal: number
|
attendeesTotal: number
|
||||||
attendeesPending: boolean
|
attendeesPending: boolean
|
||||||
waitlistEntries: GroupWaitlistEntryDto[]
|
waitlistEntries: GroupWaitlistEntryDto[]
|
||||||
waitlistTotal: number
|
waitlistTotal: number
|
||||||
waitlistPending: boolean
|
waitlistPending: boolean
|
||||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
|
preRegistrations: GroupPreRegistrationDto[]
|
||||||
|
preRegistrationsTotal: number
|
||||||
|
preRegistrationsPending: boolean
|
||||||
hasFreeCapacity: boolean
|
hasFreeCapacity: boolean
|
||||||
inviteUrl: string | undefined
|
inviteUrl: string | undefined
|
||||||
invitePending: boolean
|
invitePending: boolean
|
||||||
whatsappMessage: string
|
whatsappMessage: string
|
||||||
searchFilter: string
|
searchFilter: string
|
||||||
setSearchFilter: (value: string) => void
|
setSearchFilter: (value: string) => void
|
||||||
|
/** La lista de miembros se reduce a quienes tienen el cobro vencido. */
|
||||||
|
overdueOnly: boolean
|
||||||
|
setOverdueOnly: (value: boolean) => void
|
||||||
listSection: ListSection
|
listSection: ListSection
|
||||||
setListSection: (value: ListSection) => void
|
setListSection: (value: ListSection) => void
|
||||||
activeTab: AddAttendeeTab
|
|
||||||
setActiveTab: (value: AddAttendeeTab) => void
|
|
||||||
isInviteModalOpen: boolean
|
isInviteModalOpen: boolean
|
||||||
openInviteModal: () => void
|
openInviteModal: () => void
|
||||||
closeInviteModal: () => void
|
closeInviteModal: () => void
|
||||||
isAddAttendeeModalOpen: boolean
|
|
||||||
openAddAttendeeModal: () => void
|
|
||||||
closeAddAttendeeModal: () => void
|
|
||||||
attendeeToRemove: AttendeeDto | null
|
attendeeToRemove: AttendeeDto | null
|
||||||
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
||||||
cancelRemoveAttendee: () => void
|
cancelRemoveAttendee: () => void
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||||
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
||||||
isCapacityModalOpen: boolean
|
selectedPreRegistration: GroupPreRegistrationDto | null
|
||||||
capacityPayload: CreateAttendee | null
|
setSelectedPreRegistration: (entry: GroupPreRegistrationDto | null) => void
|
||||||
closeCapacityModal: () => void
|
|
||||||
isBulkCapacityModalOpen: boolean
|
|
||||||
closeBulkCapacityModal: () => void
|
|
||||||
parsedContacts: ParsedContactRow[]
|
|
||||||
setParsedContacts: (contacts: ParsedContactRow[]) => void
|
|
||||||
removeParsedContact: (id: string) => void
|
|
||||||
fileName: string | null
|
|
||||||
setFileName: (name: string | null) => void
|
|
||||||
isParsingFile: boolean
|
|
||||||
setIsParsingFile: (value: boolean) => void
|
|
||||||
isDragging: boolean
|
|
||||||
setIsDragging: (value: boolean) => void
|
|
||||||
validRowsCount: number
|
|
||||||
invalidRowsCount: number
|
|
||||||
isSubmittingAttendee: boolean
|
|
||||||
isSubmittingForcedAttendee: boolean
|
|
||||||
isSubmittingWaitlistEntry: boolean
|
|
||||||
isSubmittingBulkImport: boolean
|
|
||||||
isSubmittingRemoval: boolean
|
isSubmittingRemoval: boolean
|
||||||
isSubmittingPromotion: boolean
|
isSubmittingPromotion: boolean
|
||||||
isSubmittingWaitlistRemoval: boolean
|
isSubmittingWaitlistRemoval: boolean
|
||||||
|
isSubmittingApproval: boolean
|
||||||
|
isSubmittingRejection: boolean
|
||||||
isRegeneratingInvite: boolean
|
isRegeneratingInvite: boolean
|
||||||
submitQuickAttendee: (payload: CreateAttendee) => void
|
|
||||||
submitForcedAttendee: () => void
|
|
||||||
submitWaitlistEntry: () => void
|
|
||||||
requestBulkImport: () => void
|
|
||||||
confirmBulkImportOverCapacity: () => void
|
|
||||||
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
||||||
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
||||||
|
approvePreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||||
|
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||||
regenerateInvite: () => void
|
regenerateInvite: () => void
|
||||||
copyInviteLink: () => Promise<void>
|
copyInviteLink: () => Promise<void>
|
||||||
copyWhatsappMessage: () => Promise<void>
|
copyWhatsappMessage: () => Promise<void>
|
||||||
@@ -118,19 +89,20 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
|
||||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||||
const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false)
|
const [listSection, setListSectionState] = useState<ListSection>('members')
|
||||||
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
|
||||||
const [listSection, setListSection] = useState<ListSection>('members')
|
|
||||||
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
||||||
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
||||||
const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false)
|
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
||||||
const [pendingCapacityPayload, setPendingCapacityPayload] = useState<CreateAttendee | null>(null)
|
|
||||||
const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false)
|
|
||||||
const [searchFilter, setSearchFilter] = useState('')
|
const [searchFilter, setSearchFilter] = useState('')
|
||||||
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([])
|
const [overdueOnly, setOverdueOnly] = useState(false)
|
||||||
const [fileName, setFileName] = useState<string | null>(null)
|
|
||||||
const [isParsingFile, setIsParsingFile] = useState(false)
|
// Los controles de la lista pertenecen a la vista que los abrió: al cambiar de
|
||||||
const [isDragging, setIsDragging] = useState(false)
|
// pestaña se limpian para no heredar un filtro sin coincidencias.
|
||||||
|
const setListSection = (value: ListSection) => {
|
||||||
|
setListSectionState(value)
|
||||||
|
setSearchFilter('')
|
||||||
|
setOverdueOnly(false)
|
||||||
|
}
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
const groupQuery = useQuery({
|
||||||
queryKey: ['group', groupId],
|
queryKey: ['group', groupId],
|
||||||
@@ -162,36 +134,33 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
enabled: Boolean(groupId),
|
enabled: Boolean(groupId),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const preRegistrationsQuery = useQuery({
|
||||||
|
queryKey: ['group-preregistrations', groupId],
|
||||||
|
queryFn: () => getGroupPreRegistrations(groupId, 1, 100),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
const group = groupQuery.data
|
const group = groupQuery.data
|
||||||
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
||||||
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
||||||
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
||||||
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
||||||
|
const preRegistrations = useMemo(
|
||||||
|
() => preRegistrationsQuery.data?.data ?? [],
|
||||||
|
[preRegistrationsQuery.data],
|
||||||
|
)
|
||||||
|
const preRegistrationsTotal =
|
||||||
|
preRegistrationsQuery.data?.pagination?.total ?? preRegistrations.length
|
||||||
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||||
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
||||||
|
|
||||||
const closeAddAttendeeFlow = () => {
|
|
||||||
setPendingCapacityPayload(null)
|
|
||||||
setIsCapacityModalOpen(false)
|
|
||||||
setIsAddAttendeeModalOpen(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const invalidateGroupQueries = () => {
|
const invalidateGroupQueries = () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-preregistrations', groupId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
|
||||||
if (result.outcome === 'created') {
|
|
||||||
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
|
||||||
} else {
|
|
||||||
toast.info(result.message)
|
|
||||||
}
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
||||||
closeAddAttendeeFlow()
|
|
||||||
}
|
|
||||||
|
|
||||||
const regenerateTokenMutation = useMutation({
|
const regenerateTokenMutation = useMutation({
|
||||||
mutationFn: () => getInviteToken(groupId, true),
|
mutationFn: () => getInviteToken(groupId, true),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
@@ -203,89 +172,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const createAttendeeMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
|
||||||
onMutate: (payload) => setPendingCapacityPayload(payload),
|
|
||||||
onSuccess: handleCreateSuccess,
|
|
||||||
onError: (err: Error) => {
|
|
||||||
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
|
||||||
setIsCapacityModalOpen(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
toast.error(err.message || 'Error al agregar miembro.')
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const createAttendeeForceMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
|
||||||
onSuccess: handleCreateSuccess,
|
|
||||||
onError: (err: Error) => {
|
|
||||||
toast.error(err.message || 'Error al agregar miembro.')
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const addToWaitlistMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload),
|
|
||||||
onMutate: async (payload: CreateGroupWaitlistEntry) => {
|
|
||||||
await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] })
|
|
||||||
const previousWaitlist = queryClient.getQueryData<GroupWaitlistList>(['group-waitlist', groupId])
|
|
||||||
|
|
||||||
if (previousWaitlist) {
|
|
||||||
const optimisticEntry: GroupWaitlistEntryDto = {
|
|
||||||
id: `temp-${Date.now()}`,
|
|
||||||
groupId,
|
|
||||||
fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(),
|
|
||||||
phone: payload.phone,
|
|
||||||
email: payload.email || null,
|
|
||||||
notes: payload.notes ?? null,
|
|
||||||
status: 'PENDING',
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
updatedAt: new Date().toISOString(),
|
|
||||||
}
|
|
||||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], {
|
|
||||||
data: [optimisticEntry, ...previousWaitlist.data],
|
|
||||||
pagination: {
|
|
||||||
...previousWaitlist.pagination,
|
|
||||||
total: previousWaitlist.pagination.total + 1,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return { previousWaitlist }
|
|
||||||
},
|
|
||||||
onSuccess: (entry) => {
|
|
||||||
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
|
||||||
invalidateGroupQueries()
|
|
||||||
closeAddAttendeeFlow()
|
|
||||||
},
|
|
||||||
onError: (err: Error, _payload, context) => {
|
|
||||||
if (context?.previousWaitlist) {
|
|
||||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
|
||||||
}
|
|
||||||
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
|
||||||
toast.info('Este número ya está en la lista de espera del grupo.')
|
|
||||||
} else {
|
|
||||||
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
|
||||||
}
|
|
||||||
setPendingCapacityPayload(null)
|
|
||||||
setIsCapacityModalOpen(false)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const bulkImportMutation = useMutation({
|
|
||||||
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
|
||||||
onSuccess: (res) => {
|
|
||||||
toast.success(res.message)
|
|
||||||
setParsedContacts([])
|
|
||||||
setFileName(null)
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
||||||
setIsAddAttendeeModalOpen(false)
|
|
||||||
},
|
|
||||||
onError: (err: Error) => {
|
|
||||||
toast.error(err.message || 'Error al importar miembros.')
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const removeAttendeeMutation = useRemoveAttendee({
|
const removeAttendeeMutation = useRemoveAttendee({
|
||||||
groupId,
|
groupId,
|
||||||
onRemoved: () => setAttendeeToRemove(null),
|
onRemoved: () => setAttendeeToRemove(null),
|
||||||
@@ -317,10 +203,56 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const approvePreRegistrationMutation = useMutation({
|
||||||
|
mutationFn: (entry: GroupPreRegistrationDto) =>
|
||||||
|
approveGroupPreRegistration(groupId, entry.id),
|
||||||
|
onSuccess: (result, entry) => {
|
||||||
|
setSelectedPreRegistration(null)
|
||||||
|
toast.success(
|
||||||
|
result.outcome === 'added'
|
||||||
|
? `${entry.fullName} ahora es miembro del grupo.`
|
||||||
|
: `${entry.fullName} fue agregado a la lista de espera: el grupo está completo.`,
|
||||||
|
)
|
||||||
|
invalidateGroupQueries()
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
if (err instanceof ApiError) {
|
||||||
|
if (err.problem?.code === 'attendee_already_registered') {
|
||||||
|
toast.error('Ya hay un miembro con ese teléfono en el grupo. Puedes rechazar la pre-inscripción.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (err.problem?.code === 'pre_registration_already_reviewed') {
|
||||||
|
toast.error('Esta pre-inscripción ya fue revisada.')
|
||||||
|
invalidateGroupQueries()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toast.error(err.message || 'No se pudo aprobar la pre-inscripción.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const rejectPreRegistrationMutation = useMutation({
|
||||||
|
mutationFn: (entry: GroupPreRegistrationDto) =>
|
||||||
|
rejectGroupPreRegistration(groupId, entry.id),
|
||||||
|
onSuccess: (_result, entry) => {
|
||||||
|
setSelectedPreRegistration(null)
|
||||||
|
toast.success(`La pre-inscripción de ${entry.fullName} fue rechazada.`)
|
||||||
|
invalidateGroupQueries()
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
if (err instanceof ApiError && err.problem?.code === 'pre_registration_already_reviewed') {
|
||||||
|
toast.error('Esta pre-inscripción ya fue revisada.')
|
||||||
|
invalidateGroupQueries()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toast.error(err.message || 'No se pudo rechazar la pre-inscripción.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const inviteUrl = inviteTokenQuery.data?.inviteUrl
|
const inviteUrl = inviteTokenQuery.data?.inviteUrl
|
||||||
const whatsappMessage =
|
const whatsappMessage =
|
||||||
group && inviteUrl
|
group && inviteUrl
|
||||||
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tus datos de inscripción en el siguiente enlace:\n${inviteUrl}`
|
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:\n${inviteUrl}`
|
||||||
: ''
|
: ''
|
||||||
const whatsappShareUrl = whatsappMessage
|
const whatsappShareUrl = whatsappMessage
|
||||||
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
||||||
@@ -359,44 +291,16 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
||||||
}
|
}
|
||||||
|
|
||||||
const validRows: BulkAttendeeRow[] = useMemo(
|
// El título grande va siempre, incluso cargando: es lo que da altura a la
|
||||||
() =>
|
// barra immersive y evita que el layout salte. Al llegar desde la ficha del
|
||||||
parsedContacts
|
// grupo el nombre ya está en caché; en la primera carga cae a "Grupo".
|
||||||
.filter((contact) => contact.isValid)
|
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
|
||||||
.map((contact) => ({
|
const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo'
|
||||||
firstName: contact.firstName,
|
|
||||||
lastName: contact.lastName,
|
|
||||||
fullName: contact.fullName,
|
|
||||||
phone: contact.phone,
|
|
||||||
email: contact.email || undefined,
|
|
||||||
notes: contact.notes || undefined,
|
|
||||||
})),
|
|
||||||
[parsedContacts],
|
|
||||||
)
|
|
||||||
|
|
||||||
const runBulkImport = () => {
|
|
||||||
if (validRows.length === 0) {
|
|
||||||
toast.error('No hay miembros válidos para importar.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
bulkImportMutation.mutate(validRows)
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestBulkImport = () => {
|
|
||||||
if (validRows.length === 0) {
|
|
||||||
toast.error('No hay miembros válidos para importar.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (group?.capacity != null && attendeesTotal + validRows.length > group.capacity) {
|
|
||||||
setIsBulkCapacityModalOpen(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
runBulkImport()
|
|
||||||
}
|
|
||||||
|
|
||||||
const value: GroupDetailContextValue = {
|
const value: GroupDetailContextValue = {
|
||||||
groupId,
|
groupId,
|
||||||
group,
|
group,
|
||||||
|
groupTitle,
|
||||||
groupQueryPending: groupQuery.isPending,
|
groupQueryPending: groupQuery.isPending,
|
||||||
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
|
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
|
||||||
attendees,
|
attendees,
|
||||||
@@ -406,22 +310,22 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
waitlistTotal,
|
waitlistTotal,
|
||||||
waitlistPending: waitlistQuery.isPending,
|
waitlistPending: waitlistQuery.isPending,
|
||||||
firstWaitlistEntry,
|
firstWaitlistEntry,
|
||||||
|
preRegistrations,
|
||||||
|
preRegistrationsTotal,
|
||||||
|
preRegistrationsPending: preRegistrationsQuery.isPending,
|
||||||
hasFreeCapacity,
|
hasFreeCapacity,
|
||||||
inviteUrl,
|
inviteUrl,
|
||||||
invitePending: inviteTokenQuery.isPending,
|
invitePending: inviteTokenQuery.isPending,
|
||||||
whatsappMessage,
|
whatsappMessage,
|
||||||
searchFilter,
|
searchFilter,
|
||||||
setSearchFilter,
|
setSearchFilter,
|
||||||
|
overdueOnly,
|
||||||
|
setOverdueOnly,
|
||||||
listSection,
|
listSection,
|
||||||
setListSection,
|
setListSection,
|
||||||
activeTab,
|
|
||||||
setActiveTab,
|
|
||||||
isInviteModalOpen,
|
isInviteModalOpen,
|
||||||
openInviteModal: () => setIsInviteModalOpen(true),
|
openInviteModal: () => setIsInviteModalOpen(true),
|
||||||
closeInviteModal: () => setIsInviteModalOpen(false),
|
closeInviteModal: () => setIsInviteModalOpen(false),
|
||||||
isAddAttendeeModalOpen,
|
|
||||||
openAddAttendeeModal: () => setIsAddAttendeeModalOpen(true),
|
|
||||||
closeAddAttendeeModal: () => setIsAddAttendeeModalOpen(false),
|
|
||||||
attendeeToRemove,
|
attendeeToRemove,
|
||||||
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
||||||
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
||||||
@@ -431,49 +335,14 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
selectedWaitlistEntry,
|
selectedWaitlistEntry,
|
||||||
setSelectedWaitlistEntry,
|
setSelectedWaitlistEntry,
|
||||||
isCapacityModalOpen,
|
selectedPreRegistration,
|
||||||
capacityPayload: pendingCapacityPayload,
|
setSelectedPreRegistration,
|
||||||
closeCapacityModal: () => {
|
|
||||||
setPendingCapacityPayload(null)
|
|
||||||
setIsCapacityModalOpen(false)
|
|
||||||
},
|
|
||||||
isBulkCapacityModalOpen,
|
|
||||||
closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false),
|
|
||||||
parsedContacts,
|
|
||||||
setParsedContacts,
|
|
||||||
removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)),
|
|
||||||
fileName,
|
|
||||||
setFileName,
|
|
||||||
isParsingFile,
|
|
||||||
setIsParsingFile,
|
|
||||||
isDragging,
|
|
||||||
setIsDragging,
|
|
||||||
validRowsCount: validRows.length,
|
|
||||||
invalidRowsCount: parsedContacts.length - validRows.length,
|
|
||||||
isSubmittingAttendee: createAttendeeMutation.isPending,
|
|
||||||
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
|
||||||
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
|
||||||
isSubmittingBulkImport: bulkImportMutation.isPending,
|
|
||||||
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
||||||
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
||||||
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
||||||
|
isSubmittingApproval: approvePreRegistrationMutation.isPending,
|
||||||
|
isSubmittingRejection: rejectPreRegistrationMutation.isPending,
|
||||||
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
||||||
submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload),
|
|
||||||
submitForcedAttendee: () => {
|
|
||||||
if (pendingCapacityPayload) {
|
|
||||||
createAttendeeForceMutation.mutate({ ...pendingCapacityPayload })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
submitWaitlistEntry: () => {
|
|
||||||
if (pendingCapacityPayload) {
|
|
||||||
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
requestBulkImport,
|
|
||||||
confirmBulkImportOverCapacity: () => {
|
|
||||||
setIsBulkCapacityModalOpen(false)
|
|
||||||
runBulkImport()
|
|
||||||
},
|
|
||||||
promoteEntry: (entry) => {
|
promoteEntry: (entry) => {
|
||||||
setSelectedWaitlistEntry(null)
|
setSelectedWaitlistEntry(null)
|
||||||
promoteWaitlistMutation.mutate(entry.id)
|
promoteWaitlistMutation.mutate(entry.id)
|
||||||
@@ -482,6 +351,12 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
setSelectedWaitlistEntry(null)
|
setSelectedWaitlistEntry(null)
|
||||||
removeWaitlistEntryMutation.mutate(entry)
|
removeWaitlistEntryMutation.mutate(entry)
|
||||||
},
|
},
|
||||||
|
approvePreRegistration: (entry) => {
|
||||||
|
approvePreRegistrationMutation.mutate(entry)
|
||||||
|
},
|
||||||
|
rejectPreRegistration: (entry) => {
|
||||||
|
rejectPreRegistrationMutation.mutate(entry)
|
||||||
|
},
|
||||||
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
||||||
copyInviteLink,
|
copyInviteLink,
|
||||||
copyWhatsappMessage,
|
copyWhatsappMessage,
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { Button } from '../../../components/ui'
|
import { Button } from '../../../components/ui'
|
||||||
import { AddAttendeeModal } from './AddAttendeeModal'
|
|
||||||
import { BulkCapacityModal } from './BulkCapacityModal'
|
|
||||||
import { CapacityModal } from './CapacityModal'
|
|
||||||
import { GroupHeader } from './GroupHeader'
|
import { GroupHeader } from './GroupHeader'
|
||||||
import { GroupInfoCard } from './GroupInfoCard'
|
import { GroupInfoCard } from './GroupInfoCard'
|
||||||
import { InviteLinkModal } from './InviteLinkModal'
|
import { InviteLinkModal } from './InviteLinkModal'
|
||||||
import { MembersWaitlistSection } from './MembersWaitlistSection'
|
import { MembersWaitlistSection } from './MembersWaitlistSection'
|
||||||
|
import { PreRegistrationDetailModal } from './PreRegistrationDetailModal'
|
||||||
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
||||||
@@ -25,36 +23,36 @@ export function GroupDetailView() {
|
|||||||
} = useGroupDetail()
|
} = useGroupDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
if (groupQueryPending) {
|
|
||||||
return (
|
|
||||||
<div className="flex items-center justify-center py-20">
|
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!group) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
|
||||||
<h2 className="text-lg font-semibold">Grupo no encontrado</h2>
|
|
||||||
<p className="mt-2 text-sm">No se pudo cargar la información de este grupo.</p>
|
|
||||||
<Button variant="outline" className="mt-4" onClick={() => void navigate({ to: '/groups' })}>
|
|
||||||
Volver a Grupos
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="animate-fade-in space-y-6">
|
<section className="animate-fade-in space-y-5 sm:space-y-6">
|
||||||
|
{/* El título grande va siempre, incluso cargando: es lo que da altura a
|
||||||
|
la barra immersive y evita que el layout salte cuando llegan los datos. */}
|
||||||
<GroupHeader />
|
<GroupHeader />
|
||||||
<GroupInfoCard />
|
|
||||||
<MembersWaitlistSection />
|
{groupQueryPending ? (
|
||||||
|
<div className="flex items-center justify-center py-20">
|
||||||
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
) : !group ? (
|
||||||
|
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||||
|
<h2 className="text-lg font-semibold">Grupo no encontrado</h2>
|
||||||
|
<p className="mt-2 text-sm">No se pudo cargar la información de este grupo.</p>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="mt-4"
|
||||||
|
onClick={() => void navigate({ to: '/groups' })}
|
||||||
|
>
|
||||||
|
Volver a Grupos
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<GroupInfoCard />
|
||||||
|
<MembersWaitlistSection />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<InviteLinkModal />
|
<InviteLinkModal />
|
||||||
<AddAttendeeModal />
|
|
||||||
<CapacityModal />
|
|
||||||
<BulkCapacityModal />
|
|
||||||
<RemoveAttendeeModal
|
<RemoveAttendeeModal
|
||||||
attendee={attendeeToRemove}
|
attendee={attendeeToRemove}
|
||||||
groupName={group?.name}
|
groupName={group?.name}
|
||||||
@@ -66,6 +64,7 @@ export function GroupDetailView() {
|
|||||||
onConfirm={confirmRemoveAttendee}
|
onConfirm={confirmRemoveAttendee}
|
||||||
/>
|
/>
|
||||||
<WaitlistEntryDetailModal />
|
<WaitlistEntryDetailModal />
|
||||||
|
<PreRegistrationDetailModal />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,77 +1,136 @@
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
||||||
import { Badge, Button } from '../../../components/ui'
|
import { Badge, Button, Tooltip } from '../../../components/ui'
|
||||||
import { RISK_LABELS } from '../constants'
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
|
import { RISK_HINT, RISK_LABELS } from '../constants'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
export function GroupHeader() {
|
export function GroupHeader() {
|
||||||
const { group, groupId, riskLevel, openInviteModal, openAddAttendeeModal } = useGroupDetail()
|
const {
|
||||||
|
group,
|
||||||
|
groupTitle,
|
||||||
|
groupId,
|
||||||
|
riskLevel,
|
||||||
|
openInviteModal,
|
||||||
|
attendeesTotal,
|
||||||
|
attendeesPending,
|
||||||
|
preRegistrationsTotal,
|
||||||
|
preRegistrationsPending,
|
||||||
|
waitlistTotal,
|
||||||
|
waitlistPending,
|
||||||
|
} = useGroupDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
|
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
|
||||||
|
|
||||||
|
// Grupo recién creado (sin miembros ni pendientes): los empty states de cada
|
||||||
|
// pestaña ya ofrecen "Compartir" y "Agregar" con su primario explicado, así
|
||||||
|
// que el header no repite las mismas acciones una segunda vez.
|
||||||
|
const listLoading = attendeesPending || preRegistrationsPending || waitlistPending
|
||||||
|
const isEmptyGroup =
|
||||||
|
!listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0
|
||||||
|
|
||||||
|
// Sin grupo todavía solo se pinta el título: los badges, la descripción y las
|
||||||
|
// acciones necesitan datos, y mostrarlos a medias daría un header parpadeante.
|
||||||
|
const hasGroup = Boolean(group)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Link
|
<LargeTitle
|
||||||
to="/groups"
|
title={groupTitle}
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
leading={
|
||||||
|
<Link
|
||||||
|
to="/groups"
|
||||||
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver a grupos</span>
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
{/* Los estados cuelgan del título y no de la barra: en la barra
|
||||||
<span>Volver a grupos</span>
|
colapsada solo va el nombre, que es lo que se usa para orientarse. */}
|
||||||
</Link>
|
{hasGroup ? (
|
||||||
|
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
<Badge variant="success" className="gap-1.5 text-[11px]">
|
||||||
<div>
|
<span className="size-1.5 rounded-full bg-success" aria-hidden="true" />
|
||||||
<div className="flex items-center gap-2.5">
|
Activo
|
||||||
<h1 className="text-2xl font-bold text-primary">{group?.name}</h1>
|
</Badge>
|
||||||
<Badge variant="success">Activo</Badge>
|
|
||||||
{hasRisk ? (
|
{hasRisk ? (
|
||||||
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
|
// El badge no puede llevar texto largo sin ensuciar el header: la
|
||||||
<span
|
// explicación (riesgo de abandono, no de cobranza) vive en el tooltip.
|
||||||
className={`size-2 rounded-full ${riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning'}`}
|
<Tooltip content={RISK_HINT}>
|
||||||
aria-hidden="true"
|
<Badge
|
||||||
/>
|
variant={riskLevel === 'HIGH' ? 'danger' : 'warning'}
|
||||||
{RISK_LABELS[riskLevel]}
|
className="gap-1.5 text-[11px]"
|
||||||
</Badge>
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'size-1.5 rounded-full',
|
||||||
|
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
|
||||||
|
)}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
{RISK_LABELS[riskLevel]}
|
||||||
|
</Badge>
|
||||||
|
</Tooltip>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{group?.description ? (
|
) : null}
|
||||||
<p className="mt-1 text-sm text-foreground/70">{group.description}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid w-full grid-cols-3 gap-2 sm:flex sm:w-auto sm:flex-wrap sm:items-center sm:gap-2.5">
|
{group?.description ? (
|
||||||
|
<p className="mt-2 text-pretty text-sm leading-relaxed text-foreground/80">
|
||||||
|
{group.description}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</LargeTitle>
|
||||||
|
|
||||||
|
{hasGroup ? (
|
||||||
|
// Una sola fila en mobile: el primario toma el ancho que sobra y las dos
|
||||||
|
// acciones de apoyo se pliegan a iconos de 44px. En sm+ recuperan el
|
||||||
|
// texto porque hay ancho de sobra y el rótulo hace más claro el destino.
|
||||||
|
<div className="mt-4 flex items-center gap-2.5 sm:mt-5 sm:justify-end">
|
||||||
|
{!isEmptyGroup ? (
|
||||||
|
// Un solo primario por pantalla: "Agregar" encabeza la jerarquía y
|
||||||
|
// las acciones de apoyo quedan al lado, en outline.
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={() =>
|
||||||
|
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
|
||||||
|
}
|
||||||
|
className="h-11 flex-1 justify-center sm:flex-none sm:w-auto"
|
||||||
|
>
|
||||||
|
<UserPlus className="size-4" />
|
||||||
|
<span>Agregar miembro</span>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() =>
|
onClick={() => void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })}
|
||||||
void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })
|
aria-label="Estadísticas"
|
||||||
}
|
className={cn(
|
||||||
className="w-full justify-center gap-1.5 border-border sm:w-auto"
|
'h-11 shrink-0 justify-center border-border',
|
||||||
|
// En grupo vacío es la única acción del header: ocupa la fila entera.
|
||||||
|
isEmptyGroup && 'w-full sm:w-auto',
|
||||||
|
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<BarChart3 className="size-4 text-accent" />
|
<BarChart3 className="size-4 text-accent" />
|
||||||
<span>Estadísticas</span>
|
<span className="hidden sm:inline">Estadísticas</span>
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={openInviteModal}
|
|
||||||
className="w-full justify-center gap-1.5 border-border sm:w-auto"
|
|
||||||
>
|
|
||||||
<Share2 className="size-4 text-accent" />
|
|
||||||
<span>
|
|
||||||
Compartir <span className="hidden sm:inline">Link</span>
|
|
||||||
</span>
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
onClick={openAddAttendeeModal}
|
|
||||||
className="w-full justify-center gap-1.5 sm:w-auto"
|
|
||||||
>
|
|
||||||
<UserPlus className="size-4" />
|
|
||||||
<span>
|
|
||||||
Agregar <span className="hidden sm:inline">Miembros</span>
|
|
||||||
</span>
|
|
||||||
</Button>
|
</Button>
|
||||||
|
{!isEmptyGroup ? (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={openInviteModal}
|
||||||
|
aria-label="Compartir enlace"
|
||||||
|
className="h-11 w-11 shrink-0 justify-center border-border sm:w-auto sm:px-4"
|
||||||
|
>
|
||||||
|
<Share2 className="size-4 text-accent" />
|
||||||
|
<span className="hidden sm:inline">Compartir</span>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,47 +1,104 @@
|
|||||||
import { CalendarClock, Users } from 'lucide-react'
|
import { CalendarClock, CircleDollarSign, Users } from 'lucide-react'
|
||||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../../lib/format'
|
import {
|
||||||
|
formatBillingMeta,
|
||||||
|
formatPrice,
|
||||||
|
WEEK_DAY_FULL_LABELS,
|
||||||
|
} from '../../../lib/format'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
|
/* Escala de la tarjeta: label 11 (etiqueta) · valor 16 (dato) · hero 24
|
||||||
|
(cupo). El cupo es lo único que se escanea de un vistazo, por eso es el
|
||||||
|
único que sube de nivel; el resto se lee en línea. El ritmo vertical está
|
||||||
|
apretado a propósito (~24px menos que antes) sin bajar la legibilidad. */
|
||||||
|
const LABEL_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground/70'
|
||||||
|
const CELL_CLASS = 'flex items-start gap-3 py-2.5 first:pt-0 last:pb-0 md:py-0'
|
||||||
|
|
||||||
export function GroupInfoCard() {
|
export function GroupInfoCard() {
|
||||||
const { group, attendees, waitlistTotal } = useGroupDetail()
|
const { group, attendeesTotal, attendeesPending, waitlistTotal } = useGroupDetail()
|
||||||
if (!group) return null
|
if (!group) return null
|
||||||
|
|
||||||
|
const daysLabel = (group.days ?? []).map((day) => WEEK_DAY_FULL_LABELS[day]).join(', ')
|
||||||
|
const capacity = group.capacity
|
||||||
|
const isFull = capacity != null && attendeesTotal >= capacity
|
||||||
|
const freeSpots = capacity != null ? Math.max(capacity - attendeesTotal, 0) : null
|
||||||
|
const occupancy = capacity ? Math.min(attendeesTotal / capacity, 1) : 0
|
||||||
|
const billingMeta = formatBillingMeta(group.billingType, group.dueDay)
|
||||||
|
|
||||||
|
const capacityMeta = !capacity
|
||||||
|
? 'Sin cupo definido'
|
||||||
|
: isFull
|
||||||
|
? 'Cupo completo'
|
||||||
|
: `${freeSpots} ${freeSpots === 1 ? 'lugar libre' : 'lugares libres'}`
|
||||||
|
const waitlistMeta = waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid grid-cols-1 gap-4 rounded-xl border border-border bg-surface p-4 text-sm md:grid-cols-3">
|
<div className="divide-y divide-border/70 rounded-2xl bg-primary-soft p-3.5 sm:p-4 md:grid md:grid-cols-3 md:divide-x md:divide-y-0">
|
||||||
<div className="flex items-center gap-3">
|
<div className={cn(CELL_CLASS, 'md:pr-6')}>
|
||||||
<CalendarClock className="size-5 shrink-0 text-accent" />
|
<CalendarClock className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||||
<div>
|
<div className="min-w-0 flex-1">
|
||||||
<p className="text-xs font-medium uppercase text-foreground/50">Horario</p>
|
<p className={LABEL_CLASS}>Horario</p>
|
||||||
<p className="font-medium text-primary">
|
<p className="mt-0.5 text-base font-semibold leading-snug text-primary">
|
||||||
{(group.days?.length ?? 0) > 0
|
{daysLabel || 'Sin horario definido'}
|
||||||
? formatSchedule(group.days ?? [], group.time)
|
|
||||||
: 'Sin horario definido'}
|
|
||||||
</p>
|
</p>
|
||||||
|
{daysLabel && group.time ? (
|
||||||
|
<p className="mt-0.5 text-sm tabular-nums text-foreground">{group.time}</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className={cn(CELL_CLASS, 'md:px-6')}>
|
||||||
<Users className="size-5 shrink-0 text-accent" />
|
<Users className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||||
<div>
|
<div className="min-w-0 flex-1">
|
||||||
<p className="text-xs font-medium uppercase text-foreground/50">Miembros & Cupo</p>
|
<p className={LABEL_CLASS}>Miembros & Cupo</p>
|
||||||
<p className="font-medium text-primary">
|
<p className="mt-0.5 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular-nums text-primary">
|
||||||
{attendees.length} inscritos {waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''}
|
<span>{attendeesPending ? '—' : attendeesTotal}</span>
|
||||||
{group.capacity ? ` · Cupo de ${group.capacity}` : ''}
|
{capacity ? (
|
||||||
|
<span className="text-base font-medium text-foreground/70">/{capacity}</span>
|
||||||
|
) : null}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
{capacity ? (
|
||||||
|
<div
|
||||||
|
role="progressbar"
|
||||||
|
aria-label="Ocupación del cupo"
|
||||||
|
aria-valuemin={0}
|
||||||
|
aria-valuemax={capacity}
|
||||||
|
aria-valuenow={attendeesPending ? 0 : attendeesTotal}
|
||||||
|
aria-valuetext={`${attendeesTotal} de ${capacity}`}
|
||||||
|
className="mt-1.5 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'h-full rounded-full transition-[width] duration-300 ease-out',
|
||||||
|
isFull ? 'bg-warning' : 'bg-accent',
|
||||||
|
)}
|
||||||
|
style={{ width: `${Math.round(occupancy * 100)}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!attendeesPending ? (
|
||||||
|
<p className={cn('mt-1 text-sm', isFull ? 'text-warning' : 'text-foreground')}>
|
||||||
|
{capacityMeta}
|
||||||
|
{waitlistMeta}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className={cn(CELL_CLASS, 'md:pl-6')}>
|
||||||
<div className="flex size-5 shrink-0 items-center justify-center font-bold text-accent">$</div>
|
<CircleDollarSign className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||||
<div>
|
<div className="min-w-0 flex-1">
|
||||||
<p className="text-xs font-medium uppercase text-foreground/50">Cobro</p>
|
<p className={LABEL_CLASS}>Cobro</p>
|
||||||
<p className="font-medium text-primary">
|
<p className="mt-0.5 text-base font-semibold tabular-nums text-primary">
|
||||||
{group.price != null ? formatPrice(group.price) : 'Sin precio'}
|
{group.price != null ? formatPrice(group.price) : 'Sin precio'}
|
||||||
{group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}
|
|
||||||
{group.dueDay ? ` · Vence día ${group.dueDay}` : ''}
|
|
||||||
</p>
|
</p>
|
||||||
|
{billingMeta && group.price != null ? (
|
||||||
|
<p className="mt-0.5 text-sm text-foreground">{billingMeta}</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ export function InviteLinkModal() {
|
|||||||
{`¡Hola! 👋 Te invito a unirte al grupo `}
|
{`¡Hola! 👋 Te invito a unirte al grupo `}
|
||||||
<strong>{group?.name}</strong>.
|
<strong>{group?.name}</strong>.
|
||||||
{'\n\n'}
|
{'\n\n'}
|
||||||
Completa tus datos de inscripción en el siguiente enlace:
|
Completa tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:
|
||||||
{'\n'}
|
{'\n'}
|
||||||
<span className="break-all text-accent underline">{inviteUrl}</span>
|
<span className="break-all text-accent underline">{inviteUrl}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user