Compare commits
86 Commits
2370895710
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| ca60733ea0 | |||
|
|
aac142d324 | ||
|
|
abb18f1815 | ||
|
|
4211d5cf39 | ||
|
|
8cb5fe9b08 | ||
|
|
f4a6f2653f | ||
| bd7712b28e | |||
|
|
2d80af082f | ||
|
|
70ef049f34 | ||
|
|
f0bb02ab73 | ||
|
|
925f1a256d | ||
|
|
70702ba852 | ||
|
|
4d50b46399 | ||
|
|
486fbaf2ca | ||
|
|
b615c17a16 | ||
|
|
243530fab2 | ||
|
|
dfb6951d7c | ||
|
|
e2d9ddf569 | ||
|
|
700b9fb91d | ||
|
|
e3dca305a4 | ||
|
|
7db9414f12 | ||
|
|
13723d5bb9 | ||
|
|
8a5768e0c0 | ||
|
|
ecdbbbbca6 | ||
|
|
96661fb807 | ||
|
|
09647672b8 | ||
|
|
cb872eb8bc | ||
|
|
ff885bddfc | ||
|
|
d21e1c3730 | ||
|
|
f1829fb5a9 | ||
|
|
fc12ec3ae0 | ||
|
|
d397e9663c | ||
|
|
b6f22ae67d | ||
| b22b6da2e1 | |||
|
|
9e4d34b5d8 | ||
|
|
bc5f676cea | ||
| f6a7b7344e | |||
|
|
060a4f09e4 | ||
|
|
b99bc4d519 | ||
|
|
90f31290d4 | ||
|
|
e6d405a71e | ||
|
|
b12ffdda37 | ||
|
|
9617447e05 | ||
|
|
cd82a1e549 | ||
|
|
f5e77c99f6 | ||
|
|
f4d2c26e29 | ||
|
|
bef4056f8e | ||
|
|
2467ebc0f6 | ||
|
|
ec65c2198d | ||
|
|
8c5caecdda | ||
| b11dd47534 | |||
|
|
21a4c69f38 | ||
| e03f510874 | |||
|
|
59a4d18ce6 | ||
|
|
faf949fc9b | ||
|
|
6d120f4b1f | ||
|
|
69275c37b4 | ||
|
|
01b35691df | ||
| a93450579a | |||
|
|
ef38f98747 | ||
|
|
ea722a42f1 | ||
|
|
416c6f12e1 | ||
|
|
b5a00b309d | ||
|
|
454f20ed25 | ||
|
|
4e86096653 | ||
|
|
27bff32e76 | ||
|
|
13c1446977 | ||
| e9b44caf54 | |||
|
|
581cf2f2b2 | ||
|
|
81ed5747f3 | ||
|
|
8ccff20473 | ||
|
|
9520763ec3 | ||
|
|
5ef393fa64 | ||
|
|
45a1f50231 | ||
|
|
0f02331dfc | ||
|
|
df510cfe45 | ||
|
|
9f2e770509 | ||
|
|
2be59f99dd | ||
|
|
56096b1e35 | ||
|
|
2fd1826014 | ||
|
|
05da085e36 | ||
|
|
2e027408e6 | ||
|
|
54f1c7ab34 | ||
|
|
88c8b2ec90 | ||
|
|
0cd74194e3 | ||
|
|
f05fbf9e30 |
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.
|
||||
File diff suppressed because one or more lines are too long
448
.archify/architecture-gruperly-20261103-121500/candidate.json
Normal file
448
.archify/architecture-gruperly-20261103-121500/candidate.json
Normal file
@@ -0,0 +1,448 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"diagram_type": "architecture",
|
||||
"meta": {
|
||||
"title": "Arquitectura de Gruperly",
|
||||
"locale": "es",
|
||||
"output": ".archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html",
|
||||
"quality_profile": "showcase",
|
||||
"repository": {
|
||||
"url": "https://git.2pidev.com/jselesan/gruperly.git",
|
||||
"link_mode": "local-only",
|
||||
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
|
||||
},
|
||||
"views": [
|
||||
{
|
||||
"id": "request",
|
||||
"label": "Pedido del profe",
|
||||
"focus": [
|
||||
"teacher",
|
||||
"web",
|
||||
"nginx",
|
||||
"guards",
|
||||
"api",
|
||||
"db"
|
||||
],
|
||||
"note": "Mismo dominio: nginx sirve el bundle y hace proxy de /api al contenedor api."
|
||||
},
|
||||
{
|
||||
"id": "students",
|
||||
"label": "App de alumnos",
|
||||
"focus": [
|
||||
"student",
|
||||
"web",
|
||||
"guards",
|
||||
"storage"
|
||||
],
|
||||
"note": "Sin Better Auth: cookie y middleware propios; comprobantes en S3 privado."
|
||||
},
|
||||
{
|
||||
"id": "integrations",
|
||||
"label": "Integraciones",
|
||||
"focus": [
|
||||
"api",
|
||||
"mp",
|
||||
"stripe",
|
||||
"whatsapp",
|
||||
"smtp",
|
||||
"storage"
|
||||
],
|
||||
"note": "Cada proveedor detrás de un puerto; sin credenciales responde 503 y el resto sigue andando."
|
||||
}
|
||||
]
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"id": "teacher",
|
||||
"type": "external",
|
||||
"label": "Profesor",
|
||||
"sublabel": "navegador / PWA",
|
||||
"icon": "person",
|
||||
"pos": [
|
||||
40,
|
||||
60
|
||||
],
|
||||
"size": [
|
||||
120,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/web/src/routes/_authenticated.tsx",
|
||||
"line": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "web",
|
||||
"type": "frontend",
|
||||
"label": "Web PWA",
|
||||
"sublabel": "React 19 · Vite",
|
||||
"pos": [
|
||||
230,
|
||||
56
|
||||
],
|
||||
"size": [
|
||||
140,
|
||||
68
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/web/vite.config.ts",
|
||||
"line": 12,
|
||||
"label": "VitePWA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "student",
|
||||
"type": "external",
|
||||
"label": "Alumno / tutor",
|
||||
"sublabel": "/i/:token · /student",
|
||||
"icon": "person",
|
||||
"pos": [
|
||||
230,
|
||||
240
|
||||
],
|
||||
"size": [
|
||||
140,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/web/src/routes/i.$token.tsx",
|
||||
"line": 1
|
||||
},
|
||||
{
|
||||
"path": "apps/web/src/routes/_student.tsx",
|
||||
"line": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "nginx",
|
||||
"type": "cloud",
|
||||
"label": "nginx",
|
||||
"sublabel": "bundle + proxy /api",
|
||||
"pos": [
|
||||
450,
|
||||
60
|
||||
],
|
||||
"size": [
|
||||
140,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/web/nginx.conf",
|
||||
"line": 14,
|
||||
"end_line": 26
|
||||
},
|
||||
{
|
||||
"path": "docker-compose.yml",
|
||||
"line": 1,
|
||||
"end_line": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "guards",
|
||||
"type": "security",
|
||||
"label": "Guards de sesión",
|
||||
"sublabel": "Better Auth · alumno",
|
||||
"pos": [
|
||||
680,
|
||||
56
|
||||
],
|
||||
"size": [
|
||||
150,
|
||||
68
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/http/session-auth.ts",
|
||||
"line": 23,
|
||||
"end_line": 48
|
||||
},
|
||||
{
|
||||
"path": "apps/backend/src/modules/student-portal/middleware.ts",
|
||||
"line": 50
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "api",
|
||||
"type": "backend",
|
||||
"label": "API Hono + jobs",
|
||||
"sublabel": "Bun.serve :4000 · cron",
|
||||
"pos": [
|
||||
880,
|
||||
56
|
||||
],
|
||||
"size": [
|
||||
150,
|
||||
68
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/server.ts",
|
||||
"line": 14,
|
||||
"end_line": 23
|
||||
},
|
||||
{
|
||||
"path": "apps/backend/src/app.ts",
|
||||
"line": 44,
|
||||
"end_line": 73
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "db",
|
||||
"type": "database",
|
||||
"label": "PostgreSQL",
|
||||
"sublabel": "Prisma 7 · adapter-pg",
|
||||
"pos": [
|
||||
1090,
|
||||
60
|
||||
],
|
||||
"size": [
|
||||
140,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/lib/prisma.ts",
|
||||
"line": 14,
|
||||
"end_line": 18
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "mp",
|
||||
"type": "external",
|
||||
"label": "Mercado Pago",
|
||||
"sublabel": "OAuth · Checkout Pro",
|
||||
"pos": [
|
||||
610,
|
||||
320
|
||||
],
|
||||
"size": [
|
||||
130,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/modules/mp/lib/mp-oauth.ts",
|
||||
"line": 3,
|
||||
"end_line": 4
|
||||
},
|
||||
{
|
||||
"path": "apps/backend/src/modules/mp/lib/mp-http.ts",
|
||||
"line": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "stripe",
|
||||
"type": "external",
|
||||
"label": "Stripe",
|
||||
"sublabel": "Pro fuera de AR",
|
||||
"pos": [
|
||||
760,
|
||||
320
|
||||
],
|
||||
"size": [
|
||||
110,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/modules/billing/providers/index.ts",
|
||||
"line": 24,
|
||||
"end_line": 31
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "whatsapp",
|
||||
"type": "external",
|
||||
"label": "WhatsApp",
|
||||
"sublabel": "OpenWA / Kapso",
|
||||
"pos": [
|
||||
890,
|
||||
320
|
||||
],
|
||||
"size": [
|
||||
130,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/modules/whatsapp/providers/index.ts",
|
||||
"line": 26,
|
||||
"end_line": 40
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "smtp",
|
||||
"type": "external",
|
||||
"label": "SMTP",
|
||||
"sublabel": "mails",
|
||||
"pos": [
|
||||
1040,
|
||||
320
|
||||
],
|
||||
"size": [
|
||||
100,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/lib/email.ts",
|
||||
"line": 181,
|
||||
"end_line": 187
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "storage",
|
||||
"type": "cloud",
|
||||
"label": "S3 (RustFS)",
|
||||
"sublabel": "comprobantes",
|
||||
"pos": [
|
||||
1160,
|
||||
320
|
||||
],
|
||||
"size": [
|
||||
130,
|
||||
60
|
||||
],
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/src/lib/storage.ts",
|
||||
"line": 38,
|
||||
"end_line": 54
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"boundaries": [
|
||||
{
|
||||
"kind": "region",
|
||||
"label": "Dokploy",
|
||||
"wraps": [
|
||||
"nginx",
|
||||
"guards",
|
||||
"api",
|
||||
"db"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "security-group",
|
||||
"label": "contenedor api",
|
||||
"wraps": [
|
||||
"guards",
|
||||
"api"
|
||||
]
|
||||
}
|
||||
],
|
||||
"connections": [
|
||||
{
|
||||
"id": "teacher-web",
|
||||
"from": "teacher",
|
||||
"to": "web",
|
||||
"label": "HTTPS",
|
||||
"variant": "emphasis"
|
||||
},
|
||||
{
|
||||
"id": "student-web",
|
||||
"from": "student",
|
||||
"to": "web",
|
||||
"label": "link de WhatsApp"
|
||||
},
|
||||
{
|
||||
"id": "web-nginx",
|
||||
"from": "web",
|
||||
"to": "nginx",
|
||||
"label": "/api/v1",
|
||||
"variant": "emphasis"
|
||||
},
|
||||
{
|
||||
"id": "nginx-guards",
|
||||
"from": "nginx",
|
||||
"to": "guards",
|
||||
"label": "proxy_pass",
|
||||
"variant": "emphasis"
|
||||
},
|
||||
{
|
||||
"id": "guards-api",
|
||||
"from": "guards",
|
||||
"to": "api",
|
||||
"variant": "security"
|
||||
},
|
||||
{
|
||||
"id": "api-db",
|
||||
"from": "api",
|
||||
"to": "db",
|
||||
"label": "SQL"
|
||||
},
|
||||
{
|
||||
"id": "api-mp",
|
||||
"from": "api",
|
||||
"to": "mp",
|
||||
"label": "cobros"
|
||||
},
|
||||
{
|
||||
"id": "api-stripe",
|
||||
"from": "api",
|
||||
"to": "stripe",
|
||||
"label": "Pro"
|
||||
},
|
||||
{
|
||||
"id": "api-whatsapp",
|
||||
"from": "api",
|
||||
"to": "whatsapp",
|
||||
"label": "mensajes"
|
||||
},
|
||||
{
|
||||
"id": "api-smtp",
|
||||
"from": "api",
|
||||
"to": "smtp",
|
||||
"label": "mails"
|
||||
},
|
||||
{
|
||||
"id": "api-storage",
|
||||
"from": "api",
|
||||
"to": "storage",
|
||||
"label": "URLs firmadas"
|
||||
}
|
||||
],
|
||||
"cards": [
|
||||
{
|
||||
"dot": "cyan",
|
||||
"title": "Entrada",
|
||||
"items": [
|
||||
"Un solo dominio público en el contenedor web: nginx sirve la PWA y hace proxy de /api a api:4000, así la cookie de sesión es first-party.",
|
||||
"Los alumnos entran por un link de invitación de un solo uso; no tienen contraseña."
|
||||
]
|
||||
},
|
||||
{
|
||||
"dot": "rose",
|
||||
"title": "Seguridad",
|
||||
"items": [
|
||||
"sessionAuthMiddleware exige sesión de Better Auth salvo la whitelist pública (isPublicApiRequest).",
|
||||
"/student-portal usa cookie y middleware propios (studentSession); una sesión de alumno no llega a rutas del profe.",
|
||||
"Los webhooks de MP, Stripe y WhatsApp son públicos y se autentican por firma."
|
||||
]
|
||||
},
|
||||
{
|
||||
"dot": "emerald",
|
||||
"title": "Jobs en el mismo proceso",
|
||||
"items": [
|
||||
"server.ts arranca los crons de MP, pagos, WhatsApp, billing y app de alumnos junto a Bun.serve.",
|
||||
"La conciliación de pagos es por polling a Mercado Pago, sin webhook."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
515
.archify/erd-personas-membresias-20261103-120000/candidate.json
Normal file
515
.archify/erd-personas-membresias-20261103-120000/candidate.json
Normal file
@@ -0,0 +1,515 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"diagram_type": "erd",
|
||||
"meta": {
|
||||
"title": "Personas y membresías",
|
||||
"locale": "es",
|
||||
"output": ".archify/erd-personas-membresias-20261103-120000/personas-membresias.html",
|
||||
"quality_profile": "standard",
|
||||
"repository": {
|
||||
"url": "https://git.2pidev.com/jselesan/gruperly.git",
|
||||
"link_mode": "local-only",
|
||||
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
|
||||
},
|
||||
"views": [
|
||||
{
|
||||
"id": "membership",
|
||||
"label": "Persona y membresía",
|
||||
"focus": [
|
||||
"people",
|
||||
"attendees",
|
||||
"groups"
|
||||
],
|
||||
"note": "Una persona del profe, una fila de attendees por cada grupo en el que está."
|
||||
},
|
||||
{
|
||||
"id": "owner",
|
||||
"label": "Todo cuelga del profe",
|
||||
"focus": [
|
||||
"users",
|
||||
"groups",
|
||||
"people",
|
||||
"student_accounts"
|
||||
],
|
||||
"note": "Grupos, personas y cuentas de alumno tienen created_by_id al profe."
|
||||
},
|
||||
{
|
||||
"id": "student_app",
|
||||
"label": "Una cuenta por persona",
|
||||
"focus": [
|
||||
"student_accounts",
|
||||
"student_account_people",
|
||||
"people"
|
||||
],
|
||||
"note": "La cuenta se vincula a la persona, así ve todos sus grupos."
|
||||
}
|
||||
]
|
||||
},
|
||||
"layout": {
|
||||
"mode": "grid",
|
||||
"gapX": 72,
|
||||
"gapY": 40
|
||||
},
|
||||
"entities": [
|
||||
{
|
||||
"id": "groups",
|
||||
"label": "groups",
|
||||
"tag": "grupos",
|
||||
"row": 0,
|
||||
"col": 0,
|
||||
"width": 256,
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/prisma/models/domain.prisma",
|
||||
"line": 3,
|
||||
"end_line": 32
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"key": "pk"
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"name": "description",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "days",
|
||||
"type": "WeekDay[]"
|
||||
},
|
||||
{
|
||||
"name": "time",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "capacity",
|
||||
"type": "int?"
|
||||
},
|
||||
{
|
||||
"name": "price",
|
||||
"type": "numeric(10,2)?"
|
||||
},
|
||||
{
|
||||
"name": "billing_type",
|
||||
"type": "BillingType?"
|
||||
},
|
||||
{
|
||||
"name": "due_day",
|
||||
"type": "int?"
|
||||
},
|
||||
{
|
||||
"name": "auto_payment_reminders",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "auto_reengagement",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "invite_token",
|
||||
"type": "text?",
|
||||
"key": "uk"
|
||||
},
|
||||
{
|
||||
"name": "created_by_id",
|
||||
"type": "text",
|
||||
"key": "fk",
|
||||
"references": "users.id"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "timestamp"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "timestamp"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "attendees",
|
||||
"label": "attendees",
|
||||
"sublabel": "membresía",
|
||||
"tag": "membresías",
|
||||
"row": 0,
|
||||
"col": 1,
|
||||
"width": 250,
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/prisma/models/domain.prisma",
|
||||
"line": 100,
|
||||
"end_line": 125
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"key": "pk"
|
||||
},
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "text",
|
||||
"key": [
|
||||
"fk",
|
||||
"uk"
|
||||
],
|
||||
"references": "groups.id"
|
||||
},
|
||||
{
|
||||
"name": "person_id",
|
||||
"type": "text",
|
||||
"key": [
|
||||
"fk",
|
||||
"uk"
|
||||
],
|
||||
"references": "people.id"
|
||||
},
|
||||
{
|
||||
"name": "notify_token",
|
||||
"type": "text?",
|
||||
"key": "uk"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "AttendeeStatus"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "timestamp"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "timestamp"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "people",
|
||||
"label": "people",
|
||||
"sublabel": "persona del profe",
|
||||
"tag": "personas",
|
||||
"row": 0,
|
||||
"col": 2,
|
||||
"width": 250,
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/prisma/models/domain.prisma",
|
||||
"line": 75,
|
||||
"end_line": 98
|
||||
},
|
||||
{
|
||||
"path": "apps/backend/prisma/migrations/20261102180000_add_people/migration.sql",
|
||||
"line": 155,
|
||||
"label": "índice parcial"
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"key": "pk"
|
||||
},
|
||||
{
|
||||
"name": "created_by_id",
|
||||
"type": "text",
|
||||
"key": [
|
||||
"fk",
|
||||
"uk"
|
||||
],
|
||||
"references": "users.id"
|
||||
},
|
||||
{
|
||||
"name": "full_name",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"name": "email",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "phone",
|
||||
"type": "text?",
|
||||
"key": "uk"
|
||||
},
|
||||
{
|
||||
"name": "guardian_name",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "guardian_phone",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "notes",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "timestamp"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "timestamp"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "users",
|
||||
"label": "users",
|
||||
"sublabel": "profesor",
|
||||
"tag": "profesor",
|
||||
"row": 1,
|
||||
"col": 2,
|
||||
"width": 250,
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/prisma/models/auth.prisma",
|
||||
"line": 3,
|
||||
"end_line": 34
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"key": "pk"
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"key": "uk"
|
||||
},
|
||||
{
|
||||
"name": "email_verified",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "image",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "onboarding_completed",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "country_code",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "plan_selected_at",
|
||||
"type": "timestamp?"
|
||||
},
|
||||
{
|
||||
"name": "transfer_alias",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "transfer_holder",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "timestamp"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "timestamp"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "student_account_people",
|
||||
"label": "student_account_people",
|
||||
"tag": "app de alumnos",
|
||||
"row": 0,
|
||||
"col": 3,
|
||||
"width": 300,
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/prisma/models/student-access.prisma",
|
||||
"line": 40,
|
||||
"end_line": 54
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "account_id",
|
||||
"type": "text",
|
||||
"key": [
|
||||
"pk",
|
||||
"fk"
|
||||
],
|
||||
"references": "student_accounts.id"
|
||||
},
|
||||
{
|
||||
"name": "person_id",
|
||||
"type": "text",
|
||||
"key": [
|
||||
"pk",
|
||||
"fk"
|
||||
],
|
||||
"references": "people.id"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "timestamp"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "student_accounts",
|
||||
"label": "student_accounts",
|
||||
"tag": "app de alumnos",
|
||||
"row": 1,
|
||||
"col": 3,
|
||||
"width": 300,
|
||||
"sources": [
|
||||
{
|
||||
"path": "apps/backend/prisma/models/student-access.prisma",
|
||||
"line": 10,
|
||||
"end_line": 38
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"key": "pk"
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"name": "recovery_email",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "recovery_email_verified_at",
|
||||
"type": "timestamp?"
|
||||
},
|
||||
{
|
||||
"name": "pending_recovery_email",
|
||||
"type": "text?"
|
||||
},
|
||||
{
|
||||
"name": "welcomed_at",
|
||||
"type": "timestamp?"
|
||||
},
|
||||
{
|
||||
"name": "created_by_id",
|
||||
"type": "text",
|
||||
"key": "fk",
|
||||
"references": "users.id"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "timestamp"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "timestamp"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"relationships": [
|
||||
{
|
||||
"id": "attendee_group",
|
||||
"from": "attendees",
|
||||
"to": "groups",
|
||||
"label": "en el grupo",
|
||||
"fromCardinality": "many",
|
||||
"fromOptional": true,
|
||||
"toCardinality": "one"
|
||||
},
|
||||
{
|
||||
"id": "attendee_person",
|
||||
"from": "attendees",
|
||||
"to": "people",
|
||||
"label": "membresía de",
|
||||
"fromCardinality": "many",
|
||||
"toCardinality": "one"
|
||||
},
|
||||
{
|
||||
"id": "person_owner",
|
||||
"from": "people",
|
||||
"to": "users",
|
||||
"label": "del profe",
|
||||
"fromCardinality": "many",
|
||||
"fromOptional": true,
|
||||
"toCardinality": "one"
|
||||
},
|
||||
{
|
||||
"id": "group_owner",
|
||||
"from": "groups",
|
||||
"to": "users",
|
||||
"label": "dueño",
|
||||
"fromCardinality": "many",
|
||||
"fromOptional": true,
|
||||
"toCardinality": "one"
|
||||
},
|
||||
{
|
||||
"id": "link_person",
|
||||
"from": "student_account_people",
|
||||
"to": "people",
|
||||
"fromCardinality": "many",
|
||||
"fromOptional": true,
|
||||
"toCardinality": "one"
|
||||
},
|
||||
{
|
||||
"id": "link_account",
|
||||
"from": "student_account_people",
|
||||
"to": "student_accounts",
|
||||
"fromCardinality": "many",
|
||||
"toCardinality": "one"
|
||||
},
|
||||
{
|
||||
"id": "account_owner",
|
||||
"from": "student_accounts",
|
||||
"to": "users",
|
||||
"label": "creada por",
|
||||
"fromCardinality": "many",
|
||||
"fromOptional": true,
|
||||
"toCardinality": "one"
|
||||
}
|
||||
],
|
||||
"cards": [
|
||||
{
|
||||
"dot": "cyan",
|
||||
"title": "Unicidad",
|
||||
"items": [
|
||||
"attendees: @@unique(group_id, person_id), una persona está una sola vez en cada grupo.",
|
||||
"people_owner_phone_key: (created_by_id, phone) WHERE phone IS NOT NULL, índice parcial escrito a mano (Prisma no lo modela; el choque llega como P2002)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"dot": "amber",
|
||||
"title": "Qué es de quién",
|
||||
"items": [
|
||||
"people: contacto y notas; editarlos cambia en todos los grupos.",
|
||||
"attendees: status y notify_token por grupo; asistencia, cuotas, alertas y mensajes cuelgan de esta fila (no dibujados).",
|
||||
"El límite del plan cuenta personas con al menos una membresía ACTIVE."
|
||||
]
|
||||
},
|
||||
{
|
||||
"dot": "emerald",
|
||||
"title": "Borrados",
|
||||
"items": [
|
||||
"Todas las FK son ON DELETE CASCADE.",
|
||||
"Quitar la última membresía borra también la persona, y con ella el vínculo a la cuenta de alumno."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
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
|
||||
94
.env.example
Normal file
94
.env.example
Normal file
@@ -0,0 +1,94 @@
|
||||
# Variable template for `docker compose`.
|
||||
#
|
||||
# Local: copy this file to `.env` at the root and fill in the values.
|
||||
# Dokploy: no file needed; define the same variables in the Environment tab of
|
||||
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
||||
# file). The api container receives this whole file through `env_file`, so any
|
||||
# variable the backend reads (docs/environment.md) works without touching the
|
||||
# compose.
|
||||
|
||||
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
||||
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
||||
# domain, so the session cookie is first-party.
|
||||
WEB_URL="http://localhost:8080"
|
||||
|
||||
# Production PostgreSQL.
|
||||
# The password must be percent-encoded: if it has #, @, :, /, ?, % or a space,
|
||||
# escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the
|
||||
# URL where the fragment starts and fails with P1013 "invalid port number in
|
||||
# database URL".
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
|
||||
|
||||
# Generate it with: openssl rand -base64 32
|
||||
BETTER_AUTH_SECRET=""
|
||||
|
||||
# ── Optional ─────────────────────────────────────────────────────────────────
|
||||
|
||||
# Social login with Google. Without a client id/secret the provider is not
|
||||
# registered.
|
||||
# GOOGLE_CLIENT_ID=""
|
||||
# GOOGLE_CLIENT_SECRET=""
|
||||
|
||||
# Email sending (same variables as apps/backend/.env.example).
|
||||
# EMAIL_PROVIDER="smtp"
|
||||
# EMAIL_SERVER_HOST=""
|
||||
# EMAIL_SERVER_PORT="587"
|
||||
# EMAIL_SERVER_USER=""
|
||||
# EMAIL_SERVER_PASSWORD=""
|
||||
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales
|
||||
# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando
|
||||
# (el paso "Cobros" del onboarding es salteable).
|
||||
# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded.
|
||||
# TOKEN_ENCRYPTION_KEY=""
|
||||
# Redirect URL registered in the Mercado Pago panel, character for character.
|
||||
# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel.
|
||||
# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback"
|
||||
# MP_CLIENT_ID=""
|
||||
# MP_CLIENT_SECRET=""
|
||||
|
||||
# Suscripción a Gruperly Pro (ver docs/billing.md y docs/environment.md).
|
||||
# Argentina la cobra con Suscripciones de Mercado Pago; el resto, con Stripe.
|
||||
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina. No
|
||||
# son las del OAuth del profesor. Sin las dos, Pro queda "no disponible" (503).
|
||||
# MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||
# Origen público de la API para la vuelta del checkout de Pro. Vacío =
|
||||
# BETTER_AUTH_URL, que en este compose ya es el dominio público.
|
||||
# API_PUBLIC_URL=""
|
||||
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda de
|
||||
# cada país. Secret key (sk_live_…) y signing secret del webhook (whsec_…) del
|
||||
# endpoint https://<API>/api/v1/billing/webhooks/stripe. Sin las dos, 503 ahí.
|
||||
# STRIPE_SECRET_KEY=""
|
||||
# STRIPE_WEBHOOK_SECRET=""
|
||||
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||
# BILLING_ENFORCEMENT="off"
|
||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||
# BILLING_GRACE_DAYS="7"
|
||||
|
||||
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
|
||||
# ADMIN_EMAILS=""
|
||||
|
||||
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
|
||||
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
|
||||
# whatsapp_not_configured y el paso del onboarding es salteable.
|
||||
# WHATSAPP_PROVIDER="openwa" # openwa (MVP) | kapso
|
||||
# WHATSAPP_SEND_INTERVAL_MS="5000" # pausa entre envios del mismo profesor
|
||||
#
|
||||
# OpenWA (se instala aparte, fuera de este compose).
|
||||
# OPENWA_API_URL="https://openwa.example.com/api"
|
||||
# OPENWA_API_KEY="" # key OPERATOR, sin allowedSessions
|
||||
# OPENWA_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/openwa"
|
||||
# OPENWA_WEBHOOK_SECRET="" # 16+ caracteres: openssl rand -hex 24
|
||||
#
|
||||
# Kapso (API oficial de WhatsApp Cloud).
|
||||
# KAPSO_API_KEY=""
|
||||
# KAPSO_CALLBACK_URL="https://app.gruperly.com/api/v1/whatsapp/callback"
|
||||
# KAPSO_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/kapso"
|
||||
# KAPSO_WEBHOOK_SECRET="" # el mismo del project webhook de Kapso
|
||||
|
||||
# Only if you want the API on another domain: it is baked into the Vite bundle
|
||||
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
|
||||
# origin (recommended).
|
||||
# VITE_API_URL=""
|
||||
14
.gitignore
vendored
14
.gitignore
vendored
@@ -6,6 +6,7 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.impeccable
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
@@ -90,6 +91,8 @@ out
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
# Service worker que vite-plugin-pwa escribe al serving en dev
|
||||
dev-dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
@@ -147,3 +150,14 @@ apps/backend/generated/
|
||||
# env
|
||||
apps/backend/.env
|
||||
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
# archify: solo se versionan el HTML final y el candidate.json; lo intermedio no
|
||||
.archify/**/*.browser-check.json
|
||||
.archify/**/*.delivery.json
|
||||
.archify/**/*.finalize.json
|
||||
.archify/**/*.finalize-summary.json
|
||||
.archify/**/candidate.before-review.json
|
||||
.archify/**/review-*/
|
||||
|
||||
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.
|
||||
72
AGENTS.md
72
AGENTS.md
@@ -21,6 +21,7 @@ bun run lint:fix # biome check --write
|
||||
bun --filter @gruperly/backend typecheck # verificación de un solo paquete
|
||||
bun --filter @gruperly/backend test # bun test (backend)
|
||||
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
||||
bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web/public/ (sharp)
|
||||
```
|
||||
|
||||
## Estructura y fronteras
|
||||
@@ -30,30 +31,89 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||
- `src/logger.ts` — pino + pino-pretty.
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`).
|
||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`).
|
||||
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; límites y precio de Pro por país se leen con `PlanCatalog`/`planCatalog`, nunca con `PLAN_LIMITS`/`PRO_PRICE_BY_COUNTRY` directo, que son solo defaults; guía en `docs/billing.md`). `admin` (backoffice de las cuentas de profesores, de solo lectura salvo **Planes** (`/admin/plans`: límites y precio de Pro, con opción de aplicar el precio a las suscripciones vivas desde el próximo cobro): acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*` y `/admin/plans*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
|
||||
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||
|
||||
## Gotchas operativos
|
||||
|
||||
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). Como la cookie de sesión es de `localhost:4000`, el callback que entra por el túnel rebota a `BETTER_AUTH_URL` con la misma query (`mpCallbackOriginMiddleware`, antes del middleware de sesión; no se dispara si ambos hosts coinciden, como en prod). El callback además exige que la sesión sea la del dueño del `state`. El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
||||
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
||||
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
||||
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
||||
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
|
||||
4. La idempotencia de los envíos es el `@@unique([kind, attendeeId, periodKey])` de `outbound_messages` (semana ISO): la fila se crea **antes** de llamar al proveedor y su id es el `Idempotency-Key`.
|
||||
5. Los teléfonos se guardan en formato nacional: el envío pasa por `toWhatsappE164` (shared) con el país del profesor.
|
||||
6. Sin SDK de Kapso (trae su propio zod): `fetch` plano.
|
||||
7. El sandbox de Kapso no soporta templates.
|
||||
8. OpenWA se instala **aparte** (no está en `docker-compose.yml`); la API le habla por `OPENWA_API_URL`. Su guard SSRF rechaza webhooks a hosts internos que no estén en `SSRF_ALLOWED_HOSTS`.
|
||||
9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`.
|
||||
10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos.
|
||||
11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`.
|
||||
- **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual), no lo que pagan los alumnos. Ojo con esto:
|
||||
1. Proveedor intercambiable detrás del puerto `BillingProvider` (`providers/billing-provider.ts`, mismo patrón que WhatsApp): Mercado Pago (`/preapproval`) en **AR** y Stripe (Checkout en modo suscripción, `fetch` plano sin SDK) en el resto; el mapa es `BILLING_PROVIDER_BY_COUNTRY` (shared). Los use-cases, `SyncSubscription` y el job **nunca** importan un adaptador: piden `getBillingProvider(id)` (inyectable como `providers` en `deps`). El país elige proveedor solo para suscripciones **nuevas**: sync/cancel/webhook usan siempre `row.provider`. MP usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_<CC>`, nunca `getMpAccessToken`); Stripe, una sola cuenta (`STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET`) que cobra en la moneda local (CLP es zero-decimal). Sin credenciales: `503 billing_not_available`. Con Stripe la suscripción no existe hasta completar el checkout: la fila guarda `checkoutRef` (la session) y la sync completa `externalId`.
|
||||
2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard.
|
||||
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
|
||||
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
|
||||
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
|
||||
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde.
|
||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||
- `.env`, `dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<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).
|
||||
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/access`, `/student/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto:
|
||||
1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`.
|
||||
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
|
||||
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
|
||||
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
|
||||
5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) es solo del lado profe y **todavía no tiene UI**.
|
||||
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
|
||||
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
|
||||
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
|
||||
9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`).
|
||||
10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`.
|
||||
- **Personas y membresías (`Person` / `Attendee`)**: una persona puede estar en varios grupos del mismo profe. Ojo con esto:
|
||||
1. `Person` (`people`, del profe vía `created_by_id`) tiene los datos de contacto y las notas; `Attendee` es la **membresía** (`group_id` + `person_id` + `status` + `notify_token`), con `@@unique([groupId, personId])`. Asistencia, cuotas, alertas y mensajes siguen siendo por attendee (por grupo). (`Member` ya existe: es la organización de Better Auth.)
|
||||
2. El teléfono es único por profe con un índice **parcial** a mano (`people_owner_phone_key`, `WHERE phone IS NOT NULL`): Prisma no lo modela y un choque llega como `P2002` (`isUniqueViolation` en `modules/people/lib/people.ts`). Los teléfonos se guardan normalizados (`normalizePhone`, también al editar); `phoneVariants` cubre filas viejas.
|
||||
3. Las altas resuelven a la persona por teléfono: el alta individual sin `personId` con un teléfono existente responde `409 person_exists` (la web lo detecta antes con `GET /people/lookup?groupId=&phone=` y manda `personId`); bulk, lista de espera y preinscripciones vinculan solas (`findOrCreatePerson`). Ya estar en el grupo es `attendee_already_registered`; una membresía `DROPPED` se reactiva.
|
||||
4. `POST /groups/:gid/attendees/:aid/add-to-group` ("Agregar a otro grupo") crea otra membresía de la misma persona; `move` sigue cambiando el `groupId` de la misma membresía. Ambas validan con `checkCanJoinGroup(db, group, personId)`.
|
||||
5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona.
|
||||
6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`).
|
||||
7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`.
|
||||
- **Multi idioma (`apps/web/src/i18n/`)**: i18next + react-i18next. Idiomas: `es-AR` (rioplatense, voseo; AR y UY), `es-419` (tuteo), `pt-BR` y `en`; la lista vive en `SUPPORTED_LOCALES` (`packages/shared/src/schemas/locale.ts`) y `resolveLocale` mapea los idiomas del dispositivo (cualquier otro `es-*` → `es-419`, cualquier `pt-*` → `pt-BR`, lo no soportado → `en`). Ojo con esto:
|
||||
1. **`es-AR` es la fuente**: `i18next.d.ts` tipa las claves con sus JSON, así que una clave que no exista ahí rompe el typecheck. `test/i18n-keys.test.ts` exige las mismas claves (salvo sufijos de plural) y variables en los 4 idiomas. Un namespace nuevo = un JSON por idioma + `NAMESPACES` (`instance.ts`) + `i18next.d.ts`.
|
||||
2. La preferencia es `'system' | AppLocale` en `localStorage['locale']`; para el profe también en `users.locale` (Better Auth `additionalFields`, validado con `appLocaleSchema`; `null` = idioma del dispositivo). `LocaleProfileSync` aplica el del perfil al iniciar sesión; `LanguageCard` lo guarda con `authClient.updateUser`. La app de alumnos solo usa `localStorage`.
|
||||
3. `main.tsx` carga el idioma (más `en` de fallback) **antes** del primer render; los JSON se cargan lazy por `import.meta.glob` (solo existe en Vite: en `bun test` el preload `test/setup.ts` carga `es-AR` del disco, por eso los tests asertan el copy rioplatense).
|
||||
4. Un componente que pinta texto traducido llama `useTranslation`, aunque el texto salga de un helper (`weekDayLabel`, `paymentStatusLabel`, `copy.ts` con `i18n.t`): es lo que lo re-renderiza al cambiar de idioma.
|
||||
5. Fechas y nombres de días/meses van en el idioma de la UI (`useIntlLocale()` / `i18n.language`), **nunca** con `'es-AR'` fijo. Montos y teléfonos **no**: `formatPrice`/`formatPhoneDisplay` siguen al **país** (`lib/region.ts`).
|
||||
6. Validación: los esquemas (shared y web) llevan **claves** (`'group.nameMin'`) en vez de texto; se pintan con `<FieldError message={errors.x?.message} />` (traduce contra el namespace `validation`). `installZodErrorMap` cubre los mensajes por defecto de Zod.
|
||||
7. Errores de la API: `errorMessage(error, fallback)` traduce el `code` del Problem Details (namespace `errors`, `codes.*`; los de Better Auth en `auth.*`); los `params` del problema (`limit`, `feature`, `max`, `capacity`) eligen variante y plural. Con la UI en español cae al `detail` del backend; si no, al `fallback`. Un error nuevo del backend que la UI muestre tiene que llevar `code` y su traducción.
|
||||
8. Lo que arma el backend en español y la UI muestra se redacta en la web a partir de datos estructurados: las alertas de `computeStudentAlerts` traen `razon` + `valores` (la web usa `alertLabel`/`alertDetail` de `features/attention/attention.ts`; `etiqueta`/`detalle` quedan para el backend), y los `message` de la API (importación masiva, preinscripción) se ignoran y se arman con los contadores. Nombres de país: `countryName` (`Intl.DisplayNames`), no `COUNTRY_LABELS`.
|
||||
9. Pendiente: mails, WhatsApp y el manifest de la PWA (`vite.config.ts`) siguen solo en español (etapa 2: usar `users.locale`).
|
||||
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||
|
||||
## Convenciones repo-específicas
|
||||
|
||||
- **Frontend en español**: copy de UI, comentarios y textos en español.
|
||||
- **Base de datos**: todas las tablas usan **snake_case** vía `@@map` en `prisma/models/*.prisma` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`). Al agregar un modelo nuevo, incluir siempre `@@map("nombre_tabla")`.
|
||||
- **Commits en inglés**: los mensajes de commit (título y cuerpo) van siempre en inglés, con prefijo Conventional Commits (`feat(i18n): …`, `fix: …`, `chore: …`). Los commits anteriores en español quedan como están.
|
||||
- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/<namespace>.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español.
|
||||
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
|
||||
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
|
||||
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
|
||||
- **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`).
|
||||
- **Router 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.
|
||||
- **Grupos y "Requiere atención"** comparten la query `['attention']` (`features/attention/queries.ts`): el "Resuelto" es optimista sobre ese caché y por eso los contadores de Grupos se mueven sin refetch. El "Nuevo grupo" de Grupos es un FAB (`NewGroupFab`, se pliega al scrollear con `useCollapseOnScroll`) y por eso los toasts en mobile van a `bottom-[calc(9rem+…)]`. Los colores de gravedad son tokens (`alert-urgent-*`, `alert-watch-*`, `free-fg`) definidos para claro y oscuro en `index.css`.
|
||||
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
||||
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
|
||||
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
||||
- **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición.
|
||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||
- **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.
|
||||
- **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). **Excepción**: `/groups/attention` ("Requiere atención", sin entrada en el nav) muestra su botón Volver también en mobile. Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
||||
|
||||
## Fuentes de contexto
|
||||
|
||||
|
||||
66
Dockerfile.backend
Normal file
66
Dockerfile.backend
Normal file
@@ -0,0 +1,66 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||
FROM oven/bun:1.4-alpine AS base
|
||||
WORKDIR /app
|
||||
ENV CI=1
|
||||
|
||||
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||
# Only the package.json files: bun needs no source code to resolve the lockfile.
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY apps/web/package.json ./apps/web/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||
|
||||
# ─── Prisma Client ───────────────────────────────────────────────────────────
|
||||
# The "prisma-client" generator emits TypeScript, so the generated client runs
|
||||
# with Bun without compilation. The URL is a placeholder: `generate` only needs
|
||||
# to read the schema, not connect to a database.
|
||||
FROM deps AS generate
|
||||
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
|
||||
ENV DATABASE_URL=$DATABASE_URL
|
||||
COPY apps/backend/prisma.config.ts ./apps/backend/
|
||||
COPY apps/backend/prisma ./apps/backend/prisma
|
||||
WORKDIR /app/apps/backend
|
||||
RUN bun run db:generate
|
||||
|
||||
# ─── API image ───────────────────────────────────────────────────────────────
|
||||
FROM base AS api
|
||||
ENV NODE_ENV=production \
|
||||
PORT=4000
|
||||
|
||||
COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs
|
||||
# `prisma migrate deploy` on every boot. With `--production` the rest of the
|
||||
# tooling does not come in: biome, typescript, turbo.
|
||||
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
|
||||
|
||||
# The Prisma CLI loads prisma.config.ts, which points to the schema.
|
||||
COPY apps/backend/prisma ./apps/backend/prisma
|
||||
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
|
||||
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
|
||||
COPY apps/backend/tsconfig.json ./apps/backend/
|
||||
COPY apps/backend/src ./apps/backend/src
|
||||
# @gruperly/shared is consumed as TS source; @gruperly/config provides the base
|
||||
# tsconfig that the backend tsconfig extends.
|
||||
COPY packages ./packages
|
||||
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
WORKDIR /app/apps/backend
|
||||
EXPOSE 4000
|
||||
# No `${...}` here: the CMD runs under /bin/sh (ash), where that is a syntax error.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||
# Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
|
||||
# same as `bun start` locally.
|
||||
CMD ["bun", "src/server.ts"]
|
||||
35
Dockerfile.web
Normal file
35
Dockerfile.web
Normal file
@@ -0,0 +1,35 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||
FROM oven/bun:1.4-alpine AS base
|
||||
WORKDIR /app
|
||||
ENV CI=1
|
||||
|
||||
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY apps/web/package.json ./apps/web/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||
|
||||
# ─── Vite build ──────────────────────────────────────────────────────────────
|
||||
FROM deps AS build
|
||||
# Vite replaces import.meta.env.* at build time, not at runtime.
|
||||
# Empty = same origin: nginx's /api proxy acts as the API.
|
||||
ARG VITE_API_URL=""
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
COPY apps/web ./apps/web
|
||||
COPY packages ./packages
|
||||
RUN bun --filter @gruperly/web build
|
||||
|
||||
# ─── Final image ─────────────────────────────────────────────────────────────
|
||||
FROM nginx:1.27-alpine AS web
|
||||
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||
CMD wget --quiet --tries=1 --spider http://127.0.0.1/ || exit 1
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
197
README.md
197
README.md
@@ -7,7 +7,7 @@ Monorepo de Gruperly. Consulta [stack.md](./stack.md) para arquitectura y especi
|
||||
- Package manager: [Bun](https://bun.sh/) 1.4
|
||||
- Monorepo: bun workspaces + Turborepo
|
||||
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
||||
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4
|
||||
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 + PWA (vite-plugin-pwa / Workbox)
|
||||
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
||||
|
||||
## Estructura
|
||||
@@ -31,9 +31,204 @@ bun run lint # biome check (backend y shared)
|
||||
bun --filter @gruperly/backend test # bun test (backend)
|
||||
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
|
||||
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
||||
bun --filter @gruperly/web icons # Regenera los iconos PWA de public/ desde el isotipo SVG
|
||||
```
|
||||
|
||||
## PWA
|
||||
|
||||
La web es instalable y abre sin conexión el shell de la app (rutas, JS, CSS, tipografía e iconos). Los datos de la API **no** se cachean: son cobros y una respuesta vieja sería peor que un error, así que offline la app carga pero las consultas fallan.
|
||||
|
||||
- **Manifest y service worker**: `apps/web/vite.config.ts` (`VitePWA`, `generateSW`, `registerType: 'autoUpdate'`). El registro se hace desde `apps/web/src/features/pwa/PwaProvider.tsx` (`injectRegister: null`) para poder avisar con un toast cuando la app ya quedó lista para offline.
|
||||
- **`workbox-window` es dependencia directa de `apps/web` a propósito**: `virtual:pwa-register` la importa desde el grafo de la app, pero llega como dependencia transitiva de `vite-plugin-pwa`. Localmente bun la hoistea a la raíz y todo anda; en la imagen de Docker bun usa el layout aislado y la deja solo en `node_modules/.bun/`, así que Rollup falla con `failed to resolve import "workbox-window"` y el build de Dokploy se cae. Declararla en `apps/web/package.json` la hace resoluble desde `apps/web/node_modules/`. **No la borres por "no estar imports en el código".**
|
||||
- **Iconos**: se generan con sharp desde `apps/web/src/assets/brand/isotipo-y-organica.svg` y se versionan en `apps/web/public/` (`pwa-192x192`, `pwa-512x512`, `pwa-maskable-512x512`, `apple-touch-icon-180`). El build **no** los regenera; corré `bun --filter @gruperly/web icons` cuando cambie el isotipo.
|
||||
- **Tipografía**: Inter variable auto-hospedada vía `@fontsource-variable/inter`, declarada a mano en `apps/web/src/index.css`. No hay `<link>` a `fonts.googleapis.com`: era una dependencia de red en runtime.
|
||||
- **Aviso de instalación**: la lógica de *cuándo* se ofrece vive en `apps/web/src/features/pwa/PwaProvider.tsx` (captura `beforeinstallprompt`, gate de sesión, dwell y descarte) y el dibujo en `InstallPrompt.tsx` → `InstallBanner.tsx` (Chromium) o `IosInstallHint.tsx` (Safari en iOS, que no dispara el evento y hay que instruir con Compartir → Agregar a pantalla de inicio).
|
||||
- Se ofrece solo con **sesión iniciada**, **fuera del onboarding** y después de **20 s seguidos en la misma ruta**; `beforeinstallprompt` llega a los segundos y sin ese margen el aviso cae en medio de la primera tarea de la visita. Navegar antes de que se cumpla el tiempo reinicia la cuenta; una vez cumplido no se oculta más al navegar.
|
||||
- El descarte es definitivo: se guarda en `localStorage['pwa-install-dismissed']` y no vuelve a preguntar en ese navegador.
|
||||
- El timer vive en el provider y no en el componente que dibuja el aviso a propósito: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un timer en el hijo se perdería en cada navegación. El provider, en cambio, sigue montado y se suscribe al router (`router.subscribe('onResolved')`) porque está fuera del `RouterProvider`.
|
||||
- Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` sin usuario—, así que el gate se chequea en el provider y no se puede inferir de dónde se monte el prompt.
|
||||
- **nginx**: `apps/web/nginx.conf` sirve `sw.js`, `workbox-*.js` y `manifest.webmanifest` con `Cache-Control: no-cache` y `=404` (no el fallback del SPA), para que una versión vieja no quede cacheada para siempre.
|
||||
|
||||
### Requisitos para que funcione
|
||||
|
||||
El service worker necesita un **contexto seguro**: HTTPS, o `http://localhost`. Probar por IP de LAN sobre `http://` no registra el SW en silencio, sin error visible. En producción el TLS lo termina Traefik adelante de nginx.
|
||||
|
||||
### Verificar
|
||||
|
||||
```bash
|
||||
bun --filter @gruperly/web build
|
||||
bun --filter @gruperly/web preview # http://localhost:4173
|
||||
```
|
||||
|
||||
En DevTools → Application: el manifest sin warnings, el service worker `activated`, y en Network → Offline un reload de `/` o `/groups` tiene que seguir pintando la app. `bun dev` también registra el SW (está en `devOptions`), así que se puede probar sin build, pero `dev-dist/` queda gitignoreado.
|
||||
|
||||
## Setup de base de datos
|
||||
|
||||
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
||||
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
||||
|
||||
## Mercado Pago (OAuth)
|
||||
|
||||
Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago en modo directo: el profesor autoriza desde el panel de MP y los pagos entran en su propia cuenta, sin comisión ni split de plataforma (`platform_id=mp`). El OAuth vive en `apps/backend/src/modules/mp/`; los links de pago y la reconciliación están en `modules/payments/` (ver [Cobros](#cobros-links-de-pago)).
|
||||
|
||||
**Panel de Mercado Pago** (Developer panel → Tu aplicación):
|
||||
|
||||
- **Redirect URL**: el panel la exige en **HTTPS** (rechaza `http://localhost`) y tiene que coincidir carácter por carácter con `MP_REDIRECT_URI`. En local, meté un túnel delante del backend y registrá esa URL HTTPS tanto en el panel como en la env var: `ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000` (el *dev domain* de ngrok es fijo por cuenta, gratis) o un túnel nombrado de Cloudflare (`cloudflared tunnel route dns …`). `WEB_URL` y `VITE_API_URL` siguen en localhost: el túnel solo lo usa el navegador para volver desde MP. Los *quick tunnels* de cloudflared generan una URL nueva en cada arranque, así que obligan a regenerar la URL en el panel y en la env var cada reinicio.
|
||||
- **PKCE (S256)**: activado. El `code_verifier` se genera y se consume en el servidor, nunca pasa por el navegador.
|
||||
- **Permisos**: `offline_access read write`. Sin `offline_access` Mercado Pago no devuelve *refresh token* y la renovación automática no tiene con qué trabajar.
|
||||
|
||||
**Variables de entorno** (`apps/backend/.env` en local, pestaña Environment del compose en Dokploy):
|
||||
|
||||
| Variable | ¿Obligatoria? | Descripción |
|
||||
| --- | --- | --- |
|
||||
| `MP_CLIENT_ID` | para vincular | Client ID de la app de MP |
|
||||
| `MP_CLIENT_SECRET` | para vincular | Secret de la app de MP |
|
||||
| `MP_REDIRECT_URI` | para vincular | Callback registrado en el panel |
|
||||
| `TOKEN_ENCRYPTION_KEY` | para vincular | `openssl rand -base64 32`. Cifra los tokens en reposo con AES-256-GCM. Si no decodifica a 32 bytes, el backend lo rechaza al guardar la cuenta |
|
||||
|
||||
Sin las cuatro, `GET /api/v1/mp/connect` responde `503 mp_not_configured` y la app sigue funcionando: el paso "Cobros" del onboarding es **salteable**.
|
||||
|
||||
En local se usan las credenciales de **producción** de la app: no existe OAuth sandbox en MP (las credenciales de prueba del panel son solo Public Key y Access Token, sin Client ID/secret). No hay riesgo, porque el OAuth solo vincula una cuenta y no mueve dinero; se prueba con una cuenta propia y se desvincúa con `DELETE /mp/connect`. Los links de pago también se prueban con la cuenta propia (crear un link no cobra nada; el cobro real le pide credenciales de pago al alumno).
|
||||
|
||||
### Cómo funciona
|
||||
|
||||
```text
|
||||
onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state + PKCE en la DB, 10 min)
|
||||
→ https://auth.mercadopago.com/authorization
|
||||
→ GET /mp/callback → ?code&state (se quema el state, se cambia el código)
|
||||
→ 302 a /onboarding?mp=success o /settings?mp=error&reason=…
|
||||
```
|
||||
|
||||
- La API de MP es `GET /mp/status` (`none` | `active` | `requires_reauth`) y `DELETE /mp/connect` (desvincula; conserva la fila para que la cuenta de MP quede reservada al mismo profesor).
|
||||
- Los tokens se guardan cifrados; `status` nunca devuelve tokens, scope ni el id completo de MP (solo los últimos 4 dígitos, para que el profesor confirme que vinculó la cuenta correcta).
|
||||
- Un cron diario (`17 3 * * *` UTC) renueva las cuentas que vencen en menos de 30 días, en lotes de 20 con `FOR UPDATE SKIP LOCKED`. Solo `invalid_grant` marca la cuenta como `requires_reauth`; un 5xx o un fallo de red se reintenta al día siguiente, para no bloquear a un profesor por una tarde mala de MP. `apps/backend/src/modules/mp/access-token.ts` (`getMpAccessToken`) renueva bajo demanda si el token está por vencer.
|
||||
|
||||
### Verificar a mano
|
||||
|
||||
1. `bun dev`, crear una cuenta nueva y llegar al paso "Cobros".
|
||||
2. **Vincular**: "Vincular cuenta" debe abrir el consent de MP; al aceptar se vuelve a `/onboarding` con el mensaje de cuenta vinculada, y Ajustes → Cobros muestra "Vinculada" con los últimos 4 dígitos.
|
||||
3. **Saltear**: con una cuenta nueva, "Lo hago después" deja crear el grupo igual; el resumen final ofrece vincularlo después desde Ajustes.
|
||||
4. **Denegar**: en la pantalla de consentimiento de MP, elegir no autorizar → vuelve con "No autorizaste la conexión en Mercado Pago" y el estado sigue en `none`.
|
||||
5. **Desvincular**: Ajustes → Cobros → Desvincular (pide confirmación) deja el estado en `none` y la tarjeta de cuenta conectada desaparece.
|
||||
6. **Reautenticación**: `UPDATE users SET ...` no hace falta; para forzarla, `UPDATE mp_accounts SET status = 'REQUIRES_REAUTH'` y recargar cualquier pantalla: aparece el aviso global (excepto en Ajustes, donde la tarjeta ofrece la acción).
|
||||
|
||||
```bash
|
||||
# Estado real, con la sesión del profesor:
|
||||
curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: <cookie de sesión>' | jq
|
||||
```
|
||||
|
||||
## Cobros (links de pago)
|
||||
|
||||
Un cobro es un **link de pago de Checkout Pro por alumno y por período**. El profesor lo dispara desde la ficha del grupo (**Cobrar**, habilitado cuando el grupo tiene precio): se crea un `Payment` por cada asistente activo y, para cada uno, una preferencia de Checkout Pro con `external_reference` = id del pago. Crear un link no cobra nada; el cobro real lo paga el alumno desde el link.
|
||||
|
||||
La moneda sale del país del profesor (`user.country`, elegido en el onboarding; default `AR` → `ARS`): `AR→ARS, BR→BRL, CL→CLP, CO→COP, MX→MXN, PE→PEN, UY→UYU`.
|
||||
|
||||
**Endpoints** (todos requieren sesión; solo grupos propios o donde el profesor es miembro):
|
||||
|
||||
| Endpoint | Qué hace |
|
||||
| --- | --- |
|
||||
| `POST /api/v1/groups/:groupId/payments/batch` | Crea el lote. Body: `{ dueDate, description?, attendeeIds? }`. Responde `201` con `{ total, linked, failed, items }`; cada item es `LINKED` (trae `checkoutUrl`) o `FAILED` (error del proveedor, la fila queda `PENDING` sin link) |
|
||||
| `POST /api/v1/payments/:id/renew` | Regenera el link de un pago que lo perdió (item `FAILED`). Idempotente: si ya tiene link, lo devuelve tal cual |
|
||||
| `GET /api/v1/payments?groupId&status&page&pageSize` | Lista paginada `{ data, pagination }` de los cobros visibles |
|
||||
|
||||
**Estados**: `PENDING` (esperando pago) → `PAID` (aprobado en MP) | `OVERDUE` (venció + 24 h de gracia y sigue sin pagar; sigue siendo cobrable) | `CANCELLED` (reservado, hoy no se usa).
|
||||
|
||||
**Reconciliación, sin webhook.** El MVP consolida por polling porque un webhook exige una URL pública y verificación de firma, y no aporta nada a esta escala: un cron cada 15 min consulta la API de MP por `external_reference`, y si el pago está `approved` marca el `Payment` como `PAID` (guarda `mpPaymentId` y `paidAt`). Solo toca pagos con link y de más de 5 min de antigüedad, en lotes de 50. Un cron diario (`4 4 * * *` UTC) convierte en `OVERDUE` los `PENDING` cuya fecha venció hace más de 24 h. Los anuncian en el log (`startPaymentJobs()` en `apps/backend/src/server.ts`).
|
||||
|
||||
**En la web**: la vista **Cobros** (nav) filtra por grupo y estado y deja copiar el link o regenerarlo con "Generar link" (botón renovar). Del modal **Cobrar** en la ficha del grupo se eligen vencimiento y descripción (default: mes en mayúscula) y se muestra un link por alumno para copiar, con los que fallaron listos para reintentar.
|
||||
|
||||
**Errores típicos**: `409 group_without_price` (el grupo no tiene precio definido), `409 no_attendees_to_bill` (sin alumnos activos), `409 mp_not_connected` (el dueño desvinculó MP), `503 mp_not_configured` (faltan las env vars del OAuth).
|
||||
|
||||
### Verificar a mano (además del flujo de OAuth)
|
||||
|
||||
1. Con un grupo con precio y alumnos, "Cobrar" → elegir vencimiento → los links se generan uno por alumno.
|
||||
2. En **Cobros** el grupo aparece con `PENDING` por alumno; "Copiar" pega un link `https://www.mercadopago.com.ar/checkout/v1/…`.
|
||||
3. Abrir el link, pagar (puede fallar si el teste es con la cuenta real: probar el "sandbox de pago" del panel si existe) y esperar la reconciliación (hasta 15 min) o correr el job a mano.
|
||||
4. Un pago aprobado pasa a `PAID`; uno cuyo vencimiento pasó (con +24 h) pasa a `OVERDUE` y permite regenerar el link.
|
||||
|
||||
## WhatsApp (recordatorios y reenganche)
|
||||
|
||||
Una vez por semana (lunes 10:00, hora de Argentina) Gruperly le escribe por WhatsApp, **desde el número del profesor**, a los miembros de los grupos que tengan la automatización prendida:
|
||||
|
||||
- **Recordatorio de pago**: cobros `PENDING`/`OVERDUE` con link que vencen en los próximos 7 días o ya vencieron.
|
||||
- **Reenganche**: los mismos que muestra "Alumnos en riesgo", como mucho uno cada 14 días.
|
||||
|
||||
Las dos se prenden por grupo (ficha del grupo → "Mensajes automáticos por WhatsApp") y vienen apagadas. El profesor vincula su número en el onboarding (paso "WhatsApp", salteable) o en Ajustes → WhatsApp.
|
||||
|
||||
El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`):
|
||||
|
||||
- **`openwa`** (MVP, default): gateway self-hosted. El profesor lo vincula escaneando un QR o, desde el teléfono, con un código para su número; los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
|
||||
- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados.
|
||||
|
||||
El código vive en `apps/backend/src/modules/whatsapp/`.
|
||||
|
||||
| Variable | ¿Obligatoria? | Descripción |
|
||||
| --- | --- | --- |
|
||||
| `WHATSAPP_PROVIDER` | no | `openwa` (default) o `kapso` |
|
||||
| `OPENWA_API_URL`, `OPENWA_API_KEY` | con OpenWA | URL de la API de OpenWA y una key OPERATOR |
|
||||
| `OPENWA_WEBHOOK_URL`, `OPENWA_WEBHOOK_SECRET` | no | Confirmaciones de entrega y lectura. El secreto es obligatorio si hay URL |
|
||||
| `KAPSO_API_KEY`, `KAPSO_CALLBACK_URL`, `KAPSO_WEBHOOK_URL`, `KAPSO_WEBHOOK_SECRET` | con Kapso | Ver la guía |
|
||||
| `WHATSAPP_SEND_INTERVAL_MS` | no | Pausa entre envíos del mismo profesor. Default `5000` |
|
||||
|
||||
Si faltan las variables del proveedor activo, `/whatsapp/*` responde `503 whatsapp_not_configured` y la app sigue funcionando.
|
||||
|
||||
La guía completa está en **[docs/whatsapp.md](docs/whatsapp.md)**: arquitectura, deploy de OpenWA y primera API key, setup de Kapso y templates, riesgos, verificación a mano, troubleshooting y una guía para el profesor.
|
||||
|
||||
## Deploy en producción (Docker / Dokploy)
|
||||
|
||||
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
||||
|
||||
- `api` corre Bun sobre el TypeScript fuente (`bun src/server.ts`), igual que en local: el cliente de Prisma se genera como TS y el tsconfig resuelve los aliases `@/*`.
|
||||
- Al arrancar, `apps/backend/docker-entrypoint.sh` aplica `prisma migrate deploy` y recién después levanta el servidor. Si la migración falla, el contenedor no levanta y el error queda en los logs del servicio. Reintenta hasta 30 veces (5s) porque la base puede seguir arrancando.
|
||||
- `web` compila con Vite y lo sirve nginx, que además hace de proxy de `/api` hacia `api`. Así el navegador siempre pega al mismo origen: la cookie de sesión es first-party y el CORS del backend no se activa.
|
||||
- Ambos servicios se enchufan a `dokploy-network`, la red donde Dokploy deja las bases de datos que administra. Dokploy solo agrega esa red al servicio al que le asociás el dominio, así que está declarada a mano en el compose: sin ella, `api` no alcanza a la base y Prisma falla con `P1001 Can't reach database server`.
|
||||
|
||||
### Variables de entorno
|
||||
|
||||
El compose las interpola desde el entorno. En Dokploy van en la pestaña **Environment** del servicio Compose (Dokploy las guarda en un `.env` al lado del `docker-compose.yml`); en local, copiá `.env.example` → `.env` en la raíz.
|
||||
|
||||
| Variable | ¿Obligatoria? | Descripción |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | sí | `postgresql://user:pass@host:5432/gruperly?schema=public`. La password va percent-encoded: `#` → `%23`, `@` → `%40`, `:` → `%3A`, `/` → `%2F`, `?` → `%3F`, `%` → `%25`, espacio → `%20`. Sin eso, Prisma corta la URL en el fragmento y falla con `P1013 invalid port number` |
|
||||
| `WEB_URL` | sí | Origen público de la app, sin barra final (`https://gruperly.com`). Alimenta `WEB_URL` y `BETTER_AUTH_URL` del contenedor, porque el proxy de nginx deja web y API en el mismo dominio |
|
||||
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider |
|
||||
| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) |
|
||||
| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) |
|
||||
| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo |
|
||||
| `WHATSAPP_PROVIDER`, `OPENWA_*`, `KAPSO_*`, `WHATSAPP_SEND_INTERVAL_MS` | no | Mensajes automáticos por WhatsApp (ver [WhatsApp](#whatsapp-recordatorios-y-reenganche)). OpenWA no está en el compose: se instala aparte y la API le habla por `OPENWA_API_URL` |
|
||||
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
|
||||
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||
|
||||
Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre de la variable en el mensaje.
|
||||
|
||||
### Pasos en Dokploy
|
||||
|
||||
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
||||
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
||||
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor** (nginx escucha `80` adentro). El compose no publica puertos en el host: Traefik llega por `dokploy-network`.
|
||||
4. Deploy.
|
||||
|
||||
Se pueden tener varias apps Compose de este repo en el mismo server (p. ej. dev y prod): como no se publican puertos en el host no chocan, y nginx le pega a su propia API por el alias `gruperly-api`, que solo existe en la red de cada stack. Cada app necesita su dominio, su `WEB_URL`, su `DATABASE_URL` (otra base) y su `BETTER_AUTH_SECRET`.
|
||||
|
||||
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 -f docker-compose.yml -f docker-compose.local.yml up --build -d # publica web en :8080
|
||||
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
||||
curl http://localhost:8080/api/v1/health
|
||||
```
|
||||
|
||||
@@ -19,3 +19,83 @@ EMAIL_SERVER_PORT="587"
|
||||
EMAIL_SERVER_USER=""
|
||||
EMAIL_SERVER_PASSWORD=""
|
||||
EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# Mercado Pago (OAuth, Authorization Code + PKCE)
|
||||
MP_CLIENT_ID=""
|
||||
MP_CLIENT_SECRET=""
|
||||
# Debe coincidir exactamente con la "Redirect URL" de la app en el panel de MP.
|
||||
# El panel exige HTTPS (rechaza http://localhost): en local usá un túnel
|
||||
# (p. ej. ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000) y cargá
|
||||
# la URL del túnel acá y en el panel.
|
||||
MP_REDIRECT_URI=""
|
||||
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
|
||||
# Generar con: openssl rand -base64 32
|
||||
TOKEN_ENCRYPTION_KEY=""
|
||||
|
||||
# Suscripción a Gruperly Pro (ver docs/billing.md). Argentina la cobra con
|
||||
# Suscripciones de Mercado Pago; el resto de los países, con Stripe.
|
||||
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina (no
|
||||
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
|
||||
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||
# Origen público de esta API, adonde MP y Stripe devuelven el navegador después
|
||||
# del checkout de Pro (GET /api/v1/billing/return, que redirige a la web). MP
|
||||
# rechaza localhost: en local poné el túnel (https://TU-DOMINIO.ngrok-free.app).
|
||||
# Vacío = BETTER_AUTH_URL.
|
||||
API_PUBLIC_URL=""
|
||||
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
|
||||
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
|
||||
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
|
||||
STRIPE_SECRET_KEY=""
|
||||
STRIPE_WEBHOOK_SECRET=""
|
||||
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||
BILLING_ENFORCEMENT="off"
|
||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||
BILLING_GRACE_DAYS="7"
|
||||
|
||||
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
|
||||
ADMIN_EMAILS=""
|
||||
|
||||
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
|
||||
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
|
||||
WHATSAPP_PROVIDER="openwa"
|
||||
# Pausa entre dos envíos del mismo profesor, en ms (OpenWA recomienda < 15 msg/min).
|
||||
WHATSAPP_SEND_INTERVAL_MS="5000"
|
||||
|
||||
# OpenWA (se instala aparte). En local: docker run, ver docs/whatsapp.md.
|
||||
OPENWA_API_URL="http://localhost:2785/api"
|
||||
# Key OPERATOR sin allowedSessions, creada con la key ADMIN de /app/data/.api-key.
|
||||
OPENWA_API_KEY=""
|
||||
# Opcional. Sin webhook la vinculación funciona (el status hace polling), pero no
|
||||
# llegan las confirmaciones de entrega/lectura. Si lo cargás, el secreto es obligatorio.
|
||||
OPENWA_WEBHOOK_URL=""
|
||||
# 16+ caracteres. Generar con: openssl rand -hex 24
|
||||
OPENWA_WEBHOOK_SECRET=""
|
||||
|
||||
# Kapso (WHATSAPP_PROVIDER="kapso"). Las URLs tienen que ser públicas (túnel en local).
|
||||
KAPSO_API_KEY=""
|
||||
KAPSO_CALLBACK_URL=""
|
||||
KAPSO_WEBHOOK_URL=""
|
||||
# El mismo secreto del project webhook configurado en el dashboard de Kapso.
|
||||
KAPSO_WEBHOOK_SECRET=""
|
||||
# KAPSO_API_URL="https://api.kapso.ai"
|
||||
|
||||
# App de alumnos (acceso sin contraseña por link de un solo uso; ver AGENTS.md).
|
||||
# Comprobantes de pago: storage privado compatible con S3 (RustFS, MinIO, R2, AWS).
|
||||
# Sin estas cuatro variables, "Informar pago" responde 503 storage_not_available.
|
||||
S3_ENDPOINT="http://localhost:9000"
|
||||
S3_BUCKET="gruperly-receipts"
|
||||
S3_ACCESS_KEY_ID=""
|
||||
S3_SECRET_ACCESS_KEY=""
|
||||
S3_REGION="us-east-1"
|
||||
# on = URLs estilo AWS (bucket.endpoint). RustFS/MinIO usan path-style: dejalo vacío.
|
||||
S3_VIRTUAL_HOSTED=""
|
||||
# Días que se guarda un comprobante después de que el profe lo revisó. 0 = para siempre.
|
||||
RECEIPT_RETENTION_DAYS="0"
|
||||
# WebAuthn (Face ID / huella del alumno). Por defecto salen de WEB_URL; cambialos
|
||||
# solo si la web se sirve desde otro origen (p. ej. un túnel para probar en el teléfono).
|
||||
# WEBAUTHN_RP_ID="localhost"
|
||||
# WEBAUTHN_ORIGIN="http://localhost:6173"
|
||||
# Proxies delante de la API que agregan X-Forwarded-For (1 = solo nginx; 2 = Traefik + nginx).
|
||||
# Define qué IP cuenta para el rate limit de "Pedir un link a mi mail".
|
||||
TRUSTED_PROXY_HOPS="1"
|
||||
|
||||
42
apps/backend/docker-entrypoint.sh
Executable file
42
apps/backend/docker-entrypoint.sh
Executable file
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Production entrypoint for the backend: applies the migrations and starts the
|
||||
# server in the same container.
|
||||
#
|
||||
# This is POSIX sh, not bash: the image is alpine and does not ship bash
|
||||
# installed (adding it would be ~10MB for a shebang).
|
||||
#
|
||||
# Set RUN_MIGRATIONS=false to start without touching the database (for example,
|
||||
# a database already migrated by hand, or one managed outside this deployment).
|
||||
set -e
|
||||
|
||||
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||
|
||||
if [ "${RUN_MIGRATIONS:-true}" = "false" ]; then
|
||||
echo "migrate: omitido (RUN_MIGRATIONS=false)"
|
||||
else
|
||||
attempts="${MIGRATE_ATTEMPTS:-30}"
|
||||
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||
i=1
|
||||
|
||||
# The database may still be starting up when this container is already
|
||||
# running, and a deploy usually overlaps a Postgres restart.
|
||||
while [ "$i" -le "$attempts" ]; do
|
||||
if bun run db:deploy; then
|
||||
echo "migrate: listo"
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$i" -eq "$attempts" ]; then
|
||||
echo "migrate: fallo tras $attempts intentos; no se levanta el servidor" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "migrate: intento $i/$attempts fallo; reintento en ${delay}s" >&2
|
||||
i=$((i + 1))
|
||||
sleep "$delay"
|
||||
done
|
||||
fi
|
||||
|
||||
# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
|
||||
# (the server uses it to close Bun.serve and disconnect Prisma).
|
||||
exec "$@"
|
||||
@@ -9,11 +9,13 @@
|
||||
"build": "prisma generate && tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test",
|
||||
"test:db": "DB_TESTS=1 bun test test/db",
|
||||
"test:watch": "bun test --watch",
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check . --write",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:deploy": "prisma migrate deploy",
|
||||
"db:push": "prisma db push",
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
@@ -22,11 +24,15 @@
|
||||
"@gruperly/shared": "workspace:*",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"@simplewebauthn/server": "13.3.3",
|
||||
"better-auth": "1.7.2",
|
||||
"dotenv": "^16.4.5",
|
||||
"hono": "^4.13.3",
|
||||
"nanoid": "^3.3.19",
|
||||
"nodemailer": "^9.0.6",
|
||||
"pino": "^9.5.0",
|
||||
"pino-pretty": "^13.0.0",
|
||||
"prisma": "^7.10.0",
|
||||
"zod": "3.24.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -35,8 +41,6 @@
|
||||
"@types/bun": "^1.4.0",
|
||||
"@types/node": "^20.17.0",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"dotenv": "^16.4.5",
|
||||
"prisma": "^7.10.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "group_pre_registrations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"groupId" TEXT NOT NULL,
|
||||
"fullName" TEXT NOT NULL,
|
||||
"phone" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,128 @@
|
||||
-- Rename camelCase columns to snake_case without recreating them or losing data.
|
||||
|
||||
-- accounts
|
||||
ALTER TABLE "accounts" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "providerId" TO "provider_id";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "accountId" TO "account_id";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "accessToken" TO "access_token";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "refreshToken" TO "refresh_token";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "idToken" TO "id_token";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "accessTokenExpiresAt" TO "access_token_expires_at";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "refreshTokenExpiresAt" TO "refresh_token_expires_at";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- attendances
|
||||
ALTER TABLE "attendances" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||
ALTER TABLE "attendances" RENAME COLUMN "classSessionId" TO "class_session_id";
|
||||
ALTER TABLE "attendances" RENAME COLUMN "markedAt" TO "marked_at";
|
||||
|
||||
-- attendees
|
||||
ALTER TABLE "attendees" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "fullName" TO "full_name";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "guardianName" TO "guardian_name";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "guardianPhone" TO "guardian_phone";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "notifyToken" TO "notify_token";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- class_sessions
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "startsAt" TO "starts_at";
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- group_members
|
||||
ALTER TABLE "group_members" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "group_members" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "group_members" RENAME COLUMN "joinedAt" TO "joined_at";
|
||||
|
||||
-- group_pre_registrations
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "fullName" TO "full_name";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "reviewedAt" TO "reviewed_at";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- group_waitlist_entries
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "fullName" TO "full_name";
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- groups
|
||||
ALTER TABLE "groups" RENAME COLUMN "billingType" TO "billing_type";
|
||||
ALTER TABLE "groups" RENAME COLUMN "dueDay" TO "due_day";
|
||||
ALTER TABLE "groups" RENAME COLUMN "inviteToken" TO "invite_token";
|
||||
ALTER TABLE "groups" RENAME COLUMN "createdById" TO "created_by_id";
|
||||
ALTER TABLE "groups" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "groups" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- invitations
|
||||
ALTER TABLE "invitations" RENAME COLUMN "organizationId" TO "organization_id";
|
||||
ALTER TABLE "invitations" RENAME COLUMN "inviterId" TO "inviter_id";
|
||||
ALTER TABLE "invitations" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||
ALTER TABLE "invitations" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- members
|
||||
ALTER TABLE "members" RENAME COLUMN "organizationId" TO "organization_id";
|
||||
ALTER TABLE "members" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "members" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- merchant_accounts
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "accessToken" TO "access_token";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "connectedAt" TO "connected_at";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- organizations
|
||||
ALTER TABLE "organizations" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "organizations" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- passkeys
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "publicKey" TO "public_key";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "credentialID" TO "credential_id";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "deviceType" TO "device_type";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "backedUp" TO "backed_up";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- payments
|
||||
ALTER TABLE "payments" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "payments" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||
ALTER TABLE "payments" RENAME COLUMN "dueDate" TO "due_date";
|
||||
ALTER TABLE "payments" RENAME COLUMN "paidAt" TO "paid_at";
|
||||
ALTER TABLE "payments" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "payments" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- sessions
|
||||
ALTER TABLE "sessions" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "ipAddress" TO "ip_address";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "userAgent" TO "user_agent";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "activeOrganizationId" TO "active_organization_id";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- slot_releases
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "classSessionId" TO "class_session_id";
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "isClaimed" TO "is_claimed";
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- users
|
||||
ALTER TABLE "users" RENAME COLUMN "emailVerified" TO "email_verified";
|
||||
ALTER TABLE "users" RENAME COLUMN "onboardingCompleted" TO "onboarding_completed";
|
||||
ALTER TABLE "users" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "users" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- verifications
|
||||
ALTER TABLE "verifications" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||
ALTER TABLE "verifications" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "verifications" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- waitlist_entries
|
||||
ALTER TABLE "waitlist_entries" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "waitlist_entries" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Mercado Pago OAuth (Authorization Code + PKCE). Replaces the simulated
|
||||
-- payment setup, where a fake access token was stored in plaintext.
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MpAccountStatus" AS ENUM ('ACTIVE', 'REQUIRES_REAUTH', 'REVOKED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mp_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"mp_user_id" TEXT NOT NULL,
|
||||
"access_token_enc" TEXT NOT NULL,
|
||||
"refresh_token_enc" TEXT NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"scope" TEXT,
|
||||
"live_mode" BOOLEAN NOT NULL DEFAULT false,
|
||||
"status" "MpAccountStatus" NOT NULL DEFAULT 'ACTIVE',
|
||||
"connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "mp_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mp_oauth_states" (
|
||||
"state" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"code_verifier" TEXT NOT NULL,
|
||||
"return_to" TEXT NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "mp_oauth_states_pkey" PRIMARY KEY ("state")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "mp_accounts_status_expiresAt_idx" ON "mp_accounts"("status", "expires_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "mp_accounts_ownerId_key" ON "mp_accounts"("owner_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "mp_accounts_mpUserId_key" ON "mp_accounts"("mp_user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "mp_oauth_states_expiresAt_idx" ON "mp_oauth_states"("expires_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mp_accounts" ADD CONSTRAINT "mp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "merchant_accounts";
|
||||
|
||||
-- DropEnum
|
||||
DROP TYPE "PaymentProvider";
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Country of the professor (onboarding) + Mercado Pago Checkout Pro payment links.
|
||||
|
||||
-- AlterTable (users)
|
||||
ALTER TABLE "users" ADD COLUMN "country_code" TEXT;
|
||||
|
||||
-- AlterTable (payments)
|
||||
ALTER TABLE "payments" ADD COLUMN "description" TEXT;
|
||||
ALTER TABLE "payments" ADD COLUMN "checkout_url" TEXT;
|
||||
ALTER TABLE "payments" ADD COLUMN "mp_preference_id" TEXT;
|
||||
ALTER TABLE "payments" ADD COLUMN "mp_payment_id" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "payments_mp_preference_id_key" ON "payments"("mp_preference_id");
|
||||
@@ -0,0 +1,129 @@
|
||||
-- WhatsApp messaging: linked accounts (provider-agnostic), Kapso templates,
|
||||
-- outbound message log and webhook dedupe; plus the per-group automation switches.
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MessagingProviderId" AS ENUM ('OPENWA', 'KAPSO');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WhatsappAccountStatus" AS ENUM ('PENDING', 'ACTIVE', 'DISCONNECTED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WhatsappMessageKind" AS ENUM ('PAYMENT_REMINDER', 'REENGAGEMENT');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "OutboundMessageStatus" AS ENUM ('QUEUED', 'SENT', 'DELIVERED', 'READ', 'FAILED', 'SKIPPED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WhatsappTemplateStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'DISABLED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "groups" ADD COLUMN "auto_payment_reminders" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "auto_reengagement" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- AlterTable (pre-existing drift: the schema already declares this default)
|
||||
ALTER TABLE "payments" ALTER COLUMN "currency" SET DEFAULT 'ARS';
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "whatsapp_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"provider" "MessagingProviderId" NOT NULL,
|
||||
"status" "WhatsappAccountStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"external_id" TEXT,
|
||||
"display_phone_number" TEXT,
|
||||
"provider_data" JSONB,
|
||||
"connected_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "whatsapp_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "whatsapp_templates" (
|
||||
"id" TEXT NOT NULL,
|
||||
"account_id" TEXT NOT NULL,
|
||||
"kind" "WhatsappMessageKind" NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"language" TEXT NOT NULL,
|
||||
"meta_template_id" TEXT,
|
||||
"status" "WhatsappTemplateStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"rejected_reason" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "whatsapp_templates_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "outbound_messages" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"group_id" TEXT NOT NULL,
|
||||
"attendee_id" TEXT NOT NULL,
|
||||
"payment_id" TEXT,
|
||||
"kind" "WhatsappMessageKind" NOT NULL,
|
||||
"provider" "MessagingProviderId" NOT NULL,
|
||||
"period_key" TEXT NOT NULL,
|
||||
"to_phone" TEXT NOT NULL,
|
||||
"provider_message_id" TEXT,
|
||||
"status" "OutboundMessageStatus" NOT NULL DEFAULT 'QUEUED',
|
||||
"error_code" TEXT,
|
||||
"error_message" TEXT,
|
||||
"sent_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "outbound_messages_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "whatsapp_webhook_events" (
|
||||
"provider" "MessagingProviderId" NOT NULL,
|
||||
"dedupe_key" TEXT NOT NULL,
|
||||
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "whatsapp_webhook_events_pkey" PRIMARY KEY ("provider","dedupe_key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "whatsapp_accounts_ownerId_key" ON "whatsapp_accounts"("owner_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "whatsapp_accounts_provider_externalId_key" ON "whatsapp_accounts"("provider", "external_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "whatsapp_templates_status_idx" ON "whatsapp_templates"("status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "whatsapp_templates_accountId_kind_key" ON "whatsapp_templates"("account_id", "kind");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "outbound_messages_attendeeId_kind_createdAt_idx" ON "outbound_messages"("attendee_id", "kind", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "outbound_messages_groupId_createdAt_idx" ON "outbound_messages"("group_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "outbound_messages_kind_attendeeId_periodKey_key" ON "outbound_messages"("kind", "attendee_id", "period_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "outbound_messages_provider_providerMessageId_key" ON "outbound_messages"("provider", "provider_message_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "whatsapp_webhook_events_receivedAt_idx" ON "whatsapp_webhook_events"("received_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "whatsapp_accounts" ADD CONSTRAINT "whatsapp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "whatsapp_templates" ADD CONSTRAINT "whatsapp_templates_accountId_fkey" FOREIGN KEY ("account_id") REFERENCES "whatsapp_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_groupId_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_attendeeId_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_paymentId_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,74 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SubscriptionStatus" AS ENUM ('PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "plan_selected_at" TIMESTAMP(3);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "billing_subscriptions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"user_id" TEXT NOT NULL,
|
||||
"country_code" TEXT NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"amount" DECIMAL(12,2) NOT NULL,
|
||||
"payer_email" TEXT NOT NULL,
|
||||
"mp_preapproval_id" TEXT,
|
||||
"status" "SubscriptionStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"authorized_at" TIMESTAMP(3),
|
||||
"next_payment_date" TIMESTAMP(3),
|
||||
"paid_through" TIMESTAMP(3),
|
||||
"last_synced_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "billing_subscriptions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "billing_charges" (
|
||||
"id" TEXT NOT NULL,
|
||||
"subscription_id" TEXT NOT NULL,
|
||||
"mp_authorized_payment_id" TEXT NOT NULL,
|
||||
"amount" DECIMAL(12,2) NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL,
|
||||
"paid_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "billing_charges_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "billing_webhook_events" (
|
||||
"country_code" TEXT NOT NULL,
|
||||
"dedupe_key" TEXT NOT NULL,
|
||||
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "billing_webhook_events_pkey" PRIMARY KEY ("country_code","dedupe_key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "billing_subscriptions_userId_key" ON "billing_subscriptions"("user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "billing_subscriptions_mpPreapprovalId_key" ON "billing_subscriptions"("mp_preapproval_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_subscriptions_status_lastSyncedAt_idx" ON "billing_subscriptions"("status", "last_synced_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "billing_charges_mpAuthorizedPaymentId_key" ON "billing_charges"("mp_authorized_payment_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_charges_subscriptionId_createdAt_idx" ON "billing_charges"("subscription_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_webhook_events_receivedAt_idx" ON "billing_webhook_events"("received_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "billing_subscriptions" ADD CONSTRAINT "billing_subscriptions_userId_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "billing_charges" ADD CONSTRAINT "billing_charges_subscriptionId_fkey" FOREIGN KEY ("subscription_id") REFERENCES "billing_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Pro billing behind a provider port: Mercado Pago (AR) or Stripe (the rest).
|
||||
-- Columns are renamed, not dropped, so existing Mercado Pago rows keep their ids.
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "BillingProviderId" AS ENUM ('MERCADO_PAGO', 'STRIPE');
|
||||
|
||||
-- billing_subscriptions: provider + provider-neutral ids
|
||||
ALTER TABLE "billing_subscriptions" ADD COLUMN "provider" "BillingProviderId" NOT NULL DEFAULT 'MERCADO_PAGO';
|
||||
ALTER TABLE "billing_subscriptions" ADD COLUMN "checkout_ref" TEXT;
|
||||
ALTER TABLE "billing_subscriptions" RENAME COLUMN "mp_preapproval_id" TO "external_id";
|
||||
ALTER INDEX "billing_subscriptions_mpPreapprovalId_key" RENAME TO "billing_subscriptions_externalId_key";
|
||||
CREATE UNIQUE INDEX "billing_subscriptions_checkoutRef_key" ON "billing_subscriptions"("checkout_ref");
|
||||
|
||||
-- billing_charges: provider-neutral id and normalized status
|
||||
ALTER TABLE "billing_charges" RENAME COLUMN "mp_authorized_payment_id" TO "external_id";
|
||||
ALTER INDEX "billing_charges_mpAuthorizedPaymentId_key" RENAME TO "billing_charges_externalId_key";
|
||||
UPDATE "billing_charges"
|
||||
SET "status" = CASE
|
||||
WHEN "status" = 'approved' THEN 'approved'
|
||||
WHEN "status" IN ('rejected', 'cancelled', 'refunded', 'charged_back') THEN 'rejected'
|
||||
ELSE 'pending'
|
||||
END;
|
||||
|
||||
-- billing_webhook_events: dedupe per sending account (`mp:<CC>` or `stripe`)
|
||||
ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
|
||||
UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";
|
||||
@@ -0,0 +1,20 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "attendee_alert_resolutions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"attendee_id" TEXT NOT NULL,
|
||||
"kind" "StudentAlertKind" NOT NULL,
|
||||
"signature" TEXT NOT NULL,
|
||||
"resolved_by_id" TEXT NOT NULL,
|
||||
"resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,248 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StudentTokenKind" AS ENUM ('INVITATION', 'RECOVERY', 'EMAIL_CONFIRMATION');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WebauthnChallengePurpose" AS ENUM ('REGISTER', 'LOGIN');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AbsenceReason" AS ENUM ('HEALTH', 'TRAVEL', 'WORK_STUDY', 'OTHER');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ReportedPaymentStatus" AS ENUM ('REPORTED', 'CONFIRMED', 'REJECTED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "transfer_alias" TEXT,
|
||||
ADD COLUMN "transfer_holder" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"recovery_email" TEXT,
|
||||
"recovery_email_verified_at" TIMESTAMP(3),
|
||||
"pending_recovery_email" TEXT,
|
||||
"welcomed_at" TIMESTAMP(3),
|
||||
"created_by_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "student_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_account_attendees" (
|
||||
"account_id" TEXT NOT NULL,
|
||||
"attendee_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "student_account_attendees_pkey" PRIMARY KEY ("account_id","attendee_id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_access_tokens" (
|
||||
"id" TEXT NOT NULL,
|
||||
"token_hash" TEXT NOT NULL,
|
||||
"account_id" TEXT NOT NULL,
|
||||
"kind" "StudentTokenKind" NOT NULL,
|
||||
"email" TEXT,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"used_at" TIMESTAMP(3),
|
||||
"revoked_at" TIMESTAMP(3),
|
||||
"created_by_id" TEXT,
|
||||
"used_ip" TEXT,
|
||||
"used_user_agent" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "student_access_tokens_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_sessions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"account_id" TEXT NOT NULL,
|
||||
"token_hash" TEXT NOT NULL,
|
||||
"device" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"last_used_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"revoked_at" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "student_sessions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_passkeys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"account_id" TEXT NOT NULL,
|
||||
"credential_id" TEXT NOT NULL,
|
||||
"public_key" BYTEA NOT NULL,
|
||||
"counter" INTEGER NOT NULL DEFAULT 0,
|
||||
"transports" TEXT[],
|
||||
"device" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"last_used_at" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "student_passkeys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_webauthn_challenges" (
|
||||
"id" TEXT NOT NULL,
|
||||
"challenge" TEXT NOT NULL,
|
||||
"account_id" TEXT,
|
||||
"purpose" "WebauthnChallengePurpose" NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "student_webauthn_challenges_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "rate_limit_events" (
|
||||
"id" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "rate_limit_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "absence_notices" (
|
||||
"id" TEXT NOT NULL,
|
||||
"attendee_id" TEXT NOT NULL,
|
||||
"class_session_id" TEXT NOT NULL,
|
||||
"account_id" TEXT,
|
||||
"reason" "AbsenceReason",
|
||||
"message" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"cancelled_at" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "absence_notices_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "reported_payments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"attendee_id" TEXT NOT NULL,
|
||||
"group_id" TEXT NOT NULL,
|
||||
"account_id" TEXT,
|
||||
"total_amount" DECIMAL(10,2) NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"receipt_key" TEXT,
|
||||
"receipt_mime" TEXT NOT NULL,
|
||||
"receipt_name" TEXT NOT NULL,
|
||||
"receipt_size" INTEGER NOT NULL,
|
||||
"status" "ReportedPaymentStatus" NOT NULL DEFAULT 'REPORTED',
|
||||
"reviewed_by_id" TEXT,
|
||||
"reviewed_at" TIMESTAMP(3),
|
||||
"rejection_reason" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "reported_payments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "reported_payment_items" (
|
||||
"reported_payment_id" TEXT NOT NULL,
|
||||
"payment_id" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "reported_payment_items_pkey" PRIMARY KEY ("reported_payment_id","payment_id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_accounts_recovery_email_idx" ON "student_accounts"("recovery_email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_accounts_created_by_id_idx" ON "student_accounts"("created_by_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_account_attendees_attendee_id_idx" ON "student_account_attendees"("attendee_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "student_access_tokens_token_hash_key" ON "student_access_tokens"("token_hash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_access_tokens_account_id_kind_idx" ON "student_access_tokens"("account_id", "kind");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "student_sessions_token_hash_key" ON "student_sessions"("token_hash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_sessions_account_id_idx" ON "student_sessions"("account_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "student_passkeys_credential_id_key" ON "student_passkeys"("credential_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_passkeys_account_id_idx" ON "student_passkeys"("account_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_webauthn_challenges_expires_at_idx" ON "student_webauthn_challenges"("expires_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "rate_limit_events_key_created_at_idx" ON "rate_limit_events"("key", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "absence_notices_attendee_id_class_session_id_idx" ON "absence_notices"("attendee_id", "class_session_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "absence_notices_class_session_id_idx" ON "absence_notices"("class_session_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "reported_payments_group_id_status_idx" ON "reported_payments"("group_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "reported_payments_attendee_id_idx" ON "reported_payments"("attendee_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "reported_payment_items_payment_id_idx" ON "reported_payment_items"("payment_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_accounts" ADD CONSTRAINT "student_accounts_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_access_tokens" ADD CONSTRAINT "student_access_tokens_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_sessions" ADD CONSTRAINT "student_sessions_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_passkeys" ADD CONSTRAINT "student_passkeys_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_webauthn_challenges" ADD CONSTRAINT "student_webauthn_challenges_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_class_session_id_fkey" FOREIGN KEY ("class_session_id") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_reported_payment_id_fkey" FOREIGN KEY ("reported_payment_id") REFERENCES "reported_payments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_payment_id_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- At most one active (not cancelled) absence notice per attendee and class.
|
||||
-- Partial index: Prisma can't express it in the schema.
|
||||
CREATE UNIQUE INDEX "absence_notices_active_attendee_class_key" ON "absence_notices"("attendee_id", "class_session_id") WHERE "cancelled_at" IS NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT;
|
||||
@@ -0,0 +1,182 @@
|
||||
-- A person (contact data, per teacher) can now be in several groups: `attendees`
|
||||
-- becomes the membership and points to `people`. Existing attendees of the same
|
||||
-- teacher with the same phone (digits only) are merged into one person, and
|
||||
-- their student-app accounts into one account.
|
||||
|
||||
-- All or nothing: a half-applied data migration cannot be retried.
|
||||
BEGIN;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "people" (
|
||||
"id" TEXT NOT NULL,
|
||||
"created_by_id" TEXT NOT NULL,
|
||||
"full_name" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"phone" TEXT,
|
||||
"guardian_name" TEXT,
|
||||
"guardian_phone" TEXT,
|
||||
"notes" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "people_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_account_people" (
|
||||
"account_id" TEXT NOT NULL,
|
||||
"person_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "student_account_people_pkey" PRIMARY KEY ("account_id","person_id")
|
||||
);
|
||||
|
||||
-- Grouping: same teacher + same phone digits. `group_rank` splits the (rare)
|
||||
-- rows that already shared a phone inside one group, which the per-group unique
|
||||
-- membership would reject: the extra ones become their own person.
|
||||
CREATE TEMP TABLE "_attendee_keys" AS
|
||||
SELECT
|
||||
a."id" AS attendee_id,
|
||||
a."group_id",
|
||||
a."created_at",
|
||||
g."created_by_id",
|
||||
NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') AS phone_digits,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY g."created_by_id", a."group_id", NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '')
|
||||
ORDER BY a."created_at", a."id"
|
||||
) AS group_rank
|
||||
FROM "attendees" a
|
||||
JOIN "groups" g ON g."id" = a."group_id";
|
||||
|
||||
CREATE TEMP TABLE "_attendee_person" AS
|
||||
SELECT
|
||||
k.attendee_id,
|
||||
k.created_by_id,
|
||||
-- The person reuses the id of its oldest attendee.
|
||||
FIRST_VALUE(k.attendee_id) OVER (
|
||||
PARTITION BY k.created_by_id,
|
||||
CASE WHEN k.phone_digits IS NULL THEN k.attendee_id ELSE k.phone_digits || '#' || k.group_rank END
|
||||
ORDER BY k.created_at, k.attendee_id
|
||||
) AS person_id,
|
||||
(k.phone_digits IS NOT NULL AND k.group_rank > 1) AS phone_clash
|
||||
FROM "_attendee_keys" k;
|
||||
|
||||
INSERT INTO "people" ("id", "created_by_id", "full_name", "email", "phone", "guardian_name", "guardian_phone", "notes", "created_at", "updated_at")
|
||||
SELECT
|
||||
p.person_id,
|
||||
MIN(p.created_by_id),
|
||||
MIN(rep."full_name"),
|
||||
(ARRAY_AGG(a."email" ORDER BY a."created_at") FILTER (WHERE a."email" IS NOT NULL))[1],
|
||||
CASE WHEN BOOL_OR(p.phone_clash) THEN NULL ELSE NULLIF(TRIM(MIN(rep."phone")), '') END,
|
||||
(ARRAY_AGG(a."guardian_name" ORDER BY a."created_at") FILTER (WHERE a."guardian_name" IS NOT NULL))[1],
|
||||
(ARRAY_AGG(a."guardian_phone" ORDER BY a."created_at") FILTER (WHERE a."guardian_phone" IS NOT NULL))[1],
|
||||
NULLIF(CONCAT_WS(E'\n\n',
|
||||
STRING_AGG(DISTINCT NULLIF(TRIM(a."notes"), ''), E'\n\n'),
|
||||
CASE WHEN BOOL_OR(p.phone_clash) THEN 'Teléfono: ' || MIN(rep."phone") END
|
||||
), ''),
|
||||
MIN(a."created_at"),
|
||||
CURRENT_TIMESTAMP
|
||||
FROM "_attendee_person" p
|
||||
JOIN "attendees" a ON a."id" = p.attendee_id
|
||||
JOIN "attendees" rep ON rep."id" = p.person_id
|
||||
GROUP BY p.person_id;
|
||||
|
||||
-- AlterTable: attendees -> membership
|
||||
ALTER TABLE "attendees" ADD COLUMN "person_id" TEXT;
|
||||
UPDATE "attendees" a SET "person_id" = p.person_id FROM "_attendee_person" p WHERE p.attendee_id = a."id";
|
||||
ALTER TABLE "attendees" ALTER COLUMN "person_id" SET NOT NULL;
|
||||
|
||||
-- Student accounts: link them to the person instead of the membership.
|
||||
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
|
||||
SELECT sa."account_id", p.person_id, MIN(sa."created_at")
|
||||
FROM "student_account_attendees" sa
|
||||
JOIN "_attendee_person" p ON p.attendee_id = sa."attendee_id"
|
||||
GROUP BY sa."account_id", p.person_id;
|
||||
|
||||
-- A merged person may end up with several accounts: keep the one used most
|
||||
-- recently (else the oldest) and fold the others into it.
|
||||
CREATE TEMP TABLE "_account_merge" AS
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
sap."person_id",
|
||||
sap."account_id",
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY sap."person_id"
|
||||
ORDER BY (
|
||||
SELECT MAX(s."last_used_at") FROM "student_sessions" s
|
||||
WHERE s."account_id" = sap."account_id" AND s."revoked_at" IS NULL
|
||||
) DESC NULLS LAST, acc."created_at", acc."id"
|
||||
) AS rn
|
||||
FROM "student_account_people" sap
|
||||
JOIN "student_accounts" acc ON acc."id" = sap."account_id"
|
||||
)
|
||||
SELECT DISTINCT ON (d."account_id") d."account_id" AS old_id, k."account_id" AS keep_id
|
||||
FROM ranked d
|
||||
JOIN ranked k ON k."person_id" = d."person_id" AND k.rn = 1
|
||||
WHERE d.rn > 1 AND d."account_id" <> k."account_id"
|
||||
ORDER BY d."account_id";
|
||||
|
||||
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
|
||||
SELECT m.keep_id, sap."person_id", sap."created_at"
|
||||
FROM "student_account_people" sap
|
||||
JOIN "_account_merge" m ON m.old_id = sap."account_id"
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
UPDATE "absence_notices" n SET "account_id" = m.keep_id FROM "_account_merge" m WHERE n."account_id" = m.old_id;
|
||||
UPDATE "reported_payments" r SET "account_id" = m.keep_id FROM "_account_merge" m WHERE r."account_id" = m.old_id;
|
||||
|
||||
UPDATE "student_accounts" k
|
||||
SET "recovery_email" = o."recovery_email", "recovery_email_verified_at" = o."recovery_email_verified_at"
|
||||
FROM "_account_merge" m
|
||||
JOIN "student_accounts" o ON o."id" = m.old_id
|
||||
WHERE k."id" = m.keep_id AND k."recovery_email" IS NULL AND o."recovery_email" IS NOT NULL;
|
||||
|
||||
-- Sessions, tokens and passkeys of the folded accounts go with them (cascade);
|
||||
-- their links are removed by hand because that FK is created further down.
|
||||
DELETE FROM "student_account_people" WHERE "account_id" IN (SELECT old_id FROM "_account_merge");
|
||||
DELETE FROM "student_accounts" WHERE "id" IN (SELECT old_id FROM "_account_merge");
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "student_account_attendees";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "attendees"
|
||||
DROP COLUMN "full_name",
|
||||
DROP COLUMN "email",
|
||||
DROP COLUMN "phone",
|
||||
DROP COLUMN "guardian_name",
|
||||
DROP COLUMN "guardian_phone",
|
||||
DROP COLUMN "notes";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "people_created_by_id_idx" ON "people"("created_by_id");
|
||||
|
||||
-- One person per phone and teacher. Partial: Prisma does not model it.
|
||||
CREATE UNIQUE INDEX "people_owner_phone_key" ON "people"("created_by_id", "phone") WHERE "phone" IS NOT NULL;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_account_people_person_id_idx" ON "student_account_people"("person_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "attendees_person_id_idx" ON "attendees"("person_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "attendees_group_id_person_id_key" ON "attendees"("group_id", "person_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "people" ADD CONSTRAINT "people_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "attendees" ADD CONSTRAINT "attendees_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
DROP TABLE "_account_merge";
|
||||
DROP TABLE "_attendee_person";
|
||||
DROP TABLE "_attendee_keys";
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN "locale" TEXT;
|
||||
@@ -0,0 +1,67 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PlanId" AS ENUM ('FREE', 'PRO');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "billing_subscriptions" ADD COLUMN "pending_amount" DECIMAL(12,2),
|
||||
ADD COLUMN "price_change_attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "price_change_error" TEXT,
|
||||
ADD COLUMN "price_change_id" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "plan_configs" (
|
||||
"plan" "PlanId" NOT NULL,
|
||||
"max_groups" INTEGER,
|
||||
"max_attendees" INTEGER,
|
||||
"whatsapp_automations" BOOLEAN NOT NULL,
|
||||
"mp_charges" BOOLEAN NOT NULL,
|
||||
"updated_by_id" TEXT,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "plan_configs_pkey" PRIMARY KEY ("plan")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "plan_prices" (
|
||||
"country_code" TEXT NOT NULL,
|
||||
"amount" DECIMAL(12,2) NOT NULL,
|
||||
"updated_by_id" TEXT,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "plan_prices_pkey" PRIMARY KEY ("country_code")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "plan_price_changes" (
|
||||
"id" TEXT NOT NULL,
|
||||
"country_code" TEXT NOT NULL,
|
||||
"previous_amount" DECIMAL(12,2),
|
||||
"new_amount" DECIMAL(12,2) NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"apply_to_existing" BOOLEAN NOT NULL,
|
||||
"queued" INTEGER NOT NULL DEFAULT 0,
|
||||
"created_by_id" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "plan_price_changes_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "plan_price_changes_country_created_at_idx" ON "plan_price_changes"("country_code", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_subscriptions_pending_amount_idx" ON "billing_subscriptions"("pending_amount");
|
||||
|
||||
-- Seed with the defaults that lived in code (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`
|
||||
-- in packages/shared), so nothing changes on deploy.
|
||||
INSERT INTO "plan_configs" ("plan", "max_groups", "max_attendees", "whatsapp_automations", "mp_charges", "updated_at") VALUES
|
||||
('FREE', 1, 15, false, false, CURRENT_TIMESTAMP),
|
||||
('PRO', NULL, NULL, true, true, CURRENT_TIMESTAMP);
|
||||
|
||||
INSERT INTO "plan_prices" ("country_code", "amount", "updated_at") VALUES
|
||||
('AR', 15000, CURRENT_TIMESTAMP),
|
||||
('BR', 49, CURRENT_TIMESTAMP),
|
||||
('CL', 9900, CURRENT_TIMESTAMP),
|
||||
('CO', 39900, CURRENT_TIMESTAMP),
|
||||
('MX', 199, CURRENT_TIMESTAMP),
|
||||
('PE', 39, CURRENT_TIMESTAMP),
|
||||
('UY', 390, CURRENT_TIMESTAMP);
|
||||
@@ -8,43 +8,44 @@ enum AttendanceStatus {
|
||||
|
||||
model ClassSession {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
startsAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
groupId String @map("group_id")
|
||||
startsAt DateTime @map("starts_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
absenceNotices AbsenceNotice[]
|
||||
|
||||
@@unique([groupId, startsAt])
|
||||
@@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
|
||||
@@map("class_sessions")
|
||||
}
|
||||
|
||||
model Attendance {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String
|
||||
classSessionId String
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
status AttendanceStatus
|
||||
markedAt DateTime @default(now())
|
||||
markedAt DateTime @default(now()) @map("marked_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "attendances_attendeeId_fkey")
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "attendances_classSessionId_fkey")
|
||||
|
||||
@@unique([attendeeId, classSessionId])
|
||||
@@unique([attendeeId, classSessionId], map: "attendances_attendeeId_classSessionId_key")
|
||||
@@map("attendances")
|
||||
}
|
||||
|
||||
model SlotRelease {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String
|
||||
classSessionId String
|
||||
isClaimed Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
isClaimed Boolean @default(false) @map("is_claimed")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "slot_releases_attendeeId_fkey")
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "slot_releases_classSessionId_fkey")
|
||||
|
||||
@@unique([attendeeId, classSessionId])
|
||||
@@unique([attendeeId, classSessionId], map: "slot_releases_attendeeId_classSessionId_key")
|
||||
@@map("slot_releases")
|
||||
}
|
||||
|
||||
@@ -4,11 +4,19 @@ model User {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
email String @unique
|
||||
emailVerified Boolean @default(false)
|
||||
emailVerified Boolean @default(false) @map("email_verified")
|
||||
image String?
|
||||
onboardingCompleted Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
country String? @map("country_code")
|
||||
// UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device.
|
||||
locale String? @map("locale")
|
||||
// When the professor chose Free or Pro in the onboarding (mandatory step).
|
||||
planSelectedAt DateTime? @map("plan_selected_at")
|
||||
// Bank transfer details shown to students when they report a payment.
|
||||
transferAlias String? @map("transfer_alias")
|
||||
transferHolder String? @map("transfer_holder")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
@@ -18,46 +26,50 @@ model User {
|
||||
orgMemberships Member[]
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
waitlist WaitlistEntry[]
|
||||
merchantAccount MerchantAccount?
|
||||
mpAccount MpAccount?
|
||||
whatsappAccount WhatsappAccount?
|
||||
subscription BillingSubscription?
|
||||
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
||||
people Person[] @relation("OwnerPeople")
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Account {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
providerId String
|
||||
accountId String
|
||||
userId String @map("user_id")
|
||||
providerId String @map("provider_id")
|
||||
accountId String @map("account_id")
|
||||
issuer String
|
||||
accessToken String?
|
||||
refreshToken String?
|
||||
idToken String?
|
||||
accessTokenExpiresAt DateTime?
|
||||
refreshTokenExpiresAt DateTime?
|
||||
accessToken String? @map("access_token")
|
||||
refreshToken String? @map("refresh_token")
|
||||
idToken String? @map("id_token")
|
||||
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
|
||||
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
|
||||
scope String?
|
||||
password String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "accounts_userId_fkey")
|
||||
|
||||
@@unique([issuer, accountId])
|
||||
@@index([userId])
|
||||
@@unique([issuer, accountId], map: "accounts_issuer_accountId_key")
|
||||
@@index([userId], map: "accounts_userId_idx")
|
||||
@@map("accounts")
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
userId String @map("user_id")
|
||||
token String @unique
|
||||
expiresAt DateTime
|
||||
ipAddress String?
|
||||
userAgent String?
|
||||
activeOrganizationId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime @map("expires_at")
|
||||
ipAddress String? @map("ip_address")
|
||||
userAgent String? @map("user_agent")
|
||||
activeOrganizationId String? @map("active_organization_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "sessions_userId_fkey")
|
||||
|
||||
@@map("sessions")
|
||||
}
|
||||
@@ -66,9 +78,9 @@ model Verification {
|
||||
id String @id @default(cuid())
|
||||
identifier String
|
||||
value String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@unique([identifier, value])
|
||||
@@map("verifications")
|
||||
@@ -81,8 +93,8 @@ model Organization {
|
||||
slug String @unique
|
||||
logo String?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
members Member[]
|
||||
invitations Invitation[]
|
||||
@@ -92,32 +104,32 @@ model Organization {
|
||||
|
||||
model Member {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
userId String
|
||||
organizationId String @map("organization_id")
|
||||
userId String @map("user_id")
|
||||
role String @default("member")
|
||||
createdAt DateTime @default(now())
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "members_organizationId_fkey")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "members_userId_fkey")
|
||||
|
||||
@@unique([organizationId, userId])
|
||||
@@unique([organizationId, userId], map: "members_organizationId_userId_key")
|
||||
@@map("members")
|
||||
}
|
||||
|
||||
model Invitation {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organizationId String @map("organization_id")
|
||||
email String
|
||||
role String
|
||||
status String @default("pending")
|
||||
inviterId String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
inviterId String @map("inviter_id")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "invitations_organizationId_fkey")
|
||||
inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade, map: "invitations_inviterId_fkey")
|
||||
|
||||
@@index([organizationId])
|
||||
@@index([organizationId], map: "invitations_organizationId_idx")
|
||||
@@map("invitations")
|
||||
}
|
||||
|
||||
@@ -125,18 +137,18 @@ model Invitation {
|
||||
model Passkey {
|
||||
id String @id @default(cuid())
|
||||
name String?
|
||||
publicKey String
|
||||
credentialID String @unique
|
||||
userId String
|
||||
publicKey String @map("public_key")
|
||||
credentialID String @unique(map: "passkeys_credentialID_key") @map("credential_id")
|
||||
userId String @map("user_id")
|
||||
counter Int
|
||||
deviceType String
|
||||
backedUp Boolean
|
||||
deviceType String @map("device_type")
|
||||
backedUp Boolean @map("backed_up")
|
||||
transports String?
|
||||
createdAt DateTime @default(now())
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
aaguid String?
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "passkeys_userId_fkey")
|
||||
|
||||
@@index([userId])
|
||||
@@index([userId], map: "passkeys_userId_idx")
|
||||
@@map("passkeys")
|
||||
}
|
||||
138
apps/backend/prisma/models/billing.prisma
Normal file
138
apps/backend/prisma/models/billing.prisma
Normal file
@@ -0,0 +1,138 @@
|
||||
// Gruperly's own billing: the professor pays a monthly Pro subscription,
|
||||
// collected by Mercado Pago Subscriptions (preapproval, Argentina) or Stripe
|
||||
// (every other country), see `modules/billing/providers/`. Not to be confused
|
||||
// with `Payment`, which is what students pay the professor.
|
||||
|
||||
enum BillingProviderId {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
}
|
||||
|
||||
enum SubscriptionStatus {
|
||||
PENDING
|
||||
AUTHORIZED
|
||||
PAUSED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
model BillingSubscription {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique(map: "billing_subscriptions_userId_key") @map("user_id")
|
||||
country String @map("country_code")
|
||||
currency String
|
||||
amount Decimal @db.Decimal(12, 2)
|
||||
payerEmail String @map("payer_email")
|
||||
// Who collects it. Sync and cancel always follow this, never the current country.
|
||||
provider BillingProviderId @default(MERCADO_PAGO)
|
||||
// The provider's subscription id (MP preapproval, Stripe subscription). Null
|
||||
// until the provider creates it: right after MP answers, or once the
|
||||
// professor completes Stripe Checkout.
|
||||
externalId String? @unique(map: "billing_subscriptions_externalId_key") @map("external_id")
|
||||
// Stripe Checkout Session of the current attempt; null for Mercado Pago.
|
||||
checkoutRef String? @unique(map: "billing_subscriptions_checkoutRef_key") @map("checkout_ref")
|
||||
status SubscriptionStatus @default(PENDING)
|
||||
// When the current attempt started: re-subscribing reuses the row.
|
||||
requestedAt DateTime @default(now()) @map("requested_at")
|
||||
authorizedAt DateTime? @map("authorized_at")
|
||||
nextPaymentDate DateTime? @map("next_payment_date")
|
||||
// Last day covered by an approved charge. Pro lasts until then plus the grace
|
||||
// period, even after a cancellation or a failed renewal.
|
||||
paidThrough DateTime? @map("paid_through")
|
||||
lastSyncedAt DateTime? @map("last_synced_at")
|
||||
// A new price queued by the backoffice for this live subscription: the job
|
||||
// pushes it to the provider (from the next charge) and moves it to `amount`.
|
||||
pendingAmount Decimal? @db.Decimal(12, 2) @map("pending_amount")
|
||||
priceChangeId String? @map("price_change_id")
|
||||
priceChangeAttempts Int @default(0) @map("price_change_attempts")
|
||||
priceChangeError String? @map("price_change_error")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "billing_subscriptions_userId_fkey")
|
||||
charges BillingCharge[]
|
||||
|
||||
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
|
||||
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
|
||||
@@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx")
|
||||
@@map("billing_subscriptions")
|
||||
}
|
||||
|
||||
// One monthly invoice of a subscription (MP authorized payment, Stripe invoice).
|
||||
model BillingCharge {
|
||||
id String @id @default(cuid())
|
||||
subscriptionId String @map("subscription_id")
|
||||
externalId String @unique(map: "billing_charges_externalId_key") @map("external_id")
|
||||
amount Decimal @db.Decimal(12, 2)
|
||||
currency String
|
||||
// Normalized across providers: approved, pending or rejected.
|
||||
status String
|
||||
paidAt DateTime? @map("paid_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey")
|
||||
|
||||
@@index([subscriptionId, createdAt], map: "billing_charges_subscriptionId_createdAt_idx")
|
||||
@@map("billing_charges")
|
||||
}
|
||||
|
||||
// Deduplication of billing webhook deliveries, per sending account: `mp:<CC>`
|
||||
// (one Mercado Pago account per country) or `stripe`.
|
||||
model BillingWebhookEvent {
|
||||
source String @map("source")
|
||||
dedupeKey String @map("dedupe_key")
|
||||
receivedAt DateTime @default(now()) @map("received_at")
|
||||
|
||||
@@id([source, dedupeKey], map: "billing_webhook_events_pkey")
|
||||
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
|
||||
@@map("billing_webhook_events")
|
||||
}
|
||||
|
||||
enum PlanId {
|
||||
FREE
|
||||
PRO
|
||||
}
|
||||
|
||||
// What each plan allows, edited from the backoffice. Seeded with the defaults
|
||||
// of `PLAN_LIMITS` (shared); a missing row falls back to them. Applies at once.
|
||||
model PlanConfig {
|
||||
plan PlanId @id
|
||||
// Null means no limit.
|
||||
maxGroups Int? @map("max_groups")
|
||||
maxAttendees Int? @map("max_attendees")
|
||||
whatsappAutomations Boolean @map("whatsapp_automations")
|
||||
mpCharges Boolean @map("mp_charges")
|
||||
updatedById String? @map("updated_by_id")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@map("plan_configs")
|
||||
}
|
||||
|
||||
// Monthly price of Pro per country, in the country's currency. Seeded with
|
||||
// `PRO_PRICE_BY_COUNTRY` (shared). New subscriptions take it; live ones keep
|
||||
// their own `amount` unless a price change is applied to them.
|
||||
model PlanPrice {
|
||||
country String @id @map("country_code")
|
||||
amount Decimal @db.Decimal(12, 2)
|
||||
updatedById String? @map("updated_by_id")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@map("plan_prices")
|
||||
}
|
||||
|
||||
// Audit of every price edit from the backoffice.
|
||||
model PlanPriceChange {
|
||||
id String @id @default(cuid())
|
||||
country String @map("country_code")
|
||||
previousAmount Decimal? @db.Decimal(12, 2) @map("previous_amount")
|
||||
newAmount Decimal @db.Decimal(12, 2) @map("new_amount")
|
||||
currency String
|
||||
applyToExisting Boolean @map("apply_to_existing")
|
||||
// Live subscriptions queued to move to the new price.
|
||||
queued Int @default(0)
|
||||
createdById String? @map("created_by_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@index([country, createdAt], map: "plan_price_changes_country_created_at_idx")
|
||||
@@map("plan_price_changes")
|
||||
}
|
||||
@@ -8,19 +8,25 @@ model Group {
|
||||
time String?
|
||||
capacity Int?
|
||||
price Decimal? @db.Decimal(10, 2)
|
||||
billingType BillingType?
|
||||
dueDay Int?
|
||||
inviteToken String? @unique
|
||||
createdById String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
billingType BillingType? @map("billing_type")
|
||||
dueDay Int? @map("due_day")
|
||||
// Weekly WhatsApp automations, off until the teacher turns them on.
|
||||
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
||||
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
||||
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
||||
createdById String @map("created_by_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade)
|
||||
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
|
||||
members GroupMember[]
|
||||
attendees Attendee[]
|
||||
payments Payment[]
|
||||
waitlist GroupWaitlistEntry[]
|
||||
preRegistrations GroupPreRegistration[]
|
||||
classSessions ClassSession[]
|
||||
outboundMessages OutboundMessage[]
|
||||
reportedPayments ReportedPayment[]
|
||||
|
||||
@@map("groups")
|
||||
}
|
||||
@@ -42,15 +48,15 @@ enum BillingType {
|
||||
|
||||
model GroupMember {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
userId String
|
||||
groupId String @map("group_id")
|
||||
userId String @map("user_id")
|
||||
role Role @default(MEMBER) // OWNER, ADMIN, MEMBER
|
||||
joinedAt DateTime @default(now())
|
||||
joinedAt DateTime @default(now()) @map("joined_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_members_groupId_fkey")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "group_members_userId_fkey")
|
||||
|
||||
@@unique([groupId, userId])
|
||||
@@unique([groupId, userId], map: "group_members_groupId_userId_key")
|
||||
@@map("group_members")
|
||||
}
|
||||
|
||||
@@ -66,46 +72,103 @@ enum AttendeeStatus {
|
||||
DROPPED
|
||||
}
|
||||
|
||||
model Attendee {
|
||||
// A person the teacher works with (student, or the guardian's child). Contact
|
||||
// data lives here once; `Attendee` is their membership in each group, so one
|
||||
// person can be in several groups of the same teacher. The phone is unique per
|
||||
// teacher through a hand-written partial index (`people_owner_phone_key`,
|
||||
// `WHERE phone IS NOT NULL`): Prisma does not model it.
|
||||
model Person {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
createdById String @map("created_by_id")
|
||||
fullName String @map("full_name")
|
||||
email String?
|
||||
phone String?
|
||||
guardianName String?
|
||||
guardianPhone String?
|
||||
guardianName String? @map("guardian_name")
|
||||
guardianPhone String? @map("guardian_phone")
|
||||
notes String?
|
||||
notifyToken String? @unique @default(cuid())
|
||||
status AttendeeStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
|
||||
attendees Attendee[]
|
||||
studentAccounts StudentAccountPerson[]
|
||||
|
||||
@@index([createdById])
|
||||
@@map("people")
|
||||
}
|
||||
|
||||
// Membership of a person in a group. Status, attendance, fees and the absence
|
||||
// link (`notifyToken`) are per group.
|
||||
model Attendee {
|
||||
id String @id @default(cuid())
|
||||
groupId String @map("group_id")
|
||||
personId String @map("person_id")
|
||||
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
|
||||
status AttendeeStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
||||
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
|
||||
payments Payment[]
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
outboundMessages OutboundMessage[]
|
||||
alertResolutions AttendeeAlertResolution[]
|
||||
absenceNotices AbsenceNotice[]
|
||||
reportedPayments ReportedPayment[]
|
||||
|
||||
@@index([groupId])
|
||||
@@unique([groupId, personId])
|
||||
@@index([groupId], map: "attendees_groupId_idx")
|
||||
@@index([personId])
|
||||
@@map("attendees")
|
||||
}
|
||||
|
||||
enum StudentAlertKind {
|
||||
ATTENDANCE
|
||||
PAYMENT
|
||||
}
|
||||
|
||||
// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
|
||||
// it hides the alert while its signature (last absence / overdue fees) stays
|
||||
// the same, so a new absence or a new overdue fee brings it back on its own.
|
||||
model AttendeeAlertResolution {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String @map("attendee_id")
|
||||
kind StudentAlertKind
|
||||
signature String
|
||||
resolvedById String @map("resolved_by_id")
|
||||
resolvedAt DateTime @default(now()) @map("resolved_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([attendeeId, kind])
|
||||
@@map("attendee_alert_resolutions")
|
||||
}
|
||||
|
||||
model Payment {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
attendeeId String
|
||||
groupId String @map("group_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
currency String @default("MXN")
|
||||
currency String @default("ARS")
|
||||
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
|
||||
dueDate DateTime
|
||||
paidAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
dueDate DateTime @map("due_date")
|
||||
description String? @map("description")
|
||||
checkoutUrl String? @map("checkout_url")
|
||||
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
|
||||
mpPaymentId String? @map("mp_payment_id")
|
||||
paidAt DateTime? @map("paid_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
|
||||
outboundMessages OutboundMessage[]
|
||||
reportedItems ReportedPaymentItem[]
|
||||
|
||||
@@index([groupId])
|
||||
@@index([attendeeId])
|
||||
@@index([groupId], map: "payments_groupId_idx")
|
||||
@@index([attendeeId], map: "payments_attendeeId_idx")
|
||||
@@map("payments")
|
||||
}
|
||||
|
||||
@@ -121,12 +184,12 @@ model WaitlistEntry {
|
||||
email String
|
||||
name String?
|
||||
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String? @unique
|
||||
userId String? @unique(map: "waitlist_entries_userId_key") @map("user_id")
|
||||
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull, map: "waitlist_entries_userId_fkey")
|
||||
|
||||
@@unique([email])
|
||||
@@map("waitlist_entries")
|
||||
@@ -134,19 +197,19 @@ model WaitlistEntry {
|
||||
|
||||
model GroupWaitlistEntry {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
notes String?
|
||||
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_waitlist_entries_groupId_fkey")
|
||||
|
||||
@@unique([groupId, phone])
|
||||
@@index([groupId])
|
||||
@@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key")
|
||||
@@index([groupId], map: "group_waitlist_entries_groupId_idx")
|
||||
@@map("group_waitlist_entries")
|
||||
}
|
||||
|
||||
@@ -157,22 +220,73 @@ enum WaitlistStatus {
|
||||
DECLINED
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
enum PreRegistrationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model MerchantAccount {
|
||||
model GroupPreRegistration {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique
|
||||
provider PaymentProvider
|
||||
accessToken String?
|
||||
sandbox Boolean @default(true)
|
||||
connectedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
status PreRegistrationStatus @default(PENDING)
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey")
|
||||
|
||||
@@map("merchant_accounts")
|
||||
@@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
|
||||
@@index([groupId], map: "group_pre_registrations_groupId_idx")
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum MpAccountStatus {
|
||||
ACTIVE
|
||||
REQUIRES_REAUTH
|
||||
REVOKED
|
||||
}
|
||||
|
||||
// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
|
||||
// Tokens are stored encrypted (AES-256-GCM); there is a single active account per
|
||||
// teacher and a Mercado Pago user cannot be linked to two teachers.
|
||||
model MpAccount {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
|
||||
mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
|
||||
accessTokenEnc String @map("access_token_enc")
|
||||
refreshTokenEnc String @map("refresh_token_enc")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
scope String?
|
||||
liveMode Boolean @default(false) @map("live_mode")
|
||||
status MpAccountStatus @default(ACTIVE)
|
||||
connectedAt DateTime @default(now()) @map("connected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
|
||||
|
||||
// The daily refresh job looks for ACTIVE accounts expiring within 30 days.
|
||||
@@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx")
|
||||
@@map("mp_accounts")
|
||||
}
|
||||
|
||||
// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE
|
||||
// `code_verifier`. The `state` is the primary key because consuming it (deleting
|
||||
// the row) is what makes it single use.
|
||||
model MpOAuthState {
|
||||
state String @id
|
||||
ownerId String @map("owner_id")
|
||||
codeVerifier String @map("code_verifier")
|
||||
// Constrained to 'onboarding' | 'settings'; decides where the callback lands.
|
||||
returnTo String @map("return_to")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
// Expired rows are swept on every new authorization request.
|
||||
@@index([expiresAt], map: "mp_oauth_states_expiresAt_idx")
|
||||
@@map("mp_oauth_states")
|
||||
}
|
||||
240
apps/backend/prisma/models/student-access.prisma
Normal file
240
apps/backend/prisma/models/student-access.prisma
Normal file
@@ -0,0 +1,240 @@
|
||||
// Student access (attendees or their guardians), without passwords.
|
||||
//
|
||||
// The teacher sends a single-use invitation link over WhatsApp; consuming it
|
||||
// creates a long sliding session on that device. Passkeys and a recovery email
|
||||
// are optional and let the student get back in without the teacher. None of
|
||||
// this goes through Better Auth: students have no mandatory email and their
|
||||
// session must never pass the teacher's endpoints (separate cookie and
|
||||
// middleware under /api/v1/student).
|
||||
|
||||
// The person who signs in: the attendee or a guardian. Linked to one or more
|
||||
// attendees (a guardian may have several children), always by the teacher.
|
||||
model StudentAccount {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
// Verified recovery email (the student loads it, optional).
|
||||
recoveryEmail String? @map("recovery_email")
|
||||
recoveryEmailVerifiedAt DateTime? @map("recovery_email_verified_at")
|
||||
// Email waiting for its confirmation link; never used to recover.
|
||||
pendingRecoveryEmail String? @map("pending_recovery_email")
|
||||
// First sign-in done: the welcome screen is shown only once.
|
||||
welcomedAt DateTime? @map("welcomed_at")
|
||||
createdById String @map("created_by_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
|
||||
people StudentAccountPerson[]
|
||||
tokens StudentAccessToken[]
|
||||
sessions StudentSession[]
|
||||
passkeys StudentPasskey[]
|
||||
challenges StudentWebauthnChallenge[]
|
||||
absenceNotices AbsenceNotice[]
|
||||
reportedPayments ReportedPayment[]
|
||||
|
||||
@@index([recoveryEmail])
|
||||
@@index([createdById])
|
||||
@@map("student_accounts")
|
||||
}
|
||||
|
||||
// The account is linked to people, not to memberships: it sees every group the
|
||||
// person is in (also the ones added later). A guardian may be linked to several
|
||||
// children (N:N).
|
||||
model StudentAccountPerson {
|
||||
accountId String @map("account_id")
|
||||
personId String @map("person_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([accountId, personId])
|
||||
@@index([personId])
|
||||
@@map("student_account_people")
|
||||
}
|
||||
|
||||
enum StudentTokenKind {
|
||||
INVITATION
|
||||
RECOVERY
|
||||
EMAIL_CONFIRMATION
|
||||
}
|
||||
|
||||
// Link token. Only its SHA-256 is stored. Consuming it is a conditional update
|
||||
// (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now()`), so the
|
||||
// first device wins and the link dies.
|
||||
model StudentAccessToken {
|
||||
id String @id @default(cuid())
|
||||
tokenHash String @unique @map("token_hash")
|
||||
accountId String @map("account_id")
|
||||
kind StudentTokenKind
|
||||
// EMAIL_CONFIRMATION only: the address being confirmed.
|
||||
email String?
|
||||
expiresAt DateTime @map("expires_at")
|
||||
usedAt DateTime? @map("used_at")
|
||||
// A new invitation revokes the account's pending tokens.
|
||||
revokedAt DateTime? @map("revoked_at")
|
||||
// Teacher who generated the invitation (null for recovery/confirmation).
|
||||
createdById String? @map("created_by_id")
|
||||
usedIp String? @map("used_ip")
|
||||
usedUserAgent String? @map("used_user_agent")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([accountId, kind])
|
||||
@@map("student_access_tokens")
|
||||
}
|
||||
|
||||
// Long sliding session (90 days, renewed on use). The cookie carries the raw
|
||||
// token; only its hash is stored.
|
||||
model StudentSession {
|
||||
id String @id @default(cuid())
|
||||
accountId String @map("account_id")
|
||||
tokenHash String @unique @map("token_hash")
|
||||
// Human readable, derived from the user agent ("iPhone · Safari").
|
||||
device String
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
lastUsedAt DateTime @default(now()) @map("last_used_at")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
revokedAt DateTime? @map("revoked_at")
|
||||
|
||||
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([accountId])
|
||||
@@map("student_sessions")
|
||||
}
|
||||
|
||||
model StudentPasskey {
|
||||
id String @id @default(cuid())
|
||||
accountId String @map("account_id")
|
||||
credentialId String @unique @map("credential_id")
|
||||
publicKey Bytes @map("public_key")
|
||||
counter Int @default(0)
|
||||
transports String[]
|
||||
device String
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
lastUsedAt DateTime? @map("last_used_at")
|
||||
|
||||
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([accountId])
|
||||
@@map("student_passkeys")
|
||||
}
|
||||
|
||||
enum WebauthnChallengePurpose {
|
||||
REGISTER
|
||||
LOGIN
|
||||
}
|
||||
|
||||
// Pending WebAuthn challenge, single use (deleted when verified), 5 minutes.
|
||||
model StudentWebauthnChallenge {
|
||||
id String @id @default(cuid())
|
||||
challenge String
|
||||
// Registration only: the signed-in account. Login is discoverable (no account).
|
||||
accountId String? @map("account_id")
|
||||
purpose WebauthnChallengePurpose
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([expiresAt])
|
||||
@@map("student_webauthn_challenges")
|
||||
}
|
||||
|
||||
// Generic sliding-window rate limit: one row per hit, counted by key within
|
||||
// the window (e.g. "recovery:email:<sha256>", "recovery:ip:<ip>").
|
||||
model RateLimitEvent {
|
||||
id String @id @default(cuid())
|
||||
key String
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@index([key, createdAt])
|
||||
@@map("rate_limit_events")
|
||||
}
|
||||
|
||||
enum AbsenceReason {
|
||||
HEALTH
|
||||
TRAVEL
|
||||
WORK_STUDY
|
||||
OTHER
|
||||
}
|
||||
|
||||
// Absence notice from the student. It only marks the attendance as EXCUSED
|
||||
// (which already doesn't count for the attendance risk rules); the teacher
|
||||
// sees it. At most one active (not cancelled) notice per attendee and class:
|
||||
// enforced by a partial unique index in the migration.
|
||||
model AbsenceNotice {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
accountId String? @map("account_id")
|
||||
reason AbsenceReason?
|
||||
message String?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
cancelledAt DateTime? @map("cancelled_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
|
||||
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([attendeeId, classSessionId])
|
||||
@@index([classSessionId])
|
||||
@@map("absence_notices")
|
||||
}
|
||||
|
||||
enum ReportedPaymentStatus {
|
||||
REPORTED
|
||||
CONFIRMED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
// Payment reported by the student with a receipt. It stays REPORTED until the
|
||||
// teacher confirms it (the fees become PAID) or rejects it. `Payment.status` is
|
||||
// not touched while REPORTED: the MP reconciliation and the overdue job keep
|
||||
// working as before, and "Requiere atención" skips fees covered by a REPORTED
|
||||
// report.
|
||||
model ReportedPayment {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String @map("attendee_id")
|
||||
groupId String @map("group_id")
|
||||
accountId String? @map("account_id")
|
||||
totalAmount Decimal @map("total_amount") @db.Decimal(10, 2)
|
||||
currency String
|
||||
// Private object key in the storage; null once the retention policy deletes it.
|
||||
receiptKey String? @map("receipt_key")
|
||||
receiptMime String @map("receipt_mime")
|
||||
receiptName String @map("receipt_name")
|
||||
receiptSize Int @map("receipt_size")
|
||||
// Optional message from the student to the teacher.
|
||||
note String?
|
||||
status ReportedPaymentStatus @default(REPORTED)
|
||||
reviewedById String? @map("reviewed_by_id")
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
rejectionReason String? @map("rejection_reason")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
|
||||
items ReportedPaymentItem[]
|
||||
|
||||
@@index([groupId, status])
|
||||
@@index([attendeeId])
|
||||
@@map("reported_payments")
|
||||
}
|
||||
|
||||
// Fees a report covers. A fee can't be in two REPORTED reports at once
|
||||
// (checked in the use-case, inside the transaction).
|
||||
model ReportedPaymentItem {
|
||||
reportedPaymentId String @map("reported_payment_id")
|
||||
paymentId String @map("payment_id")
|
||||
|
||||
reportedPayment ReportedPayment @relation(fields: [reportedPaymentId], references: [id], onDelete: Cascade)
|
||||
payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([reportedPaymentId, paymentId])
|
||||
@@index([paymentId])
|
||||
@@map("reported_payment_items")
|
||||
}
|
||||
130
apps/backend/prisma/models/whatsapp.prisma
Normal file
130
apps/backend/prisma/models/whatsapp.prisma
Normal file
@@ -0,0 +1,130 @@
|
||||
// WhatsApp messaging (automated payment reminders and re-engagement).
|
||||
//
|
||||
// Nothing here is tied to one provider: the teacher links their own number
|
||||
// through whichever `MessagingProvider` the server runs (OpenWA for the MVP,
|
||||
// Kapso afterwards) and the row records which one it was linked with. Changing
|
||||
// `WHATSAPP_PROVIDER` leaves the old rows behind as "requires reconnect".
|
||||
|
||||
enum MessagingProviderId {
|
||||
OPENWA
|
||||
KAPSO
|
||||
}
|
||||
|
||||
enum WhatsappAccountStatus {
|
||||
PENDING
|
||||
ACTIVE
|
||||
DISCONNECTED
|
||||
}
|
||||
|
||||
enum WhatsappMessageKind {
|
||||
PAYMENT_REMINDER
|
||||
REENGAGEMENT
|
||||
}
|
||||
|
||||
enum OutboundMessageStatus {
|
||||
QUEUED
|
||||
SENT
|
||||
DELIVERED
|
||||
READ
|
||||
FAILED
|
||||
SKIPPED
|
||||
}
|
||||
|
||||
enum WhatsappTemplateStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
DISABLED
|
||||
}
|
||||
|
||||
// The teacher's linked WhatsApp. One per teacher.
|
||||
model WhatsappAccount {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @unique(map: "whatsapp_accounts_ownerId_key") @map("owner_id")
|
||||
provider MessagingProviderId
|
||||
status WhatsappAccountStatus @default(PENDING)
|
||||
// OpenWA: session id. Kapso: phone_number_id (null until the setup finishes).
|
||||
externalId String? @map("external_id")
|
||||
displayPhoneNumber String? @map("display_phone_number")
|
||||
// Provider-specific identifiers (Kapso: customerId, setupLinkId, businessAccountId).
|
||||
// Never secrets: API keys and webhook secrets live in the environment.
|
||||
providerData Json? @map("provider_data")
|
||||
connectedAt DateTime? @map("connected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "whatsapp_accounts_ownerId_fkey")
|
||||
templates WhatsappTemplate[]
|
||||
|
||||
// A number (or session) cannot be linked to two teachers.
|
||||
@@unique([provider, externalId], map: "whatsapp_accounts_provider_externalId_key")
|
||||
@@map("whatsapp_accounts")
|
||||
}
|
||||
|
||||
// Message templates submitted to Meta for one account (Kapso only: OpenWA sends
|
||||
// free text). Meta approves them per WhatsApp Business Account.
|
||||
model WhatsappTemplate {
|
||||
id String @id @default(cuid())
|
||||
accountId String @map("account_id")
|
||||
kind WhatsappMessageKind
|
||||
name String
|
||||
language String
|
||||
metaTemplateId String? @map("meta_template_id")
|
||||
status WhatsappTemplateStatus @default(PENDING)
|
||||
rejectedReason String? @map("rejected_reason")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
account WhatsappAccount @relation(fields: [accountId], references: [id], onDelete: Cascade, map: "whatsapp_templates_accountId_fkey")
|
||||
|
||||
@@unique([accountId, kind], map: "whatsapp_templates_accountId_kind_key")
|
||||
@@index([status], map: "whatsapp_templates_status_idx")
|
||||
@@map("whatsapp_templates")
|
||||
}
|
||||
|
||||
// One automated message to one member. It is the send log and the idempotency
|
||||
// key at once: the row is created before calling the provider, and the unique
|
||||
// (kind, attendee, week) is what stops a second run of the weekly job from
|
||||
// writing to the same person twice.
|
||||
model OutboundMessage {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @map("owner_id")
|
||||
groupId String @map("group_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
paymentId String? @map("payment_id")
|
||||
kind WhatsappMessageKind
|
||||
provider MessagingProviderId
|
||||
// ISO week the job ran for, e.g. "2026-W43".
|
||||
periodKey String @map("period_key")
|
||||
toPhone String @map("to_phone")
|
||||
providerMessageId String? @map("provider_message_id")
|
||||
status OutboundMessageStatus @default(QUEUED)
|
||||
errorCode String? @map("error_code")
|
||||
errorMessage String? @map("error_message")
|
||||
sentAt DateTime? @map("sent_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
|
||||
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
|
||||
|
||||
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
|
||||
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
|
||||
// Re-engagement cooldown: "was this member written to in the last 14 days?"
|
||||
@@index([attendeeId, kind, createdAt], map: "outbound_messages_attendeeId_kind_createdAt_idx")
|
||||
@@index([groupId, createdAt], map: "outbound_messages_groupId_createdAt_idx")
|
||||
@@map("outbound_messages")
|
||||
}
|
||||
|
||||
// Webhook deliveries already processed. Both providers deliver at least once and
|
||||
// retry, so the delivery's idempotency key is burned here before applying it.
|
||||
model WhatsappWebhookEvent {
|
||||
provider MessagingProviderId
|
||||
dedupeKey String @map("dedupe_key")
|
||||
receivedAt DateTime @default(now()) @map("received_at")
|
||||
|
||||
@@id([provider, dedupeKey], map: "whatsapp_webhook_events_pkey")
|
||||
@@index([receivedAt], map: "whatsapp_webhook_events_receivedAt_idx")
|
||||
@@map("whatsapp_webhook_events")
|
||||
}
|
||||
@@ -10,20 +10,28 @@ import { requestLoggerMiddleware } from '@/http/request-logger';
|
||||
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
|
||||
import { sessionAuthMiddleware } from '@/http/session-auth';
|
||||
import { logger } from '@/logger';
|
||||
import { adminRoutes } from './modules/admin';
|
||||
import {
|
||||
groupsRiskOverviewRoute,
|
||||
studentStatusRoutes,
|
||||
} from './modules/analytics';
|
||||
import { attendeesRoutes } from './modules/attendees';
|
||||
import { attentionRoutes } from './modules/attention';
|
||||
import { authRoutes } from './modules/auth';
|
||||
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
|
||||
import { classesRoutes } from './modules/classes';
|
||||
import { groupsRoutes } from './modules/groups';
|
||||
import { healthCheckRoutes } from './modules/health-check';
|
||||
import { homeRoutes } from './modules/home';
|
||||
import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { mpCallbackOriginMiddleware } from './modules/mp/lib';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { peopleRoutes } from './modules/people';
|
||||
import { studentPortalRoutes } from './modules/student-portal';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
import { whatsappRoutes } from './modules/whatsapp';
|
||||
|
||||
const app = new Hono<BackendEnv>();
|
||||
|
||||
@@ -36,20 +44,37 @@ app.get('/', (c) => c.json({ name: 'Gruperly API', status: 'ok' }));
|
||||
|
||||
const api = app.basePath('/api/v1');
|
||||
|
||||
// Local development: the MP callback comes back through the tunnel, without the
|
||||
// session cookie of localhost. Replay it there before asking for a session.
|
||||
api.use('/mp/callback', mpCallbackOriginMiddleware);
|
||||
api.use('*', sessionAuthMiddleware);
|
||||
|
||||
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
|
||||
// onboarding and the MP/WhatsApp links stay open: that is how they get out of it.
|
||||
const planReadOnly = planReadOnlyMiddleware();
|
||||
for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/students', '/waitlist']) {
|
||||
api.use(`${prefix}/*`, planReadOnly);
|
||||
}
|
||||
|
||||
api.route('/admin', adminRoutes);
|
||||
api.route('/auth', authRoutes);
|
||||
api.route('/health', healthCheckRoutes);
|
||||
api.route('/invitations', invitationsRoutes);
|
||||
api.route('/groups', groupsRoutes);
|
||||
api.route('/home', homeRoutes);
|
||||
api.route('/onboarding', onboardingRoutes);
|
||||
api.route('/mp', mpRoutes);
|
||||
api.route('/whatsapp', whatsappRoutes);
|
||||
api.route('/attendees', attendeesRoutes);
|
||||
api.route('/payments', paymentsRoutes);
|
||||
api.route('/billing', billingRoutes);
|
||||
api.route('/waitlist', waitlistRoutes);
|
||||
api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||
api.route('/attention', attentionRoutes);
|
||||
api.route('/people', peopleRoutes);
|
||||
api.route('/student-portal', studentPortalRoutes);
|
||||
|
||||
app.notFound((c) => {
|
||||
return problemJson(c, notFoundProblem(c.req.path));
|
||||
|
||||
@@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth';
|
||||
|
||||
type AuthSession = typeof auth.$Infer.Session;
|
||||
|
||||
/** Signed-in student (attendee or guardian): set only on /student-portal. */
|
||||
export type StudentContext = { accountId: string; sessionId: string };
|
||||
|
||||
export type BackendEnv = {
|
||||
Variables: {
|
||||
user: AuthSession['user'] | null;
|
||||
session: AuthSession['session'] | null;
|
||||
requestId: string;
|
||||
student: StudentContext | null;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -15,5 +19,6 @@ declare module 'hono' {
|
||||
user: AuthSession['user'] | null;
|
||||
session: AuthSession['session'] | null;
|
||||
requestId: string;
|
||||
student: StudentContext | null;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export function conflictProblem(params: {
|
||||
detail: string;
|
||||
code?: string;
|
||||
instance?: string;
|
||||
params?: ProblemDetails['params'];
|
||||
}): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/conflict`,
|
||||
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
|
||||
detail: params.detail,
|
||||
instance: params.instance,
|
||||
code: params.code,
|
||||
...(params.params ? { params: params.params } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,13 +73,108 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl
|
||||
return notFoundProblem(`${resourceName} ${id}`);
|
||||
}
|
||||
|
||||
export function paymentNotSetupProblem(): ProblemDetails {
|
||||
export function mpNotConnectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.',
|
||||
code: 'payment_not_setup',
|
||||
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
|
||||
code: 'mp_not_connected',
|
||||
});
|
||||
}
|
||||
|
||||
export function mpRequiresReauthProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Tu cuenta de Mercado Pago necesita volver a vincularse.',
|
||||
code: 'mp_requires_reauth',
|
||||
});
|
||||
}
|
||||
|
||||
export function mpAccountInUseProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.',
|
||||
code: 'mp_account_in_use',
|
||||
});
|
||||
}
|
||||
|
||||
/** The server is missing MP_CLIENT_ID / MP_CLIENT_SECRET / MP_REDIRECT_URI. */
|
||||
export function mpNotConfiguredProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/mercadopago-not-configured`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'La vinculación con Mercado Pago no está disponible en este momento.',
|
||||
code: 'mp_not_configured',
|
||||
};
|
||||
}
|
||||
|
||||
/** Mercado Pago refused the request, or could not be reached. */
|
||||
export function mpProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/mercadopago-unavailable`,
|
||||
title: 'Bad Gateway',
|
||||
status: 502,
|
||||
detail: 'No pudimos completar la vinculación con Mercado Pago.',
|
||||
code: 'mp_provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
/** The server is missing the variables of the active WhatsApp provider. */
|
||||
export function whatsappNotConfiguredProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/whatsapp-not-configured`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'La vinculación con WhatsApp no está disponible en este momento.',
|
||||
code: 'whatsapp_not_configured',
|
||||
};
|
||||
}
|
||||
|
||||
export function whatsappNotConnectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'No tenés un WhatsApp vinculado.',
|
||||
code: 'whatsapp_not_connected',
|
||||
});
|
||||
}
|
||||
|
||||
export function whatsappNumberInUseProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ese número de WhatsApp ya está vinculado a otro profesor.',
|
||||
code: 'whatsapp_number_in_use',
|
||||
});
|
||||
}
|
||||
|
||||
export function whatsappLinkingNotStartedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Empezá la vinculación de WhatsApp antes de pedir el código.',
|
||||
code: 'whatsapp_linking_not_started',
|
||||
});
|
||||
}
|
||||
|
||||
/** The provider links by QR or redirect only (Kapso). */
|
||||
export function whatsappPairingUnsupportedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Este proveedor de WhatsApp no permite vincular con el número de teléfono.',
|
||||
code: 'whatsapp_pairing_unsupported',
|
||||
});
|
||||
}
|
||||
|
||||
/** The session is not ready to hand out a code yet; retryable in seconds. */
|
||||
export function whatsappPairingNotReadyProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.',
|
||||
code: 'whatsapp_pairing_not_ready',
|
||||
});
|
||||
}
|
||||
|
||||
/** The WhatsApp gateway refused the request, or could not be reached. */
|
||||
export function whatsappProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/whatsapp-unavailable`,
|
||||
title: 'Bad Gateway',
|
||||
status: 502,
|
||||
detail: 'No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos.',
|
||||
code: 'whatsapp_provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
export function onboardingAlreadyCompletedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya completaste el onboarding de Gruperly.',
|
||||
@@ -91,6 +188,7 @@ export function capacityReachedProblem(capacity: number | null): ProblemDetails
|
||||
? `El grupo alcanzó su cupo máximo de ${capacity} miembros.`
|
||||
: 'El grupo alcanzó su cupo máximo de miembros.',
|
||||
code: 'group_capacity_reached',
|
||||
...(capacity ? { params: { capacity } } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -107,3 +205,117 @@ export function attendeeHasPaymentsProblem(): ProblemDetails {
|
||||
code: 'attendee_has_payments',
|
||||
});
|
||||
}
|
||||
|
||||
export function groupWithoutPriceProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Definí el precio del grupo antes de generar los cobros.',
|
||||
code: 'group_without_price',
|
||||
});
|
||||
}
|
||||
|
||||
export function noAttendeesToBillProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'No hay miembros activos con un cobro pendiente para este grupo.',
|
||||
code: 'no_attendees_to_bill',
|
||||
});
|
||||
}
|
||||
function paymentRequiredProblem(params: {
|
||||
detail: string;
|
||||
code: string;
|
||||
params?: ProblemDetails['params'];
|
||||
}): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/plan`,
|
||||
title: 'Payment Required',
|
||||
status: 402,
|
||||
detail: params.detail,
|
||||
code: params.code,
|
||||
...(params.params ? { params: params.params } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export type PlanLimitKind = 'groups' | 'attendees';
|
||||
|
||||
/** The Free plan does not allow one more group or attendee. */
|
||||
export function planLimitReachedProblem(limit: PlanLimitKind, max: number): ProblemDetails {
|
||||
return paymentRequiredProblem({
|
||||
detail:
|
||||
limit === 'groups'
|
||||
? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.`
|
||||
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
|
||||
code: 'plan_limit_reached',
|
||||
params: { limit, max },
|
||||
});
|
||||
}
|
||||
|
||||
/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */
|
||||
export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails {
|
||||
return paymentRequiredProblem({
|
||||
detail:
|
||||
feature === 'mpCharges'
|
||||
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
|
||||
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
||||
code: 'plan_feature_required',
|
||||
params: { feature },
|
||||
});
|
||||
}
|
||||
|
||||
/** Free plan with more usage than its limits: only reads and deletes. */
|
||||
export function planReadOnlyProblem(): ProblemDetails {
|
||||
return paymentRequiredProblem({
|
||||
detail:
|
||||
'Tu cuenta está en solo lectura porque superás los límites del plan Free. Pasate a Pro o reducí el uso para volver a editar.',
|
||||
code: 'plan_read_only',
|
||||
});
|
||||
}
|
||||
|
||||
/** The billing provider of the professor's country is not configured. */
|
||||
export function billingNotAvailableProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/billing-not-available`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'La suscripción a Pro todavía no está disponible en tu país.',
|
||||
code: 'billing_not_available',
|
||||
};
|
||||
}
|
||||
|
||||
/** The billing provider (Mercado Pago or Stripe) refused the request, or could not be reached. */
|
||||
export function billingProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`,
|
||||
title: 'Bad Gateway',
|
||||
status: 502,
|
||||
detail: 'No pudimos comunicarnos con el procesador de pagos. Intentá de nuevo en unos minutos.',
|
||||
code: 'billing_provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
/** Mercado Pago makes the payer log in with this exact email, so it cannot be left out. */
|
||||
export function payerEmailRequiredProblem(): ProblemDetails {
|
||||
return validationProblem({
|
||||
detail: 'Ingresá el email de tu cuenta de Mercado Pago.',
|
||||
errors: { payerEmail: ['Ingresá el email de tu cuenta de Mercado Pago.'] },
|
||||
});
|
||||
}
|
||||
|
||||
export function subscriptionAlreadyActiveProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya tenés una suscripción a Pro activa.',
|
||||
code: 'subscription_already_active',
|
||||
});
|
||||
}
|
||||
|
||||
export function noActiveSubscriptionProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'No tenés una suscripción para cancelar.',
|
||||
code: 'no_active_subscription',
|
||||
});
|
||||
}
|
||||
|
||||
export function planNotSelectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Elegí un plan antes de crear tu primer grupo.',
|
||||
code: 'plan_not_selected',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -27,19 +27,48 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
|
||||
const normalizedPath = normalizePath(path);
|
||||
|
||||
// Aviso de ausencia con token personal del alumno (sin sesión).
|
||||
// Absence notice sent with the attendee's personal token (no session).
|
||||
if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
|
||||
return true;
|
||||
}
|
||||
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
|
||||
return true;
|
||||
}
|
||||
// WhatsApp provider webhooks: no session, authenticated by their HMAC signature.
|
||||
if (
|
||||
method === 'POST'
|
||||
&& (normalizedPath === '/api/v1/whatsapp/webhooks/openwa'
|
||||
|| normalizedPath === '/api/v1/whatsapp/webhooks/kapso')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
// Mercado Pago notifications about Pro subscriptions, one URL per country:
|
||||
// no session, authenticated by Mercado Pago's `x-signature`.
|
||||
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
|
||||
return true;
|
||||
}
|
||||
// Mercado Pago notifications about a Checkout Pro payment: no session; the
|
||||
// owner's Mercado Pago account is asked before anything changes.
|
||||
if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/[A-Za-z0-9_-]+$/.test(normalizedPath)) {
|
||||
return true;
|
||||
}
|
||||
// Back from the Pro checkout: only redirects to the web, which has the session.
|
||||
if (method === 'GET' && normalizedPath === '/api/v1/billing/return') {
|
||||
return true;
|
||||
}
|
||||
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
|
||||
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
normalizedPath === '/api/v1/health'
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/auth')
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/invitations')
|
||||
// Student app: its own cookie and middleware (modules/student-portal), never
|
||||
// the teacher's session.
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/student-portal')
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,15 +4,33 @@ import nodemailer, { type Transporter } from 'nodemailer'
|
||||
type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
||||
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
||||
type ProPriceChangedData = {
|
||||
email: string
|
||||
name: string
|
||||
/** Already formatted in the professor's currency. */
|
||||
amount: string
|
||||
/** Already formatted; `null` when the provider has not scheduled the next charge. */
|
||||
nextPaymentDate: string | null
|
||||
billingUrl: string
|
||||
}
|
||||
type StudentPaymentReviewedData = {
|
||||
email: string
|
||||
name: string
|
||||
confirmed: boolean
|
||||
amount: string
|
||||
reason?: string | null
|
||||
}
|
||||
|
||||
// Colores de marca (mismo sistema que la web: index.css de apps/web).
|
||||
// Brand colors (same system as the web app: index.css in apps/web).
|
||||
const BRAND_600 = '#2544ea'
|
||||
const TEXT_STRONG = '#0f172a'
|
||||
const TEXT_MUTED = '#475569'
|
||||
const ON_ACCENT = '#ffffff'
|
||||
const LINK_BG = BRAND_600
|
||||
|
||||
// Logotipo embebido como data URI para que los mails no dependan de hosting.
|
||||
// Logo embedded as a data URI so the emails don't depend on hosting.
|
||||
function loadLogoTypoDataUri(): string {
|
||||
try {
|
||||
const base64 = readFileSync(
|
||||
@@ -26,10 +44,28 @@ function loadLogoTypoDataUri(): string {
|
||||
|
||||
const LOGO_DATA_URI = loadLogoTypoDataUri()
|
||||
|
||||
interface EmailProvider {
|
||||
export interface EmailProvider {
|
||||
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
||||
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
||||
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
||||
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
||||
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
||||
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
||||
sendProPriceChanged(data: ProPriceChangedData): Promise<void>
|
||||
}
|
||||
|
||||
// Names come from what teachers and students type: never raw into the HTML.
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function button(url: string, label: string): string {
|
||||
return `<a href="${escapeHtml(url)}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">${escapeHtml(label)}</a>`
|
||||
}
|
||||
|
||||
class SMTPEmailProvider implements EmailProvider {
|
||||
@@ -66,7 +102,7 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
// With no SMTP configured (dev) the flow still doesn't break: it only logs a warning
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
@@ -109,10 +145,65 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendStudentEmailConfirmation({ email, url, name }: StudentEmailConfirmationData) {
|
||||
await this.send(
|
||||
email,
|
||||
'Confirmá tu mail de recuperación en Gruperly',
|
||||
this.layout(
|
||||
'Confirmá tu mail',
|
||||
`Hola ${escapeHtml(name)}, confirmá este mail para poder pedir un link de ingreso si perdés el acceso a la app (el enlace vence en 24 horas). Si no fuiste vos, ignorá este mail.<br/><br/>${button(url, 'Confirmar mail')}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) {
|
||||
// A guardian may have one account per child with the same email: one button each.
|
||||
const buttons = links
|
||||
.map((link) =>
|
||||
links.length > 1
|
||||
? `<p style="margin:12px 0 4px;">${escapeHtml(link.name)}</p>${button(link.url, 'Ingresar')}`
|
||||
: button(link.url, 'Ingresar'),
|
||||
)
|
||||
.join('<br/>')
|
||||
await this.send(
|
||||
email,
|
||||
'Tu link para ingresar a Gruperly',
|
||||
this.layout(
|
||||
'Tu link de ingreso',
|
||||
`Pediste un link para volver a entrar. Sirve una sola vez y vence en 15 minutos. Si no fuiste vos, ignorá este mail.<br/><br/>${buttons}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendStudentPaymentReviewed({ email, name, confirmed, amount, reason }: StudentPaymentReviewedData) {
|
||||
const body = confirmed
|
||||
? `Hola ${escapeHtml(name)}, tu profe confirmó el pago de ${escapeHtml(amount)}. ¡Gracias!`
|
||||
: `Hola ${escapeHtml(name)}, tu profe no pudo confirmar el pago de ${escapeHtml(amount)}.${reason ? `<br/><br/>Motivo: ${escapeHtml(reason)}` : ''}<br/><br/>Podés volver a informarlo desde la app.`
|
||||
await this.send(
|
||||
email,
|
||||
confirmed ? 'Tu pago fue confirmado' : 'Tu pago no fue confirmado',
|
||||
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
||||
)
|
||||
}
|
||||
|
||||
async sendProPriceChanged({ email, name, amount, nextPaymentDate, billingUrl }: ProPriceChangedData) {
|
||||
const when = nextPaymentDate
|
||||
? `desde tu próximo cobro, el ${escapeHtml(nextPaymentDate)}`
|
||||
: 'desde tu próximo cobro'
|
||||
await this.send(
|
||||
email,
|
||||
'Cambia el precio de Gruperly Pro',
|
||||
this.layout(
|
||||
'Nuevo precio de Gruperly Pro',
|
||||
`Hola ${escapeHtml(name)}, te avisamos que el precio de tu suscripción a Gruperly Pro pasa a ser de ${escapeHtml(amount)} por mes ${when}. Lo que ya pagaste no cambia.<br/><br/>Si no querés seguir, podés cancelar la suscripción cuando quieras y vas a seguir con Pro hasta el final del período pago.<br/><br/>${button(billingUrl, 'Ver mi plan')}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||
// Add implementations and switch between them with EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
36
apps/backend/src/lib/file-type.ts
Normal file
36
apps/backend/src/lib/file-type.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/* Real type of an uploaded file from its first bytes (magic numbers), never
|
||||
from the name or the Content-Type the browser claims. */
|
||||
|
||||
export type ReceiptMime = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/heic' | 'application/pdf';
|
||||
|
||||
export const RECEIPT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
export const RECEIPT_EXTENSIONS: Record<ReceiptMime, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/webp': 'webp',
|
||||
'image/heic': 'heic',
|
||||
'application/pdf': 'pdf',
|
||||
};
|
||||
|
||||
// ISO-BMFF brands used by HEIC/HEIF photos (iPhone camera).
|
||||
const HEIF_BRANDS = new Set(['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1']);
|
||||
|
||||
function ascii(bytes: Uint8Array, start: number, length: number): string {
|
||||
return String.fromCharCode(...bytes.subarray(start, start + length));
|
||||
}
|
||||
|
||||
export function detectReceiptType(bytes: Uint8Array): ReceiptMime | null {
|
||||
if (bytes.length < 12) return null;
|
||||
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
||||
if (
|
||||
bytes[0] === 0x89 && ascii(bytes, 1, 3) === 'PNG'
|
||||
&& bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
|
||||
) {
|
||||
return 'image/png';
|
||||
}
|
||||
if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'image/webp';
|
||||
if (ascii(bytes, 4, 4) === 'ftyp' && HEIF_BRANDS.has(ascii(bytes, 8, 4))) return 'image/heic';
|
||||
if (ascii(bytes, 0, 5) === '%PDF-') return 'application/pdf';
|
||||
return null;
|
||||
}
|
||||
17
apps/backend/src/lib/public-origin.ts
Normal file
17
apps/backend/src/lib/public-origin.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
const DEFAULT_API_ORIGIN = 'http://localhost:4000';
|
||||
|
||||
/**
|
||||
* Public origin of this API, as the billing providers reach it. Mercado Pago
|
||||
* refuses a non-public `back_url` and `notification_url` (localhost), so in local development it is the
|
||||
* ngrok tunnel. Falls back to `BETTER_AUTH_URL`, which is the API's base URL
|
||||
* (in production the same origin as the web, since nginx proxies `/api`).
|
||||
*/
|
||||
export function getApiPublicOrigin(env: Record<string, string | undefined> = process.env): string {
|
||||
const configured = env.API_PUBLIC_URL?.trim() || env.BETTER_AUTH_URL?.trim();
|
||||
if (!configured) return DEFAULT_API_ORIGIN;
|
||||
try {
|
||||
return new URL(configured).origin;
|
||||
} catch {
|
||||
return DEFAULT_API_ORIGIN;
|
||||
}
|
||||
}
|
||||
54
apps/backend/src/lib/storage.ts
Normal file
54
apps/backend/src/lib/storage.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { S3Client } from 'bun';
|
||||
|
||||
/* Private file storage (payment receipts). Behind a port, like the WhatsApp and
|
||||
billing providers: the use-cases never talk to S3 directly, and the tests
|
||||
inject an in-memory fake. Objects are never public; the teacher sees them
|
||||
through short-lived signed URLs. */
|
||||
export interface FileStorage {
|
||||
put(key: string, body: Uint8Array, contentType: string): Promise<void>;
|
||||
/** GET URL valid for `expiresInSeconds`. */
|
||||
signedUrl(key: string, expiresInSeconds: number): string;
|
||||
remove(key: string): Promise<void>;
|
||||
}
|
||||
|
||||
/* Any S3-compatible service (RustFS, MinIO, R2, AWS). Path-style addressing by
|
||||
default, which is what self-hosted services expect; S3_VIRTUAL_HOSTED=on for
|
||||
AWS-style bucket subdomains. */
|
||||
class S3FileStorage implements FileStorage {
|
||||
constructor(private readonly client: S3Client) {}
|
||||
|
||||
async put(key: string, body: Uint8Array, contentType: string): Promise<void> {
|
||||
await this.client.write(key, body, { type: contentType });
|
||||
}
|
||||
|
||||
signedUrl(key: string, expiresInSeconds: number): string {
|
||||
return this.client.presign(key, { method: 'GET', expiresIn: expiresInSeconds });
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.client.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
let storage: FileStorage | null | undefined;
|
||||
|
||||
/** null when S3 isn't configured: the endpoints that need it answer 503. */
|
||||
export function getFileStorage(): FileStorage | null {
|
||||
if (storage !== undefined) return storage;
|
||||
const { S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY } = process.env;
|
||||
if (!S3_ENDPOINT || !S3_BUCKET || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) {
|
||||
storage = null;
|
||||
return storage;
|
||||
}
|
||||
storage = new S3FileStorage(
|
||||
new S3Client({
|
||||
endpoint: S3_ENDPOINT,
|
||||
bucket: S3_BUCKET,
|
||||
region: process.env.S3_REGION || 'us-east-1',
|
||||
accessKeyId: S3_ACCESS_KEY_ID,
|
||||
secretAccessKey: S3_SECRET_ACCESS_KEY,
|
||||
virtualHostedStyle: process.env.S3_VIRTUAL_HOSTED === 'on',
|
||||
}),
|
||||
);
|
||||
return storage;
|
||||
}
|
||||
12
apps/backend/src/modules/admin/features/get-account/route.ts
Normal file
12
apps/backend/src/modules/admin/features/get-account/route.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { GetAccount } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/accounts/:accountId', async (c) => {
|
||||
const result = await new GetAccount().execute(c.req.param('accountId'));
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
101
apps/backend/src/modules/admin/features/get-account/use-case.ts
Normal file
101
apps/backend/src/modules/admin/features/get-account/use-case.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import {
|
||||
exceedsLimits,
|
||||
getGraceDays,
|
||||
isBillingEnforced,
|
||||
type PlanCatalogReader,
|
||||
planCatalog,
|
||||
toBillingChargeDto,
|
||||
} from '@/modules/billing/lib';
|
||||
import { accountPlan, toAccountListItem } from '../../lib';
|
||||
|
||||
const RECENT_CHARGES = 12;
|
||||
|
||||
type GetAccountDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'billingCharge'>;
|
||||
enforced?: boolean;
|
||||
graceDays?: number;
|
||||
now?: () => Date;
|
||||
catalog?: PlanCatalogReader;
|
||||
};
|
||||
|
||||
/** One professor's account: plan, links, groups and the latest Pro charges. */
|
||||
export class GetAccount {
|
||||
constructor(private readonly deps: GetAccountDeps = {}) {}
|
||||
|
||||
async execute(userId: string): Promise<Result<AdminAccountDetail, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const context = {
|
||||
now: this.deps.now?.() ?? new Date(),
|
||||
graceDays: this.deps.graceDays ?? getGraceDays(),
|
||||
};
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: {
|
||||
subscription: true,
|
||||
mpAccount: { select: { status: true } },
|
||||
whatsappAccount: { select: { status: true } },
|
||||
groupsOwner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
createdAt: true,
|
||||
_count: { select: { attendees: { where: { status: 'ACTIVE' } } } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!user) return err(notFoundResourceProblem('User', userId));
|
||||
|
||||
const charges = await db.billingCharge.findMany({
|
||||
where: { subscription: { userId } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: RECENT_CHARGES,
|
||||
});
|
||||
|
||||
const groups = user.groupsOwner.map((group) => ({
|
||||
id: group.id,
|
||||
name: group.name,
|
||||
createdAt: group.createdAt.toISOString(),
|
||||
attendeesCount: group._count.attendees,
|
||||
}));
|
||||
const usage = {
|
||||
groupsCount: groups.length,
|
||||
attendeesCount: groups.reduce((sum, group) => sum + group.attendeesCount, 0),
|
||||
};
|
||||
const summary = toAccountListItem(user, usage, context);
|
||||
const { graceUntil } = accountPlan(user, context);
|
||||
const enforced = this.deps.enforced ?? isBillingEnforced();
|
||||
const subscription = user.subscription;
|
||||
// Same rule as the PlanGuard: an account without a plan is held to Free.
|
||||
const limits = await (this.deps.catalog ?? planCatalog).getLimits(summary.plan ?? 'FREE');
|
||||
|
||||
return ok({
|
||||
...summary,
|
||||
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
|
||||
graceUntil: graceUntil?.toISOString() ?? null,
|
||||
readOnly:
|
||||
enforced && exceedsLimits(limits, { groups: usage.groupsCount, attendees: usage.attendeesCount }),
|
||||
limits,
|
||||
subscription:
|
||||
summary.subscription && subscription
|
||||
? {
|
||||
...summary.subscription,
|
||||
payerEmail: subscription.payerEmail,
|
||||
authorizedAt: subscription.authorizedAt?.toISOString() ?? null,
|
||||
requestedAt: subscription.requestedAt.toISOString(),
|
||||
}
|
||||
: null,
|
||||
mpStatus: user.mpAccount?.status ?? null,
|
||||
whatsappStatus: user.whatsappAccount?.status ?? null,
|
||||
groups,
|
||||
charges: charges.map(toBillingChargeDto),
|
||||
});
|
||||
}
|
||||
}
|
||||
12
apps/backend/src/modules/admin/features/get-plans/route.ts
Normal file
12
apps/backend/src/modules/admin/features/get-plans/route.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { GetPlans } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/plans', async (c) => {
|
||||
const result = await new GetPlans().execute();
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AdminPlansDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { billingProviderForCountry, COUNTRY_CURRENCY, countryCodeSchema, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { MAX_PRICE_CHANGE_ATTEMPTS } from '@/modules/billing/jobs';
|
||||
import { type PlanCatalogReader, planCatalog } from '@/modules/billing/lib';
|
||||
|
||||
/** The subscriptions "apply to existing" moves: live, with a provider subscription. */
|
||||
export const LIVE_SUBSCRIPTION_STATUSES = ['AUTHORIZED', 'PAUSED'] as const;
|
||||
|
||||
type GetPlansDeps = {
|
||||
db?: Pick<PrismaClient, 'planPrice' | 'billingSubscription'>;
|
||||
catalog?: PlanCatalogReader;
|
||||
};
|
||||
|
||||
/** Limits of both plans and, per country, the price of Pro and how it reached live subscriptions. */
|
||||
export class GetPlans {
|
||||
constructor(private readonly deps: GetPlansDeps = {}) {}
|
||||
|
||||
async execute(): Promise<Result<AdminPlansDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const catalog = await (this.deps.catalog ?? planCatalog).snapshot();
|
||||
|
||||
const [priceRows, live] = await Promise.all([
|
||||
db.planPrice.findMany({ select: { country: true, updatedAt: true } }),
|
||||
db.billingSubscription.findMany({
|
||||
where: { status: { in: [...LIVE_SUBSCRIPTION_STATUSES] }, externalId: { not: null } },
|
||||
select: { country: true, amount: true, pendingAmount: true, priceChangeAttempts: true },
|
||||
}),
|
||||
]);
|
||||
const updatedAt = new Map(priceRows.map((row) => [row.country, row.updatedAt]));
|
||||
|
||||
const prices = countryCodeSchema.options.map((country) => {
|
||||
const amount = catalog.proPrices[country];
|
||||
const rows = live.filter((row) => row.country === country);
|
||||
const queued = rows.filter((row) => row.pendingAmount !== null);
|
||||
const failed = queued.filter((row) => row.priceChangeAttempts >= MAX_PRICE_CHANGE_ATTEMPTS);
|
||||
return {
|
||||
country,
|
||||
amount,
|
||||
currency: COUNTRY_CURRENCY[country],
|
||||
provider: billingProviderForCountry(country),
|
||||
updatedAt: updatedAt.get(country)?.toISOString() ?? null,
|
||||
liveSubscriptions: rows.length,
|
||||
atOtherPrice: rows.filter(
|
||||
(row) => Number((row.pendingAmount ?? row.amount).toString()) !== amount,
|
||||
).length,
|
||||
pendingChanges: queued.length - failed.length,
|
||||
failedChanges: failed.length,
|
||||
};
|
||||
});
|
||||
|
||||
return ok({ limits: catalog.limits, prices });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { AdminAccountQuery } from '@gruperly/shared';
|
||||
import { AdminAccountQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListAccounts } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/accounts', validate.query(AdminAccountQuerySchema), async (c) => {
|
||||
const query = c.req.valid('query') as AdminAccountQuery;
|
||||
const result = await new ListAccounts().execute(query);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AdminAccountList, AdminAccountQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getGraceDays } from '@/modules/billing/lib';
|
||||
import { type AccountUsage, buildAccountWhere, toAccountListItem } from '../../lib';
|
||||
|
||||
type ListAccountsDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'group'>;
|
||||
graceDays?: number;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
/** Every professor's account, newest first, with plan and usage. */
|
||||
export class ListAccounts {
|
||||
constructor(private readonly deps: ListAccountsDeps = {}) {}
|
||||
|
||||
async execute(query: AdminAccountQuery): Promise<Result<AdminAccountList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const context = {
|
||||
now: this.deps.now?.() ?? new Date(),
|
||||
graceDays: this.deps.graceDays ?? getGraceDays(),
|
||||
};
|
||||
const where = buildAccountWhere(query, context);
|
||||
|
||||
const [users, total] = await Promise.all([
|
||||
db.user.findMany({
|
||||
where,
|
||||
include: { subscription: true },
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
db.user.count({ where }),
|
||||
]);
|
||||
|
||||
// Usage of the whole page in one query, same rule as the plan limits:
|
||||
// groups the professor owns and their ACTIVE attendees.
|
||||
const groups = users.length
|
||||
? await db.group.findMany({
|
||||
where: { createdById: { in: users.map((user) => user.id) } },
|
||||
select: {
|
||||
createdById: true,
|
||||
_count: { select: { attendees: { where: { status: 'ACTIVE' } } } },
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const usage = new Map<string, AccountUsage>();
|
||||
for (const group of groups) {
|
||||
const current = usage.get(group.createdById) ?? { groupsCount: 0, attendeesCount: 0 };
|
||||
usage.set(group.createdById, {
|
||||
groupsCount: current.groupsCount + 1,
|
||||
attendeesCount: current.attendeesCount + group._count.attendees,
|
||||
});
|
||||
}
|
||||
|
||||
return ok({
|
||||
data: users.map((user) =>
|
||||
toAccountListItem(user, usage.get(user.id) ?? { groupsCount: 0, attendeesCount: 0 }, context),
|
||||
),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/admin/features/me/route.ts
Normal file
16
apps/backend/src/modules/admin/features/me/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { AdminMeDto } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { isAdminEmail } from '../../lib';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Open to every signed-in user: the web asks it to decide whether to show the backoffice.
|
||||
route.get('/me', (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
return c.json({ isAdmin: isAdminEmail(user.email) } satisfies AdminMeDto);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { PlanLimitsImpactQuery } from '@gruperly/shared';
|
||||
import { PlanLimitsImpactQuerySchema, planSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { PlanLimitsImpact } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get(
|
||||
'/plans/:plan/impact',
|
||||
validate.param(z.object({ plan: planSchema })),
|
||||
validate.query(PlanLimitsImpactQuerySchema),
|
||||
async (c) => {
|
||||
const { plan } = c.req.valid('param');
|
||||
const query = c.req.valid('query') as PlanLimitsImpactQuery;
|
||||
const result = await new PlanLimitsImpact().execute(plan, query);
|
||||
return resultJson(c, result);
|
||||
},
|
||||
);
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { Plan, PlanLimitsImpactDto, PlanLimitsImpactQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getGraceDays, proSubscriptionWhere } from '@/modules/billing/lib';
|
||||
|
||||
type PlanLimitsImpactDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'person' | 'user'>;
|
||||
graceDays?: number;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many accounts on a plan would exceed new limits, i.e. become read only
|
||||
* as soon as they are saved (limits apply at once). Usage is the PlanGuard's:
|
||||
* groups owned, and people with at least one ACTIVE membership.
|
||||
*/
|
||||
export class PlanLimitsImpact {
|
||||
constructor(private readonly deps: PlanLimitsImpactDeps = {}) {}
|
||||
|
||||
async execute(plan: Plan, query: PlanLimitsImpactQuery): Promise<Result<PlanLimitsImpactDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
const graceDays = this.deps.graceDays ?? getGraceDays();
|
||||
|
||||
const [overGroups, overAttendees] = await Promise.all([
|
||||
query.maxGroups === null
|
||||
? []
|
||||
: db.group.groupBy({
|
||||
by: ['createdById'],
|
||||
having: { id: { _count: { gt: query.maxGroups } } },
|
||||
}),
|
||||
query.maxAttendees === null
|
||||
? []
|
||||
: db.person.groupBy({
|
||||
by: ['createdById'],
|
||||
where: { attendees: { some: { status: 'ACTIVE' } } },
|
||||
having: { id: { _count: { gt: query.maxAttendees } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const candidates = [...new Set([...overGroups, ...overAttendees].map((row) => row.createdById))];
|
||||
if (candidates.length === 0) return ok({ affectedAccounts: 0 });
|
||||
|
||||
// Same split as the PlanGuard: anyone without a live Pro is held to Free.
|
||||
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
|
||||
const affectedAccounts = await db.user.count({
|
||||
where: { id: { in: candidates }, ...(plan === 'PRO' ? isPro : { NOT: isPro }) },
|
||||
});
|
||||
return ok({ affectedAccounts });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { UpdatePlanLimitsInput } from '@gruperly/shared';
|
||||
import { planSchema, UpdatePlanLimitsInputSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { UpdatePlanLimits } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.put(
|
||||
'/plans/:plan/limits',
|
||||
validate.param(z.object({ plan: planSchema })),
|
||||
validate.json(UpdatePlanLimitsInputSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
const { plan } = c.req.valid('param');
|
||||
const input = c.req.valid('json') as UpdatePlanLimitsInput;
|
||||
const result = await new UpdatePlanLimits().execute(plan, input, user.id);
|
||||
return resultJson(c, result);
|
||||
},
|
||||
);
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { Plan, PlanLimits, ProblemDetails, Result, UpdatePlanLimitsInput } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
|
||||
|
||||
type UpdatePlanLimitsDeps = {
|
||||
db?: Pick<PrismaClient, 'planConfig'>;
|
||||
catalog?: Pick<PlanCatalog, 'invalidate'>;
|
||||
};
|
||||
|
||||
/** New limits for a plan. They apply at once to every account on it. */
|
||||
export class UpdatePlanLimits {
|
||||
constructor(private readonly deps: UpdatePlanLimitsDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
plan: Plan,
|
||||
input: UpdatePlanLimitsInput,
|
||||
adminId: string,
|
||||
): Promise<Result<PlanLimits, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const data = { ...input, updatedById: adminId };
|
||||
await db.planConfig.upsert({ where: { plan }, create: { plan, ...data }, update: data });
|
||||
(this.deps.catalog ?? planCatalog).invalidate();
|
||||
logger.info({ plan, adminId, limits: input }, 'Plan limits updated');
|
||||
return ok(input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { UpdatePlanPriceInput } from '@gruperly/shared';
|
||||
import { countryCodeSchema, UpdatePlanPriceInputSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { runPriceChanges } from '@/modules/billing/jobs';
|
||||
import { UpdatePlanPrice } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.put(
|
||||
'/plans/prices/:country',
|
||||
validate.param(z.object({ country: countryCodeSchema })),
|
||||
validate.json(UpdatePlanPriceInputSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
const { country } = c.req.valid('param');
|
||||
const input = c.req.valid('json') as UpdatePlanPriceInput;
|
||||
const result = await new UpdatePlanPrice({ applyQueued: runPriceChanges }).execute(country, input, user.id);
|
||||
return resultJson(c, result);
|
||||
},
|
||||
);
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { CountryCode, ProblemDetails, Result, UpdatePlanPriceInput, UpdatePlanPriceResultDto } from '@gruperly/shared';
|
||||
import { COUNTRY_CURRENCY, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
|
||||
import { LIVE_SUBSCRIPTION_STATUSES } from '../get-plans/use-case';
|
||||
|
||||
type UpdatePlanPriceDeps = {
|
||||
db?: Pick<PrismaClient, '$transaction'>;
|
||||
catalog?: Pick<PlanCatalog, 'invalidate' | 'getProPrice'>;
|
||||
/** Kicks the job that pushes queued prices to the providers. */
|
||||
applyQueued?: () => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* New monthly price of Pro in a country. New subscriptions take it right away.
|
||||
* With `applyToExisting`, the country's live subscriptions are queued to move
|
||||
* to it (`pending_amount`); the job tells each provider to charge it from the
|
||||
* next charge on, and emails the professor.
|
||||
*
|
||||
* PENDING subscriptions are left alone: a checkout half done keeps its amount,
|
||||
* and trying again starts a new one at the new price.
|
||||
*/
|
||||
export class UpdatePlanPrice {
|
||||
constructor(private readonly deps: UpdatePlanPriceDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
country: CountryCode,
|
||||
input: UpdatePlanPriceInput,
|
||||
adminId: string,
|
||||
): Promise<Result<UpdatePlanPriceResultDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const catalog = this.deps.catalog ?? planCatalog;
|
||||
catalog.invalidate();
|
||||
const previousAmount = await catalog.getProPrice(country);
|
||||
const currency = COUNTRY_CURRENCY[country];
|
||||
|
||||
const queued = await db.$transaction(async (tx) => {
|
||||
await tx.planPrice.upsert({
|
||||
where: { country },
|
||||
create: { country, amount: input.amount, updatedById: adminId },
|
||||
update: { amount: input.amount, updatedById: adminId },
|
||||
});
|
||||
const change = await tx.planPriceChange.create({
|
||||
data: {
|
||||
country,
|
||||
previousAmount,
|
||||
newAmount: input.amount,
|
||||
currency,
|
||||
applyToExisting: input.applyToExisting,
|
||||
createdById: adminId,
|
||||
},
|
||||
});
|
||||
if (!input.applyToExisting) return 0;
|
||||
|
||||
// Rows already at the new price (or already moving to it) are not touched.
|
||||
const moved = await tx.billingSubscription.updateMany({
|
||||
where: {
|
||||
country,
|
||||
status: { in: [...LIVE_SUBSCRIPTION_STATUSES] },
|
||||
externalId: { not: null },
|
||||
OR: [
|
||||
{ pendingAmount: null, amount: { not: input.amount } },
|
||||
{ pendingAmount: { not: null, notIn: [input.amount] } },
|
||||
],
|
||||
},
|
||||
data: {
|
||||
pendingAmount: input.amount,
|
||||
priceChangeId: change.id,
|
||||
priceChangeAttempts: 0,
|
||||
priceChangeError: null,
|
||||
},
|
||||
});
|
||||
await tx.planPriceChange.update({ where: { id: change.id }, data: { queued: moved.count } });
|
||||
return moved.count;
|
||||
});
|
||||
|
||||
catalog.invalidate();
|
||||
logger.info({ country, adminId, amount: input.amount, queued }, 'Pro price updated');
|
||||
|
||||
if (queued > 0 && this.deps.applyQueued) {
|
||||
// In the background: the providers are slow, and the cron retries anyway.
|
||||
void this.deps.applyQueued();
|
||||
}
|
||||
|
||||
return ok({ country, amount: input.amount, queued });
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/admin/index.ts
Normal file
1
apps/backend/src/modules/admin/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as adminRoutes } from './routes';
|
||||
39
apps/backend/src/modules/admin/lib/access.ts
Normal file
39
apps/backend/src/modules/admin/lib/access.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { forbiddenProblem } from '@/http/problem-builders';
|
||||
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
|
||||
/**
|
||||
* The backoffice is for Gruperly's own staff, listed by email in `ADMIN_EMAILS`
|
||||
* (comma separated, case-insensitive). An empty or missing list means nobody.
|
||||
*/
|
||||
export function isAdminEmail(
|
||||
email: string | null | undefined,
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): boolean {
|
||||
if (!email) return false;
|
||||
const allowed = (env.ADMIN_EMAILS ?? '')
|
||||
.split(',')
|
||||
.map((entry) => entry.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
return allowed.includes(email.trim().toLowerCase());
|
||||
}
|
||||
|
||||
export function adminOnlyMiddleware(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): MiddlewareHandler<BackendEnv> {
|
||||
return async (c, next) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
if (!isAdminEmail(user.email, env)) {
|
||||
return problemJson(
|
||||
c,
|
||||
forbiddenProblem({
|
||||
detail: 'Solo el equipo de Gruperly puede entrar al backoffice.',
|
||||
code: 'admin_required',
|
||||
}),
|
||||
);
|
||||
}
|
||||
await next();
|
||||
};
|
||||
}
|
||||
94
apps/backend/src/modules/admin/lib/account-summary.ts
Normal file
94
apps/backend/src/modules/admin/lib/account-summary.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { BillingSubscription, Prisma } from '@generated/prisma/client';
|
||||
import type { AdminAccountListItem, AdminAccountQuery, Plan } from '@gruperly/shared';
|
||||
import { countryCodeSchema } from '@gruperly/shared';
|
||||
import { proSubscriptionWhere, resolvePlan } from '@/modules/billing/lib';
|
||||
|
||||
export type AccountRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
country: string | null;
|
||||
createdAt: Date;
|
||||
onboardingCompleted: boolean;
|
||||
planSelectedAt: Date | null;
|
||||
subscription: BillingSubscription | null;
|
||||
};
|
||||
|
||||
export type AccountUsage = { groupsCount: number; attendeesCount: number };
|
||||
|
||||
export type PlanContext = { now: Date; graceDays: number };
|
||||
|
||||
/** Pro by its subscription; otherwise Free once chosen, `null` while not chosen. */
|
||||
export function accountPlan(
|
||||
account: Pick<AccountRecord, 'planSelectedAt' | 'subscription'>,
|
||||
{ now, graceDays }: PlanContext,
|
||||
): { plan: Plan | null; graceUntil: Date | null } {
|
||||
const resolution = resolvePlan(account.subscription, now, graceDays);
|
||||
if (resolution.plan === 'PRO') return resolution;
|
||||
return { plan: account.planSelectedAt ? 'FREE' : null, graceUntil: null };
|
||||
}
|
||||
|
||||
export function toAccountListItem(
|
||||
account: AccountRecord,
|
||||
usage: AccountUsage,
|
||||
context: PlanContext,
|
||||
): AdminAccountListItem {
|
||||
const country = countryCodeSchema.safeParse(account.country);
|
||||
const subscription = account.subscription;
|
||||
return {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
email: account.email,
|
||||
country: country.success ? country.data : null,
|
||||
createdAt: account.createdAt.toISOString(),
|
||||
onboardingCompleted: account.onboardingCompleted,
|
||||
plan: accountPlan(account, context).plan,
|
||||
subscription: subscription
|
||||
? {
|
||||
provider: subscription.provider,
|
||||
status: subscription.status,
|
||||
amount: Number(subscription.amount.toString()),
|
||||
currency: subscription.currency,
|
||||
paidThrough: subscription.paidThrough?.toISOString() ?? null,
|
||||
nextPaymentDate:
|
||||
subscription.status === 'AUTHORIZED'
|
||||
? (subscription.nextPaymentDate?.toISOString() ?? null)
|
||||
: null,
|
||||
}
|
||||
: null,
|
||||
...usage,
|
||||
};
|
||||
}
|
||||
|
||||
/** The list filters as a `user` query. The plan follows `accountPlan`. */
|
||||
export function buildAccountWhere(
|
||||
query: Pick<AdminAccountQuery, 'search' | 'country' | 'plan' | 'subscriptionStatus'>,
|
||||
{ now, graceDays }: PlanContext,
|
||||
): Prisma.UserWhereInput {
|
||||
const and: Prisma.UserWhereInput[] = [];
|
||||
|
||||
if (query.search) {
|
||||
and.push({
|
||||
OR: [
|
||||
{ name: { contains: query.search, mode: 'insensitive' } },
|
||||
{ email: { contains: query.search, mode: 'insensitive' } },
|
||||
],
|
||||
});
|
||||
}
|
||||
if (query.country) and.push({ country: query.country });
|
||||
|
||||
if (query.subscriptionStatus === 'NONE') {
|
||||
and.push({ subscription: { is: null } });
|
||||
} else if (query.subscriptionStatus) {
|
||||
and.push({ subscription: { is: { status: query.subscriptionStatus } } });
|
||||
}
|
||||
|
||||
if (query.plan) {
|
||||
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
|
||||
if (query.plan === 'PRO') and.push(isPro);
|
||||
if (query.plan === 'FREE') and.push({ planSelectedAt: { not: null }, NOT: isPro });
|
||||
if (query.plan === 'NOT_SELECTED') and.push({ planSelectedAt: null, NOT: isPro });
|
||||
}
|
||||
|
||||
return and.length > 0 ? { AND: and } : {};
|
||||
}
|
||||
9
apps/backend/src/modules/admin/lib/index.ts
Normal file
9
apps/backend/src/modules/admin/lib/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export { adminOnlyMiddleware, isAdminEmail } from './access';
|
||||
export {
|
||||
type AccountRecord,
|
||||
type AccountUsage,
|
||||
accountPlan,
|
||||
buildAccountWhere,
|
||||
type PlanContext,
|
||||
toAccountListItem,
|
||||
} from './account-summary';
|
||||
27
apps/backend/src/modules/admin/routes.ts
Normal file
27
apps/backend/src/modules/admin/routes.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Hono } from 'hono';
|
||||
import getAccountRoute from './features/get-account/route';
|
||||
import getPlansRoute from './features/get-plans/route';
|
||||
import listAccountsRoute from './features/list-accounts/route';
|
||||
import meRoute from './features/me/route';
|
||||
import planLimitsImpactRoute from './features/plan-limits-impact/route';
|
||||
import updatePlanLimitsRoute from './features/update-plan-limits/route';
|
||||
import updatePlanPriceRoute from './features/update-plan-price/route';
|
||||
import { adminOnlyMiddleware } from './lib';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', meRoute);
|
||||
|
||||
// Everything below `/me` is the backoffice itself.
|
||||
routes.use('/accounts', adminOnlyMiddleware());
|
||||
routes.use('/accounts/*', adminOnlyMiddleware());
|
||||
routes.use('/plans', adminOnlyMiddleware());
|
||||
routes.use('/plans/*', adminOnlyMiddleware());
|
||||
routes.route('/', listAccountsRoute);
|
||||
routes.route('/', getAccountRoute);
|
||||
routes.route('/', getPlansRoute);
|
||||
routes.route('/', planLimitsImpactRoute);
|
||||
routes.route('/', updatePlanLimitsRoute);
|
||||
routes.route('/', updatePlanPriceRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
|
||||
export const HISTORY_SESSIONS_LIMIT = 20;
|
||||
@@ -33,14 +34,27 @@ export class GetAttendeeHistory {
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { id: true, fullName: true },
|
||||
});
|
||||
select: { id: true, createdAt: true, person: { select: { fullName: true } } },
|
||||
}).then((row) => row && flattenPerson(row));
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
// Same effective join date as the risk rule (`toMemberAttendance`): an
|
||||
// attendee loaded after their first classes were already recorded starts
|
||||
// at that first class, not at `createdAt`. Otherwise this screen said
|
||||
// "1 de 3 clases" while the group list said "1 de 5" for the same person.
|
||||
const firstAttendance = await db.attendance.findFirst({
|
||||
where: { attendeeId },
|
||||
orderBy: { classSession: { startsAt: 'asc' } },
|
||||
select: { classSession: { select: { startsAt: true } } },
|
||||
});
|
||||
const firstClassAt = firstAttendance?.classSession.startsAt;
|
||||
const since =
|
||||
firstClassAt && firstClassAt < attendee.createdAt ? firstClassAt : attendee.createdAt;
|
||||
|
||||
const sessions = await db.classSession.findMany({
|
||||
where: { groupId },
|
||||
where: { groupId, startsAt: { gte: since } },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
take: HISTORY_SESSIONS_LIMIT,
|
||||
select: { id: true, startsAt: true },
|
||||
|
||||
@@ -6,15 +6,18 @@ import type {
|
||||
GroupsRiskOverview,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
UrgentMemberSummary,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import {
|
||||
classifyRisk,
|
||||
monthlyAttendanceRate,
|
||||
trailingAbsentStreak,
|
||||
} from '../../lib/risk';
|
||||
ATTENDANCE_RISK_RULES,
|
||||
getGroupAttendanceSummary,
|
||||
ok,
|
||||
URGENT_MEMBERS_LIMIT,
|
||||
} from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
type GetGroupsRiskOverviewDeps = {
|
||||
@@ -27,18 +30,26 @@ type GetGroupsRiskOverviewDeps = {
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
type GroupRow = { id: string; name: string };
|
||||
type AttendeeRow = { id: string; groupId: string };
|
||||
type SessionRow = { id: string; groupId: string };
|
||||
type GroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
capacity: number | null;
|
||||
/** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
||||
_count: { waitlist: number };
|
||||
};
|
||||
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
||||
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||
type AttendanceRow = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
|
||||
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
|
||||
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
|
||||
// alguno en riesgo moderado y NONE en caso contrario.
|
||||
// Risk summary per group for the group listing and Home. Everything comes from
|
||||
// the domain rule (`getGroupAttendanceSummary`): the status light is the worst
|
||||
// level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the
|
||||
// "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree.
|
||||
export class GetGroupsRiskOverview {
|
||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||
|
||||
@@ -49,30 +60,39 @@ export class GetGroupsRiskOverview {
|
||||
|
||||
const groups = (await db.group.findMany({
|
||||
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
||||
select: { id: true, name: true },
|
||||
})) as GroupRow[];
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
capacity: true,
|
||||
_count: { select: { waitlist: { where: { status: 'PENDING' } } } },
|
||||
},
|
||||
})) as unknown as GroupRow[];
|
||||
|
||||
if (groups.length === 0) {
|
||||
return ok({ items: [] });
|
||||
}
|
||||
|
||||
const groupIds = groups.map((group) => group.id);
|
||||
const attendeeGroup = new Map<string, string>();
|
||||
const sessionCountByGroup = new Map<string, number>();
|
||||
|
||||
const [attendees, sessions, attendances] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } },
|
||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||
db.classSession.findMany({
|
||||
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
|
||||
select: { id: true, groupId: true },
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}) as Promise<SessionRow[]>,
|
||||
/* No date filter, as before: the status light streak counts over the
|
||||
attendee's full history, not over the monthly window. No cap either:
|
||||
the cut to the last 20 classes is done by `memberSessions`, over the
|
||||
group's classes and not over these rows. */
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: {
|
||||
attendeeId: true,
|
||||
classSessionId: true,
|
||||
status: true,
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
@@ -80,51 +100,93 @@ export class GetGroupsRiskOverview {
|
||||
}) as Promise<AttendanceRow[]>,
|
||||
]);
|
||||
|
||||
for (const attendee of attendees) {
|
||||
attendeeGroup.set(attendee.id, attendee.groupId);
|
||||
}
|
||||
const sessionsByGroup = new Map<string, SessionRow[]>();
|
||||
for (const session of sessions) {
|
||||
sessionCountByGroup.set(session.groupId, (sessionCountByGroup.get(session.groupId) ?? 0) + 1);
|
||||
const list = sessionsByGroup.get(session.groupId) ?? [];
|
||||
list.push(session);
|
||||
sessionsByGroup.set(session.groupId, list);
|
||||
}
|
||||
|
||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||
|
||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
||||
for (const attendee of attendees) {
|
||||
const groupId = attendeeGroup.get(attendee.id)!;
|
||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
||||
status: row.status,
|
||||
occurredAt: row.classSession.startsAt,
|
||||
}));
|
||||
const streak = trailingAbsentStreak(stream);
|
||||
const monthlyRate = monthlyAttendanceRate(
|
||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
||||
sessionCountByGroup.get(groupId) ?? 0,
|
||||
const items: GroupRiskSummary[] = groups.map((group) =>
|
||||
buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
|
||||
);
|
||||
const riskLevel = classifyRisk(streak, monthlyRate);
|
||||
if (!riskLevel) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
|
||||
if (
|
||||
riskLevel === 'HIGH' ||
|
||||
(riskLevel === 'MEDIUM' && current === 'NONE')
|
||||
) {
|
||||
worstRiskByGroup.set(groupId, riskLevel);
|
||||
}
|
||||
}
|
||||
|
||||
const items: GroupRiskSummary[] = groups.map((group) => ({
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
|
||||
}));
|
||||
|
||||
return ok({ items });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-level summary consumed by the listing card and Home. It comes from
|
||||
* `getGroupAttendanceSummary`, the same domain function that
|
||||
* `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
||||
* copies: one here and another in the client.
|
||||
*
|
||||
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
|
||||
* summary counts the group members and the card needs the capacity slots to
|
||||
* paint the indicator.
|
||||
*/
|
||||
function buildSummary(
|
||||
group: GroupRow,
|
||||
attendees: AttendeeRow[],
|
||||
sessionsByGroup: Map<string, SessionRow[]>,
|
||||
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
||||
now: Date,
|
||||
): GroupRiskSummary {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: group.id,
|
||||
capacity: group.capacity,
|
||||
waitlistCount: group._count.waitlist,
|
||||
now,
|
||||
members: attendees
|
||||
.filter((attendee) => attendee.groupId === group.id)
|
||||
.map((attendee) =>
|
||||
toMemberAttendance(
|
||||
attendee,
|
||||
sessionsByGroup.get(group.id) ?? [],
|
||||
attendanceByAttendee.get(attendee.id) ?? [],
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
// Why there is risk, over every member and not only the urgent ones sent to
|
||||
// the client. Disjoint: an absence streak counts in the first and only
|
||||
// there; the second groups the rest (inactivity or a declining trend).
|
||||
const atRisk = resumen.urgentes.filter((member) => member.level !== 'ok');
|
||||
const absenceStreakCount = atRisk.filter(
|
||||
(member) => member.consecutiveAbsences >= ATTENDANCE_RISK_RULES.attentionAbsenceStreak,
|
||||
).length;
|
||||
|
||||
const urgentes: UrgentMemberSummary[] = resumen.urgentes
|
||||
.slice(0, URGENT_MEMBERS_LIMIT)
|
||||
.map((urgente) => ({
|
||||
attendeeId: urgente.attendeeId,
|
||||
fullName: urgente.fullName,
|
||||
level: urgente.level,
|
||||
consecutiveAbsences: urgente.consecutiveAbsences,
|
||||
daysSinceLastAttendance: urgente.daysSinceLastAttendance,
|
||||
attendanceRate: urgente.attendanceRate,
|
||||
}));
|
||||
|
||||
const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE';
|
||||
|
||||
return {
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
riskLevel,
|
||||
absenceStreakCount,
|
||||
lowAttendanceCount: atRisk.length - absenceStreakCount,
|
||||
riesgoAlto: resumen.riesgoAlto,
|
||||
atencion: resumen.atencion,
|
||||
ok: resumen.ok,
|
||||
libres: resumen.libres,
|
||||
enEspera: resumen.enEspera,
|
||||
asistencia: resumen.asistencia,
|
||||
urgentes,
|
||||
};
|
||||
}
|
||||
|
||||
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
||||
const byAttendee = new Map<string, AttendanceRow[]>();
|
||||
for (const row of rows) {
|
||||
|
||||
@@ -6,24 +6,22 @@ import type {
|
||||
StudentAtRisk,
|
||||
StudentsAtRisk,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
import {
|
||||
classifyRisk,
|
||||
lastAttendedAt,
|
||||
monthlyAttendanceRate,
|
||||
trailingAbsentStreak,
|
||||
} from '../../lib/risk';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
type GetStudentsAtRiskDeps = {
|
||||
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
|
||||
db?: AnalyticsAccessDb & StudentsAtRiskDb;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
type AttendanceStreamRow = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
@@ -37,26 +35,52 @@ export class GetStudentsAtRisk {
|
||||
): Promise<Result<StudentsAtRisk, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) {
|
||||
return access;
|
||||
}
|
||||
|
||||
const atRisk = await findStudentsAtRisk(db, groupId, now);
|
||||
|
||||
return ok({
|
||||
groupName: access.value.name,
|
||||
data: atRisk,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
|
||||
|
||||
/**
|
||||
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
|
||||
* the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged
|
||||
* with the same domain rule as the group listing and Home
|
||||
* (`summarizeMemberAttendance`), so every screen agrees on who is at risk.
|
||||
* Does not check access: callers do.
|
||||
*/
|
||||
export async function findStudentsAtRisk(
|
||||
db: StudentsAtRiskDb,
|
||||
groupId: string,
|
||||
now: Date,
|
||||
): Promise<StudentAtRisk[]> {
|
||||
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
||||
|
||||
const [windowSessions, attendees, attendances] = await Promise.all([
|
||||
db.classSession.findMany({
|
||||
where: { groupId, startsAt: { gte: since } },
|
||||
select: { id: true },
|
||||
select: { id: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}),
|
||||
db.attendee.findMany({
|
||||
where: { groupId, status: 'ACTIVE' },
|
||||
select: { id: true, fullName: true, phone: true },
|
||||
}),
|
||||
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
|
||||
}).then((rows) => rows.map(flattenPerson)),
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId } },
|
||||
select: {
|
||||
attendeeId: true,
|
||||
classSessionId: true,
|
||||
status: true,
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
@@ -69,20 +93,21 @@ export class GetStudentsAtRisk {
|
||||
|
||||
const atRisk: StudentAtRisk[] = [];
|
||||
for (const attendee of attendees) {
|
||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
||||
status: row.status,
|
||||
occurredAt: row.classSession.startsAt,
|
||||
}));
|
||||
const consecutiveAbsences = trailingAbsentStreak(stream);
|
||||
const rows = streamByAttendee.get(attendee.id) ?? [];
|
||||
const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
|
||||
const riskLevel = toRiskLevel(signals.level);
|
||||
if (!riskLevel) {
|
||||
continue;
|
||||
}
|
||||
// Display only: the verdict is the domain's. The rate keeps counting
|
||||
// unrecorded classes as missed, which is what "asistencia mensual" says.
|
||||
const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt }));
|
||||
const consecutiveAbsences = signals.consecutiveAbsences;
|
||||
const attendedAt = lastAttendedAt(stream);
|
||||
const monthlyRate = monthlyAttendanceRate(
|
||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
||||
totalWindowSessions,
|
||||
);
|
||||
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
|
||||
if (!riskLevel) {
|
||||
continue;
|
||||
}
|
||||
atRisk.push({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
@@ -104,11 +129,7 @@ export class GetStudentsAtRisk {
|
||||
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
|
||||
});
|
||||
|
||||
return ok({
|
||||
groupName: access.value.name,
|
||||
data: atRisk,
|
||||
});
|
||||
}
|
||||
return atRisk;
|
||||
}
|
||||
|
||||
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
|
||||
|
||||
@@ -12,7 +12,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo. Devuelve el grupo si tiene acceso.
|
||||
// Verifies the user is the group owner or a member. Returns the group if they have access.
|
||||
export async function findGroupForUser(
|
||||
db: AnalyticsAccessDb,
|
||||
groupId: string,
|
||||
|
||||
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberClassSession, RiskLevel } from '@gruperly/shared';
|
||||
|
||||
/* How many classes we look back per attendee. That is the real ceiling of the
|
||||
model: `class_sessions` are not created on their own, they get materialized
|
||||
when someone opens "today's classes", so pulling years of rows makes no
|
||||
sense. 20 classes is enough for the streak, for the 6-class window and for
|
||||
the attendance rate the card shows. */
|
||||
export const MEMBER_HISTORY_LIMIT = 20;
|
||||
|
||||
export type MemberAttendeeRow = { id: string; fullName: string; createdAt: Date };
|
||||
export type MemberSessionRow = { id: string; startsAt: Date };
|
||||
export type MemberAttendanceRow = {
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
|
||||
/**
|
||||
* The input of the domain risk rule (`summarizeMemberAttendance` in shared) for
|
||||
* one attendee. The group listing, Home, the "Alumnos en riesgo" screen and the
|
||||
* re-engagement job all build it here, so they can't disagree on who is at risk.
|
||||
*
|
||||
* `groupSessions` must come most recent first (as the queries order them).
|
||||
*/
|
||||
export function toMemberAttendance(
|
||||
attendee: MemberAttendeeRow,
|
||||
groupSessions: MemberSessionRow[],
|
||||
attendances: MemberAttendanceRow[],
|
||||
): MemberAttendance {
|
||||
// If the attendee has attendances before their enrollment date in the DB
|
||||
// (e.g. created today but with past classes already recorded), their
|
||||
// effective join date is the first class they were marked for.
|
||||
const earliestAttendance = attendances.reduce<Date | null>(
|
||||
(earliest, att) =>
|
||||
!earliest || att.classSession.startsAt < earliest ? att.classSession.startsAt : earliest,
|
||||
null,
|
||||
);
|
||||
const enrolledAt =
|
||||
earliestAttendance && earliestAttendance < attendee.createdAt
|
||||
? earliestAttendance
|
||||
: attendee.createdAt;
|
||||
|
||||
return {
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
enrolledAt: enrolledAt.toISOString(),
|
||||
sessions: memberSessions(groupSessions, attendances),
|
||||
};
|
||||
}
|
||||
|
||||
/** The domain level as the at-risk endpoints speak it; `null` for `ok`. */
|
||||
export function toRiskLevel(level: AttendanceRiskLevel): RiskLevel | null {
|
||||
if (level === 'riesgo_alto') return 'HIGH';
|
||||
if (level === 'atencion') return 'MEDIUM';
|
||||
return null;
|
||||
}
|
||||
|
||||
/* The universe of classes is the group's, not the `Attendance` rows'.
|
||||
Attendance is recorded attendee by attendee and only when someone marks a
|
||||
class, so "this class happened and this attendee has no record" is a real
|
||||
and frequent state, not an absence. If the list were built from the
|
||||
attendance rows those classes wouldn't exist and the streak wouldn't break:
|
||||
two absences separated by an unmarked class would count as three in a row.
|
||||
The domain already treats them as neutral (`status: null`), so all that is
|
||||
left here is to pick the right universe and keep the criterion on one side.
|
||||
`sessions` comes from most recent to oldest, so keeping the first
|
||||
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
|
||||
and not global, so a group with a long history doesn't steal window from
|
||||
the groups listed after it. */
|
||||
function memberSessions(
|
||||
sessions: MemberSessionRow[],
|
||||
attendances: MemberAttendanceRow[],
|
||||
): MemberClassSession[] {
|
||||
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
|
||||
|
||||
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
|
||||
sessionId: session.id,
|
||||
startsAt: session.startsAt.toISOString(),
|
||||
status: statusBySession.get(session.id) ?? null,
|
||||
}));
|
||||
}
|
||||
@@ -3,22 +3,7 @@ export type AttendanceStreamEntry = {
|
||||
occurredAt: Date;
|
||||
};
|
||||
|
||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
||||
|
||||
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
|
||||
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
|
||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
let streak = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.status !== 'ABSENT') {
|
||||
break;
|
||||
}
|
||||
streak += 1;
|
||||
}
|
||||
return streak;
|
||||
}
|
||||
|
||||
// Fecha de la última clase a la que el alumno asistió (PRESENT), o null.
|
||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.status === 'PRESENT') {
|
||||
@@ -28,8 +13,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Porcentaje de asistencia sobre el total de sesiones del período.
|
||||
// Las sesiones sin registrar cuentan como no asistidas.
|
||||
// Attendance rate over the total number of sessions in the period.
|
||||
// Sessions with no record count as not attended.
|
||||
export function monthlyAttendanceRate(
|
||||
entries: AttendanceStreamEntry[],
|
||||
totalSessions: number,
|
||||
@@ -40,17 +25,3 @@ export function monthlyAttendanceRate(
|
||||
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
|
||||
return Math.round((present / totalSessions) * 100);
|
||||
}
|
||||
|
||||
// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 50%.
|
||||
export function classifyRisk(
|
||||
consecutiveAbsences: number,
|
||||
monthlyRate: number,
|
||||
): RiskLevel | null {
|
||||
if (consecutiveAbsences >= 3) {
|
||||
return 'HIGH';
|
||||
}
|
||||
if (consecutiveAbsences === 2 || monthlyRate < 50) {
|
||||
return 'MEDIUM';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared';
|
||||
import { AddAttendeeToGroupSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { AddAttendeeToGroup } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new AddAttendeeToGroup();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
|
||||
import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type AddAttendeeToGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
};
|
||||
|
||||
type AddAttendeeToGroupCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
targetGroupId: string;
|
||||
};
|
||||
|
||||
/* "Agregar a otro grupo": the same person gets a membership in another group of
|
||||
the teacher and keeps this one. It does not take a new student slot of the
|
||||
plan (the person is already counted) but the target's capacity applies. A
|
||||
former membership there (DROPPED) is reactivated, history included. */
|
||||
export class AddAttendeeToGroup {
|
||||
constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {}
|
||||
|
||||
async execute(command: AddAttendeeToGroupCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, targetGroupId } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!sourceResult.ok) return sourceResult;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
if (targetGroupId === groupId) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'El miembro ya pertenece a este grupo.',
|
||||
code: 'attendee_same_group',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
|
||||
if (!targetResult.ok) return targetResult;
|
||||
const target = targetResult.value;
|
||||
|
||||
try {
|
||||
return await unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const former = await tx.attendee.findFirst({
|
||||
where: { groupId: targetGroupId, personId: attendee.personId },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem());
|
||||
|
||||
const canJoin = await checkCanJoinGroup(tx, target, null);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const membership = former
|
||||
? await tx.attendee.update({
|
||||
where: { id: former.id },
|
||||
data: { status: 'ACTIVE' },
|
||||
include: attendeeWithPerson,
|
||||
})
|
||||
: await tx.attendee.create({
|
||||
data: { groupId: targetGroupId, personId: attendee.personId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(membership));
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
// Two clicks at once: the unique (group, person) lets only one through.
|
||||
if (isUniqueViolation(error)) return err(alreadyInGroupProblem());
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { phoneVariants } from '@/modules/people/lib/people';
|
||||
import { normalizePhone } from '../../lib/helpers';
|
||||
|
||||
type AddToGroupWaitlistDeps = {
|
||||
@@ -72,10 +73,7 @@ export class AddToGroupWaitlist {
|
||||
const existingAttendee = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
person: { phone: { in: phoneVariants(payload.phone) } },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -8,10 +8,12 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type BulkCreateAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
export class BulkCreateAttendeesUseCase {
|
||||
@@ -41,23 +43,29 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Cargar teléfonos existentes del grupo
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
/* The teacher's people by phone: a row whose phone is already someone they
|
||||
have is added to this group as that person (linked), unless that person
|
||||
is already in the group (duplicate). */
|
||||
const people = await db.person.findMany({
|
||||
where: { createdById: group.createdById, phone: { not: null } },
|
||||
select: {
|
||||
id: true,
|
||||
phone: true,
|
||||
attendees: { select: { groupId: true, status: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const existingPhones = new Set<string>();
|
||||
for (const a of existingAttendees) {
|
||||
if (a.phone) {
|
||||
existingPhones.add(normalizePhone(a.phone));
|
||||
}
|
||||
const peopleByPhone = new Map<string, (typeof people)[number]>();
|
||||
for (const person of people) {
|
||||
if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person);
|
||||
}
|
||||
|
||||
let duplicatesCount = 0;
|
||||
let invalidCount = 0;
|
||||
const toCreateData: Array<{
|
||||
groupId: string;
|
||||
// Only people not active in any group take a new slot of the plan.
|
||||
let newlyCounted = 0;
|
||||
const seenPhones = new Set<string>();
|
||||
const toLink: string[] = [];
|
||||
const toCreate: Array<{
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
@@ -73,14 +81,21 @@ export class BulkCreateAttendeesUseCase {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existingPhones.has(phone)) {
|
||||
const existing = peopleByPhone.get(phone);
|
||||
if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) {
|
||||
duplicatesCount++;
|
||||
continue;
|
||||
}
|
||||
seenPhones.add(phone);
|
||||
|
||||
existingPhones.add(phone);
|
||||
toCreateData.push({
|
||||
groupId,
|
||||
if (existing) {
|
||||
toLink.push(existing.id);
|
||||
if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++;
|
||||
continue;
|
||||
}
|
||||
|
||||
newlyCounted++;
|
||||
toCreate.push({
|
||||
fullName: rawFullName,
|
||||
phone,
|
||||
email: item.email?.trim() || null,
|
||||
@@ -88,20 +103,48 @@ export class BulkCreateAttendeesUseCase {
|
||||
});
|
||||
}
|
||||
|
||||
// All or nothing: a partial import that stops at the limit is harder to
|
||||
// reason about than a clear "your plan allows N".
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
||||
group.createdById,
|
||||
newlyCounted,
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const createdRecords: AttendeeRecord[] = [];
|
||||
for (const data of toCreateData) {
|
||||
const record = await db.attendee.create({ data });
|
||||
createdRecords.push(record as unknown as AttendeeRecord);
|
||||
for (const personId of toLink) {
|
||||
createdRecords.push(
|
||||
await db.attendee.create({
|
||||
data: { groupId, personId },
|
||||
include: attendeeWithPerson,
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const data of toCreate) {
|
||||
createdRecords.push(
|
||||
await db.attendee.create({
|
||||
data: {
|
||||
group: { connect: { id: groupId } },
|
||||
person: { create: { ...data, createdById: group.createdById } },
|
||||
},
|
||||
include: attendeeWithPerson,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const createdCount = createdRecords.length;
|
||||
const linkedCount = toLink.length;
|
||||
const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : '';
|
||||
const message = duplicatesCount > 0
|
||||
? `${createdCount} alumnos agregados con éxito, ${duplicatesCount} duplicados omitidos.`
|
||||
: `${createdCount} alumnos agregados con éxito.`;
|
||||
? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.`
|
||||
: `${createdCount} alumnos agregados con éxito${linkedNote}.`;
|
||||
|
||||
return ok({
|
||||
totalProcessed: payload.attendees.length,
|
||||
createdCount,
|
||||
linkedCount,
|
||||
duplicatesCount,
|
||||
invalidCount,
|
||||
message,
|
||||
|
||||
@@ -4,15 +4,22 @@ import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
alreadyWaitlistedProblem,
|
||||
capacityReachedProblem,
|
||||
conflictProblem,
|
||||
noGroupAccessProblem,
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import {
|
||||
alreadyInGroupProblem,
|
||||
findPersonByPhone,
|
||||
isUniqueViolation,
|
||||
personExistsProblem,
|
||||
} from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type CreateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
type CreateAttendeeOptions = {
|
||||
@@ -48,26 +55,38 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
|
||||
const phone = normalizePhone(payload.phone);
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
/* The person: the one the form picked (`personId`, after the "ya existe"
|
||||
hint) or a new one. A phone the teacher already has is never duplicated. */
|
||||
let person: { id: string; fullName: string } | null = null;
|
||||
if (payload.personId) {
|
||||
person = await db.person.findFirst({
|
||||
where: { id: payload.personId, createdById: group.createdById },
|
||||
select: { id: true, fullName: true },
|
||||
});
|
||||
if (!person) {
|
||||
return err(notFoundResourceProblem('Person', payload.personId));
|
||||
}
|
||||
} else {
|
||||
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
|
||||
if (samePhone) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
}),
|
||||
samePhone.attendees.some((membership) => membership.groupId === groupId)
|
||||
? alreadyInGroupProblem()
|
||||
: personExistsProblem(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
// A former member (DROPPED) comes back on the same membership: history included.
|
||||
const membership = person
|
||||
? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } })
|
||||
: null;
|
||||
if (membership && membership.status !== 'DROPPED') {
|
||||
return err(alreadyInGroupProblem());
|
||||
}
|
||||
|
||||
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
@@ -106,19 +125,51 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
// The owner's plan pays for the attendee, whoever adds it. It counts people:
|
||||
// someone already active in another group does not take a new slot.
|
||||
const alreadyCounted = person
|
||||
? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0
|
||||
: false;
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
||||
group.createdById,
|
||||
alreadyCounted ? 0 : 1,
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
try {
|
||||
const attendee = membership
|
||||
? await db.attendee.update({
|
||||
where: { id: membership.id },
|
||||
data: { status: 'ACTIVE' },
|
||||
include: attendeeWithPerson,
|
||||
})
|
||||
: await db.attendee.create({
|
||||
data: {
|
||||
groupId,
|
||||
group: { connect: { id: groupId } },
|
||||
person: person
|
||||
? { connect: { id: person.id } }
|
||||
: {
|
||||
create: {
|
||||
createdById: group.createdById,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
notes: payload.notes?.trim() || null,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
|
||||
return ok({
|
||||
outcome: 'created',
|
||||
attendee: toAttendeeDto(attendee as unknown as AttendeeRecord),
|
||||
});
|
||||
return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) });
|
||||
} catch (error) {
|
||||
// Lost a race: someone created that person or membership meanwhile.
|
||||
if (isUniqueViolation(error)) {
|
||||
return err(person ? alreadyInGroupProblem() : personExistsProblem());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers';
|
||||
import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers';
|
||||
|
||||
type ListAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee'>;
|
||||
@@ -18,17 +18,37 @@ export class ListAttendees {
|
||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
/* Each row's summary travels in the same query instead of being built
|
||||
with one request per member. Both relations are capped on purpose:
|
||||
the payments table grows one row per month forever, and the listing
|
||||
only needs each person's current state. */
|
||||
db.attendee.findMany({
|
||||
...(where ? { where } : {}),
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
...attendeeWithPerson,
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
select: { status: true },
|
||||
},
|
||||
payments: {
|
||||
where: { status: { not: 'CANCELLED' } },
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 3,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
where ? db.attendee.count({ where }) : db.attendee.count(),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map((r) => toAttendeeDto(r as AttendeeRecord)),
|
||||
data: records.map((record) => toAttendeeListItemDto(record)),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
|
||||
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
||||
|
||||
type GetAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export class GetAttendee {
|
||||
@@ -18,7 +19,7 @@ export class GetAttendee {
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
): Promise<Result<AttendeeDetailDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
@@ -26,11 +27,40 @@ export class GetAttendee {
|
||||
return access;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const billingPeriod = currentMonthRange((this.deps.now ?? (() => new Date()))());
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
include: {
|
||||
person: { select: { ...personContactSelect, ...personMembershipsSelect } },
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
dueDate: { gte: billingPeriod.start, lt: billingPeriod.end },
|
||||
},
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 1,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
return ok(toAttendeeDto(attendee));
|
||||
const { attendees: memberships, ...person } = attendee.person;
|
||||
return ok(
|
||||
toAttendeeDetailDto({
|
||||
...attendee,
|
||||
person,
|
||||
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function currentMonthRange(now: Date) {
|
||||
return {
|
||||
start: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),
|
||||
end: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)),
|
||||
};
|
||||
}
|
||||
|
||||
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared';
|
||||
import { MoveAttendeeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { MoveAttendee } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new MoveAttendee();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
77
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
77
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type MoveAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
type MoveAttendeeCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
targetGroupId: string;
|
||||
};
|
||||
|
||||
/* Moves a member to another group of the same teacher. It is the same attendee
|
||||
with another `groupId`: past attendance, fees (they stay owed to the old
|
||||
group) and the student app access go with them. Only what was booked for
|
||||
the old group's future classes is undone: absence notices, the EXCUSED rows
|
||||
they left and the released slots. */
|
||||
export class MoveAttendee {
|
||||
constructor(private readonly deps: MoveAttendeeDeps = {}) {}
|
||||
|
||||
async execute(command: MoveAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, targetGroupId } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
|
||||
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!sourceResult.ok) return sourceResult;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
if (targetGroupId === groupId) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'El miembro ya pertenece a este grupo.',
|
||||
code: 'attendee_same_group',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
|
||||
if (!targetResult.ok) return targetResult;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
|
||||
await tx.absenceNotice.updateMany({
|
||||
where: { attendeeId, cancelledAt: null, ...futureOldClasses },
|
||||
data: { cancelledAt: now },
|
||||
});
|
||||
await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } });
|
||||
await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } });
|
||||
|
||||
const moved = await tx.attendee.update({
|
||||
where: { id: attendeeId },
|
||||
data: { groupId: targetGroupId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(moved));
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,10 @@ export class RemoveAttendee {
|
||||
}
|
||||
const group = groupResult.value;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
@@ -49,6 +52,10 @@ export class RemoveAttendee {
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => {
|
||||
await tx.attendee.delete({ where: { id: attendeeId } });
|
||||
// Their last group: the person goes too (with their student app link).
|
||||
await tx.person.deleteMany({
|
||||
where: { id: attendee.personId, attendees: { none: {} } },
|
||||
});
|
||||
|
||||
if (!options.promoteFromWaitlist) {
|
||||
return ok({ removedAttendeeId: attendeeId, promoted: null });
|
||||
|
||||
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { UpdateAttendee } from '@gruperly/shared';
|
||||
import { UpdateAttendeeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { UpdateAttendeeDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.patch('/:groupId/attendees/:attendeeId', validate.json(UpdateAttendeeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new UpdateAttendeeDetails();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
input: c.req.valid('json') as UpdateAttendee,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result, UpdateAttendee } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type UpdateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
|
||||
};
|
||||
|
||||
type UpdateAttendeeCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
input: UpdateAttendee;
|
||||
};
|
||||
|
||||
export class UpdateAttendeeDetails {
|
||||
constructor(private readonly deps: UpdateAttendeeDeps = {}) {}
|
||||
|
||||
async execute(command: UpdateAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, input } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
// Contact data is the person's: the change shows in every group they are in.
|
||||
try {
|
||||
await db.person.update({
|
||||
where: { id: attendee.personId },
|
||||
data: normalizeEditableFields(input),
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.attendee.findUniqueOrThrow({
|
||||
where: { id: attendeeId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(updated));
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
|
||||
return Object.fromEntries(
|
||||
Object.entries(input).map(([key, value]) => {
|
||||
if (value === '') return [key, null];
|
||||
// Same normalization as the add form, so the phone keeps matching.
|
||||
if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)];
|
||||
return [key, value];
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -1,38 +1,112 @@
|
||||
import type { AttendeeDto } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
|
||||
export type AttendeeRecord = {
|
||||
/* Contact data of the person behind an attendee (shared by all their groups). */
|
||||
export const personContactSelect = {
|
||||
id: true,
|
||||
fullName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
guardianName: true,
|
||||
guardianPhone: true,
|
||||
notes: true,
|
||||
} as const;
|
||||
|
||||
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
||||
export const attendeeWithPerson = { person: { select: personContactSelect } } as const;
|
||||
|
||||
export type PersonContactRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
guardianName: string | null;
|
||||
guardianPhone: string | null;
|
||||
notes: string | null;
|
||||
};
|
||||
|
||||
export type AttendeeRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
personId: string;
|
||||
notifyToken?: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
person: PersonContactRecord;
|
||||
};
|
||||
|
||||
/** Listing item with the attendance and payment summary already resolved. */
|
||||
export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
|
||||
payments: {
|
||||
status: NonNullable<AttendeeListItem['payment']>['status'];
|
||||
dueDate: Date;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||
payments: AttendeeListItemRecord['payments'];
|
||||
otherGroups: AttendeeDetailDto['otherGroups'];
|
||||
};
|
||||
|
||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
email: record.email,
|
||||
phone: record.phone,
|
||||
guardianName: record.guardianName,
|
||||
guardianPhone: record.guardianPhone,
|
||||
notes: record.notes,
|
||||
personId: record.personId,
|
||||
fullName: record.person.fullName,
|
||||
email: record.person.email,
|
||||
phone: record.person.phone,
|
||||
guardianName: record.person.guardianName,
|
||||
guardianPhone: record.person.guardianPhone,
|
||||
notes: record.person.notes,
|
||||
notifyToken: record.notifyToken ?? null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/* The row that summarizes the current charge. If something is unpaid the
|
||||
oldest due date wins: someone carrying an old charge has to see how many
|
||||
days late they are, not the due date of a new charge. If nothing is left
|
||||
unpaid, the last closed payment serves to mark the row as ok. */
|
||||
function pickRelevantPayment(
|
||||
payments: AttendeeListItemRecord['payments'],
|
||||
): AttendeeListItem['payment'] {
|
||||
// CANCELLED is not a charge. The query already filters them out, but dropping
|
||||
// them here too keeps a voided charge from winning the row for being the oldest.
|
||||
const byDueDate = payments
|
||||
.filter((payment) => payment.status !== 'CANCELLED')
|
||||
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());
|
||||
const outstanding = byDueDate.find((payment) => payment.status !== 'PAID');
|
||||
const relevant = outstanding ?? byDueDate[byDueDate.length - 1];
|
||||
|
||||
if (!relevant) {
|
||||
return null;
|
||||
}
|
||||
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
|
||||
}
|
||||
|
||||
export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetailDto {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
payment: pickRelevantPayment(record.payments),
|
||||
otherGroups: record.otherGroups,
|
||||
};
|
||||
}
|
||||
|
||||
/* The query comes in descending order; the row shows them from oldest to most
|
||||
recent so the dot on the right is the latest event. */
|
||||
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
recentAttendance: [...record.attendances].reverse().map((attendance) => attendance.status),
|
||||
payment: pickRelevantPayment(record.payments),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
|
||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||
* Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
|
||||
* Keeps a leading '+' for international numbers.
|
||||
*/
|
||||
export function normalizePhone(rawPhone: string): string {
|
||||
const trimmed = rawPhone.trim();
|
||||
@@ -40,3 +114,13 @@ export function normalizePhone(rawPhone: string): string {
|
||||
const digitsOnly = trimmed.replace(/\D/g, '');
|
||||
return hasPlus ? `+${digitsOnly}` : digitsOnly;
|
||||
}
|
||||
|
||||
/* For queries that select a few person fields next to the attendee's: turns
|
||||
`{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading
|
||||
flat rows stays as it was. */
|
||||
export function flattenPerson<TRow extends { person: object }>(
|
||||
row: TRow,
|
||||
): Omit<TRow, 'person'> & TRow['person'] {
|
||||
const { person, ...rest } = row;
|
||||
return { ...rest, ...person };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetAttentionOverview } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const useCase = new GetAttentionOverview();
|
||||
const result = await useCase.execute(user.id);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import type {
|
||||
AttendanceStatus,
|
||||
AttentionGroup,
|
||||
AttentionMember,
|
||||
AttentionOverview,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
StudentAlertType,
|
||||
} from '@gruperly/shared';
|
||||
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { contactPhone } from '@/modules/people/lib/people';
|
||||
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
||||
|
||||
type GetAttentionOverviewDeps = {
|
||||
db?: {
|
||||
group: Prisma.GroupDelegate;
|
||||
attendee: Prisma.AttendeeDelegate;
|
||||
classSession: Prisma.ClassSessionDelegate;
|
||||
attendance: Prisma.AttendanceDelegate;
|
||||
payment: Prisma.PaymentDelegate;
|
||||
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
|
||||
user: Prisma.UserDelegate;
|
||||
};
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
type GroupRow = { id: string; name: string; capacity: number | null };
|
||||
type AttendeeRow = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
phone: string | null;
|
||||
guardianPhone: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||
type AttendanceRow = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
type PaymentRow = {
|
||||
id: string;
|
||||
attendeeId: string;
|
||||
amount: Prisma.Decimal;
|
||||
currency: string;
|
||||
dueDate: Date;
|
||||
checkoutUrl: string | null;
|
||||
};
|
||||
type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string };
|
||||
|
||||
/* Every ACTIVE member of the user's groups with their alerts ("Requiere
|
||||
atención"). The list screen draws all the avatars from here, so it returns
|
||||
members without alerts too. The rule is `computeStudentAlerts` (shared) over
|
||||
the same attendance input the risk overview builds (`toMemberAttendance`). */
|
||||
export class GetAttentionOverview {
|
||||
constructor(private readonly deps: GetAttentionOverviewDeps = {}) {}
|
||||
|
||||
async execute(userId: string): Promise<Result<AttentionOverview, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const groups = (await db.group.findMany({
|
||||
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
||||
select: { id: true, name: true, capacity: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
})) as GroupRow[];
|
||||
|
||||
if (groups.length === 0) {
|
||||
return ok({ groups: [] });
|
||||
}
|
||||
|
||||
const groupIds = groups.map((group) => group.id);
|
||||
|
||||
const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([
|
||||
// Phones are stored the way people write them (`11 2345-6789`): the
|
||||
// professor's country settles the calling code, as in the WhatsApp jobs.
|
||||
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: {
|
||||
id: true,
|
||||
groupId: true,
|
||||
createdAt: true,
|
||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||
// Past classes only, most recent first: `toMemberAttendance` keeps the
|
||||
// last 20 per attendee, more than the 6-class window needs.
|
||||
db.classSession.findMany({
|
||||
where: { groupId: { in: groupIds }, startsAt: { lte: now } },
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}) as Promise<SessionRow[]>,
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
|
||||
select: {
|
||||
attendeeId: true,
|
||||
classSessionId: true,
|
||||
status: true,
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
}) as Promise<AttendanceRow[]>,
|
||||
db.payment.findMany({
|
||||
where: {
|
||||
groupId: { in: groupIds },
|
||||
status: 'OVERDUE',
|
||||
attendee: { status: 'ACTIVE' },
|
||||
// A fee the student reported (with a receipt) is out of the alert while
|
||||
// the teacher reviews it; a rejection brings it back.
|
||||
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
|
||||
},
|
||||
select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true },
|
||||
orderBy: { dueDate: 'asc' },
|
||||
}) as Promise<PaymentRow[]>,
|
||||
db.attendeeAlertResolution.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: { attendeeId: true, kind: true, signature: true },
|
||||
}) as Promise<ResolutionRow[]>,
|
||||
]);
|
||||
|
||||
const country = countryCodeSchema.safeParse(owner?.country);
|
||||
const sessionsByGroup = groupBy(sessions, (session) => session.groupId);
|
||||
const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId);
|
||||
const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId);
|
||||
const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId);
|
||||
const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId);
|
||||
|
||||
const items: AttentionGroup[] = groups.map((group) => ({
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
capacity: group.capacity,
|
||||
members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => {
|
||||
const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({
|
||||
id: payment.id,
|
||||
amount: Number(payment.amount),
|
||||
currency: payment.currency,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
}));
|
||||
const alerts = computeStudentAlerts(
|
||||
{
|
||||
attendance: toMemberAttendance(
|
||||
attendee,
|
||||
sessionsByGroup.get(group.id) ?? [],
|
||||
attendanceByAttendee.get(attendee.id) ?? [],
|
||||
),
|
||||
overduePayments,
|
||||
},
|
||||
now,
|
||||
);
|
||||
const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({
|
||||
tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType,
|
||||
firma: row.signature,
|
||||
}));
|
||||
|
||||
const phone = contactPhone(attendee);
|
||||
return {
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
phone,
|
||||
whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null,
|
||||
alerts: applyResolutions(alerts, resolved),
|
||||
overduePayments,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
return ok({ groups: items });
|
||||
}
|
||||
}
|
||||
|
||||
function groupBy<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
|
||||
const map = new Map<string, T[]>();
|
||||
for (const row of rows) {
|
||||
const list = map.get(key(row)) ?? [];
|
||||
list.push(row);
|
||||
map.set(key(row), list);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import type { ResolveAlert } from '@gruperly/shared';
|
||||
import { ResolveAlertSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ResolveStudentAlert } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const payload = c.req.valid('json') as ResolveAlert;
|
||||
const useCase = new ResolveStudentAlert();
|
||||
const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind';
|
||||
|
||||
type ResolveAlertDeps = {
|
||||
db?: {
|
||||
attendee: Prisma.AttendeeDelegate;
|
||||
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
|
||||
};
|
||||
};
|
||||
|
||||
export type ResolveAlertResult = ResolveAlert & { attendeeId: string };
|
||||
|
||||
/* "Resuelto": stores the signature of the alert the professor saw. One row per
|
||||
attendee and type, overwritten on each resolve, so the table never grows past
|
||||
two rows per attendee. An attendee outside the user's groups is a 404, not a
|
||||
403: we don't confirm that the id exists. */
|
||||
export class ResolveStudentAlert {
|
||||
constructor(private readonly deps: ResolveAlertDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
payload: ResolveAlert,
|
||||
): Promise<Result<ResolveAlertResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
const kind = ALERT_TYPE_TO_KIND[payload.tipo];
|
||||
await db.attendeeAlertResolution.upsert({
|
||||
where: { attendeeId_kind: { attendeeId, kind } },
|
||||
create: { attendeeId, kind, signature: payload.firma, resolvedById: userId },
|
||||
update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma });
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/attention/index.ts
Normal file
1
apps/backend/src/modules/attention/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as attentionRoutes } from './routes';
|
||||
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { StudentAlertKind } from '@generated/prisma/client';
|
||||
import type { StudentAlertType } from '@gruperly/shared';
|
||||
|
||||
/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */
|
||||
export const ALERT_KIND_TO_TYPE: Record<StudentAlertKind, StudentAlertType> = {
|
||||
ATTENDANCE: 'asistencia',
|
||||
PAYMENT: 'pago',
|
||||
};
|
||||
|
||||
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
|
||||
asistencia: 'ATTENDANCE',
|
||||
pago: 'PAYMENT',
|
||||
};
|
||||
10
apps/backend/src/modules/attention/routes.ts
Normal file
10
apps/backend/src/modules/attention/routes.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Hono } from 'hono';
|
||||
import getOverviewRoute from './features/get-overview/route';
|
||||
import resolveRoute from './features/resolve/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getOverviewRoute);
|
||||
routes.route('/', resolveRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { passkey } from '@better-auth/passkey';
|
||||
import { appLocaleSchema } from '@gruperly/shared';
|
||||
import { betterAuth } from 'better-auth';
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma';
|
||||
import { organization } from 'better-auth/plugins/organization';
|
||||
@@ -11,9 +12,22 @@ export const auth = betterAuth({
|
||||
database: prismaAdapter(getPrismaClient(), {
|
||||
provider: 'postgresql',
|
||||
}),
|
||||
user: {
|
||||
additionalFields: {
|
||||
// UI language chosen in Ajustes; null means "follow the device". The web
|
||||
// saves it with updateUser and reads it back from the session.
|
||||
locale: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
input: true,
|
||||
validator: { input: appLocaleSchema.nullable() },
|
||||
},
|
||||
},
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await emailProvider.sendPasswordResetEmail({
|
||||
email: user.email,
|
||||
|
||||
15
apps/backend/src/modules/billing/features/cancel/route.ts
Normal file
15
apps/backend/src/modules/billing/features/cancel/route.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { CancelSubscription } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/cancel', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const result = await new CancelSubscription().execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
49
apps/backend/src/modules/billing/features/cancel/use-case.ts
Normal file
49
apps/backend/src/modules/billing/features/cancel/use-case.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { noActiveSubscriptionProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { subscriptionRefOf } from '../../lib';
|
||||
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
|
||||
|
||||
type CancelSubscriptionDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription'>;
|
||||
providers?: BillingProviderResolver;
|
||||
};
|
||||
|
||||
/**
|
||||
* Stops the monthly charge with the provider that collects it. `paidThrough`
|
||||
* stays: the professor keeps Pro until the end of what they already paid
|
||||
* (plus the grace period).
|
||||
*/
|
||||
export class CancelSubscription {
|
||||
constructor(private readonly deps: CancelSubscriptionDeps = {}) {}
|
||||
|
||||
async execute(userId: string): Promise<Result<{ status: SubscriptionStatus }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const subscription = await db.billingSubscription.findUnique({ where: { userId } });
|
||||
if (
|
||||
!subscription
|
||||
|| (!subscription.externalId && !subscription.checkoutRef)
|
||||
|| subscription.status === 'CANCELLED'
|
||||
) {
|
||||
return err(noActiveSubscriptionProblem());
|
||||
}
|
||||
|
||||
try {
|
||||
await (this.deps.providers ?? getBillingProvider)(subscription.provider).cancel(
|
||||
subscriptionRefOf(subscription),
|
||||
);
|
||||
} catch (error) {
|
||||
return err(toBillingProblem(error));
|
||||
}
|
||||
|
||||
await db.billingSubscription.update({
|
||||
where: { id: subscription.id },
|
||||
data: { status: 'CANCELLED', nextPaymentDate: null },
|
||||
});
|
||||
|
||||
return ok({ status: 'CANCELLED' });
|
||||
}
|
||||
}
|
||||
19
apps/backend/src/modules/billing/features/charges/route.ts
Normal file
19
apps/backend/src/modules/billing/features/charges/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { BillingChargesQuery } from '@gruperly/shared';
|
||||
import { BillingChargesQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListBillingCharges } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/charges', validate.query(BillingChargesQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const query = c.req.valid('query') as BillingChargesQuery;
|
||||
const result = await new ListBillingCharges().execute(query, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { BillingChargeList, BillingChargesQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { toBillingChargeDto } from '../../lib';
|
||||
|
||||
type ListBillingChargesDeps = { db?: Pick<PrismaClient, 'billingCharge'> };
|
||||
|
||||
/** The professor's own Pro charges, newest first. */
|
||||
export class ListBillingCharges {
|
||||
constructor(private readonly deps: ListBillingChargesDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
query: BillingChargesQuery,
|
||||
userId: string,
|
||||
): Promise<Result<BillingChargeList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const where = { subscription: { userId } };
|
||||
|
||||
const [charges, total] = await Promise.all([
|
||||
db.billingCharge.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
}),
|
||||
db.billingCharge.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: charges.map(toBillingChargeDto),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/billing/features/plans/route.ts
Normal file
16
apps/backend/src/modules/billing/features/plans/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { planCatalog, toPlanCatalogDto } from '../../lib';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
/**
|
||||
* What each plan allows and what Pro costs in every country. The onboarding
|
||||
* asks before the professor's country is stored, so it gets all of them.
|
||||
*/
|
||||
route.get('/plans', async (c) => {
|
||||
return resultJson(c, ok(toPlanCatalogDto(await planCatalog.snapshot())));
|
||||
});
|
||||
|
||||
export default route;
|
||||
19
apps/backend/src/modules/billing/features/return/route.ts
Normal file
19
apps/backend/src/modules/billing/features/return/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { billingReturnToSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { getWebOrigin } from '@/modules/mp/lib';
|
||||
import { buildSubscriptionReturnUrl } from '../../lib';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
/**
|
||||
* The `back_url` of the Pro checkout (Mercado Pago and Stripe). Public: the
|
||||
* browser comes from the provider, maybe through a tunnel without the session
|
||||
* cookie. It only redirects to a fixed page of the web, so whatever the
|
||||
* provider appends to the query is dropped and nothing can steer the redirect.
|
||||
*/
|
||||
route.get('/return', (c) => {
|
||||
const parsed = billingReturnToSchema.safeParse(c.req.query('to'));
|
||||
return c.redirect(buildSubscriptionReturnUrl(getWebOrigin(), parsed.success ? parsed.data : 'billing'));
|
||||
});
|
||||
|
||||
export default route;
|
||||
15
apps/backend/src/modules/billing/features/status/route.ts
Normal file
15
apps/backend/src/modules/billing/features/status/route.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetBillingStatus } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/status', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const result = await new GetBillingStatus().execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
98
apps/backend/src/modules/billing/features/status/use-case.ts
Normal file
98
apps/backend/src/modules/billing/features/status/use-case.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { countryOf, type PlanCatalogReader, PlanGuard, planCatalog, SyncSubscription } from '../../lib';
|
||||
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
|
||||
|
||||
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
|
||||
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
|
||||
|
||||
type GetBillingStatusDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription' | 'billingCharge'>;
|
||||
guard?: PlanGuard;
|
||||
catalog?: PlanCatalogReader;
|
||||
sync?: Pick<SyncSubscription, 'execute'>;
|
||||
providers?: BillingProviderResolver;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export class GetBillingStatus {
|
||||
constructor(private readonly deps: GetBillingStatusDeps = {}) {}
|
||||
|
||||
async execute(userId: string): Promise<Result<BillingStatusDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
|
||||
const user = await db.user.findUnique({ where: { id: userId } });
|
||||
if (!user) return err(notFoundResourceProblem('User', userId));
|
||||
const country = countryOf(user);
|
||||
|
||||
let subscription = await db.billingSubscription.findUnique({ where: { userId } });
|
||||
|
||||
// Coming back from the provider's checkout, the webhook may not have
|
||||
// arrived yet (or may never arrive in local dev): ask directly, throttled.
|
||||
if (
|
||||
subscription?.status === 'PENDING'
|
||||
&& (subscription.externalId || subscription.checkoutRef)
|
||||
&& (!subscription.lastSyncedAt
|
||||
|| now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS)
|
||||
) {
|
||||
const synced = await (this.deps.sync ?? new SyncSubscription()).execute(subscription.id);
|
||||
if (synced.ok && synced.value.synced) {
|
||||
subscription = await db.billingSubscription.findUnique({ where: { userId } });
|
||||
}
|
||||
}
|
||||
|
||||
const entitlements = await (this.deps.guard ?? new PlanGuard()).getEntitlements(userId);
|
||||
// A live subscription keeps the price it was created with; otherwise the
|
||||
// current price of the country is what subscribing would cost.
|
||||
const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null;
|
||||
// An authorized subscription stays with its provider; a new attempt (or
|
||||
// retrying a PENDING one) goes to the country's current provider.
|
||||
const provider = (this.deps.providers ?? getBillingProvider)(
|
||||
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
|
||||
);
|
||||
|
||||
const priceAmount = live
|
||||
? Number(live.amount.toString())
|
||||
: await (this.deps.catalog ?? planCatalog).getProPrice(country);
|
||||
|
||||
// A price change from the backoffice applies from the next charge: show it
|
||||
// while it is queued, and after it reached the provider until it is charged.
|
||||
let nextPriceAmount: number | null = null;
|
||||
if (live?.pendingAmount) {
|
||||
nextPriceAmount = Number(live.pendingAmount.toString());
|
||||
} else if (live?.status === 'AUTHORIZED') {
|
||||
const lastCharge = await db.billingCharge.findFirst({
|
||||
where: { subscriptionId: live.id, status: 'approved' },
|
||||
orderBy: { paidAt: 'desc' },
|
||||
select: { amount: true },
|
||||
});
|
||||
if (lastCharge && Number(lastCharge.amount.toString()) !== priceAmount) nextPriceAmount = priceAmount;
|
||||
}
|
||||
|
||||
return ok({
|
||||
plan: entitlements.plan,
|
||||
status: subscription?.status ?? null,
|
||||
readOnly: entitlements.readOnly,
|
||||
graceUntil: entitlements.graceUntil?.toISOString() ?? null,
|
||||
paidThrough: subscription?.paidThrough?.toISOString() ?? null,
|
||||
nextPaymentDate:
|
||||
subscription?.status === 'AUTHORIZED'
|
||||
? (subscription.nextPaymentDate?.toISOString() ?? null)
|
||||
: null,
|
||||
payerEmail: subscription?.payerEmail ?? null,
|
||||
priceAmount,
|
||||
nextPriceAmount,
|
||||
currency: live ? live.currency : COUNTRY_CURRENCY[country],
|
||||
country,
|
||||
provider: provider.id,
|
||||
availableInCountry: provider.isAvailable(country),
|
||||
enforced: entitlements.enforced,
|
||||
usage: entitlements.usage,
|
||||
limits: entitlements.limits,
|
||||
});
|
||||
}
|
||||
}
|
||||
21
apps/backend/src/modules/billing/features/subscribe/route.ts
Normal file
21
apps/backend/src/modules/billing/features/subscribe/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { SubscribeInput } from '@gruperly/shared';
|
||||
import { SubscribeInputSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { Subscribe } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Returns `{ checkoutUrl }`: the browser navigates there to authorize the
|
||||
// subscription in Mercado Pago, the same way `/mp/connect` works.
|
||||
route.post('/subscribe', validate.json(SubscribeInputSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const input = c.req.valid('json') as SubscribeInput;
|
||||
const result = await new Subscribe().execute(user.id, input);
|
||||
return resultJson(c, result, { status: 201 });
|
||||
});
|
||||
|
||||
export default route;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user